blob: 5c9e3eea20cf967a4f92477ac46789985b97ddbd [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
Paul Burtonc3931342016-09-27 16:03:50 +010010from __future__ import print_function
11
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 """
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 Glass5f9325d2020-04-09 15:08:40 -060048def CalcAsciiLen(text):
49 """Calculate the length of a string, ignoring any ANSI sequences
50
Simon Glassbbde0532020-04-09 15:08:41 -060051 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 Glass5f9325d2020-04-09 15:08:40 -060054 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 Glassbbde0532020-04-09 15:08:41 -060077def TrimAsciiLen(text, size):
78 """Trim a string containing ANSI sequences to the given ASCII length
79
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
Simon Glass5f9325d2020-04-09 15:08:40 -0600126
Simon Glassbbde0532020-04-09 15:08:41 -0600127def Print(text='', newline=True, colour=None, limit_to_line=False):
Simon Glassfb35f9f2014-09-05 19:00:06 -0600128 """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 Glass5f9325d2020-04-09 15:08:40 -0600138 global last_print_len
139
Simon Glassfb35f9f2014-09-05 19:00:06 -0600140 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 Glassfb35f9f2014-09-05 19:00:06 -0600146 if newline:
Simon Glass82e4c642020-04-09 15:08:39 -0600147 print(text)
Simon Glass5f9325d2020-04-09 15:08:40 -0600148 last_print_len = None
Simon Glass9c45a4e2016-09-18 16:48:30 -0600149 else:
Simon Glassbbde0532020-04-09 15:08:41 -0600150 if limit_to_line:
151 cols = shutil.get_terminal_size().columns
152 text = TrimAsciiLen(text, cols)
Simon Glass82e4c642020-04-09 15:08:39 -0600153 print(text, end='', flush=True)
Simon Glass5f9325d2020-04-09 15:08:40 -0600154 last_print_len = CalcAsciiLen(text)
155
156def 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 Glassfb35f9f2014-09-05 19:00:06 -0600163
164def SetPrintTestMode():
165 """Go into test mode, where all printing is recorded"""
166 global print_test_mode
167
168 print_test_mode = True
169
170def 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
182def EchoPrintTestLines():
183 """Print out the text lines collected"""
184 for line in print_test_list:
185 if line.colour:
186 col = Color()
Paul Burtonc3931342016-09-27 16:03:50 +0100187 print(col.Color(line.colour, line.text), end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600188 else:
Paul Burtonc3931342016-09-27 16:03:50 +0100189 print(line.text, end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600190 if line.newline:
Paul Burtonc3931342016-09-27 16:03:50 +0100191 print()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600192
193
Simon Glass26132882012-01-14 15:12:45 +0000194class Color(object):
Simon Glass381fad82014-08-28 09:43:34 -0600195 """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 Glass26132882012-01-14 15:12:45 +0000202
Simon Glass381fad82014-08-28 09:43:34 -0600203 def __init__(self, colored=COLOR_IF_TERMINAL):
204 """Create a new Color object, optionally disabling color output.
Simon Glass26132882012-01-14 15:12:45 +0000205
Simon Glass381fad82014-08-28 09:43:34 -0600206 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 Glassb0cd3412014-08-28 09:43:35 -0600210 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 Glass26132882012-01-14 15:12:45 +0000216
Simon Glass381fad82014-08-28 09:43:34 -0600217 def Start(self, color, bright=True):
218 """Returns a start color code.
Simon Glass26132882012-01-14 15:12:45 +0000219
Simon Glass381fad82014-08-28 09:43:34 -0600220 Args:
221 color: Color to use, .e.g BLACK, RED, etc.
Simon Glass26132882012-01-14 15:12:45 +0000222
Simon Glass381fad82014-08-28 09:43:34 -0600223 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 Glass26132882012-01-14 15:12:45 +0000231
Simon Glass381fad82014-08-28 09:43:34 -0600232 def Stop(self):
Anatolij Gustschinf2bcb322019-10-27 17:55:04 +0100233 """Returns a stop color code.
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 color reset sequence,
237 otherwise returns empty string
238 """
239 if self._enabled:
240 return self.RESET
241 return ''
Simon Glass26132882012-01-14 15:12:45 +0000242
Simon Glass381fad82014-08-28 09:43:34 -0600243 def Color(self, color, text, bright=True):
244 """Returns text with conditionally added color escape sequences.
Simon Glass26132882012-01-14 15:12:45 +0000245
Simon Glass381fad82014-08-28 09:43:34 -0600246 Keyword arguments:
247 color: Text color -- one of the color constants defined in this
248 class.
249 text: The text to color.
Simon Glass26132882012-01-14 15:12:45 +0000250
Simon Glass381fad82014-08-28 09:43:34 -0600251 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