You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

259 lines
10KB

  1. # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
  2. import re
  3. import sys
  4. import os
  5. from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
  6. from .winterm import WinTerm, WinColor, WinStyle
  7. from .win32 import windll, winapi_test
  8. winterm = None
  9. if windll is not None:
  10. winterm = WinTerm()
  11. class StreamWrapper(object):
  12. '''
  13. Wraps a stream (such as stdout), acting as a transparent proxy for all
  14. attribute access apart from method 'write()', which is delegated to our
  15. Converter instance.
  16. '''
  17. def __init__(self, wrapped, converter):
  18. # double-underscore everything to prevent clashes with names of
  19. # attributes on the wrapped stream object.
  20. self.__wrapped = wrapped
  21. self.__convertor = converter
  22. def __getattr__(self, name):
  23. return getattr(self.__wrapped, name)
  24. def __enter__(self, *args, **kwargs):
  25. # special method lookup bypasses __getattr__/__getattribute__, see
  26. # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit
  27. # thus, contextlib magic methods are not proxied via __getattr__
  28. return self.__wrapped.__enter__(*args, **kwargs)
  29. def __exit__(self, *args, **kwargs):
  30. return self.__wrapped.__exit__(*args, **kwargs)
  31. def write(self, text):
  32. self.__convertor.write(text)
  33. def isatty(self):
  34. stream = self.__wrapped
  35. if 'PYCHARM_HOSTED' in os.environ:
  36. if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
  37. return True
  38. try:
  39. stream_isatty = stream.isatty
  40. except AttributeError:
  41. return False
  42. else:
  43. return stream_isatty()
  44. @property
  45. def closed(self):
  46. stream = self.__wrapped
  47. try:
  48. return stream.closed
  49. except AttributeError:
  50. return True
  51. class AnsiToWin32(object):
  52. '''
  53. Implements a 'write()' method which, on Windows, will strip ANSI character
  54. sequences from the text, and if outputting to a tty, will convert them into
  55. win32 function calls.
  56. '''
  57. ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
  58. ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command
  59. def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
  60. # The wrapped stream (normally sys.stdout or sys.stderr)
  61. self.wrapped = wrapped
  62. # should we reset colors to defaults after every .write()
  63. self.autoreset = autoreset
  64. # create the proxy wrapping our output stream
  65. self.stream = StreamWrapper(wrapped, self)
  66. on_windows = os.name == 'nt'
  67. # We test if the WinAPI works, because even if we are on Windows
  68. # we may be using a terminal that doesn't support the WinAPI
  69. # (e.g. Cygwin Terminal). In this case it's up to the terminal
  70. # to support the ANSI codes.
  71. conversion_supported = on_windows and winapi_test()
  72. # should we strip ANSI sequences from our output?
  73. if strip is None:
  74. strip = conversion_supported or (not self.stream.closed and not self.stream.isatty())
  75. self.strip = strip
  76. # should we should convert ANSI sequences into win32 calls?
  77. if convert is None:
  78. convert = conversion_supported and not self.stream.closed and self.stream.isatty()
  79. self.convert = convert
  80. # dict of ansi codes to win32 functions and parameters
  81. self.win32_calls = self.get_win32_calls()
  82. # are we wrapping stderr?
  83. self.on_stderr = self.wrapped is sys.stderr
  84. def should_wrap(self):
  85. '''
  86. True if this class is actually needed. If false, then the output
  87. stream will not be affected, nor will win32 calls be issued, so
  88. wrapping stdout is not actually required. This will generally be
  89. False on non-Windows platforms, unless optional functionality like
  90. autoreset has been requested using kwargs to init()
  91. '''
  92. return self.convert or self.strip or self.autoreset
  93. def get_win32_calls(self):
  94. if self.convert and winterm:
  95. return {
  96. AnsiStyle.RESET_ALL: (winterm.reset_all, ),
  97. AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
  98. AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
  99. AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
  100. AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
  101. AnsiFore.RED: (winterm.fore, WinColor.RED),
  102. AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
  103. AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
  104. AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
  105. AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
  106. AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
  107. AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
  108. AnsiFore.RESET: (winterm.fore, ),
  109. AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),
  110. AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),
  111. AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),
  112. AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),
  113. AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),
  114. AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),
  115. AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),
  116. AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),
  117. AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
  118. AnsiBack.RED: (winterm.back, WinColor.RED),
  119. AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
  120. AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
  121. AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
  122. AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
  123. AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
  124. AnsiBack.WHITE: (winterm.back, WinColor.GREY),
  125. AnsiBack.RESET: (winterm.back, ),
  126. AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),
  127. AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),
  128. AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),
  129. AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),
  130. AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),
  131. AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),
  132. AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),
  133. AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),
  134. }
  135. return dict()
  136. def write(self, text):
  137. if self.strip or self.convert:
  138. self.write_and_convert(text)
  139. else:
  140. self.wrapped.write(text)
  141. self.wrapped.flush()
  142. if self.autoreset:
  143. self.reset_all()
  144. def reset_all(self):
  145. if self.convert:
  146. self.call_win32('m', (0,))
  147. elif not self.strip and not self.stream.closed:
  148. self.wrapped.write(Style.RESET_ALL)
  149. def write_and_convert(self, text):
  150. '''
  151. Write the given text to our wrapped stream, stripping any ANSI
  152. sequences from the text, and optionally converting them into win32
  153. calls.
  154. '''
  155. cursor = 0
  156. text = self.convert_osc(text)
  157. for match in self.ANSI_CSI_RE.finditer(text):
  158. start, end = match.span()
  159. self.write_plain_text(text, cursor, start)
  160. self.convert_ansi(*match.groups())
  161. cursor = end
  162. self.write_plain_text(text, cursor, len(text))
  163. def write_plain_text(self, text, start, end):
  164. if start < end:
  165. self.wrapped.write(text[start:end])
  166. self.wrapped.flush()
  167. def convert_ansi(self, paramstring, command):
  168. if self.convert:
  169. params = self.extract_params(command, paramstring)
  170. self.call_win32(command, params)
  171. def extract_params(self, command, paramstring):
  172. if command in 'Hf':
  173. params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))
  174. while len(params) < 2:
  175. # defaults:
  176. params = params + (1,)
  177. else:
  178. params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
  179. if len(params) == 0:
  180. # defaults:
  181. if command in 'JKm':
  182. params = (0,)
  183. elif command in 'ABCD':
  184. params = (1,)
  185. return params
  186. def call_win32(self, command, params):
  187. if command == 'm':
  188. for param in params:
  189. if param in self.win32_calls:
  190. func_args = self.win32_calls[param]
  191. func = func_args[0]
  192. args = func_args[1:]
  193. kwargs = dict(on_stderr=self.on_stderr)
  194. func(*args, **kwargs)
  195. elif command in 'J':
  196. winterm.erase_screen(params[0], on_stderr=self.on_stderr)
  197. elif command in 'K':
  198. winterm.erase_line(params[0], on_stderr=self.on_stderr)
  199. elif command in 'Hf': # cursor position - absolute
  200. winterm.set_cursor_position(params, on_stderr=self.on_stderr)
  201. elif command in 'ABCD': # cursor position - relative
  202. n = params[0]
  203. # A - up, B - down, C - forward, D - back
  204. x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]
  205. winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)
  206. def convert_osc(self, text):
  207. for match in self.ANSI_OSC_RE.finditer(text):
  208. start, end = match.span()
  209. text = text[:start] + text[end:]
  210. paramstring, command = match.groups()
  211. if command == BEL:
  212. if paramstring.count(";") == 1:
  213. params = paramstring.split(";")
  214. # 0 - change title and icon (we will only change title)
  215. # 1 - change icon (we don't support this)
  216. # 2 - change title
  217. if params[0] in '02':
  218. winterm.set_title(params[1])
  219. return text