34 lines
947 B
Python
34 lines
947 B
Python
import sys
|
|
import threading
|
|
from typing import Callable
|
|
|
|
from pynput import keyboard
|
|
|
|
from .config import HotkeyCfg
|
|
|
|
|
|
class HotkeyManager:
|
|
def __init__(self, cfg: HotkeyCfg, on_capture: Callable, on_toggle: Callable):
|
|
self._callbacks = {
|
|
cfg.capture: on_capture,
|
|
cfg.toggle: on_toggle,
|
|
}
|
|
self._listener: keyboard.GlobalHotKeys | None = None
|
|
self._lock = threading.Lock()
|
|
|
|
def start(self) -> None:
|
|
with self._lock:
|
|
if self._listener is not None:
|
|
return
|
|
try:
|
|
self._listener = keyboard.GlobalHotKeys(self._callbacks)
|
|
self._listener.start()
|
|
except Exception as e:
|
|
print(f"快捷键注册失败: {e}", file=sys.stderr)
|
|
|
|
def stop(self) -> None:
|
|
with self._lock:
|
|
if self._listener:
|
|
self._listener.stop()
|
|
self._listener = None
|