Tom Rini | 83d290c | 2018-05-06 17:58:06 -0400 | [diff] [blame] | 1 | # SPDX-License-Identifier: GPL-2.0+ |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 2 | # Copyright (c) 2011 The Chromium OS Authors. |
| 3 | # |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 4 | |
| 5 | """Terminal utilities |
| 6 | |
| 7 | This module handles terminal interaction including ANSI color codes. |
| 8 | """ |
| 9 | |
Paul Burton | a920a17 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 10 | from __future__ import print_function |
| 11 | |
Simon Glass | bbd0143 | 2012-12-15 10:42:01 +0000 | [diff] [blame] | 12 | import os |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 13 | import re |
Simon Glass | 1e13047 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 14 | import shutil |
Simon Glass | bbd0143 | 2012-12-15 10:42:01 +0000 | [diff] [blame] | 15 | import sys |
| 16 | |
| 17 | # Selection of when we want our output to be colored |
| 18 | COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3) |
| 19 | |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 20 | # Initially, we are set up to print to the terminal |
| 21 | print_test_mode = False |
| 22 | print_test_list = [] |
| 23 | |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 24 | # The length of the last line printed without a newline |
| 25 | last_print_len = None |
| 26 | |
| 27 | # credit: |
| 28 | # stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python |
| 29 | ansi_escape = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') |
| 30 | |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 31 | class PrintLine: |
| 32 | """A line of text output |
| 33 | |
| 34 | Members: |
| 35 | text: Text line that was printed |
| 36 | newline: True to output a newline after the text |
| 37 | colour: Text colour to use |
| 38 | """ |
| 39 | def __init__(self, text, newline, colour): |
| 40 | self.text = text |
| 41 | self.newline = newline |
| 42 | self.colour = colour |
| 43 | |
| 44 | def __str__(self): |
| 45 | return 'newline=%s, colour=%s, text=%s' % (self.newline, self.colour, |
| 46 | self.text) |
| 47 | |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 48 | def CalcAsciiLen(text): |
| 49 | """Calculate the length of a string, ignoring any ANSI sequences |
| 50 | |
Simon Glass | 1e13047 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 51 | When displayed on a terminal, ANSI sequences don't take any space, so we |
| 52 | need to ignore them when calculating the length of a string. |
| 53 | |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 54 | Args: |
| 55 | text: Text to check |
| 56 | |
| 57 | Returns: |
| 58 | Length of text, after skipping ANSI sequences |
| 59 | |
| 60 | >>> col = Color(COLOR_ALWAYS) |
| 61 | >>> text = col.Color(Color.RED, 'abc') |
| 62 | >>> len(text) |
| 63 | 14 |
| 64 | >>> CalcAsciiLen(text) |
| 65 | 3 |
| 66 | >>> |
| 67 | >>> text += 'def' |
| 68 | >>> CalcAsciiLen(text) |
| 69 | 6 |
| 70 | >>> text += col.Color(Color.RED, 'abc') |
| 71 | >>> CalcAsciiLen(text) |
| 72 | 9 |
| 73 | """ |
| 74 | result = ansi_escape.sub('', text) |
| 75 | return len(result) |
| 76 | |
Simon Glass | 1e13047 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 77 | def TrimAsciiLen(text, size): |
| 78 | """Trim a string containing ANSI sequences to the given ASCII length |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 79 | |
Simon Glass | 1e13047 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 80 | The string is trimmed with ANSI sequences being ignored for the length |
| 81 | calculation. |
| 82 | |
| 83 | >>> col = Color(COLOR_ALWAYS) |
| 84 | >>> text = col.Color(Color.RED, 'abc') |
| 85 | >>> len(text) |
| 86 | 14 |
| 87 | >>> CalcAsciiLen(TrimAsciiLen(text, 4)) |
| 88 | 3 |
| 89 | >>> CalcAsciiLen(TrimAsciiLen(text, 2)) |
| 90 | 2 |
| 91 | >>> text += 'def' |
| 92 | >>> CalcAsciiLen(TrimAsciiLen(text, 4)) |
| 93 | 4 |
| 94 | >>> text += col.Color(Color.RED, 'ghi') |
| 95 | >>> CalcAsciiLen(TrimAsciiLen(text, 7)) |
| 96 | 7 |
| 97 | """ |
| 98 | if CalcAsciiLen(text) < size: |
| 99 | return text |
| 100 | pos = 0 |
| 101 | out = '' |
| 102 | left = size |
| 103 | |
| 104 | # Work through each ANSI sequence in turn |
| 105 | for m in ansi_escape.finditer(text): |
| 106 | # Find the text before the sequence and add it to our string, making |
| 107 | # sure it doesn't overflow |
| 108 | before = text[pos:m.start()] |
| 109 | toadd = before[:left] |
| 110 | out += toadd |
| 111 | |
| 112 | # Figure out how much non-ANSI space we have left |
| 113 | left -= len(toadd) |
| 114 | |
| 115 | # Add the ANSI sequence and move to the position immediately after it |
| 116 | out += m.group() |
| 117 | pos = m.start() + len(m.group()) |
| 118 | |
| 119 | # Deal with text after the last ANSI sequence |
| 120 | after = text[pos:] |
| 121 | toadd = after[:left] |
| 122 | out += toadd |
| 123 | |
| 124 | return out |
| 125 | |
| 126 | |
| 127 | def Print(text='', newline=True, colour=None, limit_to_line=False): |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 128 | """Handle a line of output to the terminal. |
| 129 | |
| 130 | In test mode this is recorded in a list. Otherwise it is output to the |
| 131 | terminal. |
| 132 | |
| 133 | Args: |
| 134 | text: Text to print |
| 135 | newline: True to add a new line at the end of the text |
| 136 | colour: Colour to use for the text |
| 137 | """ |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 138 | global last_print_len |
| 139 | |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 140 | if print_test_mode: |
| 141 | print_test_list.append(PrintLine(text, newline, colour)) |
| 142 | else: |
| 143 | if colour: |
| 144 | col = Color() |
| 145 | text = col.Color(colour, text) |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 146 | if newline: |
Simon Glass | a84eb16 | 2020-04-09 15:08:39 -0600 | [diff] [blame] | 147 | print(text) |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 148 | last_print_len = None |
Simon Glass | 8b4919e | 2016-09-18 16:48:30 -0600 | [diff] [blame] | 149 | else: |
Simon Glass | 1e13047 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 150 | if limit_to_line: |
| 151 | cols = shutil.get_terminal_size().columns |
| 152 | text = TrimAsciiLen(text, cols) |
Simon Glass | a84eb16 | 2020-04-09 15:08:39 -0600 | [diff] [blame] | 153 | print(text, end='', flush=True) |
Simon Glass | 37b224f | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 154 | last_print_len = CalcAsciiLen(text) |
| 155 | |
| 156 | def PrintClear(): |
| 157 | """Clear a previously line that was printed with no newline""" |
| 158 | global last_print_len |
| 159 | |
| 160 | if last_print_len: |
| 161 | print('\r%s\r' % (' '* last_print_len), end='', flush=True) |
| 162 | last_print_len = None |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 163 | |
| 164 | def SetPrintTestMode(): |
| 165 | """Go into test mode, where all printing is recorded""" |
| 166 | global print_test_mode |
| 167 | |
| 168 | print_test_mode = True |
| 169 | |
| 170 | def GetPrintTestLines(): |
| 171 | """Get a list of all lines output through Print() |
| 172 | |
| 173 | Returns: |
| 174 | A list of PrintLine objects |
| 175 | """ |
| 176 | global print_test_list |
| 177 | |
| 178 | ret = print_test_list |
| 179 | print_test_list = [] |
| 180 | return ret |
| 181 | |
| 182 | def EchoPrintTestLines(): |
| 183 | """Print out the text lines collected""" |
| 184 | for line in print_test_list: |
| 185 | if line.colour: |
| 186 | col = Color() |
Paul Burton | a920a17 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 187 | print(col.Color(line.colour, line.text), end='') |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 188 | else: |
Paul Burton | a920a17 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 189 | print(line.text, end='') |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 190 | if line.newline: |
Paul Burton | a920a17 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 191 | print() |
Simon Glass | 3c6c0f8 | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 192 | |
| 193 | |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 194 | class Color(object): |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 195 | """Conditionally wraps text in ANSI color escape sequences.""" |
| 196 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) |
| 197 | BOLD = -1 |
| 198 | BRIGHT_START = '\033[1;%dm' |
| 199 | NORMAL_START = '\033[22;%dm' |
| 200 | BOLD_START = '\033[1m' |
| 201 | RESET = '\033[0m' |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 202 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 203 | def __init__(self, colored=COLOR_IF_TERMINAL): |
| 204 | """Create a new Color object, optionally disabling color output. |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 205 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 206 | Args: |
| 207 | enabled: True if color output should be enabled. If False then this |
| 208 | class will not add color codes at all. |
| 209 | """ |
Simon Glass | e752edc | 2014-08-28 09:43:35 -0600 | [diff] [blame] | 210 | try: |
| 211 | self._enabled = (colored == COLOR_ALWAYS or |
| 212 | (colored == COLOR_IF_TERMINAL and |
| 213 | os.isatty(sys.stdout.fileno()))) |
| 214 | except: |
| 215 | self._enabled = False |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 216 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 217 | def Start(self, color, bright=True): |
| 218 | """Returns a start color code. |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 219 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 220 | Args: |
| 221 | color: Color to use, .e.g BLACK, RED, etc. |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 222 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 223 | Returns: |
| 224 | If color is enabled, returns an ANSI sequence to start the given |
| 225 | color, otherwise returns empty string |
| 226 | """ |
| 227 | if self._enabled: |
| 228 | base = self.BRIGHT_START if bright else self.NORMAL_START |
| 229 | return base % (color + 30) |
| 230 | return '' |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 231 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 232 | def Stop(self): |
Anatolij Gustschin | ab4a6ab | 2019-10-27 17:55:04 +0100 | [diff] [blame] | 233 | """Returns a stop color code. |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 234 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 235 | Returns: |
| 236 | If color is enabled, returns an ANSI color reset sequence, |
| 237 | otherwise returns empty string |
| 238 | """ |
| 239 | if self._enabled: |
| 240 | return self.RESET |
| 241 | return '' |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 242 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 243 | def Color(self, color, text, bright=True): |
| 244 | """Returns text with conditionally added color escape sequences. |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 245 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 246 | Keyword arguments: |
| 247 | color: Text color -- one of the color constants defined in this |
| 248 | class. |
| 249 | text: The text to color. |
Simon Glass | 0d24de9 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 250 | |
Simon Glass | 6ba5737 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 251 | Returns: |
| 252 | If self._enabled is False, returns the original text. If it's True, |
| 253 | returns text with color escape sequences based on the value of |
| 254 | color. |
| 255 | """ |
| 256 | if not self._enabled: |
| 257 | return text |
| 258 | if color == self.BOLD: |
| 259 | start = self.BOLD_START |
| 260 | else: |
| 261 | base = self.BRIGHT_START if bright else self.NORMAL_START |
| 262 | start = base % (color + 30) |
| 263 | return start + text + self.RESET |