Remove destructive Backspace workaround from macOS hotkeys

This commit is contained in:
Vickenty Zherebov 2026-10-20 14:07:26 +03:00
parent 8739a521bf
commit 4f86fb2f47
6 changed files with 116 additions and 61 deletions

View file

@ -2,4 +2,4 @@
from __future__ import annotations from __future__ import annotations
__version__ = "0.3.0b8" __version__ = "0.3.0b9"

View file

@ -20,6 +20,14 @@ def main() -> None:
Если в argv передана подкоманда `headless` или `stats` — делегирует CLI. Если в 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": if len(sys.argv) > 1 and sys.argv[1] == "transcribe-file":
from voice_dictation.cli.transcribe_file import main as transcribe_main from voice_dictation.cli.transcribe_file import main as transcribe_main

View file

@ -10,7 +10,6 @@ from __future__ import annotations
import logging import logging
import re import re
import threading import threading
import time
from collections.abc import Callable from collections.abc import Callable
from typing import Any from typing import Any
@ -85,7 +84,6 @@ _KEY_CODES: dict[str, int] = {
_MODIFIER_TOKENS = {"cmd", "command", "ctrl", "control", "alt", "option", "shift", "super"} _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]: def _parse_hotkey(hotkey: str) -> tuple[set[str], str]:
@ -187,47 +185,18 @@ class MacHotkeyListener:
logger.warning("Неизвестная клавиша '%s' в хоткее '%s'", main, hotkey) logger.warning("Неизвестная клавиша '%s' в хоткее '%s'", main, hotkey)
return False return False
wrapped = self._wrap_with_backspace(callback, main)
mods_mask = _modifier_mask(mods) mods_mask = _modifier_mask(mods)
keycode = _KEY_CODES[main] keycode = _KEY_CODES[main]
for i, (m, k, *_) in enumerate(self._hotkeys): for i, (m, k, *_) in enumerate(self._hotkeys):
if m == mods and k == main: 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 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) logger.debug("Хоткей зарегистрирован: %s -> mods=%s, key=%s", hotkey, sorted(mods), main)
return True 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: def start(self) -> None:
"""Регистрирует NSEvent global monitor на main thread (non-blocking). """Регистрирует NSEvent global monitor на main thread (non-blocking).
@ -305,28 +274,3 @@ class MacHotkeyListener:
logger.debug("stop() error: %s", exc) logger.debug("stop() error: %s", exc)
finally: finally:
self._monitor = None 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)

View file

@ -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()

View file

@ -8,7 +8,7 @@ from contextlib import contextmanager
@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.""" """Temporarily replace and restore every native pasteboard representation."""
if sys.platform != "darwin": if sys.platform != "darwin":
raise RuntimeError("Native clipboard acceptance currently requires macOS") raise RuntimeError("Native clipboard acceptance currently requires macOS")
@ -24,7 +24,7 @@ def synthetic_clipboard() -> Iterator[None]:
restored.setData_forType_(data, kind) restored.setData_forType_(data, kind)
saved.append(restored) saved.append(restored)
board.clearContents() board.clearContents()
board.setString_forType_("sk-test-not-a-real-key", NSPasteboardTypeString) board.setString_forType_(text, NSPasteboardTypeString)
try: try:
yield yield
finally: finally:

View file

@ -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)]