blob: 84531831760cb0c243d331ec521eae7287b140f8 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass26132882012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass26132882012-01-14 15:12:45 +00004
5"""Terminal utilities
6
7This module handles terminal interaction including ANSI color codes.
8"""
9
Simon Glass14d64e32025-04-29 07:21:59 -060010from contextlib import contextmanager
11from io import StringIO
Simon Glassa9f7edb2012-12-15 10:42:01 +000012import os
Simon Glass5f9325d2020-04-09 15:08:40 -060013import re
Simon Glassbbde0532020-04-09 15:08:41 -060014import shutil
Simon Glassa9f7edb2012-12-15 10:42:01 +000015import sys
16
17# Selection of when we want our output to be colored
18COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3)
19
Simon Glassfb35f9f2014-09-05 19:00:06 -060020# Initially, we are set up to print to the terminal
21print_test_mode = False
22print_test_list = []
23
Simon Glass5f9325d2020-04-09 15:08:40 -060024# The length of the last line printed without a newline
25last_print_len = None
26
27# credit:
28# stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
29ansi_escape = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
30
Simon Glassfb35f9f2014-09-05 19:00:06 -060031class 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 """
Simon Glass3db916d2020-10-29 21:46:35 -060039 def __init__(self, text, colour, newline=True, bright=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -060040 self.text = text
41 self.newline = newline
42 self.colour = colour
Simon Glass3db916d2020-10-29 21:46:35 -060043 self.bright = bright
44
45 def __eq__(self, other):
46 return (self.text == other.text and
47 self.newline == other.newline and
48 self.colour == other.colour and
49 self.bright == other.bright)
Simon Glassfb35f9f2014-09-05 19:00:06 -060050
51 def __str__(self):
Simon Glass3db916d2020-10-29 21:46:35 -060052 return ("newline=%s, colour=%s, bright=%d, text='%s'" %
53 (self.newline, self.colour, self.bright, self.text))
54
Simon Glassfb35f9f2014-09-05 19:00:06 -060055
Simon Glass02811582022-01-29 14:14:18 -070056def calc_ascii_len(text):
Simon Glass5f9325d2020-04-09 15:08:40 -060057 """Calculate the length of a string, ignoring any ANSI sequences
58
Simon Glassbbde0532020-04-09 15:08:41 -060059 When displayed on a terminal, ANSI sequences don't take any space, so we
60 need to ignore them when calculating the length of a string.
61
Simon Glass5f9325d2020-04-09 15:08:40 -060062 Args:
63 text: Text to check
64
65 Returns:
66 Length of text, after skipping ANSI sequences
67
68 >>> col = Color(COLOR_ALWAYS)
Simon Glassf45d3742022-01-29 14:14:17 -070069 >>> text = col.build(Color.RED, 'abc')
Simon Glass5f9325d2020-04-09 15:08:40 -060070 >>> len(text)
71 14
Simon Glass02811582022-01-29 14:14:18 -070072 >>> calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -060073 3
74 >>>
75 >>> text += 'def'
Simon Glass02811582022-01-29 14:14:18 -070076 >>> calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -060077 6
Simon Glassf45d3742022-01-29 14:14:17 -070078 >>> text += col.build(Color.RED, 'abc')
Simon Glass02811582022-01-29 14:14:18 -070079 >>> calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -060080 9
81 """
82 result = ansi_escape.sub('', text)
83 return len(result)
84
Simon Glass02811582022-01-29 14:14:18 -070085def trim_ascii_len(text, size):
Simon Glassbbde0532020-04-09 15:08:41 -060086 """Trim a string containing ANSI sequences to the given ASCII length
87
88 The string is trimmed with ANSI sequences being ignored for the length
89 calculation.
90
91 >>> col = Color(COLOR_ALWAYS)
Simon Glassf45d3742022-01-29 14:14:17 -070092 >>> text = col.build(Color.RED, 'abc')
Simon Glassbbde0532020-04-09 15:08:41 -060093 >>> len(text)
94 14
Simon Glass02811582022-01-29 14:14:18 -070095 >>> calc_ascii_len(trim_ascii_len(text, 4))
Simon Glassbbde0532020-04-09 15:08:41 -060096 3
Simon Glass02811582022-01-29 14:14:18 -070097 >>> calc_ascii_len(trim_ascii_len(text, 2))
Simon Glassbbde0532020-04-09 15:08:41 -060098 2
99 >>> text += 'def'
Simon Glass02811582022-01-29 14:14:18 -0700100 >>> calc_ascii_len(trim_ascii_len(text, 4))
Simon Glassbbde0532020-04-09 15:08:41 -0600101 4
Simon Glassf45d3742022-01-29 14:14:17 -0700102 >>> text += col.build(Color.RED, 'ghi')
Simon Glass02811582022-01-29 14:14:18 -0700103 >>> calc_ascii_len(trim_ascii_len(text, 7))
Simon Glassbbde0532020-04-09 15:08:41 -0600104 7
105 """
Simon Glass02811582022-01-29 14:14:18 -0700106 if calc_ascii_len(text) < size:
Simon Glassbbde0532020-04-09 15:08:41 -0600107 return text
108 pos = 0
109 out = ''
110 left = size
111
112 # Work through each ANSI sequence in turn
113 for m in ansi_escape.finditer(text):
114 # Find the text before the sequence and add it to our string, making
115 # sure it doesn't overflow
116 before = text[pos:m.start()]
117 toadd = before[:left]
118 out += toadd
119
120 # Figure out how much non-ANSI space we have left
121 left -= len(toadd)
122
123 # Add the ANSI sequence and move to the position immediately after it
124 out += m.group()
125 pos = m.start() + len(m.group())
126
127 # Deal with text after the last ANSI sequence
128 after = text[pos:]
129 toadd = after[:left]
130 out += toadd
131
132 return out
133
Simon Glass5f9325d2020-04-09 15:08:40 -0600134
Simon Glass02811582022-01-29 14:14:18 -0700135def tprint(text='', newline=True, colour=None, limit_to_line=False, bright=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -0600136 """Handle a line of output to the terminal.
137
138 In test mode this is recorded in a list. Otherwise it is output to the
139 terminal.
140
141 Args:
142 text: Text to print
143 newline: True to add a new line at the end of the text
144 colour: Colour to use for the text
145 """
Simon Glass5f9325d2020-04-09 15:08:40 -0600146 global last_print_len
147
Simon Glassfb35f9f2014-09-05 19:00:06 -0600148 if print_test_mode:
Simon Glass3db916d2020-10-29 21:46:35 -0600149 print_test_list.append(PrintLine(text, colour, newline, bright))
Simon Glassfb35f9f2014-09-05 19:00:06 -0600150 else:
151 if colour:
152 col = Color()
Simon Glassf45d3742022-01-29 14:14:17 -0700153 text = col.build(colour, text, bright=bright)
Simon Glassfb35f9f2014-09-05 19:00:06 -0600154 if newline:
Simon Glass82e4c642020-04-09 15:08:39 -0600155 print(text)
Simon Glass5f9325d2020-04-09 15:08:40 -0600156 last_print_len = None
Simon Glass9c45a4e2016-09-18 16:48:30 -0600157 else:
Simon Glassbbde0532020-04-09 15:08:41 -0600158 if limit_to_line:
159 cols = shutil.get_terminal_size().columns
Simon Glass02811582022-01-29 14:14:18 -0700160 text = trim_ascii_len(text, cols)
Simon Glass82e4c642020-04-09 15:08:39 -0600161 print(text, end='', flush=True)
Simon Glass02811582022-01-29 14:14:18 -0700162 last_print_len = calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -0600163
Simon Glass02811582022-01-29 14:14:18 -0700164def print_clear():
Simon Glass5f9325d2020-04-09 15:08:40 -0600165 """Clear a previously line that was printed with no newline"""
166 global last_print_len
167
168 if last_print_len:
Simon Glassc229d322024-06-23 11:55:15 -0600169 if print_test_mode:
170 print_test_list.append(PrintLine(None, None, None, None))
171 else:
172 print('\r%s\r' % (' '* last_print_len), end='', flush=True)
173 last_print_len = None
Simon Glassfb35f9f2014-09-05 19:00:06 -0600174
Simon Glass02811582022-01-29 14:14:18 -0700175def set_print_test_mode(enable=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -0600176 """Go into test mode, where all printing is recorded"""
177 global print_test_mode
178
Simon Glass3db916d2020-10-29 21:46:35 -0600179 print_test_mode = enable
Simon Glass02811582022-01-29 14:14:18 -0700180 get_print_test_lines()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600181
Simon Glass02811582022-01-29 14:14:18 -0700182def get_print_test_lines():
183 """Get a list of all lines output through tprint()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600184
185 Returns:
186 A list of PrintLine objects
187 """
188 global print_test_list
189
190 ret = print_test_list
191 print_test_list = []
192 return ret
193
Simon Glass02811582022-01-29 14:14:18 -0700194def echo_print_test_lines():
Simon Glassfb35f9f2014-09-05 19:00:06 -0600195 """Print out the text lines collected"""
196 for line in print_test_list:
197 if line.colour:
198 col = Color()
Simon Glassf45d3742022-01-29 14:14:17 -0700199 print(col.build(line.colour, line.text), end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600200 else:
Paul Burtonc3931342016-09-27 16:03:50 +0100201 print(line.text, end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600202 if line.newline:
Paul Burtonc3931342016-09-27 16:03:50 +0100203 print()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600204
205
Simon Glass26132882012-01-14 15:12:45 +0000206class Color(object):
Simon Glass381fad82014-08-28 09:43:34 -0600207 """Conditionally wraps text in ANSI color escape sequences."""
208 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
209 BOLD = -1
210 BRIGHT_START = '\033[1;%dm'
211 NORMAL_START = '\033[22;%dm'
212 BOLD_START = '\033[1m'
213 RESET = '\033[0m'
Simon Glass26132882012-01-14 15:12:45 +0000214
Simon Glass381fad82014-08-28 09:43:34 -0600215 def __init__(self, colored=COLOR_IF_TERMINAL):
216 """Create a new Color object, optionally disabling color output.
Simon Glass26132882012-01-14 15:12:45 +0000217
Simon Glass381fad82014-08-28 09:43:34 -0600218 Args:
219 enabled: True if color output should be enabled. If False then this
220 class will not add color codes at all.
221 """
Simon Glassb0cd3412014-08-28 09:43:35 -0600222 try:
223 self._enabled = (colored == COLOR_ALWAYS or
224 (colored == COLOR_IF_TERMINAL and
225 os.isatty(sys.stdout.fileno())))
226 except:
227 self._enabled = False
Simon Glass26132882012-01-14 15:12:45 +0000228
Simon Glass02811582022-01-29 14:14:18 -0700229 def start(self, color, bright=True):
Simon Glass381fad82014-08-28 09:43:34 -0600230 """Returns a start color code.
Simon Glass26132882012-01-14 15:12:45 +0000231
Simon Glass381fad82014-08-28 09:43:34 -0600232 Args:
233 color: Color to use, .e.g BLACK, RED, etc.
Simon Glass26132882012-01-14 15:12:45 +0000234
Simon Glass381fad82014-08-28 09:43:34 -0600235 Returns:
236 If color is enabled, returns an ANSI sequence to start the given
237 color, otherwise returns empty string
238 """
239 if self._enabled:
240 base = self.BRIGHT_START if bright else self.NORMAL_START
241 return base % (color + 30)
242 return ''
Simon Glass26132882012-01-14 15:12:45 +0000243
Simon Glass02811582022-01-29 14:14:18 -0700244 def stop(self):
Anatolij Gustschinf2bcb322019-10-27 17:55:04 +0100245 """Returns a stop color code.
Simon Glass26132882012-01-14 15:12:45 +0000246
Simon Glass381fad82014-08-28 09:43:34 -0600247 Returns:
248 If color is enabled, returns an ANSI color reset sequence,
249 otherwise returns empty string
250 """
251 if self._enabled:
252 return self.RESET
253 return ''
Simon Glass26132882012-01-14 15:12:45 +0000254
Simon Glassf45d3742022-01-29 14:14:17 -0700255 def build(self, color, text, bright=True):
Simon Glass381fad82014-08-28 09:43:34 -0600256 """Returns text with conditionally added color escape sequences.
Simon Glass26132882012-01-14 15:12:45 +0000257
Simon Glass381fad82014-08-28 09:43:34 -0600258 Keyword arguments:
259 color: Text color -- one of the color constants defined in this
260 class.
261 text: The text to color.
Simon Glass26132882012-01-14 15:12:45 +0000262
Simon Glass381fad82014-08-28 09:43:34 -0600263 Returns:
264 If self._enabled is False, returns the original text. If it's True,
265 returns text with color escape sequences based on the value of
266 color.
267 """
268 if not self._enabled:
269 return text
270 if color == self.BOLD:
271 start = self.BOLD_START
272 else:
273 base = self.BRIGHT_START if bright else self.NORMAL_START
274 start = base % (color + 30)
275 return start + text + self.RESET
Simon Glass14d64e32025-04-29 07:21:59 -0600276
277
278# Use this to suppress stdout/stderr output:
279# with terminal.capture() as (stdout, stderr)
280# ...do something...
281@contextmanager
282def capture():
283 capture_out, capture_err = StringIO(), StringIO()
284 old_out, old_err = sys.stdout, sys.stderr
285 try:
286 sys.stdout, sys.stderr = capture_out, capture_err
287 yield capture_out, capture_err
288 finally:
289 sys.stdout, sys.stderr = old_out, old_err