diff --git a/src/voice_dictation/__init__.py b/src/voice_dictation/__init__.py index 70df26b..b1a7f2e 100644 --- a/src/voice_dictation/__init__.py +++ b/src/voice_dictation/__init__.py @@ -2,4 +2,4 @@ from __future__ import annotations -__version__ = "0.3.0b8" +__version__ = "0.3.0b9" diff --git a/src/voice_dictation/__main__.py b/src/voice_dictation/__main__.py index 98ca1c7..5dbb57f 100644 --- a/src/voice_dictation/__main__.py +++ b/src/voice_dictation/__main__.py @@ -20,6 +20,14 @@ def main() -> None: Если в argv передана подкоманда `headless` или `stats` — делегирует CLI. """ + if len(sys.argv) == 3 and sys.argv[1] == "input-safety-check": + from pathlib import Path + + from voice_dictation.ui.hotkey_acceptance import run_input_check + + run_input_check(Path(sys.argv[2])) + return + if len(sys.argv) > 1 and sys.argv[1] == "transcribe-file": from voice_dictation.cli.transcribe_file import main as transcribe_main diff --git a/src/voice_dictation/platform/macos/hotkey_listener.py b/src/voice_dictation/platform/macos/hotkey_listener.py index 2eecd90..362da56 100644 --- a/src/voice_dictation/platform/macos/hotkey_listener.py +++ b/src/voice_dictation/platform/macos/hotkey_listener.py @@ -10,7 +10,6 @@ from __future__ import annotations import logging import re import threading -import time from collections.abc import Callable from typing import Any @@ -85,7 +84,6 @@ _KEY_CODES: dict[str, int] = { _MODIFIER_TOKENS = {"cmd", "command", "ctrl", "control", "alt", "option", "shift", "super"} # Печатные клавиши, после которых надо стереть символ из активного поля -_PRINTABLE_MAIN_KEYS = {"space", "tab", "enter", "return"} def _parse_hotkey(hotkey: str) -> tuple[set[str], str]: @@ -187,47 +185,18 @@ class MacHotkeyListener: logger.warning("Неизвестная клавиша '%s' в хоткее '%s'", main, hotkey) return False - wrapped = self._wrap_with_backspace(callback, main) mods_mask = _modifier_mask(mods) keycode = _KEY_CODES[main] for i, (m, k, *_) in enumerate(self._hotkeys): if m == mods and k == main: - self._hotkeys[i] = (mods, main, mods_mask, keycode, wrapped) + self._hotkeys[i] = (mods, main, mods_mask, keycode, callback) return True - self._hotkeys.append((mods, main, mods_mask, keycode, wrapped)) + self._hotkeys.append((mods, main, mods_mask, keycode, callback)) logger.debug("Хоткей зарегистрирован: %s -> mods=%s, key=%s", hotkey, sorted(mods), main) return True - def _wrap_with_backspace( - self, callback: Callable[[], None], main_key: str - ) -> Callable[[], None]: - """Если хоткей с печатной клавишей — после нажатия шлём Backspace. - - macOS успевает вставить пробел/таб в активное поле до перехвата хоткея - через NSEvent global monitor (он не блокирует событие, только наблюдает). - Стираем лишний символ, чтобы поле осталось чистым. - """ - if main_key not in _PRINTABLE_MAIN_KEYS: - return callback - - def _runner() -> None: - try: - # Задержка: дать (1) системе вставить символ в активное поле, - # (2) пользователю отпустить Cmd. Иначе Backspace уйдёт с - # зажатым Cmd → Cmd+Backspace = удалить до начала строки. - time.sleep(0.12) - _send_backspace_via_quartz() - except Exception as exc: - logger.debug("Не удалось послать Backspace: %s", exc) - - def _wrapped() -> None: - threading.Thread(target=_runner, name="bs-eraser", daemon=True).start() - callback() - - return _wrapped - def start(self) -> None: """Регистрирует NSEvent global monitor на main thread (non-blocking). @@ -305,28 +274,3 @@ class MacHotkeyListener: logger.debug("stop() error: %s", exc) finally: self._monitor = None - - -def _send_backspace_via_quartz() -> None: - """Эмулирует чистый Backspace через Quartz CGEvent. - - Критично явно обнулить modifierFlags на событии: иначе CGEvent наследует - текущие физические модификаторы (если юзер ещё держит Cmd после хоткея) - → получаем Cmd+Backspace = «удалить до начала строки», то есть стираем - весь набранный текст вместо одного символа-пробела. - """ - from Quartz import ( - CGEventCreateKeyboardEvent, - CGEventPost, - CGEventSetFlags, - kCGHIDEventTap, - ) - - keycode = 0x33 # Backspace virtual key code - down = CGEventCreateKeyboardEvent(None, keycode, True) - up = CGEventCreateKeyboardEvent(None, keycode, False) - # Обнуляем флаги модификаторов — стираем ОДИН символ, не до начала строки. - CGEventSetFlags(down, 0) - CGEventSetFlags(up, 0) - CGEventPost(kCGHIDEventTap, down) - CGEventPost(kCGHIDEventTap, up) diff --git a/src/voice_dictation/ui/hotkey_acceptance.py b/src/voice_dictation/ui/hotkey_acceptance.py new file mode 100644 index 0000000..e6ec645 --- /dev/null +++ b/src/voice_dictation/ui/hotkey_acceptance.py @@ -0,0 +1,57 @@ +"""Manual native input acceptance, without microphone, API, or profile changes.""" + +from __future__ import annotations + +import json +from pathlib import Path + + +def run_input_check(output: Path) -> None: + """Observe two real hotkeys and paste a fixed marker after the second one.""" + from AppKit import NSApplication + from ApplicationServices import AXIsProcessTrusted + from PyObjCTools import AppHelper + + from voice_dictation.platform.macos.autopaste import MacAutoPaste + from voice_dictation.platform.macos.hotkey_listener import MacHotkeyListener + from voice_dictation.ui.setup_acceptance import synthetic_clipboard + + trusted = bool(AXIsProcessTrusted()) + presses = 0 + + def report(stage: str) -> None: + output.write_text(json.dumps({"stage": stage, "trusted": trusted, "presses": presses})) + + if not trusted: + report("permission_required") + return + NSApplication.sharedApplication() + listener = MacHotkeyListener() + + def paste() -> None: + MacAutoPaste().paste() + report("pasted") + + def toggle() -> None: + nonlocal presses + presses += 1 + report("hotkey") + if presses == 2: + AppHelper.callLater(0.3, paste) + + listener.register("cmd+space", toggle) + with synthetic_clipboard("[DICTATION]"): + listener.start() + AppHelper.callLater(0.5, report, "ready") + if output.name.startswith("auto-"): + # Invoke the exact registered callbacks; native paste still goes to the editor. + registered_callback = listener._hotkeys[0][-1] + AppHelper.callLater(2.0, registered_callback) + AppHelper.callLater(3.0, registered_callback) + AppHelper.callLater(5.0, AppHelper.stopEventLoop) + else: + AppHelper.callLater(45, AppHelper.stopEventLoop) + try: + AppHelper.runEventLoop() + finally: + listener.stop() diff --git a/src/voice_dictation/ui/setup_acceptance.py b/src/voice_dictation/ui/setup_acceptance.py index 344a40f..e96c0e6 100644 --- a/src/voice_dictation/ui/setup_acceptance.py +++ b/src/voice_dictation/ui/setup_acceptance.py @@ -8,7 +8,7 @@ from contextlib import contextmanager @contextmanager -def synthetic_clipboard() -> Iterator[None]: +def synthetic_clipboard(text: str = "sk-test-not-a-real-key") -> Iterator[None]: """Temporarily replace and restore every native pasteboard representation.""" if sys.platform != "darwin": raise RuntimeError("Native clipboard acceptance currently requires macOS") @@ -24,7 +24,7 @@ def synthetic_clipboard() -> Iterator[None]: restored.setData_forType_(data, kind) saved.append(restored) board.clearContents() - board.setString_forType_("sk-test-not-a-real-key", NSPasteboardTypeString) + board.setString_forType_(text, NSPasteboardTypeString) try: yield finally: diff --git a/tests/unit/test_macos_input_safety.py b/tests/unit/test_macos_input_safety.py new file mode 100644 index 0000000..8e062f4 --- /dev/null +++ b/tests/unit/test_macos_input_safety.py @@ -0,0 +1,46 @@ +"""Hotkeys must never repair the user's text by synthesizing deletion keys.""" + +from __future__ import annotations + +import sys +from types import SimpleNamespace + +import pytest + +from voice_dictation.platform.macos import autopaste, hotkey_listener + + +@pytest.mark.parametrize("hotkey", ["cmd+space", "cmd+tab", "cmd+enter", "cmd+alt+d"]) +def test_start_and_stop_hotkeys_do_not_edit_text( + hotkey: str, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(hotkey_listener, "_modifier_mask", lambda _: 0) + + def forbidden_thread(*args: object, **kwargs: object) -> None: + pytest.fail("Hotkey spawned an unsolicited background input operation") + + monkeypatch.setattr(hotkey_listener.threading, "Thread", forbidden_thread) + calls: list[str] = [] + + def callback() -> None: + calls.append("toggle") + + listener = hotkey_listener.MacHotkeyListener() + assert listener.register(hotkey, callback) + for _ in range(2): + listener._hotkeys[0][-1]() + assert calls == ["toggle", "toggle"] + + +def test_paste_posts_only_command_v(monkeypatch: pytest.MonkeyPatch) -> None: + events: list[tuple[int, bool]] = [] + quartz = SimpleNamespace( + CGEventCreateKeyboardEvent=lambda source, key, down: (key, down), + CGEventPost=lambda tap, event: events.append(event), + CGEventSetFlags=lambda event, flags: None, + kCGEventFlagMaskCommand=1, + kCGHIDEventTap=0, + ) + monkeypatch.setitem(sys.modules, "Quartz", quartz) + autopaste.MacAutoPaste().paste() + assert events == [(0x09, True), (0x09, False)]