Debian Codegraph @

osrf_pycommon/terminal_color/impl.py

raw
1 # Copyright 2014 Open Source Robotics Foundation, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from __future__ import print_function
16
17 import os
18 import string
19
20 _is_windows = (os.name in ['nt'])
21
22 if _is_windows:
23 from .windows import _print_ansi_color_win32
24
25 _ansi = {
26 # Escape sequence start
27 'escape': '\x1b',
28
29 # Reset
30 'reset': '\x1b[0m',
31 '|': '\x1b[0m',
32 'atbar': '@|',
33
34 # Bold on
35 'boldon': '\x1b[1m',
36 '!': '\x1b[1m',
37 'atexclamation': '@!',
38
39 # Bold off
40 'boldoff': '\x1b[22m',
41
42 # Italics on
43 'italicson': '\x1b[3m',
44 '/': '\x1b[3m',
45 'atfwdslash': '@/',
46
47 # Intalics off
48 'italicsoff': '\x1b[23m',
49
50 # Underline on
51 'ulon': '\x1b[4m',
52 '_': '\x1b[4m',
53 'atunderscore': '@_',
54
55 # Underline off
56 'uloff': '\x1b[24m',
57
58 # Invert foreground/background on/off
59 'invon': '\x1b[7m',
60 'invoff': '\x1b[27m',
61
62 # Black foreground
63 'k': '\x1b[30m',
64 'kf': '\x1b[30m',
65 'black': '\x1b[30m',
66 'blackf': '\x1b[30m',
67
68 # Black background
69 'kb': '\x1b[40m',
70 'blackb': '\x1b[40m',
71
72 # Blue foreground
73 'b': '\x1b[34m',
74 'bf': '\x1b[34m',
75 'blue': '\x1b[34m',
76 'bluef': '\x1b[34m',
77
78 # Blue background
79 'bb': '\x1b[44m',
80 'blueb': '\x1b[44m',
81
82 # Cyan foreground
83 'c': '\x1b[36m',
84 'cf': '\x1b[36m',
85 'cyan': '\x1b[36m',
86 'cyanf': '\x1b[36m',
87
88 # Cyan background
89 'cb': '\x1b[46m',
90 'cyanb': '\x1b[46m',
91
92 # Green foreground
93 'g': '\x1b[32m',
94 'gf': '\x1b[32m',
95 'green': '\x1b[32m',
96 'greenf': '\x1b[32m',
97
98 # Green background
99 'gb': '\x1b[42m',
100 'greenb': '\x1b[42m',
101
102 # Purple (magenta) foreground
103 'p': '\x1b[35m',
104 'pf': '\x1b[35m',
105 'purple': '\x1b[35m',
106 'purplef': '\x1b[35m',
107
108 # Purple (magenta) background
109 'pb': '\x1b[45m',
110 'purpleb': '\x1b[45m',
111
112 # Red foreground
113 'r': '\x1b[31m',
114 'rf': '\x1b[31m',
115 'red': '\x1b[31m',
116 'redf': '\x1b[31m',
117
118 # Red background
119 'rb': '\x1b[41m',
120 'redb': '\x1b[41m',
121
122 # White foreground
123 'w': '\x1b[37m',
124 'wf': '\x1b[37m',
125 'white': '\x1b[37m',
126 'whitef': '\x1b[37m',
127
128 # White background
129 'wb': '\x1b[47m',
130 'whiteb': '\x1b[47m',
131
132 # Yellow foreground
133 'y': '\x1b[33m',
134 'yf': '\x1b[33m',
135 'yellow': '\x1b[33m',
136 'yellowf': '\x1b[33m',
137
138 # Yellow background
139 'yb': '\x1b[43m',
140 'yellowb': '\x1b[43m',
141 }
142 # Set all values to empty string
143 _null_ansi = dict([(k, '') for k, v in _ansi.items()])
144 # Except format preservers used by sanitize
145 _null_ansi.update({
146 'atexclamation': '@!',
147 'atfwdslash': '@/',
148 'atunderscore': '@_',
149 'atbar': '@|',
150 })
151 # Enable by default
152 _enabled = True
153
154
155 def ansi(key):
156 """Returns the escape sequence for a given ansi color key."""
157 global _ansi, _null_ansi, _enabled
158 return (_ansi if _enabled else _null_ansi)[key]
159
160
161 def get_ansi_dict():
162 """Returns a copy of the dictionary of keys and ansi escape sequences."""
163 global _ansi
164 return dict(_ansi)
165
166
167 def enable_ansi_color_substitution_globally():
168 """
169 Causes :py:func:`format_color` to replace color annotations with ansi
170 esacpe sequences.
171
172 It also affects :py:func:`ansi`.
173
174 This is the case by default, so there is no need to call this everytime.
175
176 If you have previously caused all substitutions to evaluate to an empty
177 string by calling :py:func:`disable_ansi_color_substitution_globally`, then
178 you can restore the escape sequences for substitutions by calling this
179 function.
180 """
181 global _enabled
182 _enabled = True
183
184
185 def disable_ansi_color_substitution_globally():
186 """
187 Causes :py:func:`format_color` to replace color annotations with
188 empty strings.
189
190 It also affects :py:func:`ansi`.
191
192 This is not the case by default, so if you want to make all substitutions
193 given to either function mentioned above return empty strings then call
194 this function.
195
196 The default behavior can be restored by calling
197 :py:func:`enable_ansi_color_substitution_globally`.
198 """
199 global _enabled
200 _enabled = False
201
202
203 def format_color(msg):
204 """
205 Replaces color annotations with ansi escape sequences.
206
207 See this module's documentation for the list of available substitutions.
208
209 If :py:func:`disable_ansi_color_substitution_globally` has been called
210 then all color annotations will be replaced by empty strings.
211
212 Also, on Windows all color annotations will be replaced with empty strings.
213 If you want colorization on Windows, you must pass annotated strings to
214 :py:func:`print_color`.
215
216 :param str msg: string message to be colorized
217 :returns: colorized string
218 :rtype: str
219 """
220 global _ansi, _null_ansi, _enabled
221 ansi_dict = _null_ansi if not _enabled or _is_windows else _ansi
222 return _format_color(msg, ansi_dict)
223
224
225 def _format_color(msg, ansi_dict):
226 msg = msg.replace('@!', '@{boldon}')
227 msg = msg.replace('@/', '@{italicson}')
228 msg = msg.replace('@_', '@{ulon}')
229 msg = msg.replace('@|', '@{reset}')
230
231 class ColorTemplate(string.Template):
232 delimiter = '@'
233 return ColorTemplate(msg).substitute(ansi_dict)
234
235
236 def print_ansi_color_win32(*args, **kwargs):
237 """
238 Prints color string containing ansi escape sequences to console in Windows.
239
240 If called on a non-Windows system, a :py:exc:`NotImplementedError` occurs.
241
242 Does not respect :py:func:`disable_ansi_color_substitution_globally`.
243
244 Does not substitute color annotations like ``@{r}`` or ``@!``, the string
245 must already contain the ``\\033[1m`` style ansi escape sequences.
246
247 Works by splitting each argument up by ansi escape sequence, printing
248 the text between the sequences, and doing the corresponding win32 action
249 for each ansi sequence encountered.
250 """
251 if not _is_windows:
252 raise NotImplementedError(
253 "print_ansi_color_win32() is not implemented for this system")
254 return _print_ansi_color_win32(*args, **kwargs)
255
256
257 def print_color(*args, **kwargs):
258 """
259 Colorizes and prints with an implicit ansi reset at the end
260
261 Calls :py:func:`format_color` on each positional argument and then sends
262 all positional and keyword arguments to :py:obj:`print`.
263
264 If the ``end`` keyword argument is not present then the default end value
265 ``ansi('reset') + '\\n'`` is used and passed to :py:obj:`print`.
266
267 :py:obj:`os.linesep` is used to determine the actual value for ``\\n``.
268
269 Therefore, if you use the ``end`` keyword argument be sure to include
270 an ansi reset escape sequence if necessary.
271
272 On Windows the substituted arguments and keyword arguments are passed to
273 :py:func:`print_ansi_color_win32` instead of just :py:obj:`print`.
274 """
275 global _ansi, _null_ansi, _enabled
276 # If no end given, use reset + new line
277 if 'end' not in kwargs:
278 kwargs['end'] = '{0}{1}'.format(ansi('reset'), os.linesep)
279 args = [_format_color(a, _ansi if _enabled else _null_ansi) for a in args]
280 # If windows, pass to win32 print color function
281 if _enabled and _is_windows:
282 return print_ansi_color_win32(*args, **kwargs)
283 return print(*args, **kwargs)
284
285
286 def sanitize(msg):
287 """
288 Sanitizes the given string to prevent :py:func:`format_color` from
289 substituting content.
290
291 For example, when the string ``'Email: {user}@{org}'`` is passed to
292 :py:func:`format_color` the ``@{org}`` will be incorrectly recognized
293 as a colorization annotation and it will fail to substitute with a
294 :py:exc:`KeyError`: ``org``.
295
296 In order to prevent this, you can first "sanitize" the string, add color
297 annotations, and then pass the whole string to :py:func:`format_color`.
298
299 If you give this function the string ``'Email: {user}@{org}'``, then it
300 will return ``'Email: {{user}}@@{{org}}'``. Then if you pass that to
301 :py:func:`format_color` it will return ``'Email: {user}@{org}'``.
302 In this way :py:func:`format_color` is the reverse of this function and
303 so it is safe to call this function on any incoming data if it will
304 eventually be passed to :py:func:`format_color`.
305
306 In addition to expanding ``{`` => ``{{``, ``}`` => ``}}``, and
307 ``@`` => ``@@``, this function will also replace any instances of
308 ``@!``, ``@/``, ``@_``, and ``@|`` with ``@{atexclamation}``,
309 ``@{atfwdslash}``, ``@{atunderscore}``, and ``@{atbar}`` respectively.
310 And then there are corresponding keys in the ansi dict to convert them
311 back.
312
313 For example, if you pass the string ``'|@ Notice @|'`` to this function
314 it will return ``'|@@ Notice @{atbar}'``.
315 And since ``ansi('atbar')`` always returns ``@|``, even when
316 :py:func:`disable_ansi_color_substitution_globally` has been called, the
317 result of passing that string to :py:func:`format_color` will be
318 ``'|@ Notice @|'`` again.
319
320 There are two main strategies for constructing strings which use both the
321 Python :py:func:`str.format` function and the colorization annotations.
322
323 One way is to just build each piece and concatenate the result:
324
325 .. code-block:: python
326
327 print_color("@{r}", "{error}".format(error=error_str))
328 # Or using print (remember to include an ansi reset)
329 print(format_color("@{r}" + "{error}".format(error=error_str) + "@|"))
330
331 Another way is to use this function on the format string, concatenate to
332 the annotations, pass the whole string to :py:func:`format_color`, and then
333 format the whole thing:
334
335 .. code-block:: python
336
337 print(format_color("@{r}" + sanitize("{error}") + "@|")
338 .format(error=error_str))
339
340 However, the most common use for this function is to sanitize incoming
341 strings which may have unknown content:
342
343 .. code-block:: python
344
345 def my_func(user_content):
346 print_color("@{y}" + sanitize(user_content))
347
348 This function is not intended to be used on strings with color annotations.
349
350 :param str msg: string message to be sanitized
351 :returns: sanitized string
352 :rtype: str
353 """
354 msg = msg.replace('@', '@@')
355 msg = msg.replace('{', '{{')
356 msg = msg.replace('}', '}}')
357 # Above line `msg = msg.replace('@', '@@')` will have converted @* to @@*
358 msg = msg.replace('@@!', '@{atexclamation}')
359 msg = msg.replace('@@/', '@{atfwdslash}')
360 msg = msg.replace('@@_', '@{atunderscore}')
361 msg = msg.replace('@@|', '@{atbar}')
362 return msg
363
364
365 def test_colors(file=None):
366 """Prints a color testing block using :py:func:`print_color`"""
367 print_color("| Normal | @!Bold Normal", file=file)
368 print_color("| @{kf}Black @|| @!@{kf}Bold Black", file=file)
369 print_color("| @{rf}Red @|| @!@{rf}Bold Red", file=file)
370 print_color("| @{gf}Green @|| @!@{gf}Bold Green", file=file)
371 print_color("| @{yf}Yellow @|| @!@{yf}Bold Yellow", file=file)
372 print_color("| @{bf}Blue @|| @!@{bf}Bold Blue", file=file)
373 print_color("| @{pf}Purple @|| @!@{pf}Bold Purple", file=file)
374 print_color("| @{cf}Cyan @|| @!@{cf}Bold Cyan", file=file)
375 print_color("| @{wf}White @|| @!@{wf}Bold White", file=file)