Debian Codegraph @

lib_pypy/pyrepl/windows_console.py

raw symbols SCIP
1 # Copyright 2000-2004 Michael Hudson-Doyle <[email protected]>
2 #
3 # All Rights Reserved
4 #
5 #
6 # Permission to use, copy, modify, and distribute this software and
7 # its documentation for any purpose is hereby granted without fee,
8 # provided that the above copyright notice appear in all copies and
9 # that both that copyright notice and this permission notice appear in
10 # supporting documentation.
11 #
12 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
13 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
15 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
16 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
17 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
18 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20 from __future__ import annotations
21
22 import io
23 import os
24 import sys
25 import time
26 import msvcrt
27
28 from collections import deque
29 import ctypes
30 from ctypes.wintypes import (
31 _COORD,
32 WORD,
33 SMALL_RECT,
34 BOOL,
35 HANDLE,
36 CHAR,
37 DWORD,
38 WCHAR,
39 SHORT,
40 )
41 from ctypes import Structure, POINTER, Union
42 from .console import Event, Console
43 from .trace import trace
44 from .utils import wlen
45
46 try:
47 from ctypes import GetLastError, WinDLL, windll, WinError # type: ignore[attr-defined]
48 except:
49 # Keep MyPy happy off Windows
50 from ctypes import CDLL as WinDLL, cdll as windll
51
52 def GetLastError() -> int:
53 return 42
54
55 class WinError(OSError): # type: ignore[no-redef]
56 def __init__(self, err: int | None, descr: str | None = None) -> None:
57 self.err = err
58 self.descr = descr
59
60
61 TYPE_CHECKING = False
62
63 if TYPE_CHECKING:
64 from typing import IO
65
66 VK_MAP: dict[int, str] = {
67 0x23: "end", # VK_END
68 0x24: "home", # VK_HOME
69 0x25: "left", # VK_LEFT
70 0x26: "up", # VK_UP
71 0x27: "right", # VK_RIGHT
72 0x28: "down", # VK_DOWN
73 0x2E: "delete", # VK_DELETE
74 0x70: "f1", # VK_F1
75 0x71: "f2", # VK_F2
76 0x72: "f3", # VK_F3
77 0x73: "f4", # VK_F4
78 0x74: "f5", # VK_F5
79 0x75: "f6", # VK_F6
80 0x76: "f7", # VK_F7
81 0x77: "f8", # VK_F8
82 0x78: "f9", # VK_F9
83 0x79: "f10", # VK_F10
84 0x7A: "f11", # VK_F11
85 0x7B: "f12", # VK_F12
86 0x7C: "f13", # VK_F13
87 0x7D: "f14", # VK_F14
88 0x7E: "f15", # VK_F15
89 0x7F: "f16", # VK_F16
90 0x79: "f17", # VK_F17
91 0x80: "f18", # VK_F18
92 0x81: "f19", # VK_F19
93 0x82: "f20", # VK_F20
94 }
95
96 # Console escape codes: https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
97 ERASE_IN_LINE = "\x1b[K"
98 MOVE_LEFT = "\x1b[{}D"
99 MOVE_RIGHT = "\x1b[{}C"
100 MOVE_UP = "\x1b[{}A"
101 MOVE_DOWN = "\x1b[{}B"
102 CLEAR = "\x1b[H\x1b[J"
103
104
105 class _error(Exception):
106 pass
107
108
109 class WindowsConsole(Console):
110 def __init__(
111 self,
112 f_in: IO[bytes] | int = 0,
113 f_out: IO[bytes] | int = 1,
114 term: str = "",
115 encoding: str = "",
116 ):
117 super().__init__(f_in, f_out, term, encoding)
118
119 SetConsoleMode(
120 OutHandle,
121 ENABLE_WRAP_AT_EOL_OUTPUT
122 | ENABLE_PROCESSED_OUTPUT
123 | ENABLE_VIRTUAL_TERMINAL_PROCESSING,
124 )
125 self.screen: list[str] = []
126 self.width = 80
127 self.height = 25
128 self.__offset = 0
129 self.event_queue: deque[Event] = deque()
130 try:
131 self.out = io._WindowsConsoleIO(self.output_fd, "w") # type: ignore[attr-defined]
132 except ValueError:
133 # Console I/O is redirected, fallback...
134 self.out = None
135
136 def refresh(self, screen: list[str], c_xy: tuple[int, int]) -> None:
137 """
138 Refresh the console screen.
139
140 Parameters:
141 - screen (list): List of strings representing the screen contents.
142 - c_xy (tuple): Cursor position (x, y) on the screen.
143 """
144 cx, cy = c_xy
145
146 while len(self.screen) < min(len(screen), self.height):
147 self._hide_cursor()
148 self._move_relative(0, len(self.screen) - 1)
149 self.__write("\n")
150 self.__posxy = 0, len(self.screen)
151 self.screen.append("")
152
153 px, py = self.__posxy
154 old_offset = offset = self.__offset
155 height = self.height
156
157 # we make sure the cursor is on the screen, and that we're
158 # using all of the screen if we can
159 if cy < offset:
160 offset = cy
161 elif cy >= offset + height:
162 offset = cy - height + 1
163 scroll_lines = offset - old_offset
164
165 # Scrolling the buffer as the current input is greater than the visible
166 # portion of the window. We need to scroll the visible portion and the
167 # entire history
168 self._scroll(scroll_lines, self._getscrollbacksize())
169 self.__posxy = self.__posxy[0], self.__posxy[1] + scroll_lines
170 self.__offset += scroll_lines
171
172 for i in range(scroll_lines):
173 self.screen.append("")
174 elif offset > 0 and len(screen) < offset + height:
175 offset = max(len(screen) - height, 0)
176 screen.append("")
177
178 oldscr = self.screen[old_offset : old_offset + height]
179 newscr = screen[offset : offset + height]
180
181 self.__offset = offset
182
183 self._hide_cursor()
184 for (
185 y,
186 oldline,
187 newline,
188 ) in zip(range(offset, offset + height), oldscr, newscr):
189 if oldline != newline:
190 self.__write_changed_line(y, oldline, newline, px)
191
192 y = len(newscr)
193 while y < len(oldscr):
194 self._move_relative(0, y)
195 self.__posxy = 0, y
196 self._erase_to_end()
197 y += 1
198
199 self._show_cursor()
200
201 self.screen = screen
202 self.move_cursor(cx, cy)
203
204 @property
205 def input_hook(self):
206 return None # not supported on windows
207 try:
208 import nt
209 except ImportError:
210 return None
211 if nt._is_inputhook_installed():
212 return nt._inputhook
213
214 def __write_changed_line(
215 self, y: int, oldline: str, newline: str, px_coord: int
216 ) -> None:
217 # this is frustrating; there's no reason to test (say)
218 # self.dch1 inside the loop -- but alternative ways of
219 # structuring this function are equally painful (I'm trying to
220 # avoid writing code generators these days...)
221 minlen = min(wlen(oldline), wlen(newline))
222 x_pos = 0
223 x_coord = 0
224
225 px_pos = 0
226 j = 0
227 for c in oldline:
228 if j >= px_coord:
229 break
230 j += wlen(c)
231 px_pos += 1
232
233 # reuse the oldline as much as possible, but stop as soon as we
234 # encounter an ESCAPE, because it might be the start of an escape
235 # sequene
236 while (
237 x_coord < minlen
238 and oldline[x_pos] == newline[x_pos]
239 and newline[x_pos] != "\x1b"
240 ):
241 x_coord += wlen(newline[x_pos])
242 x_pos += 1
243
244 self._hide_cursor()
245 self._move_relative(x_coord, y)
246 if wlen(oldline) > wlen(newline):
247 self._erase_to_end()
248
249 self.__write(newline[x_pos:])
250 if wlen(newline) == self.width:
251 # If we wrapped we want to start at the next line
252 self._move_relative(0, y + 1)
253 self.__posxy = 0, y + 1
254 else:
255 self.__posxy = wlen(newline), y
256
257 if "\x1b" in newline or y != self.__posxy[1]:
258 # ANSI escape characters are present, so we can't assume
259 # anything about the position of the cursor. Moving the cursor
260 # to the left margin should work to get to a known position.
261 self.move_cursor(0, y)
262
263 def _scroll(
264 self, top: int, bottom: int, left: int | None = None, right: int | None = None
265 ) -> None:
266 scroll_rect = SMALL_RECT()
267 scroll_rect.Top = SHORT(top)
268 scroll_rect.Bottom = SHORT(bottom)
269 scroll_rect.Left = SHORT(0 if left is None else left)
270 scroll_rect.Right = SHORT(
271 self.getheightwidth()[1] - 1 if right is None else right
272 )
273 destination_origin = _COORD()
274 fill_info = CHAR_INFO()
275 fill_info.UnicodeChar = " "
276
277 if not ScrollConsoleScreenBuffer(
278 OutHandle, scroll_rect, None, destination_origin, fill_info
279 ):
280 raise WinError(GetLastError())
281
282 def _hide_cursor(self):
283 self.__write("\x1b[?25l")
284
285 def _show_cursor(self):
286 self.__write("\x1b[?25h")
287
288 def _enable_blinking(self):
289 self.__write("\x1b[?12h")
290
291 def _disable_blinking(self):
292 self.__write("\x1b[?12l")
293
294 def __write(self, text: str) -> None:
295 if self.out is not None:
296 self.out.write(text.encode(self.encoding, "replace"))
297 self.out.flush()
298 else:
299 os.write(self.output_fd, text.encode(self.encoding, "replace"))
300
301 @property
302 def screen_xy(self) -> tuple[int, int]:
303 info = CONSOLE_SCREEN_BUFFER_INFO()
304 if not GetConsoleScreenBufferInfo(OutHandle, info):
305 raise WinError(GetLastError())
306 return info.dwCursorPosition.X, info.dwCursorPosition.Y
307
308 def _erase_to_end(self) -> None:
309 self.__write(ERASE_IN_LINE)
310
311 def prepare(self) -> None:
312 trace("prepare")
313 self.screen = []
314 self.height, self.width = self.getheightwidth()
315
316 self.__posxy = 0, 0
317 self.__gone_tall = 0
318 self.__offset = 0
319
320 def restore(self) -> None:
321 pass
322
323 def _move_relative(self, x: int, y: int) -> None:
324 """Moves relative to the current __posxy"""
325 dx = x - self.__posxy[0]
326 dy = y - self.__posxy[1]
327 if dx < 0:
328 self.__write(MOVE_LEFT.format(-dx))
329 elif dx > 0:
330 self.__write(MOVE_RIGHT.format(dx))
331
332 if dy < 0:
333 self.__write(MOVE_UP.format(-dy))
334 elif dy > 0:
335 self.__write(MOVE_DOWN.format(dy))
336
337 def move_cursor(self, x: int, y: int) -> None:
338 if x < 0 or y < 0:
339 raise ValueError(f"Bad cursor position {x}, {y}")
340
341 if y < self.__offset or y >= self.__offset + self.height:
342 self.event_queue.insert(0, Event("scroll", ""))
343 else:
344 self._move_relative(x, y)
345 self.__posxy = x, y
346
347 def set_cursor_vis(self, visible: bool) -> None:
348 if visible:
349 self._show_cursor()
350 else:
351 self._hide_cursor()
352
353 def getheightwidth(self) -> tuple[int, int]:
354 """Return (height, width) where height and width are the height
355 and width of the terminal window in characters."""
356 info = CONSOLE_SCREEN_BUFFER_INFO()
357 if not GetConsoleScreenBufferInfo(OutHandle, info):
358 raise WinError(GetLastError())
359 return (
360 info.srWindow.Bottom - info.srWindow.Top + 1,
361 info.srWindow.Right - info.srWindow.Left + 1,
362 )
363
364 def _getscrollbacksize(self) -> int:
365 info = CONSOLE_SCREEN_BUFFER_INFO()
366 if not GetConsoleScreenBufferInfo(OutHandle, info):
367 raise WinError(GetLastError())
368
369 return info.srWindow.Bottom # type: ignore[no-any-return]
370
371 def _read_input(self) -> INPUT_RECORD | None:
372 rec = INPUT_RECORD()
373 read = DWORD()
374 if not ReadConsoleInput(InHandle, rec, 1, read):
375 raise WinError(GetLastError())
376
377 if read.value == 0:
378 return None
379
380 return rec
381
382 def get_event(self, block: bool = True) -> Event | None:
383 """Return an Event instance. Returns None if |block| is false
384 and there is no event pending, otherwise waits for the
385 completion of an event."""
386 if self.event_queue:
387 return self.event_queue.pop()
388
389 while True:
390 rec = self._read_input()
391 if rec is None:
392 if block:
393 continue
394 return None
395
396 if rec.EventType == WINDOW_BUFFER_SIZE_EVENT:
397 return Event("resize", "")
398
399 if rec.EventType != KEY_EVENT or not rec.Event.KeyEvent.bKeyDown:
400 # Only process keys and keydown events
401 if block:
402 continue
403 return None
404
405 key = rec.Event.KeyEvent.uChar.UnicodeChar
406
407 if rec.Event.KeyEvent.uChar.UnicodeChar == "\r":
408 # Make enter make unix-like
409 return Event(evt="key", data="\n", raw=b"\n")
410 elif rec.Event.KeyEvent.wVirtualKeyCode == 8:
411 # Turn backspace directly into the command
412 return Event(
413 evt="key",
414 data="backspace",
415 raw=rec.Event.KeyEvent.uChar.UnicodeChar,
416 )
417 elif rec.Event.KeyEvent.uChar.UnicodeChar == "\x00":
418 # Handle special keys like arrow keys and translate them into the appropriate command
419 code = VK_MAP.get(rec.Event.KeyEvent.wVirtualKeyCode)
420 if code:
421 return Event(
422 evt="key", data=code, raw=rec.Event.KeyEvent.uChar.UnicodeChar
423 )
424 if block:
425 continue
426
427 return None
428
429 return Event(evt="key", data=key, raw=rec.Event.KeyEvent.uChar.UnicodeChar)
430
431 def push_char(self, char: int | bytes) -> None:
432 """
433 Push a character to the console event queue.
434 """
435 raise NotImplementedError("push_char not supported on Windows")
436
437 def beep(self) -> None:
438 self.__write("\x07")
439
440 def clear(self) -> None:
441 """Wipe the screen"""
442 self.__write(CLEAR)
443 self.__posxy = 0, 0
444 self.screen = [""]
445
446 def finish(self) -> None:
447 """Move the cursor to the end of the display and otherwise get
448 ready for end. XXX could be merged with restore? Hmm."""
449 y = len(self.screen) - 1
450 while y >= 0 and not self.screen[y]:
451 y -= 1
452 self._move_relative(0, min(y, self.height + self.__offset - 1))
453 self.__write("\r\n")
454
455 def flushoutput(self) -> None:
456 """Flush all output to the screen (assuming there's some
457 buffering going on somewhere).
458
459 All output on Windows is unbuffered so this is a nop"""
460 pass
461
462 def forgetinput(self) -> None:
463 """Forget all pending, but not yet processed input."""
464 while self._read_input() is not None:
465 pass
466
467 def getpending(self) -> Event:
468 """Return the characters that have been typed but not yet
469 processed."""
470 return Event("key", "", b"")
471
472 def wait(self, timeout: float | None) -> bool:
473 """Wait for an event."""
474 # Poor man's Windows select loop
475 start_time = time.time()
476 while True:
477 if msvcrt.kbhit(): # type: ignore[attr-defined]
478 return True
479 if timeout and time.time() - start_time > timeout:
480 return False
481 time.sleep(0.01)
482
483 def repaint(self) -> None:
484 raise NotImplementedError("No repaint support")
485
486
487 # Windows interop
488 class CONSOLE_SCREEN_BUFFER_INFO(Structure):
489 _fields_ = [
490 ("dwSize", _COORD),
491 ("dwCursorPosition", _COORD),
492 ("wAttributes", WORD),
493 ("srWindow", SMALL_RECT),
494 ("dwMaximumWindowSize", _COORD),
495 ]
496
497
498 class CONSOLE_CURSOR_INFO(Structure):
499 _fields_ = [
500 ("dwSize", DWORD),
501 ("bVisible", BOOL),
502 ]
503
504
505 class CHAR_INFO(Structure):
506 _fields_ = [
507 ("UnicodeChar", WCHAR),
508 ("Attributes", WORD),
509 ]
510
511
512 class Char(Union):
513 _fields_ = [
514 ("UnicodeChar", WCHAR),
515 ("Char", CHAR),
516 ]
517
518
519 class KeyEvent(ctypes.Structure):
520 _fields_ = [
521 ("bKeyDown", BOOL),
522 ("wRepeatCount", WORD),
523 ("wVirtualKeyCode", WORD),
524 ("wVirtualScanCode", WORD),
525 ("uChar", Char),
526 ("dwControlKeyState", DWORD),
527 ]
528
529
530 class WindowsBufferSizeEvent(ctypes.Structure):
531 _fields_ = [("dwSize", _COORD)]
532
533
534 class ConsoleEvent(ctypes.Union):
535 _fields_ = [
536 ("KeyEvent", KeyEvent),
537 ("WindowsBufferSizeEvent", WindowsBufferSizeEvent),
538 ]
539
540
541 class INPUT_RECORD(Structure):
542 _fields_ = [("EventType", WORD), ("Event", ConsoleEvent)]
543
544
545 KEY_EVENT = 0x01
546 FOCUS_EVENT = 0x10
547 MENU_EVENT = 0x08
548 MOUSE_EVENT = 0x02
549 WINDOW_BUFFER_SIZE_EVENT = 0x04
550
551 ENABLE_PROCESSED_OUTPUT = 0x01
552 ENABLE_WRAP_AT_EOL_OUTPUT = 0x02
553 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x04
554
555 STD_INPUT_HANDLE = -10
556 STD_OUTPUT_HANDLE = -11
557
558 if sys.platform == "win32":
559 _KERNEL32 = WinDLL("kernel32", use_last_error=True)
560
561 GetStdHandle = windll.kernel32.GetStdHandle
562 GetStdHandle.argtypes = [DWORD]
563 GetStdHandle.restype = HANDLE
564
565 GetConsoleScreenBufferInfo = _KERNEL32.GetConsoleScreenBufferInfo
566 GetConsoleScreenBufferInfo.argtypes = [
567 HANDLE,
568 ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),
569 ]
570 GetConsoleScreenBufferInfo.restype = BOOL
571
572 ScrollConsoleScreenBuffer = _KERNEL32.ScrollConsoleScreenBufferW
573 ScrollConsoleScreenBuffer.argtypes = [
574 HANDLE,
575 POINTER(SMALL_RECT),
576 POINTER(SMALL_RECT),
577 _COORD,
578 POINTER(CHAR_INFO),
579 ]
580 ScrollConsoleScreenBuffer.restype = BOOL
581
582 SetConsoleMode = _KERNEL32.SetConsoleMode
583 SetConsoleMode.argtypes = [HANDLE, DWORD]
584 SetConsoleMode.restype = BOOL
585
586 ReadConsoleInput = _KERNEL32.ReadConsoleInputW
587 ReadConsoleInput.argtypes = [HANDLE, POINTER(INPUT_RECORD), DWORD, POINTER(DWORD)]
588 ReadConsoleInput.restype = BOOL
589
590 OutHandle = GetStdHandle(STD_OUTPUT_HANDLE)
591 InHandle = GetStdHandle(STD_INPUT_HANDLE)
592 else:
593
594 def _win_only(*args, **kwargs):
595 raise NotImplementedError("Windows only")
596
597 GetStdHandle = _win_only
598 GetConsoleScreenBufferInfo = _win_only
599 ScrollConsoleScreenBuffer = _win_only
600 SetConsoleMode = _win_only
601 ReadConsoleInput = _win_only
602 OutHandle = 0
603 InHandle = 0