Debian Codegraph @

Lib/_pyrepl/windows_console.py

raw
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 from .windows_eventqueue import EventQueue
46
47 try:
48 from ctypes import GetLastError, WinDLL, windll, WinError # type: ignore[attr-defined]
49 except:
50 # Keep MyPy happy off Windows
51 from ctypes import CDLL as WinDLL, cdll as windll
52
53 def GetLastError() -> int:
54 return 42
55
56 class WinError(OSError): # type: ignore[no-redef]
57 def __init__(self, err: int | None, descr: str | None = None) -> None:
58 self.err = err
59 self.descr = descr
60
61
62 TYPE_CHECKING = False
63
64 if TYPE_CHECKING:
65 from typing import IO
66
67 # Virtual-Key Codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
68 VK_MAP: dict[int, str] = {
69 0x23: "end", # VK_END
70 0x24: "home", # VK_HOME
71 0x25: "left", # VK_LEFT
72 0x26: "up", # VK_UP
73 0x27: "right", # VK_RIGHT
74 0x28: "down", # VK_DOWN
75 0x2E: "delete", # VK_DELETE
76 0x70: "f1", # VK_F1
77 0x71: "f2", # VK_F2
78 0x72: "f3", # VK_F3
79 0x73: "f4", # VK_F4
80 0x74: "f5", # VK_F5
81 0x75: "f6", # VK_F6
82 0x76: "f7", # VK_F7
83 0x77: "f8", # VK_F8
84 0x78: "f9", # VK_F9
85 0x79: "f10", # VK_F10
86 0x7A: "f11", # VK_F11
87 0x7B: "f12", # VK_F12
88 0x7C: "f13", # VK_F13
89 0x7D: "f14", # VK_F14
90 0x7E: "f15", # VK_F15
91 0x7F: "f16", # VK_F16
92 0x80: "f17", # VK_F17
93 0x81: "f18", # VK_F18
94 0x82: "f19", # VK_F19
95 0x83: "f20", # VK_F20
96 }
97
98 # Virtual terminal output sequences
99 # Reference: https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#output-sequences
100 # Check `windows_eventqueue.py` for input sequences
101 ERASE_IN_LINE = "\x1b[K"
102 MOVE_LEFT = "\x1b[{}D"
103 MOVE_RIGHT = "\x1b[{}C"
104 MOVE_UP = "\x1b[{}A"
105 MOVE_DOWN = "\x1b[{}B"
106 CLEAR = "\x1b[H\x1b[J"
107
108 # State of control keys: https://learn.microsoft.com/en-us/windows/console/key-event-record-str
109 ALT_ACTIVE = 0x01 | 0x02
110 CTRL_ACTIVE = 0x04 | 0x08
111
112
113 class _error(Exception):
114 pass
115
116 def _supports_vt():
117 try:
118 import nt
119 return nt._supports_virtual_terminal()
120 except (ImportError, AttributeError):
121 return False
122
123 class WindowsConsole(Console):
124 def __init__(
125 self,
126 f_in: IO[bytes] | int = 0,
127 f_out: IO[bytes] | int = 1,
128 term: str = "",
129 encoding: str = "",
130 ):
131 super().__init__(f_in, f_out, term, encoding)
132
133 self.__vt_support = _supports_vt()
134
135 if self.__vt_support:
136 trace('console supports virtual terminal')
137
138 # Save original console modes so we can recover on cleanup.
139 original_input_mode = DWORD()
140 GetConsoleMode(InHandle, original_input_mode)
141 trace(f'saved original input mode 0x{original_input_mode.value:x}')
142 self.__original_input_mode = original_input_mode.value
143
144 SetConsoleMode(
145 OutHandle,
146 ENABLE_WRAP_AT_EOL_OUTPUT
147 | ENABLE_PROCESSED_OUTPUT
148 | ENABLE_VIRTUAL_TERMINAL_PROCESSING,
149 )
150
151 self.screen: list[str] = []
152 self.width = 80
153 self.height = 25
154 self.__offset = 0
155 self.event_queue = EventQueue(encoding)
156 try:
157 self.out = io._WindowsConsoleIO(self.output_fd, "w") # type: ignore[attr-defined]
158 except ValueError:
159 # Console I/O is redirected, fallback...
160 self.out = None
161
162 def refresh(self, screen: list[str], c_xy: tuple[int, int]) -> None:
163 """
164 Refresh the console screen.
165
166 Parameters:
167 - screen (list): List of strings representing the screen contents.
168 - c_xy (tuple): Cursor position (x, y) on the screen.
169 """
170 cx, cy = c_xy
171
172 while len(self.screen) < min(len(screen), self.height):
173 self._hide_cursor()
174 if self.screen:
175 self._move_relative(0, len(self.screen) - 1)
176 self.__write("\n")
177 self.posxy = 0, len(self.screen)
178 self.screen.append("")
179
180 px, py = self.posxy
181 old_offset = offset = self.__offset
182 height = self.height
183
184 # we make sure the cursor is on the screen, and that we're
185 # using all of the screen if we can
186 if cy < offset:
187 offset = cy
188 elif cy >= offset + height:
189 offset = cy - height + 1
190 scroll_lines = offset - old_offset
191
192 # Scrolling the buffer as the current input is greater than the visible
193 # portion of the window. We need to scroll the visible portion and the
194 # entire history
195 self._scroll(scroll_lines, self._getscrollbacksize())
196 self.posxy = self.posxy[0], self.posxy[1] + scroll_lines
197 self.__offset += scroll_lines
198
199 for i in range(scroll_lines):
200 self.screen.append("")
201 elif offset > 0 and len(screen) < offset + height:
202 offset = max(len(screen) - height, 0)
203 screen.append("")
204
205 oldscr = self.screen[old_offset : old_offset + height]
206 newscr = screen[offset : offset + height]
207
208 self.__offset = offset
209
210 self._hide_cursor()
211 for (
212 y,
213 oldline,
214 newline,
215 ) in zip(range(offset, offset + height), oldscr, newscr):
216 if oldline != newline:
217 self.__write_changed_line(y, oldline, newline, px)
218
219 y = len(newscr)
220 while y < len(oldscr):
221 self._move_relative(0, y)
222 self.posxy = 0, y
223 self._erase_to_end()
224 y += 1
225
226 self._show_cursor()
227
228 self.screen = screen
229 self.move_cursor(cx, cy)
230
231 @property
232 def input_hook(self):
233 try:
234 import nt
235 except ImportError:
236 return None
237 if nt._is_inputhook_installed():
238 return nt._inputhook
239
240 def __write_changed_line(
241 self, y: int, oldline: str, newline: str, px_coord: int
242 ) -> None:
243 # this is frustrating; there's no reason to test (say)
244 # self.dch1 inside the loop -- but alternative ways of
245 # structuring this function are equally painful (I'm trying to
246 # avoid writing code generators these days...)
247 minlen = min(wlen(oldline), wlen(newline))
248 x_pos = 0
249 x_coord = 0
250
251 px_pos = 0
252 j = 0
253 for c in oldline:
254 if j >= px_coord:
255 break
256 j += wlen(c)
257 px_pos += 1
258
259 # reuse the oldline as much as possible, but stop as soon as we
260 # encounter an ESCAPE, because it might be the start of an escape
261 # sequene
262 while (
263 x_coord < minlen
264 and oldline[x_pos] == newline[x_pos]
265 and newline[x_pos] != "\x1b"
266 ):
267 x_coord += wlen(newline[x_pos])
268 x_pos += 1
269
270 self._hide_cursor()
271 self._move_relative(x_coord, y)
272 if wlen(oldline) > wlen(newline):
273 self._erase_to_end()
274
275 self.__write(newline[x_pos:])
276 self.posxy = min(wlen(newline), self.width - 1), y
277
278 if "\x1b" in newline or y != self.posxy[1] or '\x1a' in newline:
279 # ANSI escape characters are present, so we can't assume
280 # anything about the position of the cursor. Moving the cursor
281 # to the left margin should work to get to a known position.
282 self.move_cursor(0, y)
283
284 def _scroll(
285 self, top: int, bottom: int, left: int | None = None, right: int | None = None
286 ) -> None:
287 scroll_rect = SMALL_RECT()
288 scroll_rect.Top = SHORT(top)
289 scroll_rect.Bottom = SHORT(bottom)
290 scroll_rect.Left = SHORT(0 if left is None else left)
291 scroll_rect.Right = SHORT(
292 self.getheightwidth()[1] - 1 if right is None else right
293 )
294 destination_origin = _COORD()
295 fill_info = CHAR_INFO()
296 fill_info.UnicodeChar = " "
297
298 if not ScrollConsoleScreenBuffer(
299 OutHandle, scroll_rect, None, destination_origin, fill_info
300 ):
301 raise WinError(GetLastError())
302
303 def _hide_cursor(self):
304 self.__write("\x1b[?25l")
305
306 def _show_cursor(self):
307 self.__write("\x1b[?25h")
308
309 def _enable_blinking(self):
310 self.__write("\x1b[?12h")
311
312 def _disable_blinking(self):
313 self.__write("\x1b[?12l")
314
315 def _enable_bracketed_paste(self) -> None:
316 self.__write("\x1b[?2004h")
317
318 def _disable_bracketed_paste(self) -> None:
319 self.__write("\x1b[?2004l")
320
321 def __write(self, text: str) -> None:
322 if "\x1a" in text:
323 text = ''.join(["^Z" if x == '\x1a' else x for x in text])
324
325 if self.out is not None:
326 self.out.write(text.encode(self.encoding, "replace"))
327 self.out.flush()
328 else:
329 os.write(self.output_fd, text.encode(self.encoding, "replace"))
330
331 @property
332 def screen_xy(self) -> tuple[int, int]:
333 info = CONSOLE_SCREEN_BUFFER_INFO()
334 if not GetConsoleScreenBufferInfo(OutHandle, info):
335 raise WinError(GetLastError())
336 return info.dwCursorPosition.X, info.dwCursorPosition.Y
337
338 def _erase_to_end(self) -> None:
339 self.__write(ERASE_IN_LINE)
340
341 def prepare(self) -> None:
342 trace("prepare")
343 self.screen = []
344 self.height, self.width = self.getheightwidth()
345
346 self.posxy = 0, 0
347 self.__gone_tall = 0
348 self.__offset = 0
349
350 if self.__vt_support:
351 SetConsoleMode(InHandle, self.__original_input_mode | ENABLE_VIRTUAL_TERMINAL_INPUT)
352 self._enable_bracketed_paste()
353
354 def restore(self) -> None:
355 if self.__vt_support:
356 # Recover to original mode before running REPL
357 self._disable_bracketed_paste()
358 SetConsoleMode(InHandle, self.__original_input_mode)
359
360 def _move_relative(self, x: int, y: int) -> None:
361 """Moves relative to the current posxy"""
362 dx = x - self.posxy[0]
363 dy = y - self.posxy[1]
364 if dx < 0:
365 self.__write(MOVE_LEFT.format(-dx))
366 elif dx > 0:
367 self.__write(MOVE_RIGHT.format(dx))
368
369 if dy < 0:
370 self.__write(MOVE_UP.format(-dy))
371 elif dy > 0:
372 self.__write(MOVE_DOWN.format(dy))
373
374 def move_cursor(self, x: int, y: int) -> None:
375 if x < 0 or y < 0:
376 raise ValueError(f"Bad cursor position {x}, {y}")
377
378 if y < self.__offset or y >= self.__offset + self.height:
379 self.event_queue.insert(Event("scroll", ""))
380 else:
381 self._move_relative(x, y)
382 self.posxy = x, y
383
384 def set_cursor_vis(self, visible: bool) -> None:
385 if visible:
386 self._show_cursor()
387 else:
388 self._hide_cursor()
389
390 def getheightwidth(self) -> tuple[int, int]:
391 """Return (height, width) where height and width are the height
392 and width of the terminal window in characters."""
393 info = CONSOLE_SCREEN_BUFFER_INFO()
394 if not GetConsoleScreenBufferInfo(OutHandle, info):
395 raise WinError(GetLastError())
396 return (
397 info.srWindow.Bottom - info.srWindow.Top + 1,
398 info.srWindow.Right - info.srWindow.Left + 1,
399 )
400
401 def _getscrollbacksize(self) -> int:
402 info = CONSOLE_SCREEN_BUFFER_INFO()
403 if not GetConsoleScreenBufferInfo(OutHandle, info):
404 raise WinError(GetLastError())
405
406 return info.srWindow.Bottom # type: ignore[no-any-return]
407
408 def _read_input(self, block: bool = True) -> INPUT_RECORD | None:
409 if not block:
410 events = DWORD()
411 if not GetNumberOfConsoleInputEvents(InHandle, events):
412 raise WinError(GetLastError())
413 if not events.value:
414 return None
415
416 rec = INPUT_RECORD()
417 read = DWORD()
418 if not ReadConsoleInput(InHandle, rec, 1, read):
419 raise WinError(GetLastError())
420
421 return rec
422
423 def get_event(self, block: bool = True) -> Event | None:
424 """Return an Event instance. Returns None if |block| is false
425 and there is no event pending, otherwise waits for the
426 completion of an event."""
427
428 while self.event_queue.empty():
429 rec = self._read_input(block)
430 if rec is None:
431 return None
432
433 if rec.EventType == WINDOW_BUFFER_SIZE_EVENT:
434 return Event("resize", "")
435
436 if rec.EventType != KEY_EVENT or not rec.Event.KeyEvent.bKeyDown:
437 # Only process keys and keydown events
438 if block:
439 continue
440 return None
441
442 key_event = rec.Event.KeyEvent
443 raw_key = key = key_event.uChar.UnicodeChar
444
445 if key == "\r":
446 # Make enter unix-like
447 return Event(evt="key", data="\n")
448 elif key_event.wVirtualKeyCode == 8:
449 # Turn backspace directly into the command
450 key = "backspace"
451 elif key == "\x00":
452 # Handle special keys like arrow keys and translate them into the appropriate command
453 key = VK_MAP.get(key_event.wVirtualKeyCode)
454 if key:
455 if key_event.dwControlKeyState & CTRL_ACTIVE:
456 key = f"ctrl {key}"
457 elif key_event.dwControlKeyState & ALT_ACTIVE:
458 # queue the key, return the meta command
459 self.event_queue.insert(Event(evt="key", data=key))
460 return Event(evt="key", data="\033") # keymap.py uses this for meta
461 return Event(evt="key", data=key)
462 if block:
463 continue
464
465 return None
466 elif self.__vt_support:
467 # If virtual terminal is enabled, scanning VT sequences
468 for char in raw_key.encode(self.event_queue.encoding, "replace"):
469 self.event_queue.push(char)
470 continue
471
472 if key_event.dwControlKeyState & ALT_ACTIVE:
473 # Do not swallow characters that have been entered via AltGr:
474 # Windows internally converts AltGr to CTRL+ALT, see
475 # https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-vkkeyscanw
476 if not key_event.dwControlKeyState & CTRL_ACTIVE:
477 # queue the key, return the meta command
478 self.event_queue.insert(Event(evt="key", data=key))
479 return Event(evt="key", data="\033") # keymap.py uses this for meta
480
481 return Event(evt="key", data=key)
482 return self.event_queue.get()
483
484 def push_char(self, char: int | bytes) -> None:
485 """
486 Push a character to the console event queue.
487 """
488 raise NotImplementedError("push_char not supported on Windows")
489
490 def beep(self) -> None:
491 self.__write("\x07")
492
493 def clear(self) -> None:
494 """Wipe the screen"""
495 self.__write(CLEAR)
496 self.posxy = 0, 0
497 self.screen = []
498
499 def finish(self) -> None:
500 """Move the cursor to the end of the display and otherwise get
501 ready for end. XXX could be merged with restore? Hmm."""
502 y = len(self.screen) - 1
503 while y >= 0 and not self.screen[y]:
504 y -= 1
505 self._move_relative(0, min(y, self.height + self.__offset - 1))
506 self.__write("\r\n")
507
508 def flushoutput(self) -> None:
509 """Flush all output to the screen (assuming there's some
510 buffering going on somewhere).
511
512 All output on Windows is unbuffered so this is a nop"""
513 pass
514
515 def forgetinput(self) -> None:
516 """Forget all pending, but not yet processed input."""
517 if not FlushConsoleInputBuffer(InHandle):
518 raise WinError(GetLastError())
519
520 def getpending(self) -> Event:
521 """Return the characters that have been typed but not yet
522 processed."""
523 return Event("key", "", b"")
524
525 def wait_for_event(self, timeout: float | None) -> bool:
526 """Wait for an event."""
527 # Poor man's Windows select loop
528 start_time = time.time()
529 while True:
530 if msvcrt.kbhit(): # type: ignore[attr-defined]
531 return True
532 if timeout and time.time() - start_time > timeout / 1000:
533 return False
534 time.sleep(0.01)
535
536 def wait(self, timeout: float | None) -> bool:
537 """
538 Wait for events on the console.
539 """
540 return (
541 not self.event_queue.empty()
542 or self.wait_for_event(timeout)
543 )
544
545 def repaint(self) -> None:
546 raise NotImplementedError("No repaint support")
547
548
549 # Windows interop
550 class CONSOLE_SCREEN_BUFFER_INFO(Structure):
551 _fields_ = [
552 ("dwSize", _COORD),
553 ("dwCursorPosition", _COORD),
554 ("wAttributes", WORD),
555 ("srWindow", SMALL_RECT),
556 ("dwMaximumWindowSize", _COORD),
557 ]
558
559
560 class CONSOLE_CURSOR_INFO(Structure):
561 _fields_ = [
562 ("dwSize", DWORD),
563 ("bVisible", BOOL),
564 ]
565
566
567 class CHAR_INFO(Structure):
568 _fields_ = [
569 ("UnicodeChar", WCHAR),
570 ("Attributes", WORD),
571 ]
572
573
574 class Char(Union):
575 _fields_ = [
576 ("UnicodeChar", WCHAR),
577 ("Char", CHAR),
578 ]
579
580
581 class KeyEvent(ctypes.Structure):
582 _fields_ = [
583 ("bKeyDown", BOOL),
584 ("wRepeatCount", WORD),
585 ("wVirtualKeyCode", WORD),
586 ("wVirtualScanCode", WORD),
587 ("uChar", Char),
588 ("dwControlKeyState", DWORD),
589 ]
590
591
592 class WindowsBufferSizeEvent(ctypes.Structure):
593 _fields_ = [("dwSize", _COORD)]
594
595
596 class ConsoleEvent(ctypes.Union):
597 _fields_ = [
598 ("KeyEvent", KeyEvent),
599 ("WindowsBufferSizeEvent", WindowsBufferSizeEvent),
600 ]
601
602
603 class INPUT_RECORD(Structure):
604 _fields_ = [("EventType", WORD), ("Event", ConsoleEvent)]
605
606
607 KEY_EVENT = 0x01
608 FOCUS_EVENT = 0x10
609 MENU_EVENT = 0x08
610 MOUSE_EVENT = 0x02
611 WINDOW_BUFFER_SIZE_EVENT = 0x04
612
613 ENABLE_PROCESSED_INPUT = 0x0001
614 ENABLE_LINE_INPUT = 0x0002
615 ENABLE_ECHO_INPUT = 0x0004
616 ENABLE_MOUSE_INPUT = 0x0010
617 ENABLE_INSERT_MODE = 0x0020
618 ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200
619
620 ENABLE_PROCESSED_OUTPUT = 0x01
621 ENABLE_WRAP_AT_EOL_OUTPUT = 0x02
622 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x04
623
624 STD_INPUT_HANDLE = -10
625 STD_OUTPUT_HANDLE = -11
626
627 if sys.platform == "win32":
628 _KERNEL32 = WinDLL("kernel32", use_last_error=True)
629
630 GetStdHandle = windll.kernel32.GetStdHandle
631 GetStdHandle.argtypes = [DWORD]
632 GetStdHandle.restype = HANDLE
633
634 GetConsoleScreenBufferInfo = _KERNEL32.GetConsoleScreenBufferInfo
635 GetConsoleScreenBufferInfo.argtypes = [
636 HANDLE,
637 ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),
638 ]
639 GetConsoleScreenBufferInfo.restype = BOOL
640
641 ScrollConsoleScreenBuffer = _KERNEL32.ScrollConsoleScreenBufferW
642 ScrollConsoleScreenBuffer.argtypes = [
643 HANDLE,
644 POINTER(SMALL_RECT),
645 POINTER(SMALL_RECT),
646 _COORD,
647 POINTER(CHAR_INFO),
648 ]
649 ScrollConsoleScreenBuffer.restype = BOOL
650
651 GetConsoleMode = _KERNEL32.GetConsoleMode
652 GetConsoleMode.argtypes = [HANDLE, POINTER(DWORD)]
653 GetConsoleMode.restype = BOOL
654
655 SetConsoleMode = _KERNEL32.SetConsoleMode
656 SetConsoleMode.argtypes = [HANDLE, DWORD]
657 SetConsoleMode.restype = BOOL
658
659 ReadConsoleInput = _KERNEL32.ReadConsoleInputW
660 ReadConsoleInput.argtypes = [HANDLE, POINTER(INPUT_RECORD), DWORD, POINTER(DWORD)]
661 ReadConsoleInput.restype = BOOL
662
663 GetNumberOfConsoleInputEvents = _KERNEL32.GetNumberOfConsoleInputEvents
664 GetNumberOfConsoleInputEvents.argtypes = [HANDLE, POINTER(DWORD)]
665 GetNumberOfConsoleInputEvents.restype = BOOL
666
667 FlushConsoleInputBuffer = _KERNEL32.FlushConsoleInputBuffer
668 FlushConsoleInputBuffer.argtypes = [HANDLE]
669 FlushConsoleInputBuffer.restype = BOOL
670
671 OutHandle = GetStdHandle(STD_OUTPUT_HANDLE)
672 InHandle = GetStdHandle(STD_INPUT_HANDLE)
673 else:
674
675 def _win_only(*args, **kwargs):
676 raise NotImplementedError("Windows only")
677
678 GetStdHandle = _win_only
679 GetConsoleScreenBufferInfo = _win_only
680 ScrollConsoleScreenBuffer = _win_only
681 GetConsoleMode = _win_only
682 SetConsoleMode = _win_only
683 ReadConsoleInput = _win_only
684 GetNumberOfConsoleInputEvents = _win_only
685 FlushConsoleInputBuffer = _win_only
686 OutHandle = 0
687 InHandle = 0