Debian Codegraph @

osrf_pycommon/terminal_color/windows.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 # Some of the code in this module is taken from the colorama project:
16 #
17 # https://github.com/tartley/colorama
18 #
19 # Which is licensed under the standard 3-claus new BSD license, here is a copy:
20 #
21 # Copyright (c) 2010 Jonathan Hartley
22 # All rights reserved.
23 #
24 # Redistribution and use in source and binary forms, with or without
25 # modification, are permitted provided that the following conditions
26 # are met:
27 #
28 # * Redistributions of source code must retain the above copyright notice,
29 # this list of conditions and the following disclaimer.
30 #
31 # * Redistributions in binary form must reproduce the above copyright
32 # notice, this list of conditions and the following disclaimer in the
33 # documentation and/or other materials provided with the distribution.
34 #
35 # * Neither the name of the copyright holders, nor those of its
36 # contributors may be used to endorse or promote products derived from
37 # this software without specific prior written permission.
38 #
39 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
40 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
41 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
42 # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
43 # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
44 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
45 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
46 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
47 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
48 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
49 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50 #
51 # End copy.
52
53 from __future__ import print_function
54
55 import ctypes
56 try:
57 import ctypes.wintypes
58 except ValueError:
59 pass
60 import os
61 import sys
62
63 from .ansi_re import split_by_ansi_escape_sequence
64
65 # From winbase.h
66 STDOUT = -11
67 STDERR = -12
68 NORMAL = 0x00
69 BRIGHT = 0x08
70
71
72 def _print_ansi_color_win32(*args, **kwargs):
73 global STDOUT, STDERR
74 # Validate the kwargs
75 for kwarg in kwargs:
76 if kwarg not in ['sep', 'end', 'file']:
77 raise TypeError(
78 "'{0}' is an invalid keyword argument for this function"
79 .format(kwarg))
80 sep = kwargs.get('sep', ' ')
81 end = kwargs.get('end', os.linesep)
82 file = kwargs.get('file', sys.stdout)
83 file = sys.stdout if file is None else file
84 # For each argument, split into more arguments split on ansi escape
85 # sequences and replacing them with (cmd, arg) tuples for Windows
86 # For example:
87 #
88 # `\033]31mred\033]0m` => `[(_win_foreground, 4), 'red', (_win_reset, )]`
89 args = [token for arg in args
90 for token in _tokenize_ansi_string_for_win32(arg) + [sep]]
91 # There is always a trailing sep, strip it
92 args = args[:-1]
93 # Figure out where the data is getting written to
94 try:
95 fn = file.fileno()
96 except AttributeError:
97 fn = None
98 if fn == 1: # stdout
99 handle = STDOUT
100 elif fn == 2: # stderr
101 handle = STDERR
102 else: # something else, which cannot be colored
103 handle = None
104 if handle is None:
105 # Cannot colorize, strip colorization tuples and pass on to print
106 args = [a for a in args if not isinstance(a, tuple)]
107 return print(*args, sep=sep, end=end, file=file)
108 default_attrs = GetConsoleScreenBufferInfo(handle).wAttributes
109 # Print tokenized arguments
110 attrs = _print_args(args, handle, default_attrs, default_attrs, file)
111 # Print ending
112 end = _tokenize_ansi_string_for_win32(end)
113 _print_args(end, handle, attrs, default_attrs, file)
114
115
116 def _print_args(args, handle, attrs, default_attrs, file):
117 for i, arg in enumerate(args):
118 if isinstance(arg, tuple):
119 # Do the proper thing on the windows console
120 assert len(arg) > 0, arg
121 if arg[0] == _win_reset:
122 attrs = arg[0](handle, default_attrs)
123 elif arg[0] == _win_style and len(arg) > 1 and arg[1] is None:
124 # Means the style is not supported on Windows
125 continue
126 else:
127 attrs = arg[0](*(arg[1:] + (handle, attrs)))
128 else:
129 print(arg, end='', file=file)
130 return attrs
131
132
133 def _unpack_attrs(attrs):
134 return [attrs & 7, (attrs << 4) & 7, attrs & BRIGHT]
135
136
137 def _pack_attrs(foreground, background, style):
138 return foreground + (background * 16) + style
139
140
141 def _win_reset(handle, attrs):
142 SetConsoleTextAttribute(handle, attrs)
143 return attrs
144
145
146 def _win_style(style, handle, attrs):
147 attrs_list = _unpack_attrs(attrs)
148 attrs_list[2] = style
149 attrs = _pack_attrs(*attrs_list)
150 SetConsoleTextAttribute(handle, attrs)
151 return attrs
152
153
154 def _win_foreground(foreground, handle, attrs):
155 attrs_list = _unpack_attrs(attrs)
156 attrs_list[0] = foreground
157 attrs = _pack_attrs(*attrs_list)
158 SetConsoleTextAttribute(handle, attrs)
159 return attrs
160
161
162 def _win_background(background, handle, attrs):
163 attrs_list = _unpack_attrs(attrs)
164 attrs_list[1] = background
165 attrs = _pack_attrs(*attrs_list)
166 SetConsoleTextAttribute(handle, attrs)
167 return attrs
168
169
170 _ansi_to_win32 = {
171 '\x1b[0m': (_win_reset, ), # reset
172 '\x1b[1m': (_win_style, BRIGHT), # boldon, see wincon.h
173 '\x1b[22m': (_win_style, NORMAL), # boldoff, see wincon.h
174 '\x1b[3m': (_win_style, None), # italicson, nothing on Windows
175 '\x1b[23m': (_win_style, None), # italicsoff, nothing on Windows
176 '\x1b[4m': (_win_style, None), # ulon, nothing on Windows
177 '\x1b[24m': (_win_style, None), # uloff, nothing on Windows
178 '\x1b[7m': (_win_style, None), # invon, nothing on Windows
179 '\x1b[27m': (_win_style, None), # invoff, nothing on Windows
180 '\x1b[30m': (_win_foreground, 0), # blackf
181 '\x1b[40m': (_win_background, 0), # blackb
182 '\x1b[34m': (_win_foreground, 1), # bluef
183 '\x1b[44m': (_win_background, 1), # blueb
184 '\x1b[32m': (_win_foreground, 2), # greenf
185 '\x1b[42m': (_win_background, 2), # greenb
186 '\x1b[36m': (_win_foreground, 3), # cyanf
187 '\x1b[46m': (_win_background, 3), # cyanb
188 '\x1b[31m': (_win_foreground, 4), # redf
189 '\x1b[41m': (_win_background, 4), # redb
190 '\x1b[35m': (_win_foreground, 5), # purplef
191 '\x1b[45m': (_win_background, 5), # purpleb
192 '\x1b[33m': (_win_foreground, 6), # yellowf
193 '\x1b[43m': (_win_background, 6), # yellowb
194 '\x1b[37m': (_win_foreground, 7), # whitef
195 '\x1b[47m': (_win_background, 7), # whiteb
196 }
197
198
199 def _tokenize_ansi_string_for_win32(msg):
200 global _ansi_to_win32
201 tokens = filter(None, split_by_ansi_escape_sequence(msg, True))
202 tokens = [_ansi_to_win32.get(t, t) for t in tokens]
203 return tokens
204
205
206 try:
207 ctypes.winDLL
208 ctypes.wintypes
209 except AttributeError:
210 pass
211 else:
212 windll = ctypes.LibraryLoader(ctypes.WinDLL)
213
214 # Replication of types and defines from winbase.h
215
216 class CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
217 _fields_ = [
218 ("dwSize", ctypes.wintypes._COORD),
219 ("dwCursorPosition", ctypes.wintypes._COORD),
220 ("wAttributes", ctypes.wintypes.WORD),
221 ("srWindow", ctypes.wintypes.SMALL_RECT),
222 ("dwMaximumWindowSize", ctypes.wintypes._COORD),
223 ]
224
225 def __str__(self):
226 return (
227 '({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10})'
228 .format(
229 self.dwSize.Y, self.dwSize.X,
230 self.dwCursorPosition.Y, self.dwCursorPosition.X,
231 self.wAttributes,
232 self.srWindow.Top, self.srWindow.Left,
233 self.srWindow.Bottom, self.srWindow.Right,
234 self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X)
235 )
236
237 _GetStdHandle = windll.kernel32.GetStdHandle
238 _GetStdHandle.argtypes = [
239 ctypes.wintypes.DWORD,
240 ]
241 _GetStdHandle.restype = ctypes.wintypes.HANDLE
242
243 _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
244 _GetConsoleScreenBufferInfo.argtypes = [
245 ctypes.wintypes.HANDLE,
246 ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),
247 ]
248 _GetConsoleScreenBufferInfo.restype = ctypes.wintypes.BOOL
249
250 _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
251 _SetConsoleTextAttribute.argtypes = [
252 ctypes.wintypes.HANDLE,
253 ctypes.wintypes.WORD,
254 ]
255 _SetConsoleTextAttribute.restype = ctypes.wintypes.BOOL
256
257 handles = {
258 STDOUT: _GetStdHandle(STDOUT),
259 STDERR: _GetStdHandle(STDERR),
260 }
261
262 def GetConsoleScreenBufferInfo(stream_id=STDOUT):
263 global handles, CONSOLE_SCREEN_BUFFER_INFO, _GetConsoleScreenBufferInfo
264 handle = handles[stream_id]
265 csbi = CONSOLE_SCREEN_BUFFER_INFO()
266 _GetConsoleScreenBufferInfo(handle, ctypes.byref(csbi))
267 return csbi
268
269 def SetConsoleTextAttribute(stream_id, attrs):
270 global handles, _SetConsoleTextAttribute
271 handle = handles[stream_id]
272 return _SetConsoleTextAttribute(handle, attrs)