* feat(post-processing): pipe transcriptions through user-defined script Add a configurable post-processing step that passes each transcription result to an external executable via stdin and uses its stdout as the text to type. Enables custom transforms (formatting, LLM rewriting, etc.) without modifying Vocalinux. Falls back to original text on script failure or timeout. * test(post-processor): add unit tests and extract apply_post_processing Move config-reading logic from main.py closure into apply_post_processing() in post_processor.py so it can be tested independently. Add 11 unit tests covering PostProcessor.process() and apply_post_processing(). * docs(post-processing): document post-processing script feature * fix formatting of one file * fix(post-processing): run the user script with a stripped host environment Rebase compat: the host_process AST guard requires every subprocess spawned for a host binary to pass env=host_env() so an AppImage's LD_LIBRARY_PATH/GI_TYPELIB_PATH/PYTHONHOME do not leak in. Also give apply_post_processing() a typed ConfigManager parameter and keep text_callback_wrapper's local variable typed as str for mypy. * fix(post-processing): preserve paragraph breaks and tighten script handling Take script stdout verbatim instead of rstripping every trailing newline, so the "new paragraph" voice command's break survives a passthrough script. A single trailing newline is still dropped, but only when the transcription had none — it is almost always just the line terminator echo/print-style tools append. Also stop writing transformed output to the log (it can carry sensitive dictation into retained logs), catch only the expected process/OS/encoding failures instead of every Exception, and add the missing signature annotations. * fix(main): run the post-processing script off the recognition thread A user script may take seconds per segment, and text callbacks run on the recognition thread that drains the bounded audio-segment queue; stalling it drops queued dictation once the queue fills. Submit post-processing and injection to a dedicated single-worker executor so the backlog waits instead of losing speech, while keeping injection order. On timeout or failure the worker falls back to the original text, and an unexpected error is logged with a traceback and still injects the original rather than silently dropping the segment. Also pin the callback tests' get_str mock to no-script so they exercise the synchronous path deterministically, and add a callback test proving transformed text (including preserved paragraph breaks) reaches the injector. * docs(post-processing): annotate new callbacks and clarify stdout contract Add the missing type annotations on the new Settings page callbacks per the repository guide, and document that script stdout is used verbatim (a lone trailing newline added by line-oriented tools is dropped only when the transcription had none) and that scripts run on a dedicated worker. * test(main): annotate new post-processing callback tests * fix(main): bind queued dictation to its target app and drain worker on quit Route every transcription segment through the single post-processing worker (a pass-through when no script is configured) so clearing the script path mid-queue can no longer let a later segment overtake an earlier one still running. A segment that can sit in the backlog — a script is configured or a job is still running — is bound to the application focused when it was dictated; the worker drops it if focus has verifiably moved to another application, so delayed dictation cannot land in the wrong app. Wire the worker into the tray quit path via an on_quit hook: it clears the acceptance flag, cancels pending jobs, and waits — bounded by the script's own timeout — so nothing injects after the injector stops. * fix(main): keep voice actions ordered and probe focus off the recognition thread - Queue voice-command actions on the post-processing worker so an action can no longer overtake dictated text still waiting to be injected. - Move the submit-time focus probe onto a dedicated executor; the recognition thread only submits the probe, and the job joins the result at inject time, so compositor tools can no longer stall consumption of the bounded audio-segment queue. - Re-check the quit flag after the inject-time focus re-probe, then shut both workers down without waiting on a running script so quitting does not freeze on the script timeout. * fix(main): capture submit-time focus on dedicated threads and serialize quit - Replace the shared focus-probe executor with a fresh daemon thread per submission so a slow earlier probe cannot delay a later one past the focus change it is meant to capture; jobs read the result off a one-slot queue at inject time. - Give queued voice actions the same submit-time focus binding as text segments so a queued shortcut is dropped instead of fired into a newly focused application. - Hold injection_lock across the accept-check plus inject/action call so quit waits only for an in-flight injection instead of racing it. - Queue the IDLE reset of last_injected_text behind pending worker jobs so a queued 'delete that' still sees the text it targets. * fix(main): keep actions instant on a free worker and bound quit wait - An action now starts a submit-time focus probe only when it actually queues behind other jobs; with a free worker there is no delay window to bind against, so the probe's compositor calls are skipped and the action stays immediate even when a script is configured. - Probe and executor submission now happen inside pending_jobs_lock so queue order matches callback order — a job that saw an empty queue can no longer slip behind one that arrived while it was submitting. - Every inject-path subprocess call (xdotool window/key/type, wtype and ydotool type) is bounded by a timeout, and the quit hook's injection_lock wait is capped, so quitting can no longer freeze on a stalled injector subprocess. * fix(main): bind every action to submit-time focus without slowing it down - Every voice action now starts a submit-time focus probe: submission never guarantees immediate execution, so skipping the binding left a focus-change window in which a shortcut could fire into another app. The worker waits on the probe for at most one second — milliseconds on a healthy desktop — so immediate actions stay immediate while a genuinely stalled probe falls back to the injector's own targeting. - Quit waits for an in-flight injection without a cap again: every inject-path subprocess is individually bounded, so the wait always ends with the injection and a long transcription is never cut off. - The wtype/ydotool typing timeout is now derived from the configured per-key delay (a generous multiple), so a legitimately slow type can never be cut mid-text; a timed-out type no longer falls through to the clipboard fallback, which would duplicate the partial fragment. * fix(main): drop unverified actions and make quit-time injection abortable - An action whose submit-time focus probe cannot answer inside its one-second bound is now dropped instead of running unverified: a stalled probe can no longer leave a shortcut pointing at whatever application happens to be focused. - Quit asks the injector to abort in-flight injections, and injection paths honour it: the xdotool chunk loop stops between chunks, the wtype/ydotool type call runs as a polling Popen that can be killed, and paste/shortcut/backspace entry points exit early. The quit hook still waits for an in-flight injection, but the wait is bounded by at most one already-running subprocess call — never the injection's full length — and no subprocess is ever stopped mid-call by a timeout cap on the wait itself. - Annotate the remaining untyped test helpers. * fix(main): wait out slow focus probes; restore run() in wayland typing - An action no longer races its submit-time focus probe on a one-second bound: the job waits for the probe's own answer, whose compositor calls already carry per-call timeouts and short-circuit absent tools. A slow but living probe delays the command instead of discarding it, so a valid "undo" can no longer be lost to timing alone, and focus verification still decides every drop. - Wayland typing goes back to subprocess.run so tests keep intercepting the same entry point. Abortability is preserved by typing in 200-character chunks with the shutdown check between calls — a whole-string call could not be interrupted, but no single chunk holds the injector for more than its own scaled budget. - The abort flag gains a class-level default so injectors built without __init__ in tests still answer the checks; each real instance gets its own event in __init__. - Update call-shape assertions for the typed-call timeout and finish annotating the test methods touched by the callback refactor. * fix(inject): never retype text a failed chunked call already sent - _PartiallyTyped carries the confirmed-delivered prefix length out of the chunked type loops, so every downstream fallback continues from the untyped remainder: the Wayland-to-xdotool switch types only the tail, and the clipboard fallback copies only the tail, never the whole string a second time. - The xdotool retry loop gains the same accounting — a retry now resumes at the first untyped chunk instead of restarting at the top and duplicating everything the failed attempt already delivered. - Annotate the remaining test signature the repository guide requires. * fix(inject): report partial typing as failure even when clipboard lands A chunked type call that dies mid-text leaves only a prefix on screen, and the remainder-fallback keeps it that way: it copies the tail for a manual paste but now returns False, so the caller no longer records the full transcription as injected and a following "delete that" cannot erase text that was never typed. * fix(inject): keep deletion state aligned with delivered text inject_text now records how many characters a call confirmed on screen as last_typed_count: the whole length on success, the typed prefix after a partial failure, -1 when the delivered amount is unknowable. The transcription caller uses it to keep last_injected_text honest — a following "delete that" erases the typed prefix or nothing, never the previous segment or text that never arrived. * fix(inject): never replay input a timed-out portal job may have delivered - RemoteDesktopPortalError.delivered=None marks an unreported job's count as unknowable; all three portal fallbacks demote and skip instead of replaying, and text injection surfaces as TimeoutExpired so no full-text clipboard copy is offered - _PartiallyTyped counts raised after a portal demote are rebased onto the original text (typed_prefix) so the caller clips the real prefix - evdev: a consumed pure-modifier press is withheld and replayed ahead of the first non-target press, so holding RightAlt for AltGr composition still reaches the application - history: extend_latest gains an expected_latest CAS guard so a late segment from an older worker merges only into its own session's snippet, never into a newer session's entry - quit path aborts in-flight injections before waiting on the lock so quitting cannot freeze behind a long transcription's typing budget - tests: stop _ensure_ydotoold leaking a real Popen in Wayland tests * fix(shortcut): replay withheld modifiers across devices and after SYN_DROPPED - Replay withheld modifier presses from every device, not only the fd the character arrived on: split keyboards deliver AltGr and the character on separate devices, and a per-fd check forwarded a plain character. - Let the post-SYN_DROPPED resync run when only withheld modifiers exist for the fd, so a press whose release the dropped burst ate is pruned instead of replaying a stale modifier on the next ordinary key. * fix(history,pads): keep late segments pad-bound deliveries and pad deletions correct - Track the worker behind the ended session's snippet so late segments from an older worker cannot merge into a newer session's entry - Skip the focus-change drop for dictation-pad segments and pad-bound editing commands, which never target the focused application - Refuse 'delete that' when a manual pad edit blurred the segment boundaries instead of deleting the stale recorded length * style: drop unneeded nonlocal for mutated worker set * fix(shortcut): share one evdev device layer across shortcut listeners Each KeyboardShortcutManager built its own EvdevKeyboardBackend, and on evdev every backend opened and grabbed the same physical keyboards: the first grabber received all events and the rest received none, so per-language shortcuts could never fire on Wayland. All backends now bind to a process-wide EvdevDeviceHub that opens each keyboard once, owns the grabs and the paired uinput clones, and fans every event out to each registered engine. An event is re-emitted to applications only when no engine consumed it, so suppression semantics stay the same while per-engine matching state (combo progress, withheld modifiers, swallowed presses) remains independent. * fix(history): own late segments per worker and decide pad routing once - ended_worker_snippets maps each ended session's worker to its own (snippet, commit epoch): late deliveries merge into their session's entry however many sessions have committed since, so one session's stragglers never split across Recent Snippets entries. - The leftover-segment commit reads the live history epoch inside the session lock: a mid-session clear() no longer makes the stale ended epoch refuse valid post-clear dictation. - The pad-bound routing decision is captured once per job and passed to the injector/action handler, so a toggle flip between the focus check and delivery cannot reroute text or shortcuts into the focused app. - Dead recognition workers are pruned from the tracking set and map so long runs don't accumulate finished threads. - The custom-terms switch now suppresses GTK's own state-set on save failure so it shows the value that actually persisted. * fix(shortcut): serialize evdev device layer teardown against restart The last listener's unregister released the engine lock before joining the monitor thread and closing devices, so a new listener registering in that gap opened keyboards the stale teardown then closed — it stayed active but dead, and briefly grabbed keyboards stopped forwarding input. A lifecycle lock now covers the whole close/open transition in register, unregister, and the monitor's unexpected-exit teardown, so a cold start can only open devices after the previous generation finished closing (also making the new generation's grabs succeed). A generation stamp tells a monitor thread that outlived its join() its incarnation is over even when running has gone True again. * fix(injection): log focus-probe failures and narrow clipboard fallback catch A crashed focus probe turned into an unknown result with no logged error, indistinguishable from unavailable focus information; the partial-typing clipboard fallback caught every exception. Log the probe failure with context and narrow the clipboard catch to the exceptions the fallback path can actually raise. * fix(shortcut): join the evdev monitor outside the lifecycle lock If the monitor exited unexpectedly while the last listener unregistered, its cleanup queued on the lifecycle lock that unregister() held for the join — stalling shutdown for the join's full 2s timeout. The close now finishes inside the lock and the join waits after it is released, so the monitor's own cleanup can run and exit instead of queueing behind it. Closing before the join also dies the monitor's read/select on the closed fds right away. A _closed gate on _open_keyboard_device keeps a rescan from opening a device between detach and close that nothing would ever close. * fix(injection): narrow focus-probe catch to the raisable exception set get_focused_window() reports Optional and never raises; the catch now covers only what can realistically escape the queue write and logs it with context, keeping the waiting job released. * fix(shortcut): tag evdev device fds with the generation that opened them A monitor that outlived join() could still touch a newer generation's devices: the loop re-checked the generation only at the top, so mid-iteration it could dispatch from, forward to, or remove devices a restarted listener had just opened. Every fd is now tagged with the generation that opened it, and the tag is verified at each point a monitor could mutate shared state — fd lookup for dispatch, clone forwarding, forwarder release, device removal, and rescan opens — while dispatch re-checks the generation between events and the per-fd loop breaks on it. Cold starts bump the generation before opening so fresh devices are tagged for the new generation. Devices an older generation opened stay tagged stale, so its reader leaves them alone. --------- Co-authored-by: Jatin K Malik <jatinkrmalik@gmail.com>
1026 lines
39 KiB
Python
1026 lines
39 KiB
Python
"""Per-language dictation shortcuts: config schema, one-shot engine override,
|
|
tray listeners, and settings-row plumbing (#805)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
import os
|
|
import queue
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
from collections.abc import Iterator
|
|
from typing import Any
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
import vocalinux.ui
|
|
from vocalinux.common_types import RecognitionState
|
|
from vocalinux.ui.config_manager import ConfigManager, normalize_language_shortcuts
|
|
from vocalinux.utils.vosk_model_info import SUPPORTED_LANGUAGES
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def settings_dialog() -> Iterator[Any]:
|
|
"""Import settings_dialog with real bases for its GTK subclasses.
|
|
|
|
Same approach as tests/test_follow_keyboard_layout.py; both sys.modules
|
|
and the package attribute are restored so later tests patching the module
|
|
by name do not reach a second module object (#686).
|
|
"""
|
|
repository = sys.modules["gi.repository"]
|
|
bases = {name: type(name, (), {}) for name in ("Box", "ListBoxRow", "Dialog")}
|
|
saved_module = sys.modules.pop("vocalinux.ui.settings_dialog", None)
|
|
saved_attribute = getattr(vocalinux.ui, "settings_dialog", None)
|
|
try:
|
|
with patch.object(repository, "Gtk", MagicMock(**bases)):
|
|
module = importlib.import_module("vocalinux.ui.settings_dialog")
|
|
yield module
|
|
finally:
|
|
sys.modules.pop("vocalinux.ui.settings_dialog", None)
|
|
if saved_module is not None:
|
|
sys.modules["vocalinux.ui.settings_dialog"] = saved_module
|
|
if saved_attribute is not None:
|
|
vocalinux.ui.settings_dialog = saved_attribute
|
|
elif hasattr(vocalinux.ui, "settings_dialog"):
|
|
del vocalinux.ui.settings_dialog
|
|
|
|
|
|
@pytest.fixture
|
|
def dialog_class(settings_dialog: Any) -> type[Any]:
|
|
return settings_dialog.SettingsDialog
|
|
|
|
|
|
# --- config normalization ---------------------------------------------------
|
|
|
|
|
|
def test_normalize_language_shortcuts_keeps_valid_bindings() -> None:
|
|
entries = normalize_language_shortcuts(
|
|
[
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "ctrl+alt+g", "language": "hu"},
|
|
{"shortcut": "f5", "language": "auto"},
|
|
]
|
|
)
|
|
assert entries == [
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "ctrl+alt+g", "language": "hu"},
|
|
{"shortcut": "f5", "language": "auto"},
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("raw", [None, "alt+d", 42, {"shortcut": "alt+d"}])
|
|
def test_normalize_language_shortcuts_rejects_non_lists(raw: Any) -> None:
|
|
assert normalize_language_shortcuts(raw) == []
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"item",
|
|
[
|
|
"alt+d", # not a mapping
|
|
{"shortcut": "alt+d"}, # missing language
|
|
{"language": "de"}, # missing shortcut
|
|
{"shortcut": 5, "language": "de"}, # wrong types
|
|
{"shortcut": "alt+d", "language": "klingon"}, # not a catalog id
|
|
{"shortcut": "alt", "language": "de"}, # bare modifier, unbindable
|
|
{"shortcut": "", "language": "de"}, # empty shortcut
|
|
{"shortcut": "alt+d", "language": "layout"}, # sentinel, not a language
|
|
],
|
|
)
|
|
def test_normalize_language_shortcuts_drops_bad_entries(item: Any) -> None:
|
|
assert normalize_language_shortcuts([item]) == []
|
|
|
|
|
|
def test_normalize_language_shortcuts_dedupes_by_shortcut() -> None:
|
|
"""The first binding wins when two rows claim the same key."""
|
|
entries = normalize_language_shortcuts(
|
|
[
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "alt+d", "language": "fr"},
|
|
]
|
|
)
|
|
assert entries == [{"shortcut": "alt+d", "language": "de"}]
|
|
|
|
|
|
def test_language_shortcuts_roundtrip_through_config(tmp_path: Any) -> None:
|
|
config_dir = tmp_path / "vocalinux"
|
|
config_dir.mkdir()
|
|
config_file = config_dir / "config.json"
|
|
with (
|
|
patch("vocalinux.ui.config_manager.CONFIG_DIR", str(config_dir)),
|
|
patch("vocalinux.ui.config_manager.CONFIG_FILE", str(config_file)),
|
|
patch("vocalinux.utils.system_language.detect_system_language", return_value=None),
|
|
):
|
|
manager = ConfigManager()
|
|
assert manager.get_language_shortcuts() == []
|
|
|
|
manager.set_language_shortcuts(
|
|
[
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "broken", "language": "fr"}, # dropped by normalize
|
|
]
|
|
)
|
|
assert manager.config["shortcuts"]["language_shortcuts"] == [
|
|
{"shortcut": "alt+d", "language": "de"}
|
|
]
|
|
assert manager.get_language_shortcuts() == [{"shortcut": "alt+d", "language": "de"}]
|
|
|
|
# Persisted to disk.
|
|
manager.save_config()
|
|
reloaded = ConfigManager()
|
|
assert reloaded.get_language_shortcuts() == [{"shortcut": "alt+d", "language": "de"}]
|
|
|
|
|
|
def test_get_language_shortcuts_survives_a_broken_shortcuts_section() -> None:
|
|
"""A hand-edited config replacing the section with a scalar reads as empty."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
config_dir = os.path.join(temp_dir, "vocalinux")
|
|
config_file = os.path.join(config_dir, "config.json")
|
|
os.makedirs(config_dir, exist_ok=True)
|
|
with open(config_file, "w") as handle:
|
|
handle.write('{"shortcuts": "oops"}')
|
|
with (
|
|
patch("vocalinux.ui.config_manager.CONFIG_DIR", config_dir),
|
|
patch("vocalinux.ui.config_manager.CONFIG_FILE", config_file),
|
|
patch(
|
|
"vocalinux.utils.system_language.detect_system_language",
|
|
return_value=None,
|
|
),
|
|
):
|
|
manager = ConfigManager()
|
|
assert manager.get_language_shortcuts() == []
|
|
manager.set_language_shortcuts([{"shortcut": "alt+d", "language": "de"}])
|
|
assert manager.get_language_shortcuts() == [{"shortcut": "alt+d", "language": "de"}]
|
|
|
|
|
|
# --- one-shot language override on the manager ------------------------------
|
|
|
|
|
|
def _manager_stub(
|
|
engine: str = "whisper_cpp",
|
|
model_size: str = "small",
|
|
language: str = "en-us",
|
|
language_preference: str = "en-us",
|
|
) -> Any:
|
|
"""A manager carrying only the fields the one-shot path touches."""
|
|
from vocalinux.speech_recognition.recognition_manager import SpeechRecognitionManager
|
|
|
|
manager = SpeechRecognitionManager.__new__(SpeechRecognitionManager)
|
|
manager.engine = engine
|
|
manager.model_size = model_size
|
|
manager.language = language
|
|
manager.language_preference = language_preference
|
|
manager.state = RecognitionState.IDLE
|
|
manager.state_callbacks = []
|
|
manager._faster_whisper_engine = None
|
|
manager.command_processor = MagicMock()
|
|
manager._pending_language_override = None
|
|
manager._oneshot_language_restore = None
|
|
manager._segment_started_at = None
|
|
return manager
|
|
|
|
|
|
def test_language_shortcut_starts_dictation_in_that_language() -> None:
|
|
import vocalinux.speech_recognition.recognition_manager as rm
|
|
|
|
manager = _manager_stub()
|
|
manager.start_recognition = MagicMock(
|
|
side_effect=lambda mode="toggle": (manager._apply_pending_language_override(), True)[1]
|
|
)
|
|
|
|
assert manager.start_recognition_with_language("de") is True
|
|
manager.start_recognition.assert_called_once_with(mode="toggle")
|
|
assert manager.language == "de"
|
|
assert manager.command_processor.set_language.call_args.args == ("de",)
|
|
# Consumed: a later plain start must not see the override.
|
|
assert manager._pending_language_override is None
|
|
assert manager._oneshot_language_restore == "en-us"
|
|
|
|
|
|
def test_language_shortcut_wins_over_follow_layout() -> None:
|
|
"""An explicit key press outranks the follow-mode resolution (#821)."""
|
|
import vocalinux.speech_recognition.recognition_manager as rm
|
|
|
|
manager = _manager_stub(language_preference="layout")
|
|
|
|
def fake_start(mode: str = "toggle") -> bool:
|
|
manager._refresh_language_from_layout()
|
|
manager._apply_pending_language_override()
|
|
return True
|
|
|
|
manager.start_recognition = MagicMock(side_effect=fake_start)
|
|
with patch.object(rm, "language_for_active_layout", return_value="fr"):
|
|
assert manager.start_recognition_with_language("de") is True
|
|
|
|
assert manager.language == "de"
|
|
assert manager._oneshot_language_restore == "fr"
|
|
manager._update_state(RecognitionState.IDLE)
|
|
assert manager.language == "fr"
|
|
|
|
|
|
def test_language_is_restored_when_dictation_ends() -> None:
|
|
"""The configured language comes back on the IDLE transition."""
|
|
manager = _manager_stub()
|
|
manager._oneshot_language_restore = "en-us"
|
|
manager.language = "de"
|
|
|
|
manager._update_state(RecognitionState.IDLE)
|
|
|
|
assert manager.language == "en-us"
|
|
assert manager._oneshot_language_restore is None
|
|
manager.command_processor.set_language.assert_called_with("en-us")
|
|
|
|
|
|
def test_language_is_restored_on_error_too() -> None:
|
|
manager = _manager_stub()
|
|
manager._oneshot_language_restore = "en-us"
|
|
manager.language = "de"
|
|
|
|
manager._update_state(RecognitionState.ERROR)
|
|
|
|
assert manager.language == "en-us"
|
|
assert manager._oneshot_language_restore is None
|
|
|
|
|
|
def test_shortcut_language_matching_current_language_leaves_no_restore() -> None:
|
|
"""No-op overrides never register a restore."""
|
|
manager = _manager_stub(language="de")
|
|
manager._pending_language_override = "de"
|
|
|
|
manager._apply_pending_language_override()
|
|
|
|
assert manager.language == "de"
|
|
assert manager._oneshot_language_restore is None
|
|
manager.command_processor.set_language.assert_not_called()
|
|
|
|
|
|
@pytest.mark.parametrize("engine,model_size", [("vosk", "small"), ("parakeet", "turbo")])
|
|
def test_unsupported_engine_refuses_instead_of_dictating_wrong(
|
|
engine: str, model_size: str
|
|
) -> None:
|
|
"""VOSK/Parakeet cannot honour a per-utterance language; refuse loudly."""
|
|
import vocalinux.speech_recognition.recognition_manager as rm
|
|
|
|
manager = _manager_stub(engine=engine, model_size=model_size, language="en-us")
|
|
manager.start_recognition = MagicMock(return_value=True)
|
|
|
|
with (
|
|
patch.object(rm, "play_error_sound") as mock_error,
|
|
patch.object(rm, "_show_notification") as mock_notify,
|
|
):
|
|
assert manager.start_recognition_with_language("de") is False
|
|
|
|
manager.start_recognition.assert_not_called()
|
|
mock_error.assert_called_once()
|
|
mock_notify.assert_called_once()
|
|
assert manager.language == "en-us"
|
|
assert manager._pending_language_override is None
|
|
|
|
|
|
def test_english_only_whispercpp_model_refuses_the_shortcut() -> None:
|
|
"""small.en has no non-English weights to aim the shortcut at."""
|
|
import vocalinux.speech_recognition.recognition_manager as rm
|
|
|
|
manager = _manager_stub(model_size="small.en")
|
|
manager.start_recognition = MagicMock(return_value=True)
|
|
|
|
with (
|
|
patch.object(rm, "play_error_sound") as mock_error,
|
|
patch.object(rm, "_show_notification") as mock_notify,
|
|
):
|
|
assert manager.start_recognition_with_language("de") is False
|
|
|
|
manager.start_recognition.assert_not_called()
|
|
mock_error.assert_called_once()
|
|
mock_notify.assert_called_once()
|
|
|
|
|
|
def test_same_language_shortcut_runs_on_english_only_model() -> None:
|
|
"""No language switch is needed to dictate in the model's own language."""
|
|
import vocalinux.speech_recognition.recognition_manager as rm
|
|
|
|
manager = _manager_stub(model_size="small.en", language="en-us")
|
|
manager.start_recognition = MagicMock(return_value=True)
|
|
|
|
with patch.object(rm, "_show_notification") as mock_notify:
|
|
assert manager.start_recognition_with_language("en-us") is True
|
|
|
|
mock_notify.assert_not_called()
|
|
|
|
|
|
def test_pending_override_is_consumed_even_when_start_is_refused() -> None:
|
|
"""A refused start (auto-pause, model missing) must not leak the override."""
|
|
manager = _manager_stub()
|
|
manager.start_recognition = MagicMock(return_value=False)
|
|
|
|
assert manager.start_recognition_with_language("de") is False
|
|
assert manager._pending_language_override is None
|
|
assert manager._oneshot_language_restore is None
|
|
|
|
|
|
def test_reconfiguring_the_language_clears_a_pending_restore() -> None:
|
|
"""A mid-dictation language change must not be undone by the restore."""
|
|
manager = _manager_stub()
|
|
manager._oneshot_language_restore = "en-us"
|
|
manager.language = "de"
|
|
manager._voice_commands_preference = None
|
|
manager._snapshot_reconfigure_state = MagicMock(return_value={})
|
|
|
|
manager.reconfigure(language="fr")
|
|
|
|
assert manager._oneshot_language_restore is None
|
|
assert manager.language == "fr"
|
|
|
|
|
|
# --- tray wiring ------------------------------------------------------------
|
|
|
|
|
|
def _tray_stub(shortcut_mode: str = "toggle", entries: Any = None) -> Any:
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = TrayIndicator.__new__(TrayIndicator)
|
|
tray.config_manager = MagicMock()
|
|
config_values = {
|
|
"mode": shortcut_mode,
|
|
"toggle_recognition": "right_alt+right_alt",
|
|
}
|
|
tray.config_manager.get_str.side_effect = lambda section, key, default="": config_values.get(
|
|
key, default
|
|
)
|
|
tray.config_manager.get_language_shortcuts.return_value = entries or []
|
|
tray.speech_engine = MagicMock()
|
|
tray.speech_engine.state = RecognitionState.IDLE
|
|
tray._language_shortcut_managers = []
|
|
# D-Bus activation unavailable -> the internal listener family is on,
|
|
# which is what these tests exercise.
|
|
tray._external_activation_unavailable = True
|
|
return tray
|
|
|
|
|
|
def test_tray_builds_one_listener_per_binding() -> None:
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(
|
|
entries=[
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "ctrl+alt+g", "language": "hu"},
|
|
]
|
|
)
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
created = [MagicMock(), MagicMock()]
|
|
manager_class.side_effect = created
|
|
|
|
TrayIndicator._setup_language_shortcuts(tray)
|
|
|
|
assert manager_class.call_count == 2
|
|
manager_class.assert_any_call(shortcut="alt+d", mode="toggle")
|
|
manager_class.assert_any_call(shortcut="ctrl+alt+g", mode="toggle")
|
|
assert tray._language_shortcut_managers == created
|
|
for manager in created:
|
|
manager.register_toggle_callback.assert_called_once()
|
|
manager.start.assert_called_once()
|
|
|
|
|
|
def test_tray_skips_bindings_that_collide() -> None:
|
|
"""A language shortcut equal to the main one cannot fire both."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(
|
|
entries=[
|
|
{"shortcut": "right_alt+right_alt", "language": "de"}, # main
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "alt+d", "language": "fr"}, # duplicate of previous
|
|
]
|
|
)
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
TrayIndicator._setup_language_shortcuts(tray)
|
|
|
|
manager_class.assert_called_once_with(shortcut="alt+d", mode="toggle")
|
|
|
|
|
|
def test_tray_language_managers_follow_push_to_talk() -> None:
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(
|
|
shortcut_mode="push_to_talk",
|
|
entries=[{"shortcut": "alt+d", "language": "de"}],
|
|
)
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
manager = MagicMock()
|
|
manager_class.return_value = manager
|
|
|
|
TrayIndicator._setup_language_shortcuts(tray)
|
|
|
|
manager_class.assert_called_once_with(shortcut="alt+d", mode="push_to_talk")
|
|
manager.register_press_callback.assert_called_once()
|
|
# The release is routed through the owner-gated helper for this binding,
|
|
# not a stop callback shared by every listener.
|
|
release_callback = manager.register_release_callback.call_args.args[0]
|
|
assert release_callback.func == tray._release_language_push_to_talk
|
|
assert release_callback.args == (manager,)
|
|
|
|
|
|
def test_tray_toggle_in_language_starts_a_one_shot() -> None:
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub()
|
|
tray.speech_engine.state = RecognitionState.IDLE
|
|
|
|
TrayIndicator._toggle_recognition_in_language(tray, "de")
|
|
|
|
tray.speech_engine.start_recognition_with_language.assert_called_once_with("de")
|
|
|
|
|
|
def test_tray_toggle_in_language_stops_while_dictating() -> None:
|
|
"""Same as the main toggle: a press while dictating ends it."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub()
|
|
tray.speech_engine.state = RecognitionState.LISTENING
|
|
|
|
TrayIndicator._toggle_recognition_in_language(tray, "de")
|
|
|
|
tray.speech_engine.stop_recognition.assert_called_once()
|
|
tray.speech_engine.start_recognition_with_language.assert_not_called()
|
|
|
|
|
|
def test_tray_push_to_talk_in_language_starts_a_one_shot() -> None:
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub()
|
|
TrayIndicator._start_recognition_in_language(tray, "de")
|
|
|
|
tray.speech_engine.start_recognition_with_language.assert_called_once_with(
|
|
"de", mode="push_to_talk"
|
|
)
|
|
|
|
|
|
def test_tray_language_release_stops_only_its_own_session() -> None:
|
|
"""Another binding's release must not end a hold it did not start."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(shortcut_mode="push_to_talk")
|
|
german, french = MagicMock(), MagicMock()
|
|
tray.speech_engine.state = RecognitionState.LISTENING
|
|
tray._ptt_owner = german
|
|
|
|
TrayIndicator._release_language_push_to_talk(tray, french)
|
|
tray.speech_engine.stop_recognition.assert_not_called()
|
|
|
|
TrayIndicator._release_language_push_to_talk(tray, german)
|
|
tray.speech_engine.stop_recognition.assert_called_once()
|
|
assert tray._ptt_owner is None
|
|
|
|
|
|
def test_tray_ptt_release_during_start_still_ends_the_session() -> None:
|
|
"""A release landing mid-start waits for the owner claim, then stops (#805)."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(shortcut_mode="push_to_talk")
|
|
german = MagicMock()
|
|
tray.speech_engine.state = RecognitionState.IDLE
|
|
|
|
def fake_start(*_args: Any, **_kwargs: Any) -> bool:
|
|
tray.speech_engine.state = RecognitionState.LISTENING
|
|
releaser.start()
|
|
return True
|
|
|
|
releaser = threading.Thread(
|
|
target=TrayIndicator._release_language_push_to_talk, args=(tray, german)
|
|
)
|
|
tray.speech_engine.start_recognition_with_language.side_effect = fake_start
|
|
|
|
TrayIndicator._start_recognition_in_language(tray, "de", german)
|
|
releaser.join(timeout=5)
|
|
|
|
tray.speech_engine.stop_recognition.assert_called_once()
|
|
assert tray._ptt_owner is None
|
|
|
|
|
|
def test_tray_main_ptt_release_during_start_still_ends_the_session() -> None:
|
|
"""The main binding has the same deferred-release guarantee (#805)."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(shortcut_mode="push_to_talk")
|
|
tray.shortcut_manager = MagicMock()
|
|
tray.speech_engine.state = RecognitionState.IDLE
|
|
|
|
def fake_start(*_args: Any, **_kwargs: Any) -> bool:
|
|
tray.speech_engine.state = RecognitionState.LISTENING
|
|
releaser.start()
|
|
return True
|
|
|
|
releaser = threading.Thread(target=TrayIndicator._release_main_push_to_talk, args=(tray,))
|
|
tray.speech_engine.start_recognition.side_effect = fake_start
|
|
|
|
TrayIndicator._start_recognition(tray)
|
|
releaser.join(timeout=5)
|
|
|
|
tray.speech_engine.stop_recognition.assert_called_once()
|
|
assert tray._ptt_owner is None
|
|
|
|
|
|
def test_tray_skips_gesture_equivalent_bindings() -> None:
|
|
"""Different spellings of the same gesture still collide."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(
|
|
entries=[
|
|
{"shortcut": "ctrl+alt+r", "language": "de"},
|
|
{"shortcut": "alt+ctrl+r", "language": "fr"}, # reordered, same gesture
|
|
{"shortcut": "ctrl+enter", "language": "es"},
|
|
{"shortcut": "alt+return", "language": "hu"}, # enter/return alias
|
|
]
|
|
)
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
TrayIndicator._setup_language_shortcuts(tray)
|
|
|
|
armed = [call.kwargs["shortcut"] for call in manager_class.call_args_list]
|
|
assert armed == ["ctrl+alt+r", "ctrl+enter"]
|
|
|
|
|
|
def test_tray_skips_pure_modifier_gesture_overlap() -> None:
|
|
"""A one-sided hold fires inside the both-sides binding's key set."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(
|
|
entries=[
|
|
{"shortcut": "left_ctrl+left_ctrl", "language": "de"},
|
|
{"shortcut": "ctrl+ctrl", "language": "fr"}, # left ctrl fires both
|
|
{"shortcut": "right_ctrl+right_ctrl", "language": "es"}, # other side
|
|
]
|
|
)
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
TrayIndicator._setup_language_shortcuts(tray)
|
|
|
|
armed = [call.kwargs["shortcut"] for call in manager_class.call_args_list]
|
|
assert armed == ["left_ctrl+left_ctrl", "right_ctrl+right_ctrl"]
|
|
|
|
|
|
def test_refresh_does_not_rearm_under_external_activation() -> None:
|
|
"""A binding edit must not arm listeners while internal hotkeys are off."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(entries=[{"shortcut": "alt+d", "language": "de"}])
|
|
tray._external_activation_unavailable = False
|
|
tray.config_manager.get_bool.return_value = True # disable_internal_hotkey
|
|
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
TrayIndicator.refresh_language_shortcuts(tray)
|
|
|
|
manager_class.assert_not_called()
|
|
assert tray._language_shortcut_managers == []
|
|
|
|
|
|
def test_refresh_stops_a_held_push_to_talk_first() -> None:
|
|
"""Rebuilding listeners cannot strand a session waiting on its release.
|
|
|
|
While a push-to-talk hold is live the rebuild is deferred instead of
|
|
stopping the session: the manager whose release callback will end the
|
|
hold is kept alive until the IDLE transition drains the refresh.
|
|
"""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(
|
|
shortcut_mode="push_to_talk",
|
|
entries=[{"shortcut": "alt+d", "language": "de"}],
|
|
)
|
|
tray.speech_engine.state = RecognitionState.LISTENING
|
|
tray._language_shortcuts_refresh_pending = False
|
|
armed = MagicMock()
|
|
tray._language_shortcut_managers = [armed]
|
|
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager"):
|
|
TrayIndicator.refresh_language_shortcuts(tray)
|
|
|
|
tray.speech_engine.stop_recognition.assert_not_called()
|
|
assert tray._language_shortcuts_refresh_pending is True
|
|
assert tray._language_shortcut_managers == [armed] # release callback survives
|
|
armed.stop.assert_not_called()
|
|
|
|
|
|
def test_refresh_rebuilds_the_language_listeners() -> None:
|
|
"""Settings changes must reach the live listeners immediately."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(entries=[{"shortcut": "alt+d", "language": "de"}])
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
old = MagicMock()
|
|
manager_class.return_value = old
|
|
TrayIndicator._setup_language_shortcuts(tray)
|
|
|
|
tray.config_manager.get_language_shortcuts.return_value = [
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "ctrl+alt+f", "language": "fr"},
|
|
]
|
|
manager_class.side_effect = [MagicMock(), MagicMock()]
|
|
|
|
TrayIndicator.refresh_language_shortcuts(tray)
|
|
|
|
old.stop.assert_called_once()
|
|
assert len(tray._language_shortcut_managers) == 2
|
|
|
|
|
|
def test_stop_language_shortcut_managers_survives_a_bad_stop() -> None:
|
|
"""One failing listener must not orphan the rest during teardown."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub()
|
|
bad, good = MagicMock(), MagicMock()
|
|
bad.stop.side_effect = OSError("device vanished")
|
|
tray._language_shortcut_managers = [bad, good]
|
|
|
|
TrayIndicator._stop_language_shortcut_managers(tray)
|
|
|
|
bad.stop.assert_called_once()
|
|
good.stop.assert_called_once()
|
|
assert tray._language_shortcut_managers == []
|
|
|
|
|
|
def test_oneshot_restore_is_part_of_the_reconfigure_snapshot() -> None:
|
|
"""Rollback must be able to revive the pending one-shot restore (#805)."""
|
|
from vocalinux.speech_recognition.recognition_manager import SpeechRecognitionManager
|
|
|
|
assert "_oneshot_language_restore" in SpeechRecognitionManager._RECONFIGURE_STATE_ATTRS
|
|
|
|
|
|
def test_failed_reconfigure_settles_the_pending_oneshot_restore() -> None:
|
|
"""Rollback revives the pending restore, then settles it before re-init."""
|
|
manager = _manager_stub(language="de")
|
|
manager._oneshot_language_restore = "en-us"
|
|
manager._voice_commands_preference = None
|
|
manager._defer_download = True
|
|
manager._model_lock = threading.Lock()
|
|
manager._snapshot_reconfigure_state = MagicMock(
|
|
return_value={"language": "de", "_oneshot_language_restore": "en-us"}
|
|
)
|
|
manager._init_selected_engine = MagicMock(side_effect=[RuntimeError("boom"), None])
|
|
|
|
with pytest.raises(RuntimeError):
|
|
manager.reconfigure(language="fr", model_size="tiny")
|
|
|
|
assert manager.language == "en-us"
|
|
assert manager._oneshot_language_restore is None
|
|
|
|
|
|
def test_language_shortcut_allowed_when_layout_will_swap_model() -> None:
|
|
"""Follow-layout can swap in the multilingual sibling the shortcut needs."""
|
|
import vocalinux.speech_recognition.recognition_manager as rm
|
|
|
|
manager = _manager_stub(model_size="small.en", language_preference="layout")
|
|
manager.start_recognition = MagicMock(return_value=True)
|
|
|
|
with (
|
|
patch.object(rm, "is_model_downloaded", return_value=True),
|
|
patch.object(rm, "_multilingual_sibling", return_value="small"),
|
|
):
|
|
assert manager.start_recognition_with_language("de") is True
|
|
|
|
manager.start_recognition.assert_called_once()
|
|
|
|
|
|
def test_parakeet_auto_shortcut_is_still_allowed() -> None:
|
|
"""Normalizing to auto is only a refusal when it drops the request."""
|
|
manager = _manager_stub(engine="parakeet", model_size="turbo", language="auto")
|
|
manager.start_recognition = MagicMock(return_value=True)
|
|
|
|
assert manager.start_recognition_with_language("auto") is True
|
|
|
|
|
|
def test_dictation_language_tracks_the_session_snapshot() -> None:
|
|
"""Workers read the session binding, not the live configured language."""
|
|
manager = _manager_stub(language="en-us")
|
|
manager._session_language = "de"
|
|
assert manager._dictation_language() == "de"
|
|
manager._session_language = None
|
|
assert manager._dictation_language() == "en-us"
|
|
|
|
|
|
def test_dictation_language_prefers_the_segment_snapshot() -> None:
|
|
"""The stamped snapshot beats the session binding and the preference."""
|
|
manager = _manager_stub(language="en-us")
|
|
manager._session_language = "fr"
|
|
assert manager._dictation_language("de") == "de"
|
|
|
|
|
|
def test_stale_worker_keeps_the_segments_own_language() -> None:
|
|
"""A worker draining after a newer start must not adopt its language."""
|
|
manager = _manager_stub(language="en-us")
|
|
manager._segment_queue = queue.Queue(maxsize=32)
|
|
manager.should_record = False
|
|
manager._session_language = "de"
|
|
manager._process_audio_buffer = MagicMock()
|
|
|
|
manager._enqueue_audio_segment([b"audio"])
|
|
# A newer dictation binds its language before the stale worker drains.
|
|
manager._session_language = "fr"
|
|
manager._signal_recognition_stop()
|
|
manager._perform_recognition()
|
|
|
|
manager._process_audio_buffer.assert_called_once()
|
|
args = manager._process_audio_buffer.call_args.args
|
|
assert args[0] == [b"audio"]
|
|
assert args[0].language == "de"
|
|
assert args[1] == "de"
|
|
|
|
|
|
# --- settings dialog plumbing ------------------------------------------------
|
|
|
|
|
|
def _dialog_stub() -> Any:
|
|
"""A dialog carrying only what the language-shortcut plumbing reads."""
|
|
dialog = MagicMock()
|
|
dialog._initializing = False
|
|
dialog.config_manager = MagicMock()
|
|
dialog.language_shortcuts_update_callback = MagicMock()
|
|
dialog._language_shortcut_rows = []
|
|
return dialog
|
|
|
|
|
|
def test_collect_language_shortcuts_reads_every_row(dialog_class: type[Any]) -> None:
|
|
dialog = _dialog_stub()
|
|
picker, entry = MagicMock(), MagicMock()
|
|
picker.get_active_id.return_value = "de"
|
|
entry.get_text.return_value = "alt+d"
|
|
dialog._language_shortcut_rows = [{"language_picker": picker, "shortcut_entry": entry}]
|
|
|
|
assert dialog_class._collect_language_shortcuts(dialog) == [
|
|
{"shortcut": "alt+d", "language": "de"}
|
|
]
|
|
|
|
|
|
def test_persist_writes_config_and_refreshes_listeners(
|
|
dialog_class: type[Any],
|
|
) -> None:
|
|
dialog = _dialog_stub()
|
|
picker, entry = MagicMock(), MagicMock()
|
|
picker.get_active_id.return_value = "de"
|
|
entry.get_text.return_value = "alt+d"
|
|
dialog._language_shortcut_rows = [{"language_picker": picker, "shortcut_entry": entry}]
|
|
collected = dialog_class._collect_language_shortcuts(dialog)
|
|
assert collected == [{"shortcut": "alt+d", "language": "de"}]
|
|
dialog._collect_language_shortcuts = lambda: collected
|
|
|
|
dialog_class._persist_language_shortcuts(dialog)
|
|
|
|
dialog.config_manager.set_language_shortcuts.assert_called_once_with(
|
|
[{"shortcut": "alt+d", "language": "de"}]
|
|
)
|
|
dialog.config_manager.save_settings.assert_called_once()
|
|
dialog.language_shortcuts_update_callback.assert_called_once()
|
|
|
|
|
|
def test_persist_is_a_no_op_during_dialog_build(
|
|
dialog_class: type[Any],
|
|
) -> None:
|
|
"""Rows being populated must not write config or rebuild listeners."""
|
|
dialog = _dialog_stub()
|
|
dialog._initializing = True
|
|
|
|
dialog_class._persist_language_shortcuts(dialog)
|
|
|
|
dialog.config_manager.set_language_shortcuts.assert_not_called()
|
|
dialog.language_shortcuts_update_callback.assert_not_called()
|
|
|
|
|
|
def test_recorded_key_is_written_to_the_row_entry(
|
|
dialog_class: type[Any],
|
|
) -> None:
|
|
"""The shared recorder must serve a language row, not just the main entry."""
|
|
dialog = _dialog_stub()
|
|
entry, apply_fn = MagicMock(), MagicMock()
|
|
dialog._recording_shortcut = True
|
|
dialog._recording_shortcut_target = (entry, apply_fn, MagicMock(), MagicMock())
|
|
|
|
assert dialog_class._commit_recorded_shortcut(dialog, "alt+d") is True
|
|
|
|
entry.set_text.assert_called_once_with("alt+d")
|
|
apply_fn.assert_called_once_with("alt+d")
|
|
|
|
|
|
def test_recording_stays_target_free_when_not_recording(
|
|
dialog_class: type[Any],
|
|
) -> None:
|
|
dialog = _dialog_stub()
|
|
dialog._recording_shortcut = False
|
|
|
|
assert dialog_class._commit_recorded_shortcut(dialog, "alt+d") is False
|
|
|
|
|
|
def test_picker_change_retitles_the_row(dialog_class: type[Any]) -> None:
|
|
"""The row title follows the picked language so search stays honest."""
|
|
dialog = _dialog_stub()
|
|
row = MagicMock()
|
|
picker = MagicMock()
|
|
picker.get_active_id.return_value = "de"
|
|
refs = {"row": row}
|
|
dialog._persist_language_shortcuts = lambda: dialog_class._persist_language_shortcuts(dialog)
|
|
dialog._on_language_shortcut_row_changed = (
|
|
lambda *a: dialog_class._on_language_shortcut_row_changed(dialog, *a)
|
|
)
|
|
|
|
dialog_class._on_language_shortcut_picker_changed(dialog, refs, picker)
|
|
|
|
row.set_title.assert_called_once_with(SUPPORTED_LANGUAGES["de"]["name"])
|
|
dialog.language_shortcuts_update_callback.assert_called_once()
|
|
|
|
|
|
def test_persist_keeps_last_valid_binding_during_partial_edit(
|
|
dialog_class: type[Any],
|
|
) -> None:
|
|
"""A half-typed key cannot erase the row's persisted binding."""
|
|
dialog = _dialog_stub()
|
|
picker, entry = MagicMock(), MagicMock()
|
|
picker.get_active_id.return_value = "de"
|
|
entry.get_text.return_value = "alt+" # mid-typing
|
|
dialog._language_shortcut_rows = [
|
|
{
|
|
"language_picker": picker,
|
|
"shortcut_entry": entry,
|
|
"last_valid_shortcut": "alt+d",
|
|
}
|
|
]
|
|
|
|
dialog_class._persist_language_shortcuts(dialog)
|
|
|
|
dialog.config_manager.set_language_shortcuts.assert_called_once_with(
|
|
[{"shortcut": "alt+d", "language": "de"}]
|
|
)
|
|
|
|
|
|
def test_persist_reports_a_rejected_duplicate(dialog_class: type[Any]) -> None:
|
|
"""A row claiming a taken key keeps its last binding and says why."""
|
|
dialog = _dialog_stub()
|
|
first_picker, second_picker = MagicMock(), MagicMock()
|
|
first_entry, second_entry = MagicMock(), MagicMock()
|
|
first_picker.get_active_id.return_value = "de"
|
|
second_picker.get_active_id.return_value = "fr"
|
|
first_entry.get_text.return_value = "alt+d"
|
|
second_entry.get_text.return_value = "alt+d"
|
|
dialog._language_shortcut_rows = [
|
|
{
|
|
"language_picker": first_picker,
|
|
"shortcut_entry": first_entry,
|
|
"last_valid_shortcut": "alt+d",
|
|
},
|
|
{
|
|
"language_picker": second_picker,
|
|
"shortcut_entry": second_entry,
|
|
"last_valid_shortcut": "alt+f",
|
|
},
|
|
]
|
|
dialog._report_language_shortcut_rejections = (
|
|
lambda rejected: dialog_class._report_language_shortcut_rejections(dialog, rejected)
|
|
)
|
|
|
|
dialog_class._persist_language_shortcuts(dialog)
|
|
|
|
dialog.config_manager.set_language_shortcuts.assert_called_once_with(
|
|
[
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "alt+f", "language": "fr"},
|
|
]
|
|
)
|
|
dialog.language_shortcuts_info_label.set_markup.assert_called_once()
|
|
|
|
|
|
def test_removing_an_armed_row_cancels_recording(dialog_class: type[Any]) -> None:
|
|
"""A capture aimed at a removed row is cancelled before it is destroyed."""
|
|
dialog = _dialog_stub()
|
|
entry, button = MagicMock(), MagicMock()
|
|
refs = {
|
|
"row": MagicMock(),
|
|
"language_picker": MagicMock(),
|
|
"shortcut_entry": entry,
|
|
"record_button": button,
|
|
}
|
|
dialog._language_shortcut_rows = [refs]
|
|
dialog._recording_shortcut = True
|
|
dialog._recording_shortcut_target = (entry, MagicMock(), button, MagicMock())
|
|
|
|
dialog_class._on_remove_language_shortcut_clicked(dialog, refs, button)
|
|
|
|
dialog._stop_recording_shortcut.assert_called_once()
|
|
|
|
|
|
def test_begin_recording_disarms_the_previous_target(dialog_class: type[Any]) -> None:
|
|
"""Arming a second row resets the first row's 'Press keys…' button."""
|
|
dialog = _dialog_stub()
|
|
dialog._recording_shortcut = True
|
|
dialog._recording_shortcut_target = (
|
|
MagicMock(),
|
|
MagicMock(),
|
|
MagicMock(),
|
|
MagicMock(),
|
|
)
|
|
|
|
dialog_class._begin_shortcut_recording(
|
|
dialog, MagicMock(), MagicMock(), MagicMock(), MagicMock()
|
|
)
|
|
|
|
dialog._stop_recording_shortcut.assert_called_once()
|
|
|
|
|
|
def test_persist_rejects_an_edit_that_claims_another_rows_binding(
|
|
dialog_class: type[Any],
|
|
) -> None:
|
|
"""Editing a row onto another row's key must not displace that row."""
|
|
dialog = _dialog_stub()
|
|
first_picker, second_picker = MagicMock(), MagicMock()
|
|
first_entry, second_entry = MagicMock(), MagicMock()
|
|
first_picker.get_active_id.return_value = "de"
|
|
second_picker.get_active_id.return_value = "fr"
|
|
first_entry.get_text.return_value = "alt+f" # typed onto row two's key
|
|
second_entry.get_text.return_value = "alt+f" # row two still holds it
|
|
dialog._language_shortcut_rows = [
|
|
{
|
|
"language_picker": first_picker,
|
|
"shortcut_entry": first_entry,
|
|
"last_valid_shortcut": "alt+d",
|
|
},
|
|
{
|
|
"language_picker": second_picker,
|
|
"shortcut_entry": second_entry,
|
|
"last_valid_shortcut": "alt+f",
|
|
},
|
|
]
|
|
dialog._report_language_shortcut_rejections = (
|
|
lambda rejected: dialog_class._report_language_shortcut_rejections(dialog, rejected)
|
|
)
|
|
dialog.config_manager.get_language_shortcuts.return_value = [
|
|
{"shortcut": "alt+d", "language": "de"},
|
|
{"shortcut": "alt+f", "language": "fr"},
|
|
]
|
|
|
|
dialog_class._persist_language_shortcuts(dialog)
|
|
|
|
# The resolved rows match the saved bindings — the stealing edit lost —
|
|
# so nothing is rewritten and no listener rebuild is triggered.
|
|
dialog.config_manager.set_language_shortcuts.assert_not_called()
|
|
dialog.language_shortcuts_update_callback.assert_not_called()
|
|
dialog.language_shortcuts_info_label.set_markup.assert_called_once()
|
|
assert dialog._language_shortcut_rows[0]["last_valid_shortcut"] == "alt+d"
|
|
|
|
|
|
def test_refresh_defers_listener_rebuild_while_dictating() -> None:
|
|
"""A binding edit during a session waits for IDLE, it must not stop it."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(entries=[{"shortcut": "alt+d", "language": "de"}])
|
|
tray.speech_engine.state = RecognitionState.LISTENING
|
|
tray._language_shortcuts_refresh_pending = False
|
|
|
|
TrayIndicator.refresh_language_shortcuts(tray)
|
|
|
|
assert tray._language_shortcuts_refresh_pending is True
|
|
tray.speech_engine.stop_recognition.assert_not_called()
|
|
assert tray._language_shortcut_managers == []
|
|
|
|
# The next IDLE transition drains the deferred rebuild.
|
|
tray.speech_engine.state = RecognitionState.IDLE
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
manager = MagicMock()
|
|
manager_class.return_value = manager
|
|
TrayIndicator._update_ui(tray, RecognitionState.IDLE)
|
|
|
|
assert tray._language_shortcuts_refresh_pending is False
|
|
manager_class.assert_called_once_with(shortcut="alt+d", mode="toggle")
|
|
manager.start.assert_called_once()
|
|
|
|
|
|
def test_refresh_rebuilds_immediately_when_idle() -> None:
|
|
"""The normal path still rebuilds the listeners right away."""
|
|
from vocalinux.ui.tray_indicator import TrayIndicator
|
|
|
|
tray = _tray_stub(entries=[{"shortcut": "alt+d", "language": "de"}])
|
|
tray._language_shortcuts_refresh_pending = False
|
|
|
|
with patch("vocalinux.ui.tray_indicator.KeyboardShortcutManager") as manager_class:
|
|
manager = MagicMock()
|
|
manager_class.return_value = manager
|
|
TrayIndicator.refresh_language_shortcuts(tray)
|
|
|
|
assert tray._language_shortcuts_refresh_pending is False
|
|
manager_class.assert_called_once_with(shortcut="alt+d", mode="toggle")
|
|
manager.start.assert_called_once()
|
|
|
|
|
|
def test_language_shortcut_managers_share_the_evdev_device_layer() -> None:
|
|
"""Two per-language managers must not spawn competing evdev readers.
|
|
|
|
Regression test for PR #479 review: each manager used to open and grab
|
|
its own InputDevice on the same keyboard, so only the first grabber
|
|
ever saw events and language shortcuts could not fire on Wayland.
|
|
"""
|
|
from vocalinux.ui.keyboard_backends.evdev_backend import EvdevKeyboardBackend
|
|
from vocalinux.ui.keyboard_shortcuts import KeyboardShortcutManager
|
|
|
|
with patch.object(EvdevKeyboardBackend, "is_available", return_value=True):
|
|
german = KeyboardShortcutManager(backend="evdev", shortcut="alt+d", mode="toggle")
|
|
french = KeyboardShortcutManager(backend="evdev", shortcut="ctrl+alt+f", mode="toggle")
|
|
|
|
assert isinstance(german.backend_instance, EvdevKeyboardBackend)
|
|
assert isinstance(french.backend_instance, EvdevKeyboardBackend)
|
|
assert french.backend_instance._hub is german.backend_instance._hub
|