feat: add global hotkey service using win32 registration

This commit is contained in:
Ilgiz Kalmetyev 2026-04-08 23:07:12 +05:00
parent fabef47549
commit df653b26f8
7 changed files with 551 additions and 2 deletions

View File

@ -1,4 +1,4 @@
from __future__ import annotations
from __future__ import annotations
import logging
import sys
@ -7,6 +7,7 @@ from PySide6.QtWidgets import QApplication
from audio.capture_service import AudioCaptureService
from core.config_service import AppConfig, ConfigError, ConfigService
from hotkeys.hotkey_service import HotkeyService
from logging_ext.logging_service import LoggingService
from ui.main_window import MainWindow
from ui.ptt_controller import PttController
@ -52,6 +53,20 @@ def main() -> int:
_tray_controller = TrayController(app, window)
_capture_service = AudioCaptureService()
_ptt_controller = PttController(window, _capture_service, config)
_hotkey_service = HotkeyService(app=app)
_hotkey_service.pressed.connect(_ptt_controller.begin_recording)
_hotkey_service.released.connect(_ptt_controller.end_recording)
registration = _hotkey_service.set_hotkey(config.hotkey)
if registration.success:
hotkey_text = registration.combination.to_string() if registration.combination else config.hotkey
logger.info("Registered global hotkey: %s", hotkey_text)
window.set_status_message(f"Global hotkey registered: {hotkey_text}")
else:
logger.warning("Global hotkey registration failed: %s", registration.error_message)
window.set_status_message(f"Global hotkey unavailable: {registration.error_message}")
app.aboutToQuit.connect(_hotkey_service.shutdown)
window.show()
exit_code = app.exec()
LoggingService.log_shutdown(logger)

View File

@ -1,9 +1,12 @@
"""Hotkey handling package."""
from .hotkey_parser import HotkeyCombination, HotkeyParseError, HotkeyParser
from .hotkey_service import HotkeyService, HotkeyServiceState
__all__ = [
"HotkeyCombination",
"HotkeyParseError",
"HotkeyParser",
"HotkeyService",
"HotkeyServiceState",
]

189
hotkeys/hotkey_service.py Normal file
View File

@ -0,0 +1,189 @@
"""Global hotkey service for VoicePTT."""
from __future__ import annotations
import ctypes
from ctypes import wintypes
from dataclasses import dataclass
from typing import Protocol
from PySide6.QtCore import QAbstractNativeEventFilter, QObject, QTimer, Signal
from PySide6.QtWidgets import QApplication
from hotkeys.hotkey_parser import HotkeyCombination, HotkeyParseError, HotkeyParser
from platform.windows.hotkey_win32 import (
HotkeyRegistrationResult,
WM_HOTKEY,
are_hotkey_keys_released,
register_hotkey as register_win32_hotkey,
unregister_hotkey as unregister_win32_hotkey,
)
class _HotkeyBackend(Protocol):
def register_hotkey(
self,
window_handle: int | None,
hotkey_id: int,
combination: HotkeyCombination,
) -> HotkeyRegistrationResult: ...
def unregister_hotkey(self, window_handle: int | None, hotkey_id: int) -> None: ...
def are_hotkey_keys_released(self, combination: HotkeyCombination) -> bool: ...
@dataclass(frozen=True, slots=True)
class HotkeyServiceState:
hotkey: HotkeyCombination | None
active: bool
pressed: bool
class HotkeyService(QObject):
pressed = Signal()
released = Signal()
registration_failed = Signal(str)
registration_changed = Signal(bool, str)
def __init__(
self,
app: QApplication | None = None,
backend: _HotkeyBackend | None = None,
hotkey_id: int = 1,
poll_interval_ms: int = 25,
parent: QObject | None = None,
) -> None:
super().__init__(parent)
self._app = app
self._backend = backend or _Win32HotkeyBackend()
self._hotkey_id = hotkey_id
self._hotkey: HotkeyCombination | None = None
self._pressed_active = False
self._filter = _NativeHotkeyEventFilter(self)
self._poll_timer = QTimer(self)
self._poll_timer.setInterval(poll_interval_ms)
self._poll_timer.timeout.connect(self.poll_release)
if self._app is not None:
self._app.installNativeEventFilter(self._filter)
@property
def state(self) -> HotkeyServiceState:
return HotkeyServiceState(hotkey=self._hotkey, active=self.is_registered, pressed=self._pressed_active)
@property
def is_registered(self) -> bool:
return self._hotkey is not None
@property
def hotkey(self) -> HotkeyCombination | None:
return self._hotkey
@property
def hotkey_text(self) -> str:
return self._hotkey.to_string() if self._hotkey is not None else ""
@property
def is_pressed(self) -> bool:
return self._pressed_active
def set_hotkey(self, hotkey: str | HotkeyCombination) -> HotkeyRegistrationResult:
combination = self._coerce_hotkey(hotkey)
previous_hotkey = self._hotkey
if previous_hotkey is not None:
self._backend.unregister_hotkey(None, self._hotkey_id)
self._hotkey = None
self._pressed_active = False
self._poll_timer.stop()
result = self._backend.register_hotkey(None, self._hotkey_id, combination)
if result.success:
self._hotkey = combination
self.registration_changed.emit(True, combination.to_string())
return result
if previous_hotkey is not None:
restore = self._backend.register_hotkey(None, self._hotkey_id, previous_hotkey)
if restore.success:
self._hotkey = previous_hotkey
self.registration_changed.emit(True, previous_hotkey.to_string())
else:
self.registration_changed.emit(False, "")
self.registration_failed.emit(restore.error_message or "Unable to restore previous hotkey binding.")
return result
self.registration_failed.emit(result.error_message)
return result
def register_hotkey(self, hotkey: str | HotkeyCombination) -> HotkeyRegistrationResult:
return self.set_hotkey(hotkey)
def unregister_hotkey(self) -> None:
if self._hotkey is None:
return
self._backend.unregister_hotkey(None, self._hotkey_id)
self._hotkey = None
self._pressed_active = False
self._poll_timer.stop()
self.registration_changed.emit(False, "")
def handle_hotkey_activation(self) -> None:
if self._hotkey is None or self._pressed_active:
return
self._pressed_active = True
self.pressed.emit()
self._poll_timer.start()
def poll_release(self) -> None:
if self._hotkey is None or not self._pressed_active:
return
if self._backend.are_hotkey_keys_released(self._hotkey):
self._pressed_active = False
self._poll_timer.stop()
self.released.emit()
def shutdown(self) -> None:
self.unregister_hotkey()
if self._app is not None:
self._app.removeNativeEventFilter(self._filter)
def _coerce_hotkey(self, hotkey: str | HotkeyCombination) -> HotkeyCombination:
if isinstance(hotkey, HotkeyCombination):
return hotkey
if not isinstance(hotkey, str):
raise HotkeyParseError("Hotkey must be provided as a string or HotkeyCombination.")
return HotkeyParser.deserialize(hotkey)
class _Win32HotkeyBackend:
def register_hotkey(
self,
window_handle: int | None,
hotkey_id: int,
combination: HotkeyCombination,
) -> HotkeyRegistrationResult:
return register_win32_hotkey(window_handle, hotkey_id, combination)
def unregister_hotkey(self, window_handle: int | None, hotkey_id: int) -> None:
unregister_win32_hotkey(window_handle, hotkey_id)
def are_hotkey_keys_released(self, combination: HotkeyCombination) -> bool:
return are_hotkey_keys_released(combination)
class _NativeHotkeyEventFilter(QAbstractNativeEventFilter):
def __init__(self, service: HotkeyService) -> None:
super().__init__()
self._service = service
def nativeEventFilter(self, eventType, message): # noqa: N802 - Qt API name
if eventType not in ("windows_generic_MSG", "windows_dispatcher_MSG"):
return False, 0
msg = wintypes.MSG.from_address(int(message))
if msg.message == WM_HOTKEY and msg.wParam == self._service._hotkey_id:
self._service.handle_hotkey_activation()
return False, 0

View File

@ -1,2 +1,8 @@
"""Windows-specific integration helpers."""
"""Windows platform integration helpers."""
from .hotkey_win32 import HotkeyRegistrationResult, HotkeyRegistrationError
__all__ = [
"HotkeyRegistrationError",
"HotkeyRegistrationResult",
]

View File

@ -0,0 +1,199 @@
"""Win32 global hotkey helpers."""
from __future__ import annotations
import ctypes
import os
from dataclasses import dataclass
from hotkeys.hotkey_parser import HotkeyCombination
WM_HOTKEY = 0x0312
ERROR_HOTKEY_ALREADY_REGISTERED = 1409
MOD_ALT = 0x0001
MOD_CONTROL = 0x0002
MOD_SHIFT = 0x0004
MOD_WIN = 0x0008
VK_CONTROL = 0x11
VK_MENU = 0x12
VK_SHIFT = 0x10
VK_LWIN = 0x5B
VK_RWIN = 0x5C
VK_SPACE = 0x20
VK_TAB = 0x09
VK_RETURN = 0x0D
VK_ESCAPE = 0x1B
VK_BACK = 0x08
VK_INSERT = 0x2D
VK_DELETE = 0x2E
VK_HOME = 0x24
VK_END = 0x23
VK_PRIOR = 0x21
VK_NEXT = 0x22
VK_LEFT = 0x25
VK_UP = 0x26
VK_RIGHT = 0x27
VK_DOWN = 0x28
VK_OEM_COMMA = 0xBC
VK_OEM_PERIOD = 0xBE
VK_OEM_MINUS = 0xBD
VK_OEM_PLUS = 0xBB
VK_OEM_1 = 0xBA
VK_OEM_2 = 0xBF
VK_OEM_3 = 0xC0
VK_OEM_4 = 0xDB
VK_OEM_5 = 0xDC
VK_OEM_6 = 0xDD
VK_OEM_7 = 0xDE
@dataclass(frozen=True, slots=True)
class HotkeyRegistrationResult:
success: bool
hotkey_id: int
combination: HotkeyCombination | None = None
error_message: str = ""
error_code: int | None = None
conflict: bool = False
class HotkeyRegistrationError(RuntimeError):
"""Raised when a Win32 hotkey registration cannot be completed."""
if os.name == "nt":
_USER32 = ctypes.WinDLL("user32", use_last_error=True)
else: # pragma: no cover - Windows-only product, fallback keeps imports explicit.
_USER32 = None
def register_hotkey(window_handle: int | None, hotkey_id: int, combination: HotkeyCombination) -> HotkeyRegistrationResult:
if os.name != "nt":
return HotkeyRegistrationResult(
success=False,
hotkey_id=hotkey_id,
combination=combination,
error_message="Global hotkeys are only supported on Windows.",
)
modifiers = _modifier_flags(combination)
virtual_key = _virtual_key_code(combination.key)
if not _USER32.RegisterHotKey(window_handle, hotkey_id, modifiers, virtual_key):
error_code = ctypes.get_last_error()
conflict = error_code == ERROR_HOTKEY_ALREADY_REGISTERED
message = "This hotkey is already registered by another application." if conflict else _format_error_message(
error_code,
"Unable to register global hotkey.",
)
return HotkeyRegistrationResult(
success=False,
hotkey_id=hotkey_id,
combination=combination,
error_message=message,
error_code=error_code,
conflict=conflict,
)
return HotkeyRegistrationResult(success=True, hotkey_id=hotkey_id, combination=combination)
def unregister_hotkey(window_handle: int | None, hotkey_id: int) -> None:
if os.name != "nt":
return
_USER32.UnregisterHotKey(window_handle, hotkey_id)
def are_hotkey_keys_released(combination: HotkeyCombination) -> bool:
if os.name != "nt":
return True
return not any(_is_key_pressed(vk_code) for vk_code in _hotkey_virtual_key_codes(combination))
def _modifier_flags(combination: HotkeyCombination) -> int:
flags = 0
for modifier in combination.modifiers:
if modifier == "Ctrl":
flags |= MOD_CONTROL
elif modifier == "Alt":
flags |= MOD_ALT
elif modifier == "Shift":
flags |= MOD_SHIFT
elif modifier == "Win":
flags |= MOD_WIN
else: # pragma: no cover - guarded by parser.
raise HotkeyRegistrationError(f"Unsupported modifier: {modifier}")
return flags
def _hotkey_virtual_key_codes(combination: HotkeyCombination) -> tuple[int, ...]:
codes = [_virtual_key_code(combination.key)]
for modifier in combination.modifiers:
if modifier == "Ctrl":
codes.append(VK_CONTROL)
elif modifier == "Alt":
codes.append(VK_MENU)
elif modifier == "Shift":
codes.append(VK_SHIFT)
elif modifier == "Win":
codes.extend((VK_LWIN, VK_RWIN))
else: # pragma: no cover - guarded by parser.
raise HotkeyRegistrationError(f"Unsupported modifier: {modifier}")
return tuple(dict.fromkeys(codes))
def _virtual_key_code(key: str) -> int:
named_keys = {
"Space": VK_SPACE,
"Tab": VK_TAB,
"Enter": VK_RETURN,
"Esc": VK_ESCAPE,
"Backspace": VK_BACK,
"Insert": VK_INSERT,
"Delete": VK_DELETE,
"Home": VK_HOME,
"End": VK_END,
"PageUp": VK_PRIOR,
"PageDown": VK_NEXT,
"Left": VK_LEFT,
"Up": VK_UP,
"Right": VK_RIGHT,
"Down": VK_DOWN,
"Comma": VK_OEM_COMMA,
"Period": VK_OEM_PERIOD,
"Minus": VK_OEM_MINUS,
"Plus": VK_OEM_PLUS,
"Semicolon": VK_OEM_1,
"Slash": VK_OEM_2,
"Grave": VK_OEM_3,
"BracketLeft": VK_OEM_4,
"Backslash": VK_OEM_5,
"BracketRight": VK_OEM_6,
"Quote": VK_OEM_7,
}
if key in named_keys:
return named_keys[key]
if len(key) == 1 and key.isalnum():
return ord(key.upper())
if key.startswith("F") and key[1:].isdigit():
function_number = int(key[1:])
if 1 <= function_number <= 24:
return 0x70 + function_number - 1
raise HotkeyRegistrationError(f"Unsupported hotkey key: {key}")
def _is_key_pressed(virtual_key_code: int) -> bool:
return bool(_USER32.GetAsyncKeyState(virtual_key_code) & 0x8000)
def _format_error_message(error_code: int, fallback: str) -> str:
if not error_code:
return fallback
return f"{fallback} (Win32 error {error_code})"

View File

@ -0,0 +1,107 @@
from __future__ import annotations
import pytest
from PySide6.QtWidgets import QApplication
from hotkeys.hotkey_parser import HotkeyCombination, HotkeyParser
from hotkeys.hotkey_service import HotkeyService
from platform.windows.hotkey_win32 import HotkeyRegistrationResult
class FakeBackend:
def __init__(self, register_results: list[HotkeyRegistrationResult] | None = None) -> None:
self.register_results = register_results or []
self.register_calls: list[tuple[int | None, int, HotkeyCombination]] = []
self.unregister_calls: list[tuple[int | None, int]] = []
self.released = True
def register_hotkey(
self,
window_handle: int | None,
hotkey_id: int,
combination: HotkeyCombination,
) -> HotkeyRegistrationResult:
self.register_calls.append((window_handle, hotkey_id, combination))
if self.register_results:
return self.register_results.pop(0)
return HotkeyRegistrationResult(success=True, hotkey_id=hotkey_id, combination=combination)
def unregister_hotkey(self, window_handle: int | None, hotkey_id: int) -> None:
self.unregister_calls.append((window_handle, hotkey_id))
def are_hotkey_keys_released(self, combination: HotkeyCombination) -> bool:
return self.released
@pytest.fixture(scope="module")
def app() -> QApplication:
instance = QApplication.instance()
if instance is not None:
return instance
return QApplication([])
def test_hotkey_service_emits_press_and_release(app: QApplication) -> None:
backend = FakeBackend()
service = HotkeyService(app=app, backend=backend)
pressed: list[str] = []
released: list[str] = []
service.pressed.connect(lambda: pressed.append("pressed"))
service.released.connect(lambda: released.append("released"))
result = service.register_hotkey("shift + ctrl + space")
assert result.success
assert service.hotkey_text == "Ctrl+Shift+Space"
assert backend.register_calls
service.handle_hotkey_activation()
assert pressed == ["pressed"]
assert service.is_pressed is True
backend.released = False
service.poll_release()
assert released == []
assert service.is_pressed is True
backend.released = True
service.poll_release()
assert released == ["released"]
assert service.is_pressed is False
service.shutdown()
def test_hotkey_service_reports_conflicts_and_keeps_previous_binding_on_rebind_failure(app: QApplication) -> None:
success_result = HotkeyRegistrationResult(
success=True,
hotkey_id=1,
combination=HotkeyParser.parse("Ctrl+Shift+Space"),
)
conflict_result = HotkeyRegistrationResult(
success=False,
hotkey_id=1,
combination=HotkeyParser.parse("Alt+Space"),
error_message="This hotkey is already registered by another application.",
error_code=1409,
conflict=True,
)
backend = FakeBackend(register_results=[success_result, conflict_result])
service = HotkeyService(app=app, backend=backend)
service.register_hotkey("Ctrl+Shift+Space")
failures: list[str] = []
changes: list[tuple[bool, str]] = []
service.registration_failed.connect(lambda message: failures.append(message))
service.registration_changed.connect(lambda active, text: changes.append((active, text)))
result = service.set_hotkey("Alt+Space")
assert not result.success
assert result.conflict is True
assert failures == ["This hotkey is already registered by another application."]
assert changes == [(True, "Ctrl+Shift+Space")]
assert service.hotkey_text == "Ctrl+Shift+Space"
service.shutdown()

View File

@ -0,0 +1,30 @@
from __future__ import annotations
from hotkeys.hotkey_parser import HotkeyCombination
from platform.windows.hotkey_win32 import ERROR_HOTKEY_ALREADY_REGISTERED, HotkeyRegistrationResult, _hotkey_virtual_key_codes
def test_hotkey_virtual_key_codes_include_modifier_and_main_key() -> None:
combination = HotkeyCombination(modifiers=("Ctrl", "Shift", "Win"), key="Space")
codes = _hotkey_virtual_key_codes(combination)
assert codes[0] == 0x20
assert 0x11 in codes
assert 0x10 in codes
assert 0x5B in codes and 0x5C in codes
assert len(codes) == len(set(codes))
def test_hotkey_registration_result_marks_conflicts() -> None:
result = HotkeyRegistrationResult(
success=False,
hotkey_id=1,
combination=HotkeyCombination(modifiers=("Ctrl",), key="Space"),
error_code=ERROR_HOTKEY_ALREADY_REGISTERED,
conflict=True,
error_message="This hotkey is already registered by another application.",
)
assert not result.success
assert result.conflict