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 if wlen(newline) == self.width:
277 # If we wrapped we want to start at the next line
278 self._move_relative(0, y + 1)
279 self.posxy = 0, y + 1
280 else:
281 self.posxy = wlen(newline), y
282
283 if "\x1b" in newline or y != self.posxy[1] or '\x1a' in newline:
284 # ANSI escape characters are present, so we can't assume
285 # anything about the position of the cursor. Moving the cursor
286 # to the left margin should work to get to a known position.
287 self.move_cursor(0, y)
288
289 def _scroll(
290 self, top: int, bottom: int, left: int | None = None, right: int | None = None
291 ) -> None:
292 scroll_rect = SMALL_RECT()
293 scroll_rect.Top = SHORT(top)
294 scroll_rect.Bottom = SHORT(bottom)
295 scroll_rect.Left = SHORT(0 if left is None else left)
296 scroll_rect.Right = SHORT(
297 self.getheightwidth()[1] - 1 if right is None else right
298 )
299 destination_origin = _COORD()
300 fill_info = CHAR_INFO()
301 fill_info.UnicodeChar = " "
302
303 if not ScrollConsoleScreenBuffer(
304 OutHandle, scroll_rect, None, destination_origin, fill_info
305 ):
306 raise WinError(GetLastError())
307
308 def _hide_cursor(self):
309 self.__write("\x1b[?25l")
310
311 def _show_cursor(self):
312 self.__write("\x1b[?25h")
313
314 def _enable_blinking(self):
315 self.__write("\x1b[?12h")
316
317 def _disable_blinking(self):
318 self.__write("\x1b[?12l")
319
320 def _enable_bracketed_paste(self) -> None:
321 self.__write("\x1b[?2004h")
322
323 def _disable_bracketed_paste(self) -> None:
324 self.__write("\x1b[?2004l")
325
326 def __write(self, text: str) -> None:
327 if "\x1a" in text:
328 text = ''.join(["^Z" if x == '\x1a' else x for x in text])
329
330 if self.out is not None:
331 self.out.write(text.encode(self.encoding, "replace"))
332 self.out.flush()
333 else:
334 os.write(self.output_fd, text.encode(self.encoding, "replace"))
335
336 @property
337 def screen_xy(self) -> tuple[int, int]:
338 info = CONSOLE_SCREEN_BUFFER_INFO()
339 if not GetConsoleScreenBufferInfo(OutHandle, info):
340 raise WinError(GetLastError())
341 return info.dwCursorPosition.X, info.dwCursorPosition.Y
342
343 def _erase_to_end(self) -> None:
344 self.__write(ERASE_IN_LINE)
345
346 def prepare(self) -> None:
347 trace("prepare")
348 self.screen = []
349 self.height, self.width = self.getheightwidth()
350
351 self.posxy = 0, 0
352 self.__gone_tall = 0
353 self.__offset = 0
354
355 if self.__vt_support:
356 SetConsoleMode(InHandle, self.__original_input_mode | ENABLE_VIRTUAL_TERMINAL_INPUT)
357 self._enable_bracketed_paste()
358
359 def restore(self) -> None:
360 if self.__vt_support:
361 # Recover to original mode before running REPL
362 self._disable_bracketed_paste()
363 SetConsoleMode(InHandle, self.__original_input_mode)
364
365 def _move_relative(self, x: int, y: int) -> None:
366 """Moves relative to the current posxy"""
367 dx = x - self.posxy[0]
368 dy = y - self.posxy[1]
369 if dx < 0:
370 self.__write(MOVE_LEFT.format(-dx))
371 elif dx > 0:
372 self.__write(MOVE_RIGHT.format(dx))
373
374 if dy < 0:
375 self.__write(MOVE_UP.format(-dy))
376 elif dy > 0:
377 self.__write(MOVE_DOWN.format(dy))
378
379 def move_cursor(self, x: int, y: int) -> None:
380 if x < 0 or y < 0:
381 raise ValueError(f"Bad cursor position {x}, {y}")
382
383 if y < self.__offset or y >= self.__offset + self.height:
384 self.event_queue.insert(Event("scroll", ""))
385 else:
386 self._move_relative(x, y)
387 self.posxy = x, y
388
389 def set_cursor_vis(self, visible: bool) -> None:
390 if visible:
391 self._show_cursor()
392 else:
393 self._hide_cursor()
394
395 def getheightwidth(self) -> tuple[int, int]:
396 """Return (height, width) where height and width are the height
397 and width of the terminal window in characters."""
398 info = CONSOLE_SCREEN_BUFFER_INFO()
399 if not GetConsoleScreenBufferInfo(OutHandle, info):
400 raise WinError(GetLastError())
401 return (
402 info.srWindow.Bottom - info.srWindow.Top + 1,
403 info.srWindow.Right - info.srWindow.Left + 1,
404 )
405
406 def _getscrollbacksize(self) -> int:
407 info = CONSOLE_SCREEN_BUFFER_INFO()
408 if not GetConsoleScreenBufferInfo(OutHandle, info):
409 raise WinError(GetLastError())
410
411 return info.srWindow.Bottom # type: ignore[no-any-return]
412
413 def _read_input(self, block: bool = True) -> INPUT_RECORD | None:
414 if not block:
415 events = DWORD()
416 if not GetNumberOfConsoleInputEvents(InHandle, events):
417 raise WinError(GetLastError())
418 if not events.value:
419 return None
420
421 rec = INPUT_RECORD()
422 read = DWORD()
423 if not ReadConsoleInput(InHandle, rec, 1, read):
424 raise WinError(GetLastError())
425
426 return rec
427
428 def get_event(self, block: bool = True) -> Event | None:
429 """Return an Event instance. Returns None if |block| is false
430 and there is no event pending, otherwise waits for the
431 completion of an event."""
432
433 while self.event_queue.empty():
434 rec = self._read_input(block)
435 if rec is None:
436 return None
437
438 if rec.EventType == WINDOW_BUFFER_SIZE_EVENT:
439 return Event("resize", "")
440
441 if rec.EventType != KEY_EVENT or not rec.Event.KeyEvent.bKeyDown:
442 # Only process keys and keydown events
443 if block:
444 continue
445 return None
446
447 key_event = rec.Event.KeyEvent
448 raw_key = key = key_event.uChar.UnicodeChar
449
450 if key == "\r":
451 # Make enter unix-like
452 return Event(evt="key", data="\n")
453 elif key_event.wVirtualKeyCode == 8:
454 # Turn backspace directly into the command
455 key = "backspace"
456 elif key == "\x00":
457 # Handle special keys like arrow keys and translate them into the appropriate command
458 key = VK_MAP.get(key_event.wVirtualKeyCode)
459 if key:
460 if key_event.dwControlKeyState & CTRL_ACTIVE:
461 key = f"ctrl {key}"
462 elif key_event.dwControlKeyState & ALT_ACTIVE:
463 # queue the key, return the meta command
464 self.event_queue.insert(Event(evt="key", data=key))
465 return Event(evt="key", data="\033") # keymap.py uses this for meta
466 return Event(evt="key", data=key)
467 if block:
468 continue
469
470 return None
471 elif self.__vt_support:
472 # If virtual terminal is enabled, scanning VT sequences
473 for char in raw_key.encode(self.event_queue.encoding, "replace"):
474 self.event_queue.push(char)
475 continue
476
477 if key_event.dwControlKeyState & ALT_ACTIVE:
478 # Do not swallow characters that have been entered via AltGr:
479 # Windows internally converts AltGr to CTRL+ALT, see
480 # https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-vkkeyscanw
481 if not key_event.dwControlKeyState & CTRL_ACTIVE:
482 # queue the key, return the meta command
483 self.event_queue.insert(Event(evt="key", data=key))
484 return Event(evt="key", data="\033") # keymap.py uses this for meta
485
486 return Event(evt="key", data=key)
487 return self.event_queue.get()
488
489 def push_char(self, char: int | bytes) -> None:
490 """
491 Push a character to the console event queue.
492 """
493 raise NotImplementedError("push_char not supported on Windows")
494
495 def beep(self) -> None:
496 self.__write("\x07")
497
498 def clear(self) -> None:
499 """Wipe the screen"""
500 self.__write(CLEAR)
501 self.posxy = 0, 0
502 self.screen = []
503
504 def finish(self) -> None:
505 """Move the cursor to the end of the display and otherwise get
506 ready for end. XXX could be merged with restore? Hmm."""
507 y = len(self.screen) - 1
508 while y >= 0 and not self.screen[y]:
509 y -= 1
510 self._move_relative(0, min(y, self.height + self.__offset - 1))
511 self.__write("\r\n")
512
513 def flushoutput(self) -> None:
514 """Flush all output to the screen (assuming there's some
515 buffering going on somewhere).
516
517 All output on Windows is unbuffered so this is a nop"""
518 pass
519
520 def forgetinput(self) -> None:
521 """Forget all pending, but not yet processed input."""
522 if not FlushConsoleInputBuffer(InHandle):
523 raise WinError(GetLastError())
524
525 def getpending(self) -> Event:
526 """Return the characters that have been typed but not yet
527 processed."""
528 return Event("key", "", b"")
529
530 def wait_for_event(self, timeout: float | None) -> bool:
531 """Wait for an event."""
532 # Poor man's Windows select loop
533 start_time = time.time()
534 while True:
535 if msvcrt.kbhit(): # type: ignore[attr-defined]
536 return True
537 if timeout and time.time() - start_time > timeout / 1000:
538 return False
539 time.sleep(0.01)
540
541 def wait(self, timeout: float | None) -> bool:
542 """
543 Wait for events on the console.
544 """
545 return (
546 not self.event_queue.empty()
547 or self.wait_for_event(timeout)
548 )
549
550 def repaint(self) -> None:
551 raise NotImplementedError("No repaint support")
552
553
554 # Windows interop
555 class CONSOLE_SCREEN_BUFFER_INFO(Structure):
556 _fields_ = [
557 ("dwSize", _COORD),
558 ("dwCursorPosition", _COORD),
559 ("wAttributes", WORD),
560 ("srWindow", SMALL_RECT),
561 ("dwMaximumWindowSize", _COORD),
562 ]
563
564
565 class CONSOLE_CURSOR_INFO(Structure):
566 _fields_ = [
567 ("dwSize", DWORD),
568 ("bVisible", BOOL),
569 ]
570
571
572 class CHAR_INFO(Structure):
573 _fields_ = [
574 ("UnicodeChar", WCHAR),
575 ("Attributes", WORD),
576 ]
577
578
579 class Char(Union):
580 _fields_ = [
581 ("UnicodeChar", WCHAR),
582 ("Char", CHAR),
583 ]
584
585
586 class KeyEvent(ctypes.Structure):
587 _fields_ = [
588 ("bKeyDown", BOOL),
589 ("wRepeatCount", WORD),
590 ("wVirtualKeyCode", WORD),
591 ("wVirtualScanCode", WORD),
592 ("uChar", Char),
593 ("dwControlKeyState", DWORD),
594 ]
595
596
597 class WindowsBufferSizeEvent(ctypes.Structure):
598 _fields_ = [("dwSize", _COORD)]
599
600
601 class ConsoleEvent(ctypes.Union):
602 _fields_ = [
603 ("KeyEvent", KeyEvent),
604 ("WindowsBufferSizeEvent", WindowsBufferSizeEvent),
605 ]
606
607
608 class INPUT_RECORD(Structure):
609 _fields_ = [("EventType", WORD), ("Event", ConsoleEvent)]
610
611
612 KEY_EVENT = 0x01
613 FOCUS_EVENT = 0x10
614 MENU_EVENT = 0x08
615 MOUSE_EVENT = 0x02
616 WINDOW_BUFFER_SIZE_EVENT = 0x04
617
618 ENABLE_PROCESSED_INPUT = 0x0001
619 ENABLE_LINE_INPUT = 0x0002
620 ENABLE_ECHO_INPUT = 0x0004
621 ENABLE_MOUSE_INPUT = 0x0010
622 ENABLE_INSERT_MODE = 0x0020
623 ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200
624
625 ENABLE_PROCESSED_OUTPUT = 0x01
626 ENABLE_WRAP_AT_EOL_OUTPUT = 0x02
627 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x04
628
629 STD_INPUT_HANDLE = -10
630 STD_OUTPUT_HANDLE = -11
631
632 if sys.platform == "win32":
633 _KERNEL32 = WinDLL("kernel32", use_last_error=True)
634
635 GetStdHandle = windll.kernel32.GetStdHandle
636 GetStdHandle.argtypes = [DWORD]
637 GetStdHandle.restype = HANDLE
638
639 GetConsoleScreenBufferInfo = _KERNEL32.GetConsoleScreenBufferInfo
640 GetConsoleScreenBufferInfo.argtypes = [
641 HANDLE,
642 ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),
643 ]
644 GetConsoleScreenBufferInfo.restype = BOOL
645
646 ScrollConsoleScreenBuffer = _KERNEL32.ScrollConsoleScreenBufferW
647 ScrollConsoleScreenBuffer.argtypes = [
648 HANDLE,
649 POINTER(SMALL_RECT),
650 POINTER(SMALL_RECT),
651 _COORD,
652 POINTER(CHAR_INFO),
653 ]
654 ScrollConsoleScreenBuffer.restype = BOOL
655
656 GetConsoleMode = _KERNEL32.GetConsoleMode
657 GetConsoleMode.argtypes = [HANDLE, POINTER(DWORD)]
658 GetConsoleMode.restype = BOOL
659
660 SetConsoleMode = _KERNEL32.SetConsoleMode
661 SetConsoleMode.argtypes = [HANDLE, DWORD]
662 SetConsoleMode.restype = BOOL
663
664 ReadConsoleInput = _KERNEL32.ReadConsoleInputW
665 ReadConsoleInput.argtypes = [HANDLE, POINTER(INPUT_RECORD), DWORD, POINTER(DWORD)]
666 ReadConsoleInput.restype = BOOL
667
668 GetNumberOfConsoleInputEvents = _KERNEL32.GetNumberOfConsoleInputEvents
669 GetNumberOfConsoleInputEvents.argtypes = [HANDLE, POINTER(DWORD)]
670 GetNumberOfConsoleInputEvents.restype = BOOL
671
672 FlushConsoleInputBuffer = _KERNEL32.FlushConsoleInputBuffer
673 FlushConsoleInputBuffer.argtypes = [HANDLE]
674 FlushConsoleInputBuffer.restype = BOOL
675
676 OutHandle = GetStdHandle(STD_OUTPUT_HANDLE)
677 InHandle = GetStdHandle(STD_INPUT_HANDLE)
678 else:
679
680 def _win_only(*args, **kwargs):
681 raise NotImplementedError("Windows only")
682
683 GetStdHandle = _win_only
684 GetConsoleScreenBufferInfo = _win_only
685 ScrollConsoleScreenBuffer = _win_only
686 GetConsoleMode = _win_only
687 SetConsoleMode = _win_only
688 ReadConsoleInput = _win_only
689 GetNumberOfConsoleInputEvents = _win_only
690 FlushConsoleInputBuffer = _win_only
691 OutHandle = 0
692 InHandle = 0