Source code for TermTk.TTkCore.drivers.windows

# MIT License
#
# Copyright (c) 2023 Eugenio Parodi <ceccopierangiolieugenio AT googlemail DOT com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

__all__ = ['TTkSignalDriver','TTkInputDriver']

import signal

from ctypes import Structure, Union, byref, wintypes, windll

from TermTk.TTkCore.signal import pyTTkSignal, pyTTkSlot

from TermTk.TTkCore.log import TTkLog

# Based on the example ported from:
#   https://learn.microsoft.com/en-us/windows/console/reading-input-buffer-events
# https://github.com/ceccopierangiolieugenio/pyTermTk -> tests/test.input.win.01.py

# https://learn.microsoft.com/en-us/windows/console/getstdhandle
STD_INPUT_HANDLE  = wintypes.DWORD(-10) # The standard input device. Initially, this is the console input buffer, CONIN$.
STD_OUTPUT_HANDLE = wintypes.DWORD(-11) # The standard output device. Initially, this is the active console screen buffer, CONOUT$.
STD_ERROR_HANDLE  = wintypes.DWORD(-12) # The standard error device. Initially, this is the active console screen buffer, CONOUT$.

INVALID_HANDLE_VALUE = -1 # WinBase.h

# https://learn.microsoft.com/en-us/windows/console/SetConsoleMode
ENABLE_ECHO_INPUT             = 0x0004 # Characters read by the ReadFile or ReadConsole function are written to the active screen buffer as they are typed into the console. This mode can be used only if the ENABLE_LINE_INPUT mode is also enabled.
ENABLE_INSERT_MODE            = 0x0020 # When enabled, text entered in a console window will be inserted at the current cursor location and all text following that location will not be overwritten. When disabled, all following text will be overwritten.
ENABLE_LINE_INPUT             = 0x0002 # The ReadFile or ReadConsole function returns only when a carriage return character is read. If this mode is disabled, the functions return when one or more characters are available.
ENABLE_MOUSE_INPUT            = 0x0010 # If the mouse pointer is within the borders of the console window and the window has the keyboard focus, mouse events generated by mouse movement and button presses are placed in the input buffer. These events are discarded by ReadFile or ReadConsole, even when this mode is enabled. The ReadConsoleInput function can be used to read MOUSE_EVENT input records from the input buffer.
ENABLE_PROCESSED_INPUT        = 0x0001 # CTRL+C is processed by the system and is not placed in the input buffer. If the input buffer is being read by ReadFile or ReadConsole, other control keys are processed by the system and are not returned in the ReadFile or ReadConsole buffer. If the ENABLE_LINE_INPUT mode is also enabled, backspace, carriage return, and line feed characters are handled by the system.
ENABLE_QUICK_EDIT_MODE        = 0x0040 # This flag enables the user to use the mouse to select and edit text. To enable this mode, use ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS. To disable this mode, use ENABLE_EXTENDED_FLAGS without this flag.
ENABLE_WINDOW_INPUT           = 0x0008 # User interactions that change the size of the console screen buffer are reported in the console's input buffer. Information about these events can be read from the input buffer by applications using the ReadConsoleInput function, but not by those using ReadFile or ReadConsole.
ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 # Setting this flag directs the Virtual Terminal processing engine to convert user input received by the console window into Console Virtual Terminal Sequences that can be retrieved by a supporting application through ReadFile or ReadConsole functions.

ENABLE_PROCESSED_OUTPUT            = 0x0001
ENABLE_WRAP_AT_EOL_OUTPUT          = 0x0002
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
DISABLE_NEWLINE_AUTO_RETURN        = 0x0008
ENABLE_LVB_GRID_WORLDWIDE          = 0x0010

# https://learn.microsoft.com/en-us/windows/console/input-record-str
FOCUS_EVENT              = 0x0010 # The Event member contains a FOCUS_EVENT_RECORD structure. These events are used internally and should be ignored.
KEY_EVENT                = 0x0001 # The Event member contains a KEY_EVENT_RECORD structure with information about a keyboard event.
MENU_EVENT               = 0x0008 # The Event member contains a MENU_EVENT_RECORD structure. These events are used internally and should be ignored.
MOUSE_EVENT              = 0x0002 # The Event member contains a MOUSE_EVENT_RECORD structure with information about a mouse movement or button press event.
WINDOW_BUFFER_SIZE_EVENT = 0x0004 # The Event member contains a WINDOW_BUFFER_SIZE_RECORD structure with information about the new size of the console screen buffer.

# https://learn.microsoft.com/en-us/windows/console/mouse-event-record-str
# dwButtonState
FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001 # The leftmost mouse button.
FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004 # The second button fom the left.
FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008 # The third button from the left.
FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010 # The fourth button from the left.
RIGHTMOST_BUTTON_PRESSED     = 0x0002 # The rightmost mouse button.
# dwControlKeyState
CAPSLOCK_ON        = 0x0080 # The CAPS LOCK light is on.
ENHANCED_KEY       = 0x0100 # The key is enhanced. See remarks.
LEFT_ALT_PRESSED   = 0x0002 # The left ALT key is pressed.
LEFT_CTRL_PRESSED  = 0x0008 # The left CTRL key is pressed.
NUMLOCK_ON         = 0x0020 # The NUM LOCK light is on.
RIGHT_ALT_PRESSED  = 0x0001 # The right ALT key is pressed.
RIGHT_CTRL_PRESSED = 0x0004 # The right CTRL key is pressed.
SCROLLLOCK_ON      = 0x0040 # The SCROLL LOCK light is on.
SHIFT_PRESSED      = 0x0010 # The SHIFT key is pressed.
# dwEventFlags
DOUBLE_CLICK   = 0x0002 # The second click (button press) of a double-click occurred. The first click is returned as a regular button-press event.
MOUSE_HWHEELED = 0x0008 # The horizontal mouse wheel was moved.
                        # If the high word of the dwButtonState member contains a positive value, the wheel was rotated to the right. Otherwise, the wheel was rotated to the left.
MOUSE_MOVED    = 0x0001 # A change in mouse position occurred.
MOUSE_WHEELED  = 0x0004 # The vertical mouse wheel was moved.
                        # If the high word of the dwButtonState member contains a positive value, the wheel was rotated forward, away from the user. Otherwise, the wheel was rotated backward, toward the user.

# https://docs.microsoft.com/en-us/windows/console/coord-str
#
# typedef struct _COORD {
#   SHORT X;
#   SHORT Y;
# } COORD, *PCOORD;
[docs]class COORD(Structure): _fields_ = [ ("X", wintypes.SHORT), ("Y", wintypes.SHORT)]
# https://docs.microsoft.com/en-us/windows/console/key-event-record-str # # typedef struct _KEY_EVENT_RECORD { # BOOL bKeyDown; # WORD wRepeatCount; # WORD wVirtualKeyCode; # WORD wVirtualScanCode; # union { # WCHAR UnicodeChar; # CHAR AsciiChar; # } uChar; # DWORD dwControlKeyState; # } KEY_EVENT_RECORD;
[docs]class KEY_EVENT_RECORD(Structure): class _uChar(Union): _fields_ = [ ("UnicodeChar", wintypes.WCHAR) , ("AsciiChar" , wintypes.CHAR ) ] _fields_ = [ ("bKeyDown" , wintypes.BOOL ), ("wRepeatCount" , wintypes.WORD ), ("wVirtualKeyCode" , wintypes.WORD ), ("wVirtualScanCode" , wintypes.WORD ), ("uChar" , _uChar ), ("dwControlKeyState", wintypes.DWORD)]
# https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str # # typedef struct _MOUSE_EVENT_RECORD { # COORD dwMousePosition; # DWORD dwButtonState; # DWORD dwControlKeyState; # DWORD dwEventFlags; # } MOUSE_EVENT_RECORD;
[docs]class MOUSE_EVENT_RECORD(Structure): _fields_ = [ ("dwMousePosition" , COORD), ("dwButtonState" , wintypes.DWORD), ("dwControlKeyState", wintypes.DWORD), ("dwEventFlags" , wintypes.DWORD)]
# https://docs.microsoft.com/en-us/windows/console/window-buffer-size-record-str # # typedef struct _WINDOW_BUFFER_SIZE_RECORD { # COORD dwSize; # } WINDOW_BUFFER_SIZE_RECORD;
[docs]class WINDOW_BUFFER_SIZE_RECORD(Structure): _fields_ = [("dwSize", COORD)]
# https://docs.microsoft.com/en-us/windows/console/menu-event-record-str # # typedef struct _MENU_EVENT_RECORD { # UINT dwCommandId; # } MENU_EVENT_RECORD, *PMENU_EVENT_RECORD; # https://docs.microsoft.com/en-us/windows/console/focus-event-record-str # # typedef struct _FOCUS_EVENT_RECORD { # BOOL bSetFocus; # } FOCUS_EVENT_RECORD;
[docs]class FOCUS_EVENT_RECORD(Structure): _fields_ = [("bSetFocus", wintypes.BOOL)]
# https://docs.microsoft.com/en-us/windows/console/input-record-str # # typedef struct _INPUT_RECORD { # WORD EventType; # union { # KEY_EVENT_RECORD KeyEvent; # MOUSE_EVENT_RECORD MouseEvent; # WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent; # MENU_EVENT_RECORD MenuEvent; # FOCUS_EVENT_RECORD FocusEvent; # } Event; # } INPUT_RECORD;
[docs]class INPUT_RECORD(Structure): class _Event(Union): _fields_ = [ ("KeyEvent" , KEY_EVENT_RECORD ), ("MouseEvent" , MOUSE_EVENT_RECORD ), ("WindowBufferSizeEvent", WINDOW_BUFFER_SIZE_RECORD), ("MenuEvent" , MENU_EVENT_RECORD ), ("FocusEvent" , FOCUS_EVENT_RECORD )] _fields_ = [ ("EventType", wintypes.WORD), ("Event" , _Event )]
class TTkInputDriver(): windowResized = pyTTkSignal(int,int) def __init__(self): self._run = True self._initTerminal() def _initTerminal(self): # Get the standard input handle. # From: # https://learn.microsoft.com/en-us/windows/console/getstdhandle # # HANDLE WINAPI GetStdHandle( # _In_ DWORD nStdHandle # ); GetStdHandle = windll.kernel32.GetStdHandle GetStdHandle.argtypes = [wintypes.DWORD] GetStdHandle.restype = wintypes.HANDLE self._hStdIn = GetStdHandle(STD_INPUT_HANDLE) if self._hStdIn == INVALID_HANDLE_VALUE: raise Exception("GetStdHandle") self._hStdOut = GetStdHandle(STD_OUTPUT_HANDLE) if self._hStdOut == INVALID_HANDLE_VALUE: raise Exception("GetStdHandle") # Save the current input mode, to be restored on exit. # From: # https://learn.microsoft.com/en-us/windows/console/GetConsoleMode # # BOOL WINAPI GetConsoleMode( # _In_ HANDLE hConsoleHandle, # _Out_ LPDWORD lpMode # ); self._GetConsoleMode = windll.kernel32.GetConsoleMode self._GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD] self._GetConsoleMode.restype = wintypes.BOOL self._fdwSaveOldModeIn = wintypes.DWORD() if not self._GetConsoleMode(self._hStdIn, byref(self._fdwSaveOldModeIn)): raise Exception("GetConsoleMode") self._fdwSaveOldModeOut = wintypes.DWORD() if not self._GetConsoleMode(self._hStdOut, byref(self._fdwSaveOldModeOut)): raise Exception("GetConsoleMode") # TTkLog.debug(f"{fdwSaveOldModeIn.value=:02x}") # TTkLog.debug(f"{fdwSaveOldModeOut.value=:02x}") # Enable the window and mouse input events. # From: # https://learn.microsoft.com/en-us/windows/console/SetConsoleMode # # BOOL WINAPI SetConsoleMode( # _In_ HANDLE hConsoleHandle, # _In_ DWORD dwMode # ); self._SetConsoleMode = windll.kernel32.SetConsoleMode self._SetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.DWORD] self._SetConsoleMode.restype = wintypes.BOOL fdwModeIn = ENABLE_VIRTUAL_TERMINAL_INPUT # fdwModeIn = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT # fdwModeIn = 0x0218 if not self._SetConsoleMode(self._hStdIn, fdwModeIn): raise Exception("SetConsoleMode") fdwModeOut = self._fdwSaveOldModeOut.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING # fdwModeIn = 0x0218 if not self._SetConsoleMode(self._hStdOut, fdwModeOut): raise Exception("SetConsoleMode") # TTkLog.debug(f"{fdwModeIn=:02x}") # TTkLog.debug(f"{fdwModeOut=:02x}") def close(self): self._run = False # Restore input mode on exit. if not self._SetConsoleMode(self._hStdIn, self._fdwSaveOldModeIn): raise Exception("SetConsoleMode") if not self._SetConsoleMode(self._hStdOut, self._fdwSaveOldModeOut): raise Exception("SetConsoleMode") def cont(self): pass def read(self) -> str|None: # From: # https://learn.microsoft.com/en-us/windows/console/ReadConsoleInput # # BOOL WINAPI ReadConsoleInput( # _In_ HANDLE hConsoleInput, # _Out_ PINPUT_RECORD lpBuffer, # _In_ DWORD nLength, # _Out_ LPDWORD lpNumberOfEventsRead # ); ReadConsoleInput = windll.kernel32.ReadConsoleInputW # Unicode # ReadConsoleInput = windll.kernel32.ReadConsoleInputA # ANSII # ReadConsoleInput.argtypes = [wintypes.HANDLE, # wintypes.LPINT, # wintypes.DWORD, # wintypes.LPWORD] ReadConsoleInput.restype = wintypes.BOOL # DWORD cNumRead; # INPUT_RECORD irInBuf[128]; cNumRead = wintypes.DWORD(0) irInBuf = (INPUT_RECORD * 256)() # Loop to read and handle the next 100 input events. while self._run: # Wait for the events. if not ReadConsoleInput( self._hStdIn, # input buffer handle byref(irInBuf), # buffer to read into 256, # size of read buffer byref(cNumRead)): # number of records read raise Exception("ReadConsoleInput") # TTkLog.debug(f"{self._hStdIn=} {irInBuf=} {cNumRead=}") # TTkLog.debug(f"{cNumRead=}") # Dispatch the events to the appropriate handler. saveKeys = [] for bb in irInBuf[:cNumRead.value]: # if not bb.EventType: continue # TTkLog.debug(f"{bb=} {bb.EventType=} {cNumRead.value=}") if bb.EventType == KEY_EVENT: ke = bb.Event.KeyEvent if ( not ke.bKeyDown or ke.dwControlKeyState or ke.wVirtualKeyCode ): continue saveKeys.append(ke.uChar.UnicodeChar) elif bb.EventType == MOUSE_EVENT: # It is not supposed to receive Mouse Events # due to ENABLE_VIRTUAL_TERMINAL_PROCESSING # everything is received as ANSI sequence pass elif bb.EventType == WINDOW_BUFFER_SIZE_EVENT: # TTkLog.debug(f"{bb.Event.WindowBufferSizeEvent=}") # TTkLog.debug(f"{bb.Event.WindowBufferSizeEvent.dwSize.X=}") # TTkLog.debug(f"{bb.Event.WindowBufferSizeEvent.dwSize.Y=}") TTkInputDriver.windowResized.emit(bb.Event.WindowBufferSizeEvent.dwSize.X, bb.Event.WindowBufferSizeEvent.dwSize.Y) if saveKeys: yield "".join(saveKeys).encode("utf-16", "surrogatepass").decode("utf-16") class TTkSignalDriver(): sigStop = pyTTkSignal() sigCont = pyTTkSignal() sigInt = pyTTkSignal() @staticmethod def init(): # Register events # signal.signal(signal.SIGTSTP, TTkSignalDriver._SIGSTOP) # Ctrl-Z # signal.signal(signal.SIGCONT, TTkSignalDriver._SIGCONT) # Resume signal.signal(signal.SIGINT, TTkSignalDriver._SIGINT) # Ctrl-C def exit(): signal.signal(signal.SIGINT, signal.SIG_DFL) def _SIGSTOP(signum, frame): TTkSignalDriver.sigStop.emit() def _SIGCONT(signum, frame): TTkSignalDriver.sigCont.emit() def _SIGINT( signum, frame): TTkSignalDriver.sigInt.emit()