hex/src/transcription/keyboard_model_switching.rs
Dax 3f5c3d6030
free imported model definitions after rename and removal (#2498)
* free imported model definitions after rename and removal

* silence test-only lints on linux

The new state-machine tests keep macOS-only helpers and imports; clippy on Linux denies them as unused, and one test cloned a selection only to compare it.

* borrow the model definition on macOS-only paths

Meeting audio import and Parakeet's macOS load path still passed the ModelRef by value to model_path, is_installed, and validate_gguf_artifact.

* address review nits on the imported model definitions

Track every rename build with its own Weak, restore the moved doc comments verbatim, name the new registry tests in the feature map, and use is_gguf for the plain runtime checks.
2026-11-23 03:32:00 -05:00

382 lines
14 KiB
Rust

//! Input-source changes are model-picker choices, not recording-time routing.
use std::time::{Duration, Instant};
use crate::app_settings::{KeyboardModelChoice, KeyboardModelSwitching};
use crate::transcription::models::ModelDefinition;
const DEBOUNCE: Duration = Duration::from_millis(300);
const RETRY_BASE: Duration = Duration::from_secs(2);
const RETRY_MAX: Duration = Duration::from_secs(60);
fn retry_backoff(failures: u32) -> Duration {
RETRY_BASE
.saturating_mul(1_u32 << failures.min(5))
.min(RETRY_MAX)
}
/// One enabled keyboard input source, as the settings window lists it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct InputSource {
pub(crate) id: String,
pub(crate) name: String,
/// The source's BCP 47 languages, most specific first (`ru`, `zh-Hans`).
pub(crate) languages: Vec<String>,
}
impl InputSource {
/// The language a new mapping to `model` starts with: the first of this
/// source's languages the model supports, else `fallback`.
pub(crate) fn language_for(&self, model: &ModelDefinition, fallback: &str) -> String {
self.languages
.iter()
.map(|tag| tag.split(['-', '_']).next().unwrap_or(tag))
.find(|code| model.supports_language(code))
.unwrap_or(fallback)
.to_owned()
}
}
/// A native layout's 32 bits as the stable source ID Hex shows and stores,
/// `04190419`.
#[cfg(any(target_os = "windows", test))]
pub(crate) fn source_id(layout: u32) -> String {
format!("{layout:08X}")
}
/// The source a window names from the layout of the process that owns it:
/// Hex's own windows name none, so focusing Settings is not a keyboard change,
/// and a window reporting no layout (a console) names none either. The Windows
/// observer reads the window; this decides what it means.
#[cfg(any(target_os = "windows", test))]
pub(crate) fn source_from_window(
process_id: u32,
own_process_id: u32,
layout: u32,
) -> Option<String> {
(process_id != own_process_id && layout != 0).then(|| source_id(layout))
}
#[derive(Clone, Copy, Debug)]
enum SwitchState {
Idle,
Pending { due: Instant, failures: u32 },
Applying { failures: u32 },
}
/// No models or workers live here: this only admits the latest picker choice.
pub(crate) struct Switcher {
settings: KeyboardModelSwitching,
/// The observed source; unknown while switching is off, so turning it
/// on waits for the observer's first report instead of a stale source.
current: Option<String>,
state: SwitchState,
}
impl Switcher {
pub(crate) fn new(settings: KeyboardModelSwitching, current: Option<String>) -> Self {
Self {
current: current.filter(|_| settings.enabled),
settings,
state: SwitchState::Idle,
}
}
/// Returns true on a real change, so the owner can cancel obsolete work.
pub(crate) fn source_changed(&mut self, source: Option<String>, now: Instant) -> bool {
if !self.settings.enabled || self.current == source {
return false;
}
self.current = source;
self.state = if self.mapped().is_some() {
SwitchState::Pending {
due: now + DEBOUNCE,
failures: 0,
}
} else {
SwitchState::Idle
};
true
}
fn mapped(&self) -> Option<&KeyboardModelChoice> {
self.settings
.enabled
.then(|| self.settings.mappings.get(self.current.as_ref()?))
.flatten()
}
pub(crate) fn take_due(&mut self, now: Instant) -> Option<KeyboardModelChoice> {
let SwitchState::Pending { due, failures } = self.state else {
return None;
};
if now < due {
return None;
}
let choice = self.mapped().cloned();
self.state = if choice.is_some() {
SwitchState::Applying { failures }
} else {
SwitchState::Idle
};
choice
}
pub(crate) fn commit(&mut self) {
if matches!(self.state, SwitchState::Applying { .. }) {
self.state = SwitchState::Idle;
}
}
pub(crate) fn fail(&mut self, now: Instant) {
if let SwitchState::Applying { failures } = self.state {
self.state = if self.mapped().is_some() {
SwitchState::Pending {
due: now + retry_backoff(failures),
failures: failures.saturating_add(1),
}
} else {
SwitchState::Idle
};
}
}
pub(crate) fn cancel_applying(&mut self) {
if matches!(self.state, SwitchState::Applying { .. }) {
self.state = SwitchState::Idle;
}
}
pub(crate) fn manual_choice(&mut self) {
self.state = SwitchState::Idle;
}
/// Only enabling, disabling, or editing the active mapping affects work.
/// Returns true when the owner must supersede an automatic preparation.
pub(crate) fn configure(&mut self, settings: KeyboardModelSwitching, now: Instant) -> bool {
let before = (self.settings.enabled, self.mapped().cloned());
self.settings = settings;
if !self.settings.enabled {
self.current = None;
}
if before == (self.settings.enabled, self.mapped().cloned()) {
return false;
}
self.state = if self.mapped().is_some() {
SwitchState::Pending {
due: now,
failures: 0,
}
} else {
SwitchState::Idle
};
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::transcription::models::{TranscriptionModelId, definition};
fn choice(model: TranscriptionModelId, language: &str) -> KeyboardModelChoice {
KeyboardModelChoice {
model,
language: language.into(),
}
}
fn mapped(entries: &[(&str, KeyboardModelChoice)]) -> KeyboardModelSwitching {
KeyboardModelSwitching {
enabled: true,
mappings: entries
.iter()
.map(|(source, choice)| ((*source).into(), choice.clone()))
.collect(),
}
}
fn spanish() -> KeyboardModelChoice {
choice(TranscriptionModelId::ParakeetV3, "es")
}
#[test]
fn a_mapped_startup_source_does_not_switch_until_its_mapping_is_edited() {
let now = Instant::now();
let mut settings = mapped(&[("Spanish", spanish())]);
let mut switcher = Switcher::new(settings.clone(), Some("Spanish".into()));
assert_eq!(switcher.take_due(now + Duration::from_secs(1)), None);
let whisper = choice(TranscriptionModelId::WhisperLargeV3Turbo, "es");
settings.mappings.insert("Spanish".into(), whisper.clone());
assert!(switcher.configure(settings, now));
assert_eq!(switcher.take_due(now), Some(whisper));
}
#[test]
fn source_changes_are_debounced_and_duplicates_ignored() {
let now = Instant::now();
let mut switcher = Switcher::new(mapped(&[("Spanish", spanish())]), Some("ABC".into()));
assert!(!switcher.source_changed(Some("ABC".into()), now));
assert_eq!(switcher.take_due(now + Duration::from_secs(1)), None);
assert!(switcher.source_changed(Some("Spanish".into()), now));
assert_eq!(switcher.take_due(now + Duration::from_millis(299)), None);
assert_eq!(
switcher.take_due(now + Duration::from_millis(300)),
Some(spanish())
);
assert_eq!(switcher.take_due(now + Duration::from_secs(1)), None);
}
#[test]
fn a_language_only_edit_of_the_active_mapping_applies_now() {
let now = Instant::now();
let mut settings = mapped(&[("Russian", choice(TranscriptionModelId::ParakeetV3, "en"))]);
let mut switcher = Switcher::new(settings.clone(), Some("Russian".into()));
let russian = choice(TranscriptionModelId::ParakeetV3, "ru");
settings.mappings.insert("Russian".into(), russian.clone());
assert!(switcher.configure(settings, now));
assert_eq!(switcher.take_due(now), Some(russian));
}
#[test]
fn a_manual_choice_cancels_the_pending_switch_until_another_source_change() {
let now = Instant::now();
let mut switcher = Switcher::new(mapped(&[("Spanish", spanish())]), Some("ABC".into()));
switcher.source_changed(Some("Spanish".into()), now);
switcher.manual_choice();
assert_eq!(switcher.take_due(now + Duration::from_secs(1)), None);
// Duplicate native notifications must not undo the manual choice.
assert!(!switcher.source_changed(Some("Spanish".into()), now));
assert_eq!(switcher.take_due(now + Duration::from_secs(2)), None);
}
#[test]
fn enabling_or_editing_the_active_mapping_applies_now_but_other_edits_do_not() {
let now = Instant::now();
let mut switcher = Switcher::new(KeyboardModelSwitching::default(), None);
let mut settings = mapped(&[("Spanish", spanish())]);
// Enabling waits for the observer's report of the current source.
assert!(switcher.configure(settings.clone(), now));
assert_eq!(switcher.take_due(now), None);
assert!(switcher.source_changed(Some("Spanish".into()), now));
assert_eq!(switcher.take_due(now + DEBOUNCE), Some(spanish()));
settings.mappings.insert(
"ABC".into(),
choice(TranscriptionModelId::ParakeetUnifiedEnglish, "en"),
);
assert!(!switcher.configure(settings.clone(), now));
assert_eq!(switcher.take_due(now), None);
let whisper = choice(TranscriptionModelId::WhisperLargeV3Turbo, "es");
settings.mappings.insert("Spanish".into(), whisper.clone());
assert!(switcher.configure(settings.clone(), now));
assert_eq!(switcher.take_due(now), Some(whisper));
settings.enabled = false;
assert!(switcher.configure(settings, now));
assert_eq!(switcher.take_due(now), None);
}
#[test]
fn cycling_past_a_source_only_switches_to_the_last_mapping() {
let now = Instant::now();
let french = choice(TranscriptionModelId::WhisperLargeV3Turbo, "fr");
let mut switcher = Switcher::new(
mapped(&[("French", french), ("Spanish", spanish())]),
Some("ABC".into()),
);
switcher.source_changed(Some("French".into()), now);
switcher.source_changed(Some("Spanish".into()), now + Duration::from_millis(100));
assert_eq!(switcher.take_due(now + Duration::from_millis(300)), None);
assert_eq!(
switcher.take_due(now + Duration::from_millis(400)),
Some(spanish())
);
switcher.source_changed(Some("French".into()), now + Duration::from_secs(1));
switcher.source_changed(Some("ABC".into()), now + Duration::from_millis(1100));
assert_eq!(switcher.take_due(now + Duration::from_secs(2)), None);
}
#[test]
fn turning_off_the_feature_cancels_a_debounced_switch_and_forgets_the_source() {
let now = Instant::now();
let mut settings = mapped(&[("Spanish", spanish())]);
let mut switcher = Switcher::new(settings.clone(), Some("ABC".into()));
switcher.source_changed(Some("Spanish".into()), now);
settings.enabled = false;
switcher.configure(settings.clone(), now + Duration::from_millis(100));
assert_eq!(switcher.take_due(now + Duration::from_secs(1)), None);
assert!(!switcher.source_changed(Some("ABC".into()), now));
assert!(!switcher.source_changed(Some("Spanish".into()), now));
assert_eq!(switcher.take_due(now + Duration::from_secs(2)), None);
// Turning it back on does not act on the source seen before.
settings.enabled = true;
switcher.configure(settings, now);
assert_eq!(switcher.take_due(now + Duration::from_secs(3)), None);
}
#[test]
fn a_new_mapping_starts_in_the_sources_language_when_the_model_has_it() {
let source = InputSource {
id: "com.apple.keylayout.Russian".into(),
name: "Russian".into(),
languages: vec!["ru".into(), "en-US".into()],
};
let v3 = definition(TranscriptionModelId::ParakeetV3);
let english = definition(TranscriptionModelId::ParakeetUnifiedEnglish);
assert_eq!(source.language_for(&v3, "en"), "ru");
assert_eq!(source.language_for(&english, "en"), "en");
let unknown = InputSource {
languages: vec!["xx".into()],
..source
};
assert_eq!(unknown.language_for(&v3, "de"), "de");
}
#[test]
fn keyboard_source_ignores_hexs_own_window() {
assert_eq!(source_from_window(7, 7, 0x0419_0419), None);
}
#[test]
fn keyboard_source_is_another_processs_layout_id() {
assert_eq!(
source_from_window(8, 7, 0x0419_0419).as_deref(),
Some("04190419")
);
}
#[test]
fn keyboard_source_is_none_without_a_layout() {
assert_eq!(source_from_window(8, 7, 0), None);
}
#[test]
fn a_failed_keyboard_switch_retries_with_bounded_backoff_until_committed() {
let now = Instant::now();
let mut switcher = Switcher::new(mapped(&[("Spanish", spanish())]), Some("ABC".into()));
assert!(switcher.source_changed(Some("Spanish".into()), now));
assert_eq!(switcher.take_due(now + DEBOUNCE), Some(spanish()));
// While applying, duplicate ticks do not fire again.
assert_eq!(switcher.take_due(now + Duration::from_secs(5)), None);
let fail_1 = now + DEBOUNCE;
switcher.fail(fail_1);
assert_eq!(
switcher.take_due(fail_1 + Duration::from_millis(1_999)),
None
);
assert_eq!(switcher.take_due(fail_1 + RETRY_BASE), Some(spanish()));
let fail_2 = fail_1 + RETRY_BASE;
switcher.fail(fail_2);
assert_eq!(
switcher.take_due(fail_2 + Duration::from_millis(3_999)),
None
);
assert_eq!(
switcher.take_due(fail_2 + Duration::from_secs(4)),
Some(spanish())
);
switcher.commit();
assert_eq!(switcher.take_due(fail_2 + Duration::from_secs(120)), None);
}
}