blob: e72c55ba98e53469be5369b54c285bf78e69f653 [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 Glassa9f7edb2012-12-15 10:42:01 +000010import os
Simon Glass5f9325d2020-04-09 15:08:40 -060011import re
Simon Glassbbde0532020-04-09 15:08:41 -060012import shutil
Simon Glassa9f7edb2012-12-15 10:42:01 +000013import sys
14
15# Selection of when we want our output to be colored
16COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3)
17
Simon Glassfb35f9f2014-09-05 19:00:06 -060018# Initially, we are set up to print to the terminal
19print_test_mode = False
20print_test_list = []
21
Simon Glass5f9325d2020-04-09 15:08:40 -060022# The length of the last line printed without a newline
23last_print_len = None
24
25# credit:
26# stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
27ansi_escape = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
28
Simon Glassfb35f9f2014-09-05 19:00:06 -060029class PrintLine:
30 """A line of text output
31
32 Members:
33 text: Text line that was printed
34 newline: True to output a newline after the text
35 colour: Text colour to use
36 """
Simon Glass3db916d2020-10-29 21:46:35 -060037 def __init__(self, text, colour, newline=True, bright=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -060038 self.text = text
39 self.newline = newline
40 self.colour = colour
Simon Glass3db916d2020-10-29 21:46:35 -060041 self.bright = bright
42
43 def __eq__(self, other):
44 return (self.text == other.text and
45 self.newline == other.newline and
46 self.colour == other.colour and
47 self.bright == other.bright)
Simon Glassfb35f9f2014-09-05 19:00:06 -060048
49 def __str__(self):
Simon Glass3db916d2020-10-29 21:46:35 -060050 return ("newline=%s, colour=%s, bright=%d, text='%s'" %
51 (self.newline, self.colour, self.bright, self.text))
52
Simon Glassfb35f9f2014-09-05 19:00:06 -060053
Simon Glass5f9325d2020-04-09 15:08:40 -060054def CalcAsciiLen(text):
55 """Calculate the length of a string, ignoring any ANSI sequences
56
Simon Glassbbde0532020-04-09 15:08:41 -060057 When displayed on a terminal, ANSI sequences don't take any space, so we
58 need to ignore them when calculating the length of a string.
59
Simon Glass5f9325d2020-04-09 15:08:40 -060060 Args:
61 text: Text to check
62
63 Returns:
64 Length of text, after skipping ANSI sequences
65
66 >>> col = Color(COLOR_ALWAYS)
Simon Glassf45d3742022-01-29 14:14:17 -070067 >>> text = col.build(Color.RED, 'abc')
Simon Glass5f9325d2020-04-09 15:08:40 -060068 >>> len(text)
69 14
70 >>> CalcAsciiLen(text)
71 3
72 >>>
73 >>> text += 'def'
74 >>> CalcAsciiLen(text)
75 6
Simon Glassf45d3742022-01-29 14:14:17 -070076 >>> text += col.build(Color.RED, 'abc')
Simon Glass5f9325d2020-04-09 15:08:40 -060077 >>> CalcAsciiLen(text)
78 9
79 """
80 result = ansi_escape.sub('', text)
81 return len(result)
82
Simon Glassbbde0532020-04-09 15:08:41 -060083def TrimAsciiLen(text, size):
84 """Trim a string containing ANSI sequences to the given ASCII length
85
86 The string is trimmed with ANSI sequences being ignored for the length
87 calculation.
88
89 >>> col = Color(COLOR_ALWAYS)
Simon Glassf45d3742022-01-29 14:14:17 -070090 >>> text = col.build(Color.RED, 'abc')
Simon Glassbbde0532020-04-09 15:08:41 -060091 >>> len(text)
92 14
93 >>> CalcAsciiLen(TrimAsciiLen(text, 4))
94 3
95 >>> CalcAsciiLen(TrimAsciiLen(text, 2))
96 2
97 >>> text += 'def'
98 >>> CalcAsciiLen(TrimAsciiLen(text, 4))
99 4
Simon Glassf45d3742022-01-29 14:14:17 -0700100 >>> text += col.build(Color.RED, 'ghi')
Simon Glassbbde0532020-04-09 15:08:41 -0600101 >>> CalcAsciiLen(TrimAsciiLen(text, 7))
102 7
103 """
104 if CalcAsciiLen(text) < size:
105 return text
106 pos = 0
107 out = ''
108 left = size
109
110 # Work through each ANSI sequence in turn
111 for m in ansi_escape.finditer(text):
112 # Find the text before the sequence and add it to our string, making
113 # sure it doesn't overflow
114 before = text[pos:m.start()]
115 toadd = before[:left]
116 out += toadd
117
118 # Figure out how much non-ANSI space we have left
119 left -= len(toadd)
120
121 # Add the ANSI sequence and move to the position immediately after it
122 out += m.group()
123 pos = m.start() + len(m.group())
124
125 # Deal with text after the last ANSI sequence
126 after = text[pos:]
127 toadd = after[:left]
128 out += toadd
129
130 return out
131
Simon Glass5f9325d2020-04-09 15:08:40 -0600132
Simon Glass1f1e8302022-01-29 14:14:16 -0700133def Tprint(text='', newline=True, colour=None, limit_to_line=False, bright=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -0600134 """Handle a line of output to the terminal.
135
136 In test mode this is recorded in a list. Otherwise it is output to the
137 terminal.
138
139 Args:
140 text: Text to print
141 newline: True to add a new line at the end of the text
142 colour: Colour to use for the text
143 """
Simon Glass5f9325d2020-04-09 15:08:40 -0600144 global last_print_len
145
Simon Glassfb35f9f2014-09-05 19:00:06 -0600146 if print_test_mode:
Simon Glass3db916d2020-10-29 21:46:35 -0600147 print_test_list.append(PrintLine(text, colour, newline, bright))
Simon Glassfb35f9f2014-09-05 19:00:06 -0600148 else:
149 if colour:
150 col = Color()
Simon Glassf45d3742022-01-29 14:14:17 -0700151 text = col.build(colour, text, bright=bright)
Simon Glassfb35f9f2014-09-05 19:00:06 -0600152 if newline:
Simon Glass82e4c642020-04-09 15:08:39 -0600153 print(text)
Simon Glass5f9325d2020-04-09 15:08:40 -0600154 last_print_len = None
Simon Glass9c45a4e2016-09-18 16:48:30 -0600155 else:
Simon Glassbbde0532020-04-09 15:08:41 -0600156 if limit_to_line:
157 cols = shutil.get_terminal_size().columns
158 text = TrimAsciiLen(text, cols)
Simon Glass82e4c642020-04-09 15:08:39 -0600159 print(text, end='', flush=True)
Simon Glass5f9325d2020-04-09 15:08:40 -0600160 last_print_len = CalcAsciiLen(text)
161
162def PrintClear():
163 """Clear a previously line that was printed with no newline"""
164 global last_print_len
165
166 if last_print_len:
167 print('\r%s\r' % (' '* last_print_len), end='', flush=True)
168 last_print_len = None
Simon Glassfb35f9f2014-09-05 19:00:06 -0600169
Simon Glass3db916d2020-10-29 21:46:35 -0600170def SetPrintTestMode(enable=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -0600171 """Go into test mode, where all printing is recorded"""
172 global print_test_mode
173
Simon Glass3db916d2020-10-29 21:46:35 -0600174 print_test_mode = enable
175 GetPrintTestLines()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600176
177def GetPrintTestLines():
Simon Glass1f1e8302022-01-29 14:14:16 -0700178 """Get a list of all lines output through Tprint()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600179
180 Returns:
181 A list of PrintLine objects
182 """
183 global print_test_list
184
185 ret = print_test_list
186 print_test_list = []
187 return ret
188
189def EchoPrintTestLines():
190 """Print out the text lines collected"""
191 for line in print_test_list:
192 if line.colour:
193 col = Color()
Simon Glassf45d3742022-01-29 14:14:17 -0700194 print(col.build(line.colour, line.text), end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600195 else:
Paul Burtonc3931342016-09-27 16:03:50 +0100196 print(line.text, end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600197 if line.newline:
Paul Burtonc3931342016-09-27 16:03:50 +0100198 print()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600199
200
Simon Glass26132882012-01-14 15:12:45 +0000201class Color(object):
Simon Glass381fad82014-08-28 09:43:34 -0600202 """Conditionally wraps text in ANSI color escape sequences."""
203 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
204 BOLD = -1
205 BRIGHT_START = '\033[1;%dm'
206 NORMAL_START = '\033[22;%dm'
207 BOLD_START = '\033[1m'
208 RESET = '\033[0m'
Simon Glass26132882012-01-14 15:12:45 +0000209
Simon Glass381fad82014-08-28 09:43:34 -0600210 def __init__(self, colored=COLOR_IF_TERMINAL):
211 """Create a new Color object, optionally disabling color output.
Simon Glass26132882012-01-14 15:12:45 +0000212
Simon Glass381fad82014-08-28 09:43:34 -0600213 Args:
214 enabled: True if color output should be enabled. If False then this
215 class will not add color codes at all.
216 """
Simon Glassb0cd3412014-08-28 09:43:35 -0600217 try:
218 self._enabled = (colored == COLOR_ALWAYS or
219 (colored == COLOR_IF_TERMINAL and
220 os.isatty(sys.stdout.fileno())))
221 except:
222 self._enabled = False
Simon Glass26132882012-01-14 15:12:45 +0000223
Simon Glass381fad82014-08-28 09:43:34 -0600224 def Start(self, color, bright=True):
225 """Returns a start color code.
Simon Glass26132882012-01-14 15:12:45 +0000226
Simon Glass381fad82014-08-28 09:43:34 -0600227 Args:
228 color: Color to use, .e.g BLACK, RED, etc.
Simon Glass26132882012-01-14 15:12:45 +0000229
Simon Glass381fad82014-08-28 09:43:34 -0600230 Returns:
231 If color is enabled, returns an ANSI sequence to start the given
232 color, otherwise returns empty string
233 """
234 if self._enabled:
235 base = self.BRIGHT_START if bright else self.NORMAL_START
236 return base % (color + 30)
237 return ''
Simon Glass26132882012-01-14 15:12:45 +0000238
Simon Glass381fad82014-08-28 09:43:34 -0600239 def Stop(self):
Anatolij Gustschinf2bcb322019-10-27 17:55:04 +0100240 """Returns a stop color code.
Simon Glass26132882012-01-14 15:12:45 +0000241
Simon Glass381fad82014-08-28 09:43:34 -0600242 Returns:
243 If color is enabled, returns an ANSI color reset sequence,
244 otherwise returns empty string
245 """
246 if self._enabled:
247 return self.RESET
248 return ''
Simon Glass26132882012-01-14 15:12:45 +0000249
Simon Glassf45d3742022-01-29 14:14:17 -0700250 def build(self, color, text, bright=True):
Simon Glass381fad82014-08-28 09:43:34 -0600251 """Returns text with conditionally added color escape sequences.
Simon Glass26132882012-01-14 15:12:45 +0000252
Simon Glass381fad82014-08-28 09:43:34 -0600253 Keyword arguments:
254 color: Text color -- one of the color constants defined in this
255 class.
256 text: The text to color.
Simon Glass26132882012-01-14 15:12:45 +0000257
Simon Glass381fad82014-08-28 09:43:34 -0600258 Returns:
259 If self._enabled is False, returns the original text. If it's True,
260 returns text with color escape sequences based on the value of
261 color.
262 """
263 if not self._enabled:
264 return text
265 if color == self.BOLD:
266 start = self.BOLD_START
267 else:
268 base = self.BRIGHT_START if bright else self.NORMAL_START
269 start = base % (color + 30)
270 return start + text + self.RESET