Debian Codegraph @

py/_io/terminalwriter.py

raw symbols SCIP
1 """
2
3 Helper functions for writing to terminals and files.
4
5 """
6
7
8 import sys, os
9 import py
10 py3k = sys.version_info[0] >= 3
11 from py.builtin import text, bytes
12
13 win32_and_ctypes = False
14 colorama = None
15 if sys.platform == "win32":
16 try:
17 import colorama
18 except ImportError:
19 try:
20 import ctypes
21 win32_and_ctypes = True
22 except ImportError:
23 pass
24
25
26 def _getdimensions():
27 import termios,fcntl,struct
28 call = fcntl.ioctl(1,termios.TIOCGWINSZ,"\000"*8)
29 height,width = struct.unpack( "hhhh", call ) [:2]
30 return height, width
31
32
33 def get_terminal_width():
34 height = width = 0
35 try:
36 height, width = _getdimensions()
37 except py.builtin._sysex:
38 raise
39 except:
40 # pass to fallback below
41 pass
42
43 if width == 0:
44 # FALLBACK:
45 # * some exception happened
46 # * or this is emacs terminal which reports (0,0)
47 width = int(os.environ.get('COLUMNS', 80))
48
49 # XXX the windows getdimensions may be bogus, let's sanify a bit
50 if width < 40:
51 width = 80
52 return width
53
54 terminal_width = get_terminal_width()
55
56 # XXX unify with _escaped func below
57 def ansi_print(text, esc, file=None, newline=True, flush=False):
58 if file is None:
59 file = sys.stderr
60 text = text.rstrip()
61 if esc and not isinstance(esc, tuple):
62 esc = (esc,)
63 if esc and sys.platform != "win32" and file.isatty():
64 text = (''.join(['\x1b[%sm' % cod for cod in esc]) +
65 text +
66 '\x1b[0m') # ANSI color code "reset"
67 if newline:
68 text += '\n'
69
70 if esc and win32_and_ctypes and file.isatty():
71 if 1 in esc:
72 bold = True
73 esc = tuple([x for x in esc if x != 1])
74 else:
75 bold = False
76 esctable = {() : FOREGROUND_WHITE, # normal
77 (31,): FOREGROUND_RED, # red
78 (32,): FOREGROUND_GREEN, # green
79 (33,): FOREGROUND_GREEN|FOREGROUND_RED, # yellow
80 (34,): FOREGROUND_BLUE, # blue
81 (35,): FOREGROUND_BLUE|FOREGROUND_RED, # purple
82 (36,): FOREGROUND_BLUE|FOREGROUND_GREEN, # cyan
83 (37,): FOREGROUND_WHITE, # white
84 (39,): FOREGROUND_WHITE, # reset
85 }
86 attr = esctable.get(esc, FOREGROUND_WHITE)
87 if bold:
88 attr |= FOREGROUND_INTENSITY
89 STD_OUTPUT_HANDLE = -11
90 STD_ERROR_HANDLE = -12
91 if file is sys.stderr:
92 handle = GetStdHandle(STD_ERROR_HANDLE)
93 else:
94 handle = GetStdHandle(STD_OUTPUT_HANDLE)
95 oldcolors = GetConsoleInfo(handle).wAttributes
96 attr |= (oldcolors & 0x0f0)
97 SetConsoleTextAttribute(handle, attr)
98 while len(text) > 32768:
99 file.write(text[:32768])
100 text = text[32768:]
101 if text:
102 file.write(text)
103 SetConsoleTextAttribute(handle, oldcolors)
104 else:
105 file.write(text)
106
107 if flush:
108 file.flush()
109
110 def should_do_markup(file):
111 if os.environ.get('PY_COLORS') == '1':
112 return True
113 if os.environ.get('PY_COLORS') == '0':
114 return False
115 return hasattr(file, 'isatty') and file.isatty() \
116 and os.environ.get('TERM') != 'dumb' \
117 and not (sys.platform.startswith('java') and os._name == 'nt')
118
119 class TerminalWriter(object):
120 _esctable = dict(black=30, red=31, green=32, yellow=33,
121 blue=34, purple=35, cyan=36, white=37,
122 Black=40, Red=41, Green=42, Yellow=43,
123 Blue=44, Purple=45, Cyan=46, White=47,
124 bold=1, light=2, blink=5, invert=7)
125
126 # XXX deprecate stringio argument
127 def __init__(self, file=None, stringio=False, encoding=None):
128 if file is None:
129 if stringio:
130 self.stringio = file = py.io.TextIO()
131 else:
132 file = py.std.sys.stdout
133 elif py.builtin.callable(file) and not (
134 hasattr(file, "write") and hasattr(file, "flush")):
135 file = WriteFile(file, encoding=encoding)
136 if hasattr(file, "isatty") and file.isatty() and colorama:
137 file = colorama.AnsiToWin32(file).stream
138 self.encoding = encoding or getattr(file, 'encoding', "utf-8")
139 self._file = file
140 self.fullwidth = get_terminal_width()
141 self.hasmarkup = should_do_markup(file)
142 self._lastlen = 0
143
144 def _escaped(self, text, esc):
145 if esc and self.hasmarkup:
146 text = (''.join(['\x1b[%sm' % cod for cod in esc]) +
147 text +'\x1b[0m')
148 return text
149
150 def markup(self, text, **kw):
151 esc = []
152 for name in kw:
153 if name not in self._esctable:
154 raise ValueError("unknown markup: %r" %(name,))
155 if kw[name]:
156 esc.append(self._esctable[name])
157 return self._escaped(text, tuple(esc))
158
159 def sep(self, sepchar, title=None, fullwidth=None, **kw):
160 if fullwidth is None:
161 fullwidth = self.fullwidth
162 # the goal is to have the line be as long as possible
163 # under the condition that len(line) <= fullwidth
164 if sys.platform == "win32":
165 # if we print in the last column on windows we are on a
166 # new line but there is no way to verify/neutralize this
167 # (we may not know the exact line width)
168 # so let's be defensive to avoid empty lines in the output
169 fullwidth -= 1
170 if title is not None:
171 # we want 2 + 2*len(fill) + len(title) <= fullwidth
172 # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth
173 # 2*len(sepchar)*N <= fullwidth - len(title) - 2
174 # N <= (fullwidth - len(title) - 2) // (2*len(sepchar))
175 N = (fullwidth - len(title) - 2) // (2*len(sepchar))
176 fill = sepchar * N
177 line = "%s %s %s" % (fill, title, fill)
178 else:
179 # we want len(sepchar)*N <= fullwidth
180 # i.e. N <= fullwidth // len(sepchar)
181 line = sepchar * (fullwidth // len(sepchar))
182 # in some situations there is room for an extra sepchar at the right,
183 # in particular if we consider that with a sepchar like "_ " the
184 # trailing space is not important at the end of the line
185 if len(line) + len(sepchar.rstrip()) <= fullwidth:
186 line += sepchar.rstrip()
187
188 self.line(line, **kw)
189
190 def write(self, msg, **kw):
191 if msg:
192 if not isinstance(msg, (bytes, text)):
193 msg = text(msg)
194 if self.hasmarkup and kw:
195 markupmsg = self.markup(msg, **kw)
196 else:
197 markupmsg = msg
198 write_out(self._file, markupmsg)
199
200 def line(self, s='', **kw):
201 self.write(s, **kw)
202 self._checkfill(s)
203 self.write('\n')
204
205 def reline(self, line, **kw):
206 if not self.hasmarkup:
207 raise ValueError("cannot use rewrite-line without terminal")
208 self.write(line, **kw)
209 self._checkfill(line)
210 self.write('\r')
211 self._lastlen = len(line)
212
213 def _checkfill(self, line):
214 diff2last = self._lastlen - len(line)
215 if diff2last > 0:
216 self.write(" " * diff2last)
217
218 class Win32ConsoleWriter(TerminalWriter):
219 def write(self, msg, **kw):
220 if msg:
221 if not isinstance(msg, (bytes, text)):
222 msg = text(msg)
223 oldcolors = None
224 if self.hasmarkup and kw:
225 handle = GetStdHandle(STD_OUTPUT_HANDLE)
226 oldcolors = GetConsoleInfo(handle).wAttributes
227 default_bg = oldcolors & 0x00F0
228 attr = default_bg
229 if kw.pop('bold', False):
230 attr |= FOREGROUND_INTENSITY
231
232 if kw.pop('red', False):
233 attr |= FOREGROUND_RED
234 elif kw.pop('blue', False):
235 attr |= FOREGROUND_BLUE
236 elif kw.pop('green', False):
237 attr |= FOREGROUND_GREEN
238 elif kw.pop('yellow', False):
239 attr |= FOREGROUND_GREEN|FOREGROUND_RED
240 else:
241 attr |= oldcolors & 0x0007
242
243 SetConsoleTextAttribute(handle, attr)
244 write_out(self._file, msg)
245 if oldcolors:
246 SetConsoleTextAttribute(handle, oldcolors)
247
248 class WriteFile(object):
249 def __init__(self, writemethod, encoding=None):
250 self.encoding = encoding
251 self._writemethod = writemethod
252
253 def write(self, data):
254 if self.encoding:
255 data = data.encode(self.encoding, "replace")
256 self._writemethod(data)
257
258 def flush(self):
259 return
260
261
262 if win32_and_ctypes:
263 TerminalWriter = Win32ConsoleWriter
264 import ctypes
265 from ctypes import wintypes
266
267 # ctypes access to the Windows console
268 STD_OUTPUT_HANDLE = -11
269 STD_ERROR_HANDLE = -12
270 FOREGROUND_BLACK = 0x0000 # black text
271 FOREGROUND_BLUE = 0x0001 # text color contains blue.
272 FOREGROUND_GREEN = 0x0002 # text color contains green.
273 FOREGROUND_RED = 0x0004 # text color contains red.
274 FOREGROUND_WHITE = 0x0007
275 FOREGROUND_INTENSITY = 0x0008 # text color is intensified.
276 BACKGROUND_BLACK = 0x0000 # background color black
277 BACKGROUND_BLUE = 0x0010 # background color contains blue.
278 BACKGROUND_GREEN = 0x0020 # background color contains green.
279 BACKGROUND_RED = 0x0040 # background color contains red.
280 BACKGROUND_WHITE = 0x0070
281 BACKGROUND_INTENSITY = 0x0080 # background color is intensified.
282
283 SHORT = ctypes.c_short
284 class COORD(ctypes.Structure):
285 _fields_ = [('X', SHORT),
286 ('Y', SHORT)]
287 class SMALL_RECT(ctypes.Structure):
288 _fields_ = [('Left', SHORT),
289 ('Top', SHORT),
290 ('Right', SHORT),
291 ('Bottom', SHORT)]
292 class CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
293 _fields_ = [('dwSize', COORD),
294 ('dwCursorPosition', COORD),
295 ('wAttributes', wintypes.WORD),
296 ('srWindow', SMALL_RECT),
297 ('dwMaximumWindowSize', COORD)]
298
299 _GetStdHandle = ctypes.windll.kernel32.GetStdHandle
300 _GetStdHandle.argtypes = [wintypes.DWORD]
301 _GetStdHandle.restype = wintypes.HANDLE
302 def GetStdHandle(kind):
303 return _GetStdHandle(kind)
304
305 SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
306 SetConsoleTextAttribute.argtypes = [wintypes.HANDLE, wintypes.WORD]
307 SetConsoleTextAttribute.restype = wintypes.BOOL
308
309 _GetConsoleScreenBufferInfo = \
310 ctypes.windll.kernel32.GetConsoleScreenBufferInfo
311 _GetConsoleScreenBufferInfo.argtypes = [wintypes.HANDLE,
312 ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO)]
313 _GetConsoleScreenBufferInfo.restype = wintypes.BOOL
314 def GetConsoleInfo(handle):
315 info = CONSOLE_SCREEN_BUFFER_INFO()
316 _GetConsoleScreenBufferInfo(handle, ctypes.byref(info))
317 return info
318
319 def _getdimensions():
320 handle = GetStdHandle(STD_OUTPUT_HANDLE)
321 info = GetConsoleInfo(handle)
322 # Substract one from the width, otherwise the cursor wraps
323 # and the ending \n causes an empty line to display.
324 return info.dwSize.Y, info.dwSize.X - 1
325
326 def write_out(fil, msg):
327 # XXX sometimes "msg" is of type bytes, sometimes text which
328 # complicates the situation. Should we try to enforce unicode?
329 try:
330 # on py27 and above writing out to sys.stdout with an encoding
331 # should usually work for unicode messages (if the encoding is
332 # capable of it)
333 fil.write(msg)
334 except UnicodeEncodeError:
335 # on py26 it might not work because stdout expects bytes
336 if fil.encoding:
337 try:
338 fil.write(msg.encode(fil.encoding))
339 except UnicodeEncodeError:
340 # it might still fail if the encoding is not capable
341 pass
342 else:
343 fil.flush()
344 return
345 # fallback: escape all unicode characters
346 msg = msg.encode("unicode-escape").decode("ascii")
347 fil.write(msg)
348 fil.flush()