"""전역 단축키. Qt 의 QShortcut 은 우리 창이 포커스를 가졌을 때만 동작한다. 게임을 하는 중에 자막을 껐다 켜야 하므로 OS 레벨 단축키가 필요하다. Windows 에서는 `RegisterHotKey` + 네이티브 이벤트 필터로 구현하고, 다른 OS 에서는 조용히 아무 것도 하지 않는다(창이 떠 있을 때만 쓰는 QShortcut 은 상위에서 따로 건다). """ from __future__ import annotations import logging import sys from collections.abc import Callable from PySide6.QtCore import QAbstractNativeEventFilter, QObject log = logging.getLogger(__name__) WM_HOTKEY = 0x0312 MOD_ALT = 0x0001 MOD_CONTROL = 0x0002 MOD_SHIFT = 0x0004 MOD_WIN = 0x0008 MOD_NOREPEAT = 0x4000 _MODIFIERS = { "ctrl": MOD_CONTROL, "control": MOD_CONTROL, "alt": MOD_ALT, "shift": MOD_SHIFT, "win": MOD_WIN, "meta": MOD_WIN, } #: 문자/숫자가 아닌 키의 가상 키 코드 _NAMED_KEYS = { "f1": 0x70, "f2": 0x71, "f3": 0x72, "f4": 0x73, "f5": 0x74, "f6": 0x75, "f7": 0x76, "f8": 0x77, "f9": 0x78, "f10": 0x79, "f11": 0x7A, "f12": 0x7B, "space": 0x20, "enter": 0x0D, "return": 0x0D, "tab": 0x09, "esc": 0x1B, "escape": 0x1B, "insert": 0x2D, "delete": 0x2E, "home": 0x24, "end": 0x23, "pageup": 0x21, "pagedown": 0x22, "up": 0x26, "down": 0x28, "left": 0x25, "right": 0x27, "`": 0xC0, "-": 0xBD, "=": 0xBB, } class HotkeyError(RuntimeError): """단축키를 등록할 수 없을 때 (대개 다른 프로그램이 선점).""" def parse(sequence: str) -> tuple[int, int]: """"Ctrl+Alt+S" → (수정자 비트마스크, 가상 키 코드).""" parts = [p.strip().lower() for p in sequence.split("+") if p.strip()] if not parts: raise HotkeyError(f"빈 단축키입니다: {sequence!r}") mods = 0 key_part = "" for part in parts: if part in _MODIFIERS: mods |= _MODIFIERS[part] else: key_part = part if not key_part: raise HotkeyError(f"조합키만 있고 실제 키가 없습니다: {sequence!r}") if not mods: # 수정자 없는 전역 단축키는 게임 입력을 통째로 가로채므로 막는다. raise HotkeyError(f"Ctrl/Alt/Shift 중 하나는 있어야 합니다: {sequence!r}") if key_part in _NAMED_KEYS: vk = _NAMED_KEYS[key_part] elif len(key_part) == 1 and key_part.isalnum(): vk = ord(key_part.upper()) else: raise HotkeyError(f"알 수 없는 키입니다: {key_part!r}") return mods | MOD_NOREPEAT, vk class GlobalHotkeys(QObject, QAbstractNativeEventFilter): """전역 단축키 묶음. Windows 전용이며 그 외에서는 no-op.""" def __init__(self, parent: QObject | None = None) -> None: QObject.__init__(self, parent) QAbstractNativeEventFilter.__init__(self) self._callbacks: dict[int, Callable[[], None]] = {} self._next_id = 1 self._installed = False self._last_error = "" @property def supported(self) -> bool: return sys.platform == "win32" @property def last_error(self) -> str: return self._last_error def register(self, sequence: str, callback: Callable[[], None]) -> bool: """단축키 하나를 등록한다. 성공하면 True.""" if not self.supported: self._last_error = "전역 단축키는 Windows에서만 지원합니다." return False try: mods, vk = parse(sequence) except HotkeyError as exc: self._last_error = str(exc) log.warning("단축키 해석 실패: %s", exc) return False import ctypes hotkey_id = self._next_id if not ctypes.windll.user32.RegisterHotKey(None, hotkey_id, mods, vk): self._last_error = ( f"'{sequence}' 를 등록하지 못했습니다. 다른 프로그램이 쓰고 있을 수 있습니다." ) log.warning(self._last_error) return False self._callbacks[hotkey_id] = callback self._next_id += 1 self._ensure_filter() log.info("전역 단축키 등록: %s", sequence) return True def unregister_all(self) -> None: if not self.supported or not self._callbacks: return import ctypes from PySide6.QtWidgets import QApplication for hotkey_id in self._callbacks: ctypes.windll.user32.UnregisterHotKey(None, hotkey_id) self._callbacks.clear() if self._installed: app = QApplication.instance() if app is not None: app.removeNativeEventFilter(self) self._installed = False def _ensure_filter(self) -> None: if self._installed: return from PySide6.QtWidgets import QApplication app = QApplication.instance() if app is not None: app.installNativeEventFilter(self) self._installed = True def nativeEventFilter(self, event_type, message): # noqa: N802 - Qt 규약 if not self._callbacks or event_type not in (b"windows_generic_MSG", b"windows_dispatcher_MSG"): return False, 0 import ctypes import ctypes.wintypes msg = ctypes.cast(int(message), ctypes.POINTER(ctypes.wintypes.MSG)).contents if msg.message != WM_HOTKEY: return False, 0 callback = self._callbacks.get(int(msg.wParam)) if callback is None: return False, 0 try: callback() except Exception: # noqa: BLE001 - 콜백 오류로 이벤트 루프가 죽으면 안 된다 log.exception("단축키 처리 실패") return True, 0