blob: 9be03b3a6fdb449036ef68b6389811dd2daa4057 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass0d24de92012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass0d24de92012-01-14 15:12:45 +00004
5"""Terminal utilities
6
7This module handles terminal interaction including ANSI color codes.
8"""
9
Simon Glassbbd01432012-12-15 10:42:01 +000010import os
Simon Glass37b224f2020-04-09 15:08:40 -060011import re
Simon Glass1e130472020-04-09 15:08:41 -060012import shutil
Simon Glassbbd01432012-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 Glass3c6c0f82014-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 Glass37b224f2020-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 Glass3c6c0f82014-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 Glassdc6df972020-10-29 21:46:35 -060037 def __init__(self, text, colour, newline=True, bright=True):
Simon Glass3c6c0f82014-09-05 19:00:06 -060038 self.text = text
39 self.newline = newline
40 self.colour = colour
Simon Glassdc6df972020-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 Glass3c6c0f82014-09-05 19:00:06 -060048
49 def __str__(self):
Simon Glassdc6df972020-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 Glass3c6c0f82014-09-05 19:00:06 -060053
Simon Glass37b224f2020-04-09 15:08:40 -060054def CalcAsciiLen(text):
55 """Calculate the length of a string, ignoring any ANSI sequences
56
Simon Glass1e130472020-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 Glass37b224f2020-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)
67 >>> text = col.Color(Color.RED, 'abc')
68 >>> len(text)
69 14
70 >>> CalcAsciiLen(text)
71 3
72 >>>
73 >>> text += 'def'
74 >>> CalcAsciiLen(text)
75 6
76 >>> text += col.Color(Color.RED, 'abc')
77 >>> CalcAsciiLen(text)
78 9
79 """
80 result = ansi_escape.sub('', text)
81 return len(result)
82
Simon Glass1e130472020-04-09 15:08:41 -060083def TrimAsciiLen(text, size):
84 """Trim a string containing ANSI sequences to the given ASCII length
Simon Glass37b224f2020-04-09 15:08:40 -060085
Simon Glass1e130472020-04-09 15:08:41 -060086 The string is trimmed with ANSI sequences being ignored for the length
87 calculation.
88
89 >>> col = Color(COLOR_ALWAYS)
90 >>> text = col.Color(Color.RED, 'abc')
91 >>> 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
100 >>> text += col.Color(Color.RED, 'ghi')
101 >>> 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
132
Simon Glass3c541c02020-07-05 21:41:56 -0600133def Print(text='', newline=True, colour=None, limit_to_line=False, bright=True):
Simon Glass3c6c0f82014-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 Glass37b224f2020-04-09 15:08:40 -0600144 global last_print_len
145
Simon Glass3c6c0f82014-09-05 19:00:06 -0600146 if print_test_mode:
Simon Glassdc6df972020-10-29 21:46:35 -0600147 print_test_list.append(PrintLine(text, colour, newline, bright))
Simon Glass3c6c0f82014-09-05 19:00:06 -0600148 else:
149 if colour:
150 col = Color()
Simon Glass3c541c02020-07-05 21:41:56 -0600151 text = col.Color(colour, text, bright=bright)
Simon Glass3c6c0f82014-09-05 19:00:06 -0600152 if newline:
Simon Glassa84eb162020-04-09 15:08:39 -0600153 print(text)
Simon Glass37b224f2020-04-09 15:08:40 -0600154 last_print_len = None
Simon Glass8b4919e2016-09-18 16:48:30 -0600155 else:
Simon Glass1e130472020-04-09 15:08:41 -0600156 if limit_to_line:
157 cols = shutil.get_terminal_size().columns
158 text = TrimAsciiLen(text, cols)
Simon Glassa84eb162020-04-09 15:08:39 -0600159 print(text, end='', flush=True)
Simon Glass37b224f2020-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 Glass3c6c0f82014-09-05 19:00:06 -0600169
Simon Glassdc6df972020-10-29 21:46:35 -0600170def SetPrintTestMode(enable=True):
Simon Glass3c6c0f82014-09-05 19:00:06 -0600171 """Go into test mode, where all printing is recorded"""
172 global print_test_mode
173
Simon Glassdc6df972020-10-29 21:46:35 -0600174 print_test_mode = enable
175 GetPrintTestLines()
Simon Glass3c6c0f82014-09-05 19:00:06 -0600176
177def GetPrintTestLines():
178 """Get a list of all lines output through Print()
179
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()
Paul Burtona920a172016-09-27 16:03:50 +0100194 print(col.Color(line.colour, line.text), end='')
Simon Glass3c6c0f82014-09-05 19:00:06 -0600195 else:
Paul Burtona920a172016-09-27 16:03:50 +0100196 print(line.text, end='')
Simon Glass3c6c0f82014-09-05 19:00:06 -0600197 if line.newline:
Paul Burtona920a172016-09-27 16:03:50 +0100198 print()
Simon Glass3c6c0f82014-09-05 19:00:06 -0600199
200
Simon Glass0d24de92012-01-14 15:12:45 +0000201class Color(object):
Simon Glass6ba57372014-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 Glass0d24de92012-01-14 15:12:45 +0000209
Simon Glass6ba57372014-08-28 09:43:34 -0600210 def __init__(self, colored=COLOR_IF_TERMINAL):
211 """Create a new Color object, optionally disabling color output.
Simon Glass0d24de92012-01-14 15:12:45 +0000212
Simon Glass6ba57372014-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 Glasse752edc2014-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 Glass0d24de92012-01-14 15:12:45 +0000223
Simon Glass6ba57372014-08-28 09:43:34 -0600224 def Start(self, color, bright=True):
225 """Returns a start color code.
Simon Glass0d24de92012-01-14 15:12:45 +0000226
Simon Glass6ba57372014-08-28 09:43:34 -0600227 Args:
228 color: Color to use, .e.g BLACK, RED, etc.
Simon Glass0d24de92012-01-14 15:12:45 +0000229
Simon Glass6ba57372014-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 Glass0d24de92012-01-14 15:12:45 +0000238
Simon Glass6ba57372014-08-28 09:43:34 -0600239 def Stop(self):
Anatolij Gustschinab4a6ab2019-10-27 17:55:04 +0100240 """Returns a stop color code.
Simon Glass0d24de92012-01-14 15:12:45 +0000241
Simon Glass6ba57372014-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 Glass0d24de92012-01-14 15:12:45 +0000249
Simon Glass6ba57372014-08-28 09:43:34 -0600250 def Color(self, color, text, bright=True):
251 """Returns text with conditionally added color escape sequences.
Simon Glass0d24de92012-01-14 15:12:45 +0000252
Simon Glass6ba57372014-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 Glass0d24de92012-01-14 15:12:45 +0000257
Simon Glass6ba57372014-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