Debian Codegraph @

src/asyncclick/_winconsole.py

raw
1 # This module is based on the excellent work by Adam Bartoš who
2 # provided a lot of what went into the implementation here in
3 # the discussion to issue1602 in the Python bug tracker.
4 #
5 # There are some general differences in regards to how this works
6 # compared to the original patches as we do not need to patch
7 # the entire interpreter but just work in our little world of
8 # echo and prompt.
9 from __future__ import annotations
10
11 import collections.abc as cabc
12 import io
13 import sys
14 import time
15 import typing as t
16 from ctypes import Array
17 from ctypes import byref
18 from ctypes import c_char
19 from ctypes import c_char_p
20 from ctypes import c_int
21 from ctypes import c_ssize_t
22 from ctypes import c_ulong
23 from ctypes import c_void_p
24 from ctypes import POINTER
25 from ctypes import py_object
26 from ctypes import Structure
27 from ctypes.wintypes import DWORD
28 from ctypes.wintypes import HANDLE
29 from ctypes.wintypes import LPCWSTR
30 from ctypes.wintypes import LPWSTR
31
32 from ._compat import _NonClosingTextIOWrapper
33
34 assert sys.platform == "win32"
35 import msvcrt # noqa: E402
36 from ctypes import windll # noqa: E402
37 from ctypes import WINFUNCTYPE # noqa: E402
38
39 c_ssize_p = POINTER(c_ssize_t)
40
41 kernel32 = windll.kernel32
42 GetStdHandle = kernel32.GetStdHandle
43 ReadConsoleW = kernel32.ReadConsoleW
44 WriteConsoleW = kernel32.WriteConsoleW
45 GetConsoleMode = kernel32.GetConsoleMode
46 GetLastError = kernel32.GetLastError
47 GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
48 CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
49 ("CommandLineToArgvW", windll.shell32)
50 )
51 LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))
52
53 STDIN_HANDLE = GetStdHandle(-10)
54 STDOUT_HANDLE = GetStdHandle(-11)
55 STDERR_HANDLE = GetStdHandle(-12)
56
57 PyBUF_SIMPLE = 0
58 PyBUF_WRITABLE = 1
59
60 ERROR_SUCCESS = 0
61 ERROR_NOT_ENOUGH_MEMORY = 8
62 ERROR_OPERATION_ABORTED = 995
63
64 STDIN_FILENO = 0
65 STDOUT_FILENO = 1
66 STDERR_FILENO = 2
67
68 EOF = b"\x1a"
69 MAX_BYTES_WRITTEN = 32767
70
71 if t.TYPE_CHECKING:
72 try:
73 # Using `typing_extensions.Buffer` instead of `collections.abc`
74 # on Windows for some reason does not have `Sized` implemented.
75 from collections.abc import Buffer # type: ignore
76 except ImportError:
77 from typing_extensions import Buffer
78
79 try:
80 from ctypes import pythonapi
81 except ImportError:
82 # On PyPy we cannot get buffers so our ability to operate here is
83 # severely limited.
84 get_buffer = None
85 else:
86
87 class Py_buffer(Structure):
88 _fields_ = [ # noqa: RUF012
89 ("buf", c_void_p),
90 ("obj", py_object),
91 ("len", c_ssize_t),
92 ("itemsize", c_ssize_t),
93 ("readonly", c_int),
94 ("ndim", c_int),
95 ("format", c_char_p),
96 ("shape", c_ssize_p),
97 ("strides", c_ssize_p),
98 ("suboffsets", c_ssize_p),
99 ("internal", c_void_p),
100 ]
101
102 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
103 PyBuffer_Release = pythonapi.PyBuffer_Release
104
105 def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]:
106 buf = Py_buffer()
107 flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE
108 PyObject_GetBuffer(py_object(obj), byref(buf), flags)
109
110 try:
111 buffer_type = c_char * buf.len
112 out: Array[c_char] = buffer_type.from_address(buf.buf)
113 return out
114 finally:
115 PyBuffer_Release(byref(buf))
116
117
118 class _WindowsConsoleRawIOBase(io.RawIOBase):
119 def __init__(self, handle: int | None) -> None:
120 self.handle = handle
121
122 def isatty(self) -> t.Literal[True]:
123 super().isatty()
124 return True
125
126
127 class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
128 def readable(self) -> t.Literal[True]:
129 return True
130
131 def readinto(self, b: Buffer) -> int:
132 bytes_to_be_read = len(b)
133 if not bytes_to_be_read:
134 return 0
135 elif bytes_to_be_read % 2:
136 raise ValueError(
137 "cannot read odd number of bytes from UTF-16-LE encoded console"
138 )
139
140 buffer = get_buffer(b, writable=True)
141 code_units_to_be_read = bytes_to_be_read // 2
142 code_units_read = c_ulong()
143
144 rv = ReadConsoleW(
145 HANDLE(self.handle),
146 buffer,
147 code_units_to_be_read,
148 byref(code_units_read),
149 None,
150 )
151 if GetLastError() == ERROR_OPERATION_ABORTED:
152 # wait for KeyboardInterrupt
153 time.sleep(0.1)
154 if not rv:
155 raise OSError(f"Windows error: {GetLastError()}")
156
157 if buffer[0] == EOF:
158 return 0
159 return 2 * code_units_read.value
160
161
162 class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
163 def writable(self) -> t.Literal[True]:
164 return True
165
166 @staticmethod
167 def _get_error_message(errno: int) -> str:
168 if errno == ERROR_SUCCESS:
169 return "ERROR_SUCCESS"
170 elif errno == ERROR_NOT_ENOUGH_MEMORY:
171 return "ERROR_NOT_ENOUGH_MEMORY"
172 return f"Windows error {errno}"
173
174 def write(self, b: Buffer) -> int:
175 bytes_to_be_written = len(b)
176 buf = get_buffer(b)
177 code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2
178 code_units_written = c_ulong()
179
180 WriteConsoleW(
181 HANDLE(self.handle),
182 buf,
183 code_units_to_be_written,
184 byref(code_units_written),
185 None,
186 )
187 bytes_written = 2 * code_units_written.value
188
189 if bytes_written == 0 and bytes_to_be_written > 0:
190 raise OSError(self._get_error_message(GetLastError()))
191 return bytes_written
192
193
194 class ConsoleStream:
195 def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:
196 self._text_stream = text_stream
197 self.buffer = byte_stream
198
199 @property
200 def name(self) -> str:
201 return self.buffer.name
202
203 def write(self, x: t.AnyStr) -> int:
204 if isinstance(x, str):
205 return self._text_stream.write(x)
206 try:
207 self.flush()
208 except Exception:
209 pass
210 return self.buffer.write(x)
211
212 def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None:
213 for line in lines:
214 self.write(line)
215
216 def __getattr__(self, name: str) -> t.Any:
217 return getattr(self._text_stream, name)
218
219 def isatty(self) -> bool:
220 return self.buffer.isatty()
221
222 def __repr__(self) -> str:
223 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
224
225
226 def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:
227 text_stream = _NonClosingTextIOWrapper(
228 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
229 "utf-16-le",
230 "strict",
231 line_buffering=True,
232 )
233 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
234
235
236 def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:
237 text_stream = _NonClosingTextIOWrapper(
238 io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
239 "utf-16-le",
240 "strict",
241 line_buffering=True,
242 )
243 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
244
245
246 def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:
247 text_stream = _NonClosingTextIOWrapper(
248 io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
249 "utf-16-le",
250 "strict",
251 line_buffering=True,
252 )
253 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
254
255
256 _stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {
257 0: _get_text_stdin,
258 1: _get_text_stdout,
259 2: _get_text_stderr,
260 }
261
262
263 def _is_console(f: t.TextIO) -> bool:
264 if not hasattr(f, "fileno"):
265 return False
266
267 try:
268 fileno = f.fileno()
269 except (OSError, io.UnsupportedOperation):
270 return False
271
272 handle = msvcrt.get_osfhandle(fileno)
273 return bool(GetConsoleMode(handle, byref(DWORD())))
274
275
276 def _get_windows_console_stream(
277 f: t.TextIO, encoding: str | None, errors: str | None
278 ) -> t.TextIO | None:
279 if (
280 get_buffer is None
281 or encoding not in {"utf-16-le", None}
282 or errors not in {"strict", None}
283 or not _is_console(f)
284 ):
285 return None
286
287 func = _stream_factories.get(f.fileno())
288 if func is None:
289 return None
290
291 b = getattr(f, "buffer", None)
292
293 if b is None:
294 return None
295
296 return func(b)