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