diff --git a/server/keyboard_controller.py b/server/keyboard_controller.py index 53d7f50..f8e6c8e 100644 --- a/server/keyboard_controller.py +++ b/server/keyboard_controller.py @@ -1,12 +1,18 @@ import asyncio +import ctypes +import itertools import sys +import threading import time -from typing import Optional +from typing import Dict, Optional, Tuple try: - from pynput.keyboard import Controller, Key + from pynput.keyboard import Controller, Key, KeyCode _controller = Controller() except Exception as e: + Controller = None + Key = None + KeyCode = None _controller = None print(f"Avviso: Impossibile inizializzare il controller pynput: {e}") @@ -17,6 +23,287 @@ except ImportError: _lock = asyncio.Lock() +# Cache globale per evitare ritardi ad ogni carattere mantenendo reattivita' a cambi layout. +_LINUX_MAPPING_TTL_SEC = 5.0 + + +class _LinuxXTestBackend: + """ + Invia caratteri tramite estensione XTEST di X11 su Linux. + + pynput._xorg usa XTEST solo per i tasti con virtual key (es. Key.enter) e + ripiega su XSendEvent per i caratteri testuali: sotto Wayland/XWayland e in + molte app moderne (Chrome, Electron, Firefox, Terminali) XSendEvent viene + ignorato, causando l'invio del solo tasto Invio. + """ + + def __init__(self, pynput_controller): + import Xlib.X + import Xlib.XK + import Xlib.display + import Xlib.ext.xtest + import Xlib.keysymdef.xkb + + self._X = Xlib.X + self._XK = Xlib.XK + self._xkb = Xlib.keysymdef.xkb + self._xtest = Xlib.ext.xtest + self._display_cls = Xlib.display.Display + + self._XK.load_keysym_group("xkb") + self._pynput_controller = pynput_controller + self._display = self._display_cls() + ext = self._display.query_extension("XTEST") + if not ext or not ext.present: + self._display.close() + raise RuntimeError("Estensione X11 XTEST non disponibile") + + self._lock = threading.Lock() + self._mapping: Dict[int, Tuple[int, Tuple[int, ...]]] = {} + self._shift_kc = 0 + self._ctrl_kc = 0 + self._altgr_kc = 0 + self._last_refresh = 0.0 + self.refresh_mapping(force=True) + + def _first_nonzero_mod_kc(self, modmap, slot_index: int, fallback_keysym_name: str) -> int: + if len(modmap) > slot_index: + for kc in modmap[slot_index]: + if kc: + return int(kc) + ks = self._resolve_named_keysym(fallback_keysym_name) + return int(self._display.keysym_to_keycode(ks)) if ks else 0 + + def _resolve_named_keysym(self, name: str) -> int: + return int( + self._XK.string_to_keysym(name) + or getattr(self._xkb, f"XK_{name}", 0) + or 0 + ) + + def _normalize_key_entries(self, syms) -> list[Tuple[int, Tuple[int, ...]]]: + stripped = list(reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(syms))))) + if not stripped: + return [] + + ks0 = stripped[0] + ks1 = stripped[1] if len(stripped) > 1 else 0 + if ks1 == 0: + if self._XK.XK_a <= ks0 <= self._XK.XK_z: + ks1 = self._XK.XK_A + (ks0 - self._XK.XK_a) + elif self._XK.XK_A <= ks0 <= self._XK.XK_Z: + ks0, ks1 = self._XK.XK_a + (ks0 - self._XK.XK_A), ks0 + else: + ks1 = ks0 + + entries: list[Tuple[int, Tuple[int, ...]]] = [(ks0, ())] + if self._shift_kc: + entries.append((ks1, (self._shift_kc,))) + + if len(stripped) >= 5: + g2 = (stripped[4], stripped[5] if len(stripped) > 5 else 0) + elif len(stripped) >= 3: + g2 = (stripped[2], stripped[3] if len(stripped) > 3 else 0) + else: + g2 = () + + if g2 and self._altgr_kc: + if g2[0]: + entries.append((g2[0], (self._altgr_kc,))) + if len(g2) > 1 and g2[1] and self._shift_kc: + entries.append((g2[1], (self._shift_kc, self._altgr_kc))) + return entries + + def refresh_mapping(self, force: bool = False) -> None: + now = time.monotonic() + if not force and (now - self._last_refresh) < _LINUX_MAPPING_TTL_SEC: + return + + with self._lock: + modmap = self._display.get_modifier_mapping() + self._shift_kc = self._first_nonzero_mod_kc(modmap, 0, "Shift_L") + self._ctrl_kc = self._first_nonzero_mod_kc(modmap, 2, "Control_L") + + self._altgr_kc = 0 + for altgr_name in ("ISO_Level3_Shift", "Mode_switch"): + ks = self._resolve_named_keysym(altgr_name) + if ks: + kc = int(self._display.keysym_to_keycode(ks)) + if kc: + self._altgr_kc = kc + break + + min_kc = self._display.display.info.min_keycode + max_kc = self._display.display.info.max_keycode + raw = self._display.get_keyboard_mapping(min_kc, max_kc - min_kc + 1) + + best: Dict[int, Tuple[Tuple[int, int, int], int, Tuple[int, ...]]] = {} + for offset, syms in enumerate(raw): + kc = min_kc + offset + for ks, mods in self._normalize_key_entries(syms): + if not ks: + continue + # Preferisci i tasti standard (kc < 130) rispetto a tasti estesi e con meno modificatori. + score = (1 if kc >= 130 else 0, len(mods), kc) + prev = best.get(ks) + if prev is None or score < prev[0]: + best[ks] = (score, kc, mods) + + self._mapping = {ks: (kc, mods) for ks, (_, kc, mods) in best.items()} + self._last_refresh = now + + def _char_to_keysym(self, char: str) -> Optional[int]: + if self._pynput_controller is not None and KeyCode is not None: + key_to_keysym = getattr(self._pynput_controller, "_key_to_keysym", None) + if callable(key_to_keysym): + ks = key_to_keysym(KeyCode.from_char(char)) + if ks: + return int(ks) + ordinal = ord(char) + return ordinal if ordinal < 0x100 else (ordinal | 0x01000000) + + def _send_keycode(self, keycode: int, modifiers: Tuple[int, ...] = ()) -> None: + with self._lock: + for mod_kc in modifiers: + self._xtest.fake_input(self._display, self._X.KeyPress, mod_kc) + if modifiers: + self._display.sync() + time.sleep(0.001) + + self._xtest.fake_input(self._display, self._X.KeyPress, keycode) + self._display.sync() + self._xtest.fake_input(self._display, self._X.KeyRelease, keycode) + self._display.sync() + + if modifiers: + time.sleep(0.001) + for mod_kc in reversed(modifiers): + self._xtest.fake_input(self._display, self._X.KeyRelease, mod_kc) + self._display.sync() + + def type_char(self, char: str) -> bool: + keysym = self._char_to_keysym(char) + if not keysym: + return False + + target = self._mapping.get(keysym) + if target is None: + ordinal = ord(char) + target = self._mapping.get(ordinal) or self._mapping.get(ordinal | 0x01000000) + if target is None: + return False + + keycode, mods = target + self._send_keycode(keycode, mods) + return True + + def tap_named(self, keysym_name: str, with_ctrl: bool = False) -> bool: + ks = self._resolve_named_keysym(keysym_name) + if not ks: + return False + kc = int(self._display.keysym_to_keycode(ks)) + if not kc: + mapped = self._mapping.get(ks) + if not mapped: + return False + kc, extra_mods = mapped + else: + extra_mods = () + + mods = ((self._ctrl_kc,) if (with_ctrl and self._ctrl_kc) else ()) + extra_mods + if with_ctrl and not self._ctrl_kc: + return False + self._send_keycode(kc, mods) + return True + + +class _Win32KeyboardHelper: + """ + Su Windows traduce i caratteri usando il layout della finestra attiva tramite + VkKeyScanExW per inviare veri virtual key (inclusi Shift/AltGr), evitando + KEYEVENTF_UNICODE che alcuni gestionali/terminali/RDP ignorano. + """ + + def __init__(self): + from ctypes import wintypes + + self._user32 = ctypes.windll.user32 + self._GetForegroundWindow = self._user32.GetForegroundWindow + self._GetForegroundWindow.restype = wintypes.HWND + + self._GetWindowThreadProcessId = self._user32.GetWindowThreadProcessId + self._GetWindowThreadProcessId.argtypes = (wintypes.HWND, ctypes.c_void_p) + self._GetWindowThreadProcessId.restype = wintypes.DWORD + + self._GetKeyboardLayout = self._user32.GetKeyboardLayout + self._GetKeyboardLayout.argtypes = (wintypes.DWORD,) + self._GetKeyboardLayout.restype = wintypes.HKL + + self._VkKeyScanExW = self._user32.VkKeyScanExW + self._VkKeyScanExW.argtypes = (wintypes.WCHAR, wintypes.HKL) + self._VkKeyScanExW.restype = ctypes.c_short + + self._VkKeyScanW = self._user32.VkKeyScanW + self._VkKeyScanW.argtypes = (wintypes.WCHAR,) + self._VkKeyScanW.restype = ctypes.c_short + + def _active_layout(self): + hwnd = self._GetForegroundWindow() + tid = self._GetWindowThreadProcessId(hwnd, None) if hwnd else 0 + return self._GetKeyboardLayout(tid) or self._GetKeyboardLayout(0) + + def type_char(self, controller, char: str) -> bool: + if Key is None or KeyCode is None or len(char) != 1 or ord(char) > 0xFFFF: + return False + + try: + hkl = self._active_layout() + res = self._VkKeyScanExW(char, hkl) if hkl else self._VkKeyScanW(char) + except Exception: + return False + + if res == -1: + return False + + vk = res & 0xFF + shift_state = (res >> 8) & 0xFF + if vk <= 0 or vk >= 0xFF or (shift_state & ~0x07) != 0: + return False + + mods = [] + if shift_state & 0x02: + mods.append(Key.ctrl) + if shift_state & 0x04: + mods.append(Key.alt) + if shift_state & 0x01: + mods.append(Key.shift) + + vk_key = KeyCode.from_vk(vk) + if mods: + with controller.pressed(*mods): + controller.tap(vk_key) + else: + controller.tap(vk_key) + return True + + +def _init_platform_helpers(controller): + linux_xtest = None + win32_helper = None + + if sys.platform.startswith("linux") and controller is not None: + try: + linux_xtest = _LinuxXTestBackend(controller) + except Exception as e: + print(f"Avviso: backend XTEST non disponibile su Linux ({e}), uso pynput standard.") + elif sys.platform == "win32" and controller is not None: + try: + win32_helper = _Win32KeyboardHelper() + except Exception as e: + print(f"Avviso: helper VkKeyScanExW non disponibile su Windows ({e}), uso pynput standard.") + + return linux_xtest, win32_helper + class KeyboardSimulator: def __init__(self, default_suffix: str = "enter", typing_delay: float = 0.005, mode: str = "type", prefix: str = ""): @@ -26,11 +313,13 @@ class KeyboardSimulator: self.prefix = prefix self.controller = _controller self.is_mac = sys.platform == "darwin" + self.is_windows = sys.platform == "win32" + self._linux_xtest, self._win32_helper = _init_platform_helpers(self.controller) async def type_text(self, text: str, suffix: Optional[str] = None, mode: Optional[str] = None, prefix: Optional[str] = None) -> bool: """ Scrive il testo simulando la tastiera. - Supporta modalità 'type' (digitazione carattere per carattere) e 'paste' (appunti + Ctrl+V / Cmd+V). + Supporta modalita' 'type' (digitazione carattere per carattere) e 'paste' (appunti + Ctrl+V / Cmd+V). """ async with _lock: active_prefix = prefix if prefix is not None else self.prefix @@ -42,41 +331,87 @@ class KeyboardSimulator: loop = asyncio.get_running_loop() return await loop.run_in_executor(None, self._sync_type, full_text, active_suffix, active_mode) + def _tap_special(self, x11_name: str, pynput_key) -> None: + if self._linux_xtest is not None: + if self._linux_xtest.tap_named(x11_name): + return + self.controller.tap(pynput_key) + + def _type_single_char(self, char: str) -> None: + if self._linux_xtest is not None: + if self._linux_xtest.type_char(char): + return + if self._win32_helper is not None: + if self._win32_helper.type_char(self.controller, char): + return + self.controller.type(char) + + def _type_chars_sequence(self, full_text: str) -> None: + prev_was_cr = False + for char in full_text: + if char == "\r": + self._tap_special("Return", Key.enter) + prev_was_cr = True + elif char == "\n": + if not prev_was_cr: + self._tap_special("Return", Key.enter) + prev_was_cr = False + elif char == "\t": + prev_was_cr = False + self._tap_special("Tab", Key.tab) + else: + prev_was_cr = False + self._type_single_char(char) + + if self.typing_delay > 0: + time.sleep(self.typing_delay) + + def _try_paste(self, full_text: str) -> bool: + if not pyperclip: + return False + try: + pyperclip.copy(full_text) + except Exception as e: + print(f"Avviso: appunti non disponibili ({e}), fallback su digitazione tastiera.") + return False + + time.sleep(0.05) + if self._linux_xtest is not None and self._linux_xtest.tap_named("v", with_ctrl=True): + time.sleep(0.04) + return True + + modifier = Key.cmd if self.is_mac else Key.ctrl + paste_key = KeyCode.from_vk(0x56) if (self.is_windows and KeyCode is not None) else "v" + with self.controller.pressed(modifier): + self.controller.tap(paste_key) + time.sleep(0.04) + return True + def _sync_type(self, full_text: str, suffix: str, mode: str) -> bool: if not self.controller: print("Errore: controller tastiera non disponibile!") return False try: - if mode == "paste" and pyperclip: - # Modalità Incolla: copia negli appunti e invia Ctrl+V (o Cmd+V su Mac) - pyperclip.copy(full_text) - time.sleep(0.02) - modifier = Key.cmd if self.is_mac else Key.ctrl - with self.controller.pressed(modifier): - self.controller.tap("v") - time.sleep(0.02) + if self._linux_xtest is not None: + self._linux_xtest.refresh_mapping() + + if mode == "paste": + if not self._try_paste(full_text): + self._type_chars_sequence(full_text) else: - # Modalità Digitazione Tastiera: digita carattere per carattere - for char in full_text: - self.controller.type(char) - if self.typing_delay > 0: - time.sleep(self.typing_delay) + self._type_chars_sequence(full_text) # Gestione suffisso (es. Invio o Tab, tipici dei lettori barcode) suffix_lower = suffix.lower() if suffix else "none" if suffix_lower == "enter" or suffix_lower == "\\n": time.sleep(0.02) - self.controller.tap(Key.enter) + self._tap_special("Return", Key.enter) elif suffix_lower == "tab" or suffix_lower == "\\t": time.sleep(0.02) - self.controller.tap(Key.tab) + self._tap_special("Tab", Key.tab) elif suffix_lower not in ("none", ""): - # Suffisso personalizzato come stringa - for char in suffix: - self.controller.type(char) - if self.typing_delay > 0: - time.sleep(self.typing_delay) + self._type_chars_sequence(suffix) return True except Exception as e: