Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

119 KB
Raw Blame
//! Talk to your agent: hold a key, talk and point, let go, and Clipy pastes
//! what you said plus the path of the take's AREC where you were typing.
//! A second key dictates: only the microphone is captured and only the words
//! are pasted (`dictation.rs`); nothing is recorded.
//!
//! A show take is a short Local take with nothing new underneath. The
//! capture, live transcript, Flare (hold Control to point) and the AREC are
//! the ordinary Local pipeline; this module only adds the keys, the lifecycle
//! around one take, and the paste at the end. A dictation shares the keys,
//! the lifecycle and the paste, and swaps the recording for a microphone
//! capture with its own live transcript.
//!
//! Keys (Settings → Shortcuts), one per kind of take:
//! - Show (Option by default): words and recording.
//! - Dictate (Control by default): words only. Flare is off during a
//!   dictation take, since holding Control is how it is started.
//! - Hold a key to talk; letting go stops the take and pastes.
//! - Double-tap it to talk hands-free; tap it once more to stop and paste.
//! - Esc throws the take away and pastes nothing.
//! - While showing, hold Control to point, exactly as in any recording.
//!
//! Rules this module keeps:
//! - A hold only starts after `HOLD_START_MS`, and a hold that turns into a
//!   shortcut (Fn+F1, Fn+arrow, Option+letter) never starts anything.
//! - It never starts over a recording that is already running (a person's
//!   or an agent's), and a take stopped from the recording controls still
//!   pastes, since the user asked for it.
//! - The paste waits a few seconds for the transcript and never for moment
//!   selection: the AREC path is usable at once (it says Preparing) and is
//!   updated in place, which is what an agent reads.
//! - A failure never loses a show take; it stays in Local recordings, and the
//!   notification says what happened. A dictation keeps nothing: its audio
//!   lives in memory until the paste.
//! - A recording that starts during a dictation wins: the dictation ends
//!   with nothing pasted and says so.
//!
//! Windows: Show and Dictate. The keys are read by
//! polling `GetAsyncKeyState` every 15 ms, the same model as the Mac's
//! `CGEventSourceKeyState` polling, into the same `TalkTracker`: no
//! low-level keyboard hook, so Clipy can never slow down or swallow anyone's
//! typing (Windows removes a hook that answers slowly, and every keystroke
//! system-wide waits on it). Dictation's words come from the model
//! downloaded in Settings → Transcription, run on the PC after the release;
//! a Show take is a Local take transcribed by that model or by Clipy. Both
//! paste with Ctrl+V (`SendInput`). Allowed Windows keys: Ctrl, Right Ctrl
//! (dictate default), Right Shift (show default) and F1 to F20
//! (`win_allowed`).
//! Alt is refused (letting it go alone opens the focused app's menu, which
//! would take the paste), and so is the Windows key (Win+H is Windows' own
//! voice typing, and Win+letter shortcuts are everywhere).

use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::Serialize;
use tauri::AppHandle;
use tauri_plugin_store::StoreExt;

/// A press held this long without another key starts a hold-to-talk take.
/// Longer than a tap, so a quick Fn press (emoji picker, input source) does
/// not start recording.
pub(crate) const HOLD_START_MS: u64 = 300;
/// A press shorter than this, with no other key, counts as a tap.
pub(crate) const TAP_MAX_MS: u64 = 250;
/// The second press of a double tap must come within this of the first
/// release.
pub(crate) const DOUBLE_TAP_GAP_MS: u64 = 350;
/// Shorter takes are treated as an accident and discarded.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const MIN_TAKE: Duration = Duration::from_millis(800);
/// A take stops by itself after this, as if the key were let go. A
/// dictation keeps at most this much audio in memory (`dictation.rs`).
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const MAX_TAKE: Duration = Duration::from_secs(300);
/// How long a take stopped from the recording controls has to be sealed or
/// discarded before the paste gives up on it.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const EXTERNAL_STOP_WAIT: Duration = Duration::from_secs(10);
/// How long a show take's paste waits for the transcript before pasting the
/// path without it.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const WORDS_WAIT: Duration = Duration::from_secs(6);

/// The show key (words and recording). The name predates dictation.
const KEY_STORE: &str = "talk_key";
const DICTATE_KEY_STORE: &str = "dictate_key";
/// Pause playing media for the length of a take. Off unless turned on.
const PAUSE_MEDIA_STORE: &str = "talk_pause_media";

/// The two kinds of talk take, each with its own key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TalkKind {
    /// Words and the recording's AREC path: the agent sees what you showed.
    Show,
    /// Words only, like dictation. Only the microphone is captured.
    Dictate,
}

impl TalkKind {
    pub(crate) fn parse(value: &str) -> Option<Self> {
        match value {
            "show" => Some(Self::Show),
            "dictate" => Some(Self::Dictate),
            _ => None,
        }
    }
}

/// Which key talks. Stored as its `as_str`; set from Settings → Shortcuts.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum TalkKey {
    Off,
    /// Either Option key, the default. Control was the default briefly but
    /// clashed with Flare.
    #[default]
    Option,
    RightOption,
    /// Either Control key. Holding it during a take is also Flare.
    Control,
    /// The right Ctrl key alone (Windows' default dictate key).
    RightControl,
    /// The Fn / Globe key.
    Fn,
    RightShift,
    /// F1 to F20, by number.
    Function(u8),
}

const FUNCTION_NAMES: [&str; 20] = [
    "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14",
    "f15", "f16", "f17", "f18", "f19", "f20",
];
/// macOS virtual keycodes of F1 to F20.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const FUNCTION_KEYCODES: [u16; 20] = [
    122, 120, 99, 118, 96, 97, 98, 100, 101, 109, 103, 111, 105, 107, 113, 106, 64, 79, 80, 90,
];

impl TalkKey {
    /// Whether two keys share a physical key, so one press would start both
    /// kinds of take: the same key, or Option (either side) with Right Option.
    pub(crate) fn overlaps(self, other: Self) -> bool {
        if self == Self::Off || other == Self::Off {
            return false;
        }
        self == other
            || matches!(
                (self, other),
                (Self::Option, Self::RightOption)
                    | (Self::RightOption, Self::Option)
                    | (Self::Control, Self::RightControl)
                    | (Self::RightControl, Self::Control)
            )
    }

    pub(crate) fn parse(value: &str) -> Option<Self> {
        match value {
            "off" => Some(Self::Off),
            "option" => Some(Self::Option),
            "right_option" => Some(Self::RightOption),
            "control" => Some(Self::Control),
            "right_control" => Some(Self::RightControl),
            "fn" => Some(Self::Fn),
            "right_shift" => Some(Self::RightShift),
            other => FUNCTION_NAMES
                .iter()
                .position(|name| *name == other)
                .map(|i| Self::Function(i as u8 + 1)),
        }
    }

    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Option => "option",
            Self::RightOption => "right_option",
            Self::Control => "control",
            Self::RightControl => "right_control",
            Self::Fn => "fn",
            Self::RightShift => "right_shift",
            Self::Function(n) => FUNCTION_NAMES[(n.clamp(1, 20) - 1) as usize],
        }
    }

    /// The keycode of a function key, so it is not read as "another key".
    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
    fn keycode(self) -> Option<u16> {
        match self {
            Self::Function(n) => Some(FUNCTION_KEYCODES[(n.clamp(1, 20) - 1) as usize]),
            _ => None,
        }
    }
}

/// The paste for a finished take, or `None` when there is nothing to paste
/// (dictation, and nothing was heard). A dictation has no AREC; its `arec`
/// is ignored.
pub(crate) fn compose_paste(kind: TalkKind, words: Option<&str>, arec: &Path) -> Option<String> {
    let words = words.map(str::trim).filter(|w| !w.is_empty());
    let path = arec.to_string_lossy();
    match kind {
        TalkKind::Dictate => words.map(str::to_string),
        TalkKind::Show => Some(match words {
            Some(words) => format!("{words}\n\nClipy recording: {path}"),
            None => format!("Clipy recording: {path}"),
        }),
    }
}

// ---------- Key tracking (pure, tested on every platform) ----------

/// One reading of the keys.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct TalkKeys {
    /// The talk key is down.
    pub trigger: bool,
    /// A key that is not a modifier is down too (Esc not included).
    pub other_key: bool,
    pub escape: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TalkMode {
    Hold,
    HandsFree,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TalkAction {
    Start(TalkMode),
    Stop,
    Cancel,
}

/// Turns key readings into start, stop and cancel.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct TalkTracker {
    down_since: Option<u64>,
    /// Another key went down during this press: it is a shortcut.
    chorded: bool,
    /// When the last clean tap ended, for a double tap.
    last_tap_up: Option<u64>,
    active: Option<TalkMode>,
    /// The current press already did its job (started hands-free or stopped
    /// it); its release does nothing.
    swallow: bool,
    /// Ignore the key until it is let go: it was held while the other kind
    /// of take ran (Control pointing during a show take).
    wait_release: bool,
}

impl TalkTracker {
    pub(crate) fn active(&self) -> Option<TalkMode> {
        self.active
    }

    /// The take ended elsewhere (stopped from the controls, failed to
    /// start): forget it without acting on the keys still held.
    pub(crate) fn clear_active(&mut self) {
        if self.active.take().is_some() && self.down_since.is_some() {
            self.swallow = true;
        }
    }

    /// The other kind of take is running: forget everything, and ignore
    /// this key until it has been let go, so a key still held when that take
    /// ends does not start one of its own.
    pub(crate) fn hold_off(&mut self) {
        *self = Self {
            wait_release: true,
            ..Self::default()
        };
    }

    pub(crate) fn update(&mut self, keys: TalkKeys, now_ms: u64) -> Option<TalkAction> {
        if self.wait_release {
            if keys.trigger {
                return None;
            }
            self.wait_release = false;
        }
        if keys.escape {
            self.last_tap_up = None;
            if self.active.take().is_some() {
                if keys.trigger || self.down_since.is_some() {
                    self.down_since.get_or_insert(now_ms);
                    self.swallow = true;
                }
                return Some(TalkAction::Cancel);
            }
        }

        match (keys.trigger, self.down_since) {
            // Pressed.
            (true, None) => {
                self.down_since = Some(now_ms);
                self.chorded = keys.other_key || keys.escape;
                // Hands-free stops on a clean tap, decided at release: a
                // longer press is the user holding Control to point (Flare).
                if self.active == Some(TalkMode::HandsFree) {
                    return None;
                }
                let double = self
                    .last_tap_up
                    .take()
                    .is_some_and(|up| now_ms.saturating_sub(up) <= DOUBLE_TAP_GAP_MS);
                if self.active.is_none() && double && !self.chorded {
                    self.active = Some(TalkMode::HandsFree);
                    self.swallow = true;
                    return Some(TalkAction::Start(TalkMode::HandsFree));
                }
                None
            }
            // Held.
            (true, Some(since)) => {
                if keys.other_key || keys.escape {
                    self.chorded = true;
                    // A key pressed while holding to talk means the hold was
                    // a shortcut (Ctrl+C after a slow press): throw it away
                    // rather than paste on release.
                    if self.active == Some(TalkMode::Hold) {
                        self.active = None;
                        self.swallow = true;
                        return Some(TalkAction::Cancel);
                    }
                }
                if self.active.is_none()
                    && !self.chorded
                    && !self.swallow
                    && now_ms.saturating_sub(since) >= HOLD_START_MS
                {
                    self.active = Some(TalkMode::Hold);
                    return Some(TalkAction::Start(TalkMode::Hold));
                }
                None
            }
            // Released.
            (false, Some(since)) => {
                let held = now_ms.saturating_sub(since);
                let chorded = self.chorded;
                let swallow = self.swallow;
                self.down_since = None;
                self.chorded = false;
                self.swallow = false;
                if swallow {
                    return None;
                }
                if self.active == Some(TalkMode::Hold) {
                    self.active = None;
                    return Some(TalkAction::Stop);
                }
                if self.active == Some(TalkMode::HandsFree) {
                    if !chorded && held < TAP_MAX_MS {
                        self.active = None;
                        return Some(TalkAction::Stop);
                    }
                    return None;
                }
                if self.active.is_none() && !chorded && held < TAP_MAX_MS {
                    self.last_tap_up = Some(now_ms);
                }
                None
            }
            (false, None) => None,
        }
    }
}

// ---------- Settings ----------

fn stored_key(app: &AppHandle, store_key: &str) -> Option<TalkKey> {
    app.store(crate::commands::SETTINGS_STORE)
        .ok()
        .and_then(|s| s.get(store_key))
        .and_then(|v| v.as_str().and_then(TalkKey::parse))
}

/// The Mac's defaults: Option shows, Control dictates.
pub(crate) const MAC_DEFAULT_KEYS: (TalkKey, TalkKey) = (TalkKey::Option, TalkKey::Control);
/// Windows' defaults: Right Shift shows, Right Ctrl dictates. Both are
/// rarely pressed alone (capitals and one-handed shortcuts use the left
/// keys, and a letter pressed with either makes the press a shortcut), they
/// open no menu when let go (Alt does), and they leave the Windows key, and
/// Win+H voice typing, to Windows.
pub(crate) const WINDOWS_DEFAULT_KEYS: (TalkKey, TalkKey) = (TalkKey::RightShift, TalkKey::RightControl);

#[cfg(target_os = "windows")]
const DEFAULT_KEYS: (TalkKey, TalkKey) = WINDOWS_DEFAULT_KEYS;
#[cfg(not(target_os = "windows"))]
const DEFAULT_KEYS: (TalkKey, TalkKey) = MAC_DEFAULT_KEYS;

/// Both keys, with this platform's defaults applied.
pub(crate) fn resolve_keys(show: Option<TalkKey>, dictate: Option<TalkKey>) -> (TalkKey, TalkKey) {
    resolve_keys_from(show, dictate, DEFAULT_KEYS)
}

/// Both keys, with `defaults` applied. The two never share a physical key;
/// if they somehow do, showing keeps it.
pub(crate) fn resolve_keys_from(
    show: Option<TalkKey>,
    dictate: Option<TalkKey>,
    defaults: (TalkKey, TalkKey),
) -> (TalkKey, TalkKey) {
    let show = show.unwrap_or(defaults.0);
    let dictate = dictate.unwrap_or(defaults.1);
    let dictate = if dictate.overlaps(show) {
        TalkKey::Off
    } else {
        dictate
    };
    (show, dictate)
}

/// Windows: a key Windows cannot use (a Mac key name in settings copied
/// over) reads as that kind's default.
pub(crate) fn windows_keys(show: Option<TalkKey>, dictate: Option<TalkKey>) -> (TalkKey, TalkKey) {
    let allowed = |key: Option<TalkKey>| key.filter(|key| win_allowed(*key));
    resolve_keys_from(allowed(show), allowed(dictate), WINDOWS_DEFAULT_KEYS)
}

/// The show key and the dictate key.
pub(crate) fn talk_keys(app: &AppHandle) -> (TalkKey, TalkKey) {
    let show = stored_key(app, KEY_STORE);
    let dictate = stored_key(app, DICTATE_KEY_STORE);
    if cfg!(target_os = "windows") {
        windows_keys(show, dictate)
    } else {
        resolve_keys(show, dictate)
    }
}

/// Whether Windows can use `key` to talk: Ctrl, Right Ctrl, Right Shift and
/// F1 to F20 (Off clears it). Not Alt (letting it go alone opens the
/// focused app's menu, which would take the paste), not Fn (keyboards
/// handle it themselves; Windows never sees it), not the Windows key.
pub(crate) fn win_allowed(key: TalkKey) -> bool {
    matches!(
        key,
        TalkKey::Off
            | TalkKey::Control
            | TalkKey::RightControl
            | TalkKey::RightShift
            | TalkKey::Function(_)
    )
}

/// Whether to pause playing media during a take; an unset value reads as off.
pub(crate) fn pause_media(app: &AppHandle) -> bool {
    app.store(crate::commands::SETTINGS_STORE)
        .ok()
        .and_then(|s| s.get(PAUSE_MEDIA_STORE))
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TalkSettingsDto {
    /// False where talk is not built yet (everything but macOS and Windows).
    supported: bool,
    /// Show (words and a recording) is built here.
    show_supported: bool,
    /// Pausing media during a take is built here: macOS only for now.
    pause_media_supported: bool,
    /// `mac` or `windows`: which keys Settings offers and how it names them.
    platform: &'static str,
    /// The show key: words and recording.
    key: &'static str,
    /// The dictate key: words only.
    dictate_key: &'static str,
    /// Pause Apple Music, Spotify or the TV app while a take runs.
    pause_media: bool,
    /// What macOS does on a Fn press: `nothing`, `input_source`, `emoji`,
    /// `dictation`, or `None` when it could not be read. Anything but
    /// `nothing` opens on top of a Fn take, so Settings says how to change it.
    fn_usage: Option<&'static str>,
}

#[tauri::command]
pub fn get_talk_settings(app: AppHandle) -> TalkSettingsDto {
    let (show, dictate) = talk_keys(&app);
    TalkSettingsDto {
        supported: supported_here(),
        show_supported: supported_here(),
        pause_media_supported: cfg!(target_os = "macos"),
        platform: if cfg!(target_os = "windows") { "windows" } else { "mac" },
        key: show.as_str(),
        dictate_key: dictate.as_str(),
        pause_media: pause_media(&app),
        fn_usage: fn_usage(),
    }
}

#[tauri::command]
pub fn set_talk_settings(
    app: AppHandle,
    key: Option<String>,
    dictate_key: Option<String>,
    pause_media: Option<bool>,
) -> Result<(), String> {
    let store = app
        .store(crate::commands::SETTINGS_STORE)
        .map_err(|e| e.to_string())?;
    let parse = |value: &str, kind: TalkKind| -> Result<TalkKey, String> {
        let parsed = TalkKey::parse(value).ok_or_else(|| format!("unknown talk key: {value}"))?;
        key_allowed_here(parsed, kind)?;
        Ok(parsed)
    };
    let (show, dictate) = talk_keys(&app);
    let show_next = key.as_deref().map(|v| parse(v, TalkKind::Show)).transpose()?;
    let dictate_next = dictate_key
        .as_deref()
        .map(|v| parse(v, TalkKind::Dictate))
        .transpose()?;
    let (show_final, dictate_final) = (show_next.unwrap_or(show), dictate_next.unwrap_or(dictate));
    if show_final.overlaps(dictate_final) {
        return Err(crate::i18n::t("errors.talkKeyInUse"));
    }
    if let Some(next) = show_next {
        store.set(KEY_STORE, serde_json::json!(next.as_str()));
    }
    if let Some(next) = dictate_next {
        store.set(DICTATE_KEY_STORE, serde_json::json!(next.as_str()));
    }
    if let Some(on) = pause_media {
        if on && !cfg!(target_os = "macos") {
            return Err("Pausing media while talking is available on Mac only for now".into());
        }
        store.set(PAUSE_MEDIA_STORE, serde_json::json!(on));
    }
    store.save().map_err(|e| e.to_string())?;
    if pause_media == Some(true) {
        // Ask for Automation access now, not during the first take.
        crate::media_pause::request_permission();
    }
    Ok(())
}

/// Whether talk is built here: macOS, and the official Windows app. Clipy
/// Local on Windows keeps its own transcription settings, which Dictate does
/// not read yet, so it has no Dictate key.
fn supported_here() -> bool {
    cfg!(target_os = "macos") || false
}

/// Whether this platform can use `key` for `kind`. Off is always allowed.
fn key_allowed_here(key: TalkKey, kind: TalkKind) -> Result<(), String> {
    if key == TalkKey::Off {
        return Ok(());
    }
    if cfg!(target_os = "macos") {
        // The Mac never captures Right Ctrl (`captured_key`).
        return if key == TalkKey::RightControl {
            Err(crate::i18n::t("errors.talkKeyUnsupported"))
        } else {
            Ok(())
        };
    }
    if cfg!(target_os = "windows") && supported_here() {
        let _ = kind;
        return if win_allowed(key) {
            Ok(())
        } else {
            Err(crate::i18n::t("errors.talkKeyUnsupportedWindows"))
        };
    }
    Err("Talk to your agent is not available on this platform".into())
}

/// Settings → Shortcuts: waits for the next key pressed on its own and saves
/// it as the show key (`kind` "show" or absent) or the dictate key
/// ("dictate"). `None` when the capture was cancelled (Esc, a click, 15
/// seconds); `Err` names a key that cannot talk or is the other kind's key.
#[tauri::command]
pub async fn capture_talk_key(
    app: AppHandle,
    kind: Option<String>,
) -> Result<Option<&'static str>, String> {
    let kind = match kind.as_deref() {
        None => TalkKind::Show,
        Some(value) => TalkKind::parse(value).ok_or_else(|| format!("unknown talk kind: {value}"))?,
    };
    #[cfg(target_os = "macos")]
    {
        let captured = tauri::async_runtime::spawn_blocking(mac::capture_key)
            .await
            .map_err(|e| e.to_string())??;
        let Some(key) = captured else {
            return Ok(None);
        };
        let value = Some(key.as_str().to_string());
        match kind {
            TalkKind::Show => set_talk_settings(app, value, None, None)?,
            TalkKind::Dictate => set_talk_settings(app, None, value, None)?,
        }
        Ok(Some(key.as_str()))
    }
    #[cfg(target_os = "windows")]
    {
        let captured = tauri::async_runtime::spawn_blocking(win::capture_key)
            .await
            .map_err(|e| e.to_string())??;
        let Some(key) = captured else {
            return Ok(None);
        };
        let value = Some(key.as_str().to_string());
        match kind {
            TalkKind::Show => set_talk_settings(app, value, None, None)?,
            TalkKind::Dictate => set_talk_settings(app, None, value, None)?,
        }
        Ok(Some(key.as_str()))
    }
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    {
        let _ = (app, kind);
        Err("Talk to your agent is not available on this platform".into())
    }
}

#[tauri::command]
pub fn cancel_talk_key_capture() {
    #[cfg(target_os = "macos")]
    mac::cancel_capture();
    #[cfg(target_os = "windows")]
    win::cancel_capture();
}

/// `AppleFnUsageType` from `com.apple.HIToolbox`: 0 do nothing, 1 change
/// input source, 2 emoji and symbols, 3 start dictation.
#[cfg(target_os = "macos")]
fn fn_usage() -> Option<&'static str> {
    let output = std::process::Command::new("/usr/bin/defaults")
        .args(["read", "com.apple.HIToolbox", "AppleFnUsageType"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    match String::from_utf8_lossy(&output.stdout).trim() {
        "0" => Some("nothing"),
        "1" => Some("input_source"),
        "2" => Some("emoji"),
        "3" => Some("dictation"),
        _ => None,
    }
}

#[cfg(not(target_os = "macos"))]
fn fn_usage() -> Option<&'static str> {
    None
}

/// Whether a talk take is running, from the key press until its paste. Such
/// a take stays out of view: the popover is not brought back after it.
pub(crate) fn take_in_progress() -> bool {
    #[cfg(target_os = "macos")]
    {
        mac::session_active()
    }
    #[cfg(target_os = "windows")]
    {
        win::session_active()
    }
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    {
        false
    }
}

/// Starts the key watcher. Safe to call once at launch; does nothing off
/// macOS and Windows.
pub fn init(app: &AppHandle) {
    #[cfg(target_os = "macos")]
    mac::init(app);
    #[cfg(target_os = "windows")]
    if supported_here() {
        win::init(app);
    }
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    let _ = app;
}

// CGEventFlags: the generic modifier masks, and the device-dependent bits
// (NX_DEVICE*KEYMASK) that tell left from right. CGEventSourceKeyState
// reports both Option keys as 58, so sides come only from these flags.
const SHIFT_FLAG: u64 = 0x0002_0000;
const CONTROL_FLAG: u64 = 0x0004_0000;
const OPTION_FLAG: u64 = 0x0008_0000;
const COMMAND_FLAG: u64 = 0x0010_0000;
const LEFT_SHIFT_BIT: u64 = 0x2;
const RIGHT_SHIFT_BIT: u64 = 0x4;
const LEFT_OPTION_BIT: u64 = 0x20;
const RIGHT_OPTION_BIT: u64 = 0x40;

/// For a modifier talk key: whether it is down, and whether another modifier
/// is down with it, which makes the press a shortcut (Option+Shift, the
/// Control+Shift pointer). Control stays free with every key but Control
/// itself, so Flare can point during a take. Command is never a talk key:
/// Flare ignores Control while Command is held. `None` for keys that are not
/// modifiers.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn modifier_keys(key: TalkKey, flags: u64) -> Option<(bool, bool)> {
    let has = |mask: u64| flags & mask != 0;
    Some(match key {
        TalkKey::Option => (has(OPTION_FLAG), has(SHIFT_FLAG | COMMAND_FLAG)),
        TalkKey::RightOption => (
            has(OPTION_FLAG) && has(RIGHT_OPTION_BIT),
            has(SHIFT_FLAG | COMMAND_FLAG),
        ),
        TalkKey::Control => (has(CONTROL_FLAG), has(SHIFT_FLAG | OPTION_FLAG | COMMAND_FLAG)),
        TalkKey::RightShift => (
            has(SHIFT_FLAG) && has(RIGHT_SHIFT_BIT),
            has(COMMAND_FLAG | OPTION_FLAG),
        ),
        // Right Ctrl is a Windows key; the Mac never captures it.
        TalkKey::Off | TalkKey::Fn | TalkKey::RightControl | TalkKey::Function(_) => return None,
    })
}

/// The talk key a single press stands for, from the flags and the keycodes
/// held, for Settings → Shortcuts. `Err` names a key that cannot talk.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn captured_key(flags: u64, fn_down: bool, keys_down: &[u16]) -> Option<Result<TalkKey, ()>> {
    const FN_FLAG: u64 = 0x0080_0000;
    let has = |mask: u64| flags & mask != 0;
    let modifiers = [
        (has(OPTION_FLAG) && has(RIGHT_OPTION_BIT), Ok(TalkKey::RightOption)),
        (has(OPTION_FLAG) && has(LEFT_OPTION_BIT), Ok(TalkKey::Option)),
        (has(CONTROL_FLAG), Ok(TalkKey::Control)),
        // Command never talks: Flare ignores Control while it is held.
        (has(COMMAND_FLAG), Err(())),
        (has(SHIFT_FLAG) && has(RIGHT_SHIFT_BIT), Ok(TalkKey::RightShift)),
        (has(SHIFT_FLAG) && has(LEFT_SHIFT_BIT), Err(())),
        (fn_down || has(FN_FLAG), Ok(TalkKey::Fn)),
    ];
    let mut held: Vec<Result<TalkKey, ()>> = modifiers
        .into_iter()
        .filter(|(down, _)| *down)
        .map(|(_, key)| key)
        .collect();
    for code in keys_down {
        held.push(
            FUNCTION_KEYCODES
                .iter()
                .position(|c| c == code)
                .map(|i| TalkKey::Function(i as u8 + 1))
                .ok_or(()),
        );
    }
    match held.len() {
        0 => None,
        1 => held.pop(),
        _ => Some(Err(())),
    }
}

/// Where a take's transcript stands when the paste reads it.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Words {
    /// Transcription finished; `None` when nothing was heard.
    Done(Option<String>),
    /// Processing failed, or the wait ran out while it was still going.
    NotReady,
}

/// What a take's status stage means for its words: `None` while they are
/// still coming.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn words_settled(stage: &str) -> Option<bool> {
    match stage {
        "recording" | "transcribing" => None,
        "failed" => Some(false),
        _ => Some(true),
    }
}

/// The words of a take's transcript once it has settled, for the paste.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
async fn wait_for_words(dir: &Path, wait: Duration) -> Words {
    let deadline = std::time::Instant::now() + wait;
    loop {
        match crate::local::read_status(dir).and_then(|s| words_settled(&s.stage)) {
            Some(true) => return Words::Done(crate::local::transcript_words(dir)),
            Some(false) => return Words::NotReady,
            None => {}
        }
        if std::time::Instant::now() >= deadline {
            return Words::NotReady;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

/// Starts loading the chosen model while the user is still talking, so the
/// words come back without the model's load time after the key is let go.
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn prewarm_model(app: &AppHandle) {
    if let Some(model) = crate::transcription_models::chosen_model(app) {
        tauri::async_runtime::spawn_blocking(move || {
            let words = crate::transcription_dictionary::saved_prompt_words();
            crate::transcription_models::prewarm(model, &words);
        });
    }
}

#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn notify(app: &AppHandle, body: &str) {
    use tauri_plugin_notification::NotificationExt;
    let _ = app
        .notification()
        .builder()
        .title(crate::i18n::t("notifications.talkTitle"))
        .body(body)
        .show();
}

#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn arec_of(dir: &Path) -> PathBuf {
    dir.join("recording.arec")
}

/// How a take ended when it was stopped outside the talk key: `Some(true)`
/// once it was sealed (`metadata.json`), `Some(false)` once it was discarded
/// (the `cancelled` marker `local::cancel` writes, or the folder already
/// trashed), `None` while it is still undecided. Discard empties the active
/// recording before it marks the take, so "no active recording" alone does
/// not mean the take was kept.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn external_outcome(dir: &Path) -> Option<bool> {
    if !dir.exists() || dir.join("cancelled").exists() {
        Some(false)
    } else if dir.join("metadata.json").exists() {
        Some(true)
    } else {
        None
    }
}

/// Waits for `external_outcome` to decide. Undecided after the wait counts
/// as not kept: pasting the path of a take that may be gone is worse than
/// pasting nothing, and the take stays in Local recordings either way.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
async fn kept_after_external_stop(dir: &Path) -> bool {
    let deadline = std::time::Instant::now() + EXTERNAL_STOP_WAIT;
    loop {
        if let Some(kept) = external_outcome(dir) {
            return kept;
        }
        if std::time::Instant::now() >= deadline {
            return false;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

// ---------- Windows key reading (pure, tested on every platform) ----------

/// Windows virtual-key codes this module reads.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) mod vk {
    pub const SHIFT: u16 = 0x10;
    pub const CONTROL: u16 = 0x11;
    pub const MENU: u16 = 0x12;
    pub const ESCAPE: u16 = 0x1B;
    pub const F1: u16 = 0x70;
    pub const F20: u16 = 0x83;
    pub const LSHIFT: u16 = 0xA0;
    pub const RSHIFT: u16 = 0xA1;
    pub const LCONTROL: u16 = 0xA2;
    pub const RCONTROL: u16 = 0xA3;
    /// Mouse buttons: left, right, middle, X1, X2 (3 is Cancel).
    pub const MOUSE: [u16; 5] = [0x01, 0x02, 0x04, 0x05, 0x06];
    /// Every keyboard key code: from Backspace to the last OEM code. Mouse
    /// buttons (below 8) are not in it.
    pub const KEYS: std::ops::RangeInclusive<u16> = 0x08..=0xFE;
}

/// The display a point is on, from `(id, x, y, width, height)` rects in the
/// same pixel space as the point. `None` when it is on none of them: the
/// caller refuses to start rather than record another display.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) fn display_at(displays: &[(u32, f64, f64, u32, u32)], x: i32, y: i32) -> Option<u32> {
    let (x, y) = (f64::from(x), f64::from(y));
    displays
        .iter()
        .find(|(_, left, top, w, h)| {
            x >= *left && y >= *top && x < left + f64::from(*w) && y < top + f64::from(*h)
        })
        .map(|(id, ..)| *id)
}

/// The codes that are the talk key itself on Windows (the generic code
/// Windows also reports, and the sided one), so they are not read as
/// "another key".
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn win_own_keys(key: TalkKey) -> Vec<u16> {
    match key {
        TalkKey::Control => vec![vk::CONTROL, vk::LCONTROL, vk::RCONTROL],
        TalkKey::RightControl => vec![vk::CONTROL, vk::RCONTROL],
        TalkKey::RightShift => vec![vk::SHIFT, vk::RSHIFT],
        TalkKey::Function(n) if (1..=20).contains(&n) => vec![vk::F1 + u16::from(n) - 1],
        _ => Vec::new(),
    }
}

/// One reading of the keys on Windows, given which codes are down
/// (`GetAsyncKeyState`). Any key that is not the talk key (another
/// modifier included, so AltGr's fake left Ctrl or Ctrl+Shift is a
/// shortcut) makes the press a shortcut; for Ctrl, so does a mouse button
/// (Ctrl-click selects, opens links). Once a take with another key is
/// running, Ctrl is free: holding it points (Flare), as on the Mac, and
/// must not cancel the take. Esc is reported on its own.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) fn win_read_keys(key: TalkKey, in_take: bool, down: impl Fn(u16) -> bool) -> TalkKeys {
    let trigger = match key {
        TalkKey::Control => down(vk::LCONTROL) || down(vk::RCONTROL),
        TalkKey::RightControl => down(vk::RCONTROL),
        TalkKey::RightShift => down(vk::RSHIFT),
        TalkKey::Function(n) if (1..=20).contains(&n) => down(vk::F1 + u16::from(n) - 1),
        _ => false,
    };
    if !trigger && !in_take {
        return TalkKeys::default();
    }
    let mut own = win_own_keys(key);
    if in_take && !matches!(key, TalkKey::Control | TalkKey::RightControl) {
        own.extend([vk::CONTROL, vk::LCONTROL, vk::RCONTROL]);
    }
    let click = trigger
        && matches!(key, TalkKey::Control | TalkKey::RightControl)
        && vk::MOUSE.iter().any(|code| down(*code));
    let other_key = click
        || vk::KEYS
            .filter(|code| *code != vk::ESCAPE && !own.contains(code))
            .any(&down);
    TalkKeys {
        trigger,
        other_key,
        escape: down(vk::ESCAPE),
    }
}

/// The talk key a single press stands for on Windows, from the codes held,
/// for Settings → Shortcuts. `Err` names a key that cannot talk there (Alt,
/// the Windows key, left Shift, letters) or a combination.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) fn win_captured_key(held: &[u16]) -> Option<Result<TalkKey, ()>> {
    let keys: Vec<Result<TalkKey, ()>> = held
        .iter()
        // Windows reports the generic code beside the sided one.
        .filter(|code| ![vk::SHIFT, vk::CONTROL, vk::MENU].contains(code))
        .map(|code| match *code {
            vk::LCONTROL => Ok(TalkKey::Control),
            vk::RCONTROL => Ok(TalkKey::RightControl),
            vk::RSHIFT => Ok(TalkKey::RightShift),
            code @ vk::F1..=vk::F20 => Ok(TalkKey::Function((code - vk::F1 + 1) as u8)),
            _ => Err(()),
        })
        .collect();
    match keys.len() {
        0 => None,
        1 => keys.into_iter().next(),
        _ => Some(Err(())),
    }
}

#[cfg(target_os = "macos")]
mod mac {
    use super::*;
    use crate::clipboard_history::PasteTarget;
    use crate::recording::RecordingController;
    use crate::types::{CaptureSourceDto, RecordingMode, RecordingPhase};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Instant;
    use tauri::Manager;

    const POLL: Duration = Duration::from_millis(15);
    const POLL_OFF: Duration = Duration::from_millis(500);

    static STARTED: AtomicBool = AtomicBool::new(false);

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum Phase {
        Starting,
        Recording,
        Finishing,
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum End {
        Stop,
        Cancel,
        /// A recording started during a dictation.
        Interrupted,
    }

    struct Session {
        kind: TalkKind,
        phase: Phase,
        /// A show take's recording.
        recording_id: Option<String>,
        dir: Option<PathBuf>,
        /// A dictation's microphone capture, and Apple Speech's language.
        capture: Option<crate::dictation::Capture>,
        language: Option<String>,
        target: Option<PasteTarget>,
        /// The app in front when the key was let go (or Esc pressed), for
        /// the paste pop-up's "you switched apps" check. Read at the release
        /// itself, so a dictation that waited for its checks still compares
        /// against where the user was when they let go.
        released_in: Option<Option<PasteTarget>>,
        started: Instant,
        /// Stop or Esc arrived while the capture was still starting.
        pending: Option<End>,
    }

    static SESSION: parking_lot::Mutex<Option<Session>> = parking_lot::Mutex::new(None);

    pub(super) fn session_active() -> bool {
        SESSION.lock().is_some()
    }

    fn session_kind() -> Option<TalkKind> {
        SESSION.lock().as_ref().map(|s| s.kind)
    }

    /// Ends the session. Flare comes back with it, and the dictation pill
    /// goes, in case it was a dictation.
    fn clear_session(app: &AppHandle) {
        *SESSION.lock() = None;
        crate::dictation::pill::hide(app);
        crate::commands::FLARE_SUPPRESSED.store(false, Ordering::SeqCst);
        // Normally already resumed in `finish` once the take stopped; this
        // covers a take that failed to start or returned before that.
        crate::media_pause::resume_after_take();
    }

    pub(super) fn init(app: &AppHandle) {
        if STARTED.swap(true, Ordering::SeqCst) {
            return;
        }
        let app = app.clone();
        if let Err(err) = std::thread::Builder::new()
            .name("clipy-talk".to_string())
            .spawn(move || run(app))
        {
            tracing::warn!("talk key watcher did not start: {err}");
        }
    }

    #[link(name = "CoreGraphics", kind = "framework")]
    extern "C" {
        fn CGEventSourceKeyState(state_id: u32, key: u16) -> bool;
        fn CGEventSourceFlagsState(state_id: u32) -> u64;
        fn CGEventSourceButtonState(state_id: u32, button: u32) -> bool;
    }

    const FN_FLAG: u64 = 0x0080_0000;
    const KVK_FUNCTION: u16 = 0x3F;
    const KVK_ESCAPE: u16 = 0x35;

    // kCGEventSourceStateCombinedSessionState = 0.
    fn down(code: u16) -> bool {
        unsafe { CGEventSourceKeyState(0, code) }
    }

    fn flags() -> u64 {
        unsafe { CGEventSourceFlagsState(0) }
    }

    fn read_keys(key: TalkKey, in_take: bool) -> TalkKeys {
        let flags = flags();
        let (trigger, chord) = match key {
            TalkKey::Off => (false, false),
            TalkKey::Fn => (down(KVK_FUNCTION) || flags & FN_FLAG != 0, false),
            TalkKey::Function(_) => (key.keycode().is_some_and(down), false),
            modifier => modifier_keys(modifier, flags).unwrap_or((false, false)),
        };
        if !trigger && !in_take {
            return TalkKeys::default();
        }
        // Control-click is the Mac's secondary click: a mouse button down
        // with Control makes the press a shortcut, not dictation.
        // kCGMouseButtonLeft = 0, Right = 1, Center = 2.
        let chord = chord
            || (key == TalkKey::Control
                && trigger
                && (0..3u32).any(|button| unsafe { CGEventSourceButtonState(0, button) }));
        // Virtual keycodes 54-63 are the modifiers (Command, Shift, Caps Lock,
        // Option, Control, Fn); which modifiers make a shortcut is the
        // talk key's own rule (`modifier_keys`).
        let own = key.keycode();
        let other_key = chord
            || (0..128u16)
                .filter(|code| !(54..=63).contains(code) && *code != KVK_ESCAPE && Some(*code) != own)
                .any(down);
        TalkKeys {
            trigger,
            other_key,
            escape: down(KVK_ESCAPE),
        }
    }

    /// True while Settings records a new talk key, so pressing it there does
    /// not start a take.
    pub(super) static CAPTURING: AtomicBool = AtomicBool::new(false);
    static CAPTURE_CANCEL: AtomicBool = AtomicBool::new(false);

    /// Waits for one key to be pressed and released on its own, and returns
    /// it. `Ok(None)`: Esc, a cancel, or nothing within 15 seconds.
    pub(super) fn capture_key() -> Result<Option<TalkKey>, String> {
        CAPTURE_CANCEL.store(false, Ordering::SeqCst);
        CAPTURING.store(true, Ordering::SeqCst);
        let result = (|| {
            let deadline = Instant::now() + Duration::from_secs(15);
            // Wait for anything still held from the click to be let go.
            let all_up = || flags() & (SHIFT_FLAG | CONTROL_FLAG | OPTION_FLAG | COMMAND_FLAG | FN_FLAG) == 0
                && !(0..128u16).any(down);
            while !all_up() {
                if Instant::now() > deadline {
                    return Ok(None);
                }
                std::thread::sleep(POLL);
            }
            let mut seen: Option<Result<TalkKey, ()>> = None;
            loop {
                if CAPTURE_CANCEL.load(Ordering::SeqCst) || Instant::now() > deadline {
                    return Ok(None);
                }
                if down(KVK_ESCAPE) {
                    return Ok(None);
                }
                let keys: Vec<u16> = (0..128u16)
                    .filter(|code| !(54..=63).contains(code))
                    .filter(|code| down(*code))
                    .collect();
                match captured_key(flags(), down(KVK_FUNCTION), &keys) {
                    Some(now) => {
                        seen = match (seen, now) {
                            (None, now) => Some(now),
                            (Some(Ok(a)), Ok(b)) if a == b => Some(Ok(a)),
                            // Two keys together: a combination, not one key.
                            _ => Some(Err(())),
                        };
                    }
                    None => {
                        if let Some(pressed) = seen {
                            return pressed
                                .map(Some)
                                .map_err(|()| crate::i18n::t("errors.talkKeyUnsupported"));
                        }
                    }
                }
                std::thread::sleep(POLL);
            }
        })();
        CAPTURING.store(false, Ordering::SeqCst);
        result
    }

    pub(super) fn cancel_capture() {
        CAPTURE_CANCEL.store(true, Ordering::SeqCst);
    }

    fn run(app: AppHandle) {
        let clock = Instant::now();
        // One tracker per kind of take: [show, dictate].
        let mut trackers = [TalkTracker::default(), TalkTracker::default()];
        let kinds = [TalkKind::Show, TalkKind::Dictate];
        let mut keys = [TalkKey::Off, TalkKey::Off];
        let mut key_read_at: Option<Instant> = None;
        loop {
            // The settings change rarely; read them once a second.
            if key_read_at.is_none_or(|at| at.elapsed() >= Duration::from_secs(1)) {
                let (show, dictate) = talk_keys(&app);
                keys = [show, dictate];
                key_read_at = Some(Instant::now());
            }
            let all_off = keys.iter().all(|k| *k == TalkKey::Off);
            if (all_off || CAPTURING.load(Ordering::SeqCst)) && SESSION.lock().is_none() {
                trackers = [TalkTracker::default(), TalkTracker::default()];
                std::thread::sleep(POLL_OFF);
                continue;
            }
            std::thread::sleep(POLL);

            let running = session_kind();
            for i in 0..2 {
                let kind = kinds[i];
                // While a take runs, only its own key acts; the other is
                // ignored until let go (Control points during a show take).
                if running.is_some_and(|k| k != kind) {
                    trackers[i].hold_off();
                    continue;
                }
                reconcile(&app, &mut trackers[i]);
                let in_take = session_kind() == Some(kind);
                let now_ms = clock.elapsed().as_millis() as u64;
                match trackers[i].update(read_keys(keys[i], in_take), now_ms) {
                    Some(TalkAction::Start(mode)) => {
                        if !try_begin(&app, kind) {
                            trackers[i].clear_active();
                        } else {
                            tracing::info!(?mode, ?kind, "talk take starting");
                            trackers[1 - i].hold_off();
                            break;
                        }
                    }
                    Some(TalkAction::Stop) => request_end(&app, End::Stop),
                    Some(TalkAction::Cancel) => request_end(&app, End::Cancel),
                    None => {}
                }
            }
        }
    }

    /// Keeps the tracker and the session in step with what happened outside
    /// the keys: a take stopped from the controls, a failed start, the time
    /// limit, a recording that started during a dictation.
    fn reconcile(app: &AppHandle, tracker: &mut TalkTracker) {
        let mut stop_now = false;
        let mut external_stop = false;
        let mut interrupted = false;
        {
            let guard = SESSION.lock();
            match guard.as_ref() {
                None => tracker.clear_active(),
                Some(session) if session.phase == Phase::Recording => match session.kind {
                    TalkKind::Show => {
                        let ours = session.recording_id.as_deref();
                        let still = app
                            .state::<RecordingController>()
                            .active_recording_id()
                            .is_some_and(|id| Some(id.as_str()) == ours);
                        if !still {
                            external_stop = true;
                        } else if session.started.elapsed() >= MAX_TAKE {
                            stop_now = true;
                        }
                    }
                    TalkKind::Dictate => {
                        // A recording (a person's or an agent's) takes the
                        // microphone's words over; the dictation ends with
                        // nothing pasted rather than fight it.
                        if app.state::<RecordingController>().dto().phase != RecordingPhase::Idle {
                            interrupted = true;
                        } else if session.started.elapsed() >= MAX_TAKE {
                            stop_now = true;
                        }
                    }
                },
                Some(_) => {}
            }
        }
        if interrupted {
            tracker.clear_active();
            end(app, End::Interrupted, false);
        } else if external_stop {
            tracker.clear_active();
            end(app, End::Stop, true);
        } else if stop_now {
            tracker.clear_active();
            end(app, End::Stop, false);
        }
    }

    fn try_begin(app: &AppHandle, kind: TalkKind) -> bool {
        {
            let mut guard = SESSION.lock();
            if guard.is_some() {
                return false;
            }
            if app.state::<RecordingController>().dto().phase != RecordingPhase::Idle {
                return false;
            }
            // Dictation is started by holding Control, which would otherwise
            // paint Flare over the screen for the whole take.
            crate::commands::FLARE_SUPPRESSED.store(kind == TalkKind::Dictate, Ordering::SeqCst);
            *guard = Some(Session {
                kind,
                phase: Phase::Starting,
                recording_id: None,
                dir: None,
                capture: None,
                language: None,
                // Read before anything can take focus.
                target: crate::clipboard_history::frontmost_target(),
                released_in: None,
                started: Instant::now(),
                pending: None,
            });
        }
        if pause_media(app) {
            crate::media_pause::pause_for_take();
        }
        if kind == TalkKind::Dictate {
            // At once, before the microphone opens: the key press is the
            // moment the user expects to see it listening.
            crate::dictation::pill::show(app);
        }
        let app = app.clone();
        tauri::async_runtime::spawn(async move {
            let started = match kind {
                TalkKind::Show => begin(&app).await.map(|(id, dir)| Started::Show(id, dir)),
                TalkKind::Dictate => begin_dictation(&app).await.map(Started::Dictate),
            };
            match started {
                Ok(started) => {
                    let installed = {
                        let mut guard = SESSION.lock();
                        match guard.as_mut() {
                            None => Err(started),
                            Some(session) => Ok(install(session, started)),
                        }
                    };
                    match installed {
                        Ok(Some(how)) => end(&app, how, false),
                        Ok(None) => {}
                        // Cleared meanwhile. A dictation's capture went
                        // with its session (`begin_dictation` aborts one it
                        // could not hand over).
                        Err(_) => {}
                    }
                }
                Err(err) => {
                    tracing::warn!(?kind, "talk take did not start: {err:#}");
                    clear_session(&app);
                    let key = match kind {
                        TalkKind::Show => "notifications.talkStartFailed",
                        TalkKind::Dictate => "notifications.dictateStartFailed",
                    };
                    notify(
                        &app,
                        &crate::i18n::t_with(key, &[("reason", crate::api_error::user_message(&err))]),
                    );
                }
            }
        });
        true
    }

    enum Started {
        Show(String, PathBuf),
        /// The capture is already in the session; this is Apple Speech's
        /// language.
        Dictate(Option<String>),
    }

    /// Moves a started take into its session and returns a Stop or Esc that
    /// arrived while it was starting.
    fn install(session: &mut Session, started: Started) -> Option<End> {
        match started {
            Started::Show(recording_id, dir) => {
                session.recording_id = Some(recording_id);
                session.dir = Some(dir);
                session.started = Instant::now();
            }
            // A dictation is timed from the key press: the microphone was
            // already listening while the checks ran. Recognition starts
            // now, fed what was held back, unless Esc already threw it away.
            Started::Dictate(language) => {
                session.language = language;
                if session.pending != Some(End::Cancel) {
                    if let Some(capture) = session.capture.as_ref() {
                        capture.recognize();
                    }
                }
            }
        }
        session.phase = Phase::Recording;
        session.pending.take()
    }

    async fn begin(app: &AppHandle) -> anyhow::Result<(String, PathBuf)> {
        crate::local::preflight_new_recording(app).await?;
        let settings = crate::commands::get_recording_settings(app.clone()).unwrap_or_default();
        let mut audio = settings.audio;
        // Your voice is the point; the computer's own audio would only
        // muddy the words.
        audio.include_mic = true;
        audio.include_system_audio = false;
        let source = display_under_pointer().map(|id| CaptureSourceDto::Display { id });
        let recording_id = app
            .state::<RecordingController>()
            .start(
                app,
                String::new(),
                source,
                Some(audio),
                None,
                None,
                None,
                RecordingMode::Local,
                0,
            )
            .await?;
        let recording_id = recording_id.to_string();
        let dir = crate::local::directory(app, &recording_id)?;
        if let Err(err) = crate::local::mark_talk_take(&dir) {
            tracing::warn!("talk take marker could not be written: {err:#}");
        }
        Ok((recording_id, dir))
    }

    /// Opens the saved microphone and starts listening while the same
    /// account and Speech checks a Local take runs happen alongside (on the
    /// first dictation that check is the Speech Recognition prompt), so no
    /// words are lost to them. The capture goes into the session as soon as
    /// it opens, so a release or Esc during the checks stops the microphone
    /// at once (`request_end`); live recognition waits for the checks
    /// (`install` calls `recognize`). Returns the language Apple Speech
    /// transcribes in (for the English-only filler pass).
    async fn begin_dictation(app: &AppHandle) -> anyhow::Result<Option<String>> {
        prewarm_model(app);
        let check_app = app.clone();
        let checks = tauri::async_runtime::spawn(async move {
            crate::local::preflight_new_recording(&check_app).await
        });
        let settings = crate::commands::get_recording_settings(app.clone()).unwrap_or_default();
        let device = settings.audio.mic_device_id;
        let capture_app = app.clone();
        let opened = tauri::async_runtime::spawn_blocking(move || {
            crate::dictation::start(&capture_app, device)
        })
        .await
        .map_err(|e| anyhow::anyhow!("dictation capture task: {e}"))
        .and_then(|opened| opened);
        let capture = match opened {
            Ok(capture) => capture,
            Err(err) => {
                // The checks may still be showing a prompt; let them finish
                // on their own, there is nothing to start.
                return Err(err);
            }
        };
        let orphan = {
            let mut guard = SESSION.lock();
            match guard.as_mut() {
                Some(session) => {
                    // Let go (or Esc) while the microphone was opening.
                    if session.pending.is_some() {
                        capture.release();
                    }
                    session.capture = Some(capture);
                    None
                }
                None => Some(capture),
            }
        };
        if let Some(capture) = orphan {
            let _ = tauri::async_runtime::spawn_blocking(move || capture.abort()).await;
            return Ok(None);
        }
        let checked = checks
            .await
            .map_err(|e| anyhow::anyhow!("dictation checks task: {e}"))
            .and_then(|checked| checked);
        if let Err(err) = checked {
            let capture = SESSION.lock().as_mut().and_then(|s| s.capture.take());
            if let Some(capture) = capture {
                let _ = tauri::async_runtime::spawn_blocking(move || capture.abort()).await;
            }
            return Err(err);
        }
        // After the checks: Speech is authorized by now.
        Ok(tauri::async_runtime::spawn_blocking(crate::local::apple_speech_locale)
            .await
            .ok()
            .flatten())
    }

    fn display_under_pointer() -> Option<u32> {
        #[repr(C)]
        struct CGPoint {
            x: f64,
            y: f64,
        }
        #[link(name = "CoreGraphics", kind = "framework")]
        extern "C" {
            fn CGGetDisplaysWithPoint(
                point: CGPoint,
                max_displays: u32,
                displays: *mut u32,
                matching: *mut u32,
            ) -> i32;
        }
        let (x, y) = crate::cursor_track::current_cursor_position()?;
        let mut display = 0u32;
        let mut count = 0u32;
        // SAFETY: room for exactly the one display asked for.
        let err = unsafe {
            CGGetDisplaysWithPoint(
                CGPoint {
                    x: x as f64,
                    y: y as f64,
                },
                1,
                &mut display,
                &mut count,
            )
        };
        (err == 0 && count == 1).then_some(display)
    }

    fn request_end(app: &AppHandle, how: End) {
        // Read outside the lock: the app the user is in as they let go.
        let frontmost = crate::clipboard_history::frontmost_target();
        {
            let mut guard = SESSION.lock();
            let Some(session) = guard.as_mut() else {
                return;
            };
            if session.phase != Phase::Finishing {
                session.released_in.get_or_insert(frontmost);
            }
            match session.phase {
                Phase::Starting => {
                    session.pending = Some(how);
                    // A dictation's microphone may already be open while the
                    // checks run: stop it now, so nothing said after the
                    // release is pasted and Esc does not leave it listening.
                    if let Some(capture) = session.capture.as_ref() {
                        capture.release();
                    }
                    return;
                }
                Phase::Finishing => return,
                Phase::Recording => {}
            }
        }
        end(app, how, false);
    }

    /// Stops (unless it already stopped elsewhere), then pastes or discards.
    fn end(app: &AppHandle, how: End, already_stopped: bool) {
        // For an end that is not a key release (the time limit, the
        // recording controls), the app in front now stands for it.
        let frontmost = crate::clipboard_history::frontmost_target();
        enum Ending {
            Show(String, PathBuf),
            Dictate(crate::dictation::Capture, Option<String>),
        }
        let (ending, target, released_in, started) = {
            let mut guard = SESSION.lock();
            let Some(session) = guard.as_mut() else {
                return;
            };
            if session.phase == Phase::Finishing {
                return;
            }
            session.phase = Phase::Finishing;
            let ending = match session.kind {
                TalkKind::Show => session
                    .recording_id
                    .clone()
                    .zip(session.dir.clone())
                    .map(|(id, dir)| Ending::Show(id, dir)),
                TalkKind::Dictate => session
                    .capture
                    .take()
                    .map(|capture| Ending::Dictate(capture, session.language.clone())),
            };
            match ending {
                Some(ending) => (
                    ending,
                    session.target,
                    session.released_in.unwrap_or(frontmost),
                    session.started,
                ),
                None => {
                    drop(guard);
                    clear_session(app);
                    return;
                }
            }
        };
        let app = app.clone();
        tauri::async_runtime::spawn(async move {
            match ending {
                Ending::Show(recording_id, dir) => {
                    finish(
                        &app,
                        how,
                        already_stopped,
                        &recording_id,
                        &dir,
                        target,
                        released_in,
                        started,
                    )
                    .await
                }
                Ending::Dictate(capture, language) => {
                    finish_dictation(&app, how, capture, language, target, released_in, started)
                        .await
                }
            }
            clear_session(&app);
        });
    }

    async fn finish(
        app: &AppHandle,
        how: End,
        already_stopped: bool,
        recording_id: &str,
        dir: &Path,
        target: Option<PasteTarget>,
        released_in: Option<PasteTarget>,
        started: Instant,
    ) {
        let rec = app.state::<RecordingController>();
        let ours = || {
            rec.active_recording_id()
                .is_some_and(|id| id.as_str() == recording_id)
        };
        let accidental = !already_stopped && started.elapsed() < MIN_TAKE;
        if how != End::Stop || accidental {
            if ours() {
                if let Err(err) = rec.stop(app).await {
                    tracing::warn!("talk take could not be stopped for discard: {err:#}");
                }
            }
            crate::media_pause::resume_after_take();
            if let Err(err) = crate::local::discard(app, dir.to_path_buf()).await {
                tracing::warn!("talk take could not be discarded: {err:#}");
            }
            return;
        }
        if already_stopped {
            // The microphone is already off; give the music back now.
            crate::media_pause::resume_after_take();
            // Stopped from the recording controls: Stop keeps the take,
            // Discard throws it away and must paste nothing.
            if !kept_after_external_stop(dir).await {
                return;
            }
        } else if ours() {
            let stopped = rec.stop(app).await;
            // Resume as soon as the microphone is off, not after the paste,
            // which can wait seconds for words.
            crate::media_pause::resume_after_take();
            if let Err(err) = stopped {
                tracing::warn!("talk take did not stop cleanly: {err:#}");
                notify(app, &crate::i18n::t("notifications.talkStopFailed"));
                return;
            }
        }
        crate::media_pause::resume_after_take();
        let words = match wait_for_words(dir, WORDS_WAIT).await {
            Words::Done(words) => words,
            // Show pastes the path without the words; the AREC fills in.
            Words::NotReady => None,
        };
        deliver(app, TalkKind::Show, words.as_deref(), &arec_of(dir), target, released_in).await;
    }

    /// A dictation from the key's release to the paste: stop the
    /// microphone, finish Apple's live words and, when a downloaded model is
    /// chosen, transcribe the audio in memory with it at the same time, then
    /// clean the words and paste them. Nothing touches disk.
    async fn finish_dictation(
        app: &AppHandle,
        how: End,
        capture: crate::dictation::Capture,
        apple_language: Option<String>,
        target: Option<PasteTarget>,
        released_in: Option<PasteTarget>,
        started: Instant,
    ) {
        use crate::dictation::{ModelHeard, LiveHeard, Outcome};
        let accidental = started.elapsed() < MIN_TAKE;
        if how != End::Stop || accidental {
            crate::dictation::pill::hide(app);
            let _ = tauri::async_runtime::spawn_blocking(move || capture.abort()).await;
            crate::media_pause::resume_after_take();
            if how == End::Interrupted {
                notify(app, &crate::i18n::t("notifications.dictateInterrupted"));
            }
            return;
        }
        let released = Instant::now();
        crate::dictation::pill::working(app);
        let pcm = tauri::async_runtime::spawn_blocking(move || capture.stop())
            .await
            .unwrap_or_default();
        crate::media_pause::resume_after_take();
        let audio_ms = pcm.len() as u64 * 1000 / u64::from(crate::dictation::PCM_RATE);

        let live = tauri::async_runtime::spawn_blocking(crate::local::live_stt::finish_dictation);
        let model = crate::transcription_models::chosen_model(app).filter(|_| !pcm.is_empty());
        let model_run = model.map(|model| {
            tauri::async_runtime::spawn_blocking(move || {
                let words = crate::transcription_dictionary::saved_prompt_words();
                let never = std::sync::atomic::AtomicBool::new(false);
                let started = Instant::now();
                let result = crate::transcription_models::transcribe(model, &pcm, &never, &words);
                (result, started.elapsed())
            })
        });
        let live = live.await.ok().flatten().map(|result| LiveHeard {
            segments: result.segments,
            usable: result.usable,
        });
        let model_heard = match (model, model_run) {
            (Some(model), Some(run)) => match run.await {
                Ok((Ok(transcript), took)) => {
                    tracing::info!(
                        model = model.as_str(),
                        took_ms = took.as_millis() as u64,
                        segments = transcript.segments.len(),
                        "dictation model transcript"
                    );
                    if transcript.segments.is_empty() {
                        ModelHeard::Empty
                    } else {
                        let apple = live.as_ref().map(|l| l.segments.as_slice()).unwrap_or(&[]);
                        let (segments, _gaps) = crate::local::merge_model_transcript(apple, &transcript);
                        ModelHeard::Heard {
                            segments,
                            language: transcript.language.clone(),
                        }
                    }
                }
                Ok((Err(error), _)) => {
                    tracing::warn!(model = model.as_str(), "dictation model failed, using Apple Speech: {error}");
                    ModelHeard::Failed
                }
                Err(error) => {
                    tracing::warn!(model = model.as_str(), "dictation model task failed: {error}");
                    ModelHeard::Failed
                }
            },
            _ => ModelHeard::NotChosen,
        };
        let picked = crate::dictation::pick(model_heard, live, apple_language);
        let mut segments = picked.segments;
        // The same passes every local transcript gets: model noise always,
        // fillers when turned on and the language is English, then the
        // dictionary's saved spellings.
        crate::transcript_cleanup::clean_segments(&mut segments, picked.language.as_deref(), |_| false);
        crate::transcription_dictionary::correct_saved_segments(&mut segments);
        let words = crate::local::segments_words(&segments);
        let outcome = crate::dictation::outcome(words, picked.failed);
        // Counts and milliseconds only, never words.
        tracing::info!(
            source = picked.source,
            audio_ms,
            segments = segments.len(),
            release_to_words_ms = released.elapsed().as_millis() as u64,
            pasted = matches!(outcome, Outcome::Paste(_)),
            "dictation finished"
        );
        crate::dictation::pill::hide(app);
        match outcome {
            Outcome::Paste(words) => {
                deliver(
                    app,
                    TalkKind::Dictate,
                    Some(words.as_str()),
                    Path::new(""),
                    target,
                    released_in,
                )
                .await;
                tracing::info!(
                    release_to_paste_ms = released.elapsed().as_millis() as u64,
                    "dictation pasted"
                );
            }
            Outcome::NothingHeard => notify(app, &crate::i18n::t("notifications.dictateNoWords")),
            Outcome::Failed => notify(app, &crate::i18n::t("notifications.dictateFailed")),
        }
    }

    /// The paste for either kind of take, in one place: compose the text,
    /// keep it in the dictation history, paste it into the app that was
    /// frontmost when the take started (with the Copy pop-up when the paste
    /// may not have landed, `paste_fallback`), and watch that field for
    /// corrections when "Learn from my edits" is on. `released_in` is the
    /// app in front when the key was let go.
    async fn deliver(
        app: &AppHandle,
        kind: TalkKind,
        words: Option<&str>,
        arec: &Path,
        target: Option<PasteTarget>,
        released_in: Option<PasteTarget>,
    ) {
        let Some(text) = compose_paste(kind, words, arec) else {
            notify(
                app,
                &crate::i18n::t(match kind {
                    TalkKind::Show => "notifications.talkNoWords",
                    TalkKind::Dictate => "notifications.dictateNoWords",
                }),
            );
            return;
        };
        let pasted = crate::paste_fallback::deliver(app, kind, &text, target, released_in).await;
        if let Some(words) = words.map(str::trim).filter(|w| pasted && !w.is_empty()) {
            // "Learn from my edits": watch the field for corrections to the
            // words (never the path line). Does nothing unless the user
            // turned it on in Settings → Transcription → Dictionary.
            if let Some(PasteTarget::Pid(pid)) =
                target.or_else(crate::clipboard_history::frontmost_target)
            {
                crate::transcription_dictionary::watch_paste(app, pid, &text, words);
            }
        }
    }
}

/// Windows: Show and Dictate, the same session shape and lifecycle as the
/// Mac's, with the keys polled through `GetAsyncKeyState`. A Show take is
/// an ordinary Local take of the display under the pointer (the saved mic
/// forced on, system audio off), transcribed on the PC by the downloaded
/// model or by Clipy, and pasted as words plus the AREC path. A dictation
/// is the microphone only, transcribed by the downloaded model after the
/// release; there is no live recognizer, so the account check simply runs
/// while the microphone listens and must pass before the paste.
#[cfg(target_os = "windows")]
mod win {
    use super::*;
    use crate::clipboard_history::PasteTarget;
    use crate::recording::RecordingController;
    use crate::types::{CaptureSourceDto, RecordingMode, RecordingPhase};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Instant;
    use tauri::Manager;
    use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;

    const POLL: Duration = Duration::from_millis(15);
    const POLL_OFF: Duration = Duration::from_millis(500);

    static STARTED: AtomicBool = AtomicBool::new(false);

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum Phase {
        Starting,
        Recording,
        Finishing,
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum End {
        Stop,
        Cancel,
        /// A recording started during a dictation.
        Interrupted,
    }

    struct Session {
        kind: TalkKind,
        phase: Phase,
        /// A show take's recording.
        recording_id: Option<String>,
        dir: Option<PathBuf>,
        /// A dictation's microphone capture and the model chosen at the key
        /// press.
        capture: Option<crate::dictation::Capture>,
        model: Option<crate::transcription_models::ChosenModel>,
        target: Option<PasteTarget>,
        released_in: Option<Option<PasteTarget>>,
        started: Instant,
        pending: Option<End>,
    }

    static SESSION: parking_lot::Mutex<Option<Session>> = parking_lot::Mutex::new(None);

    pub(super) fn session_active() -> bool {
        SESSION.lock().is_some()
    }

    fn session_kind() -> Option<TalkKind> {
        SESSION.lock().as_ref().map(|s| s.kind)
    }

    fn session_phase() -> Option<Phase> {
        SESSION.lock().as_ref().map(|s| s.phase)
    }

    fn clear_session(app: &AppHandle) {
        *SESSION.lock() = None;
        crate::dictation::pill::hide(app);
        crate::commands::FLARE_SUPPRESSED.store(false, Ordering::SeqCst);
    }

    pub(super) fn init(app: &AppHandle) {
        if STARTED.swap(true, Ordering::SeqCst) {
            return;
        }
        let app = app.clone();
        if let Err(err) = std::thread::Builder::new()
            .name("clipy-talk".to_string())
            .spawn(move || run(app))
        {
            tracing::warn!("talk key watcher did not start: {err}");
        }
    }

    /// Whether a key is down now. The high bit of `GetAsyncKeyState` is the
    /// key's physical state, whichever app has focus.
    fn down(code: u16) -> bool {
        // SAFETY: reads the asynchronous key state only.
        unsafe { (GetAsyncKeyState(i32::from(code)) as u16) & 0x8000 != 0 }
    }

    pub(super) static CAPTURING: AtomicBool = AtomicBool::new(false);
    static CAPTURE_CANCEL: AtomicBool = AtomicBool::new(false);

    /// Waits for one key to be pressed and released on its own, and returns
    /// it. `Ok(None)`: Esc, a cancel, or nothing within 15 seconds.
    pub(super) fn capture_key() -> Result<Option<TalkKey>, String> {
        CAPTURE_CANCEL.store(false, Ordering::SeqCst);
        CAPTURING.store(true, Ordering::SeqCst);
        let result = (|| {
            let deadline = Instant::now() + Duration::from_secs(15);
            // Wait for anything still held from the click to be let go.
            while vk::KEYS.any(down) {
                if Instant::now() > deadline {
                    return Ok(None);
                }
                std::thread::sleep(POLL);
            }
            let mut seen: Option<Result<TalkKey, ()>> = None;
            loop {
                if CAPTURE_CANCEL.load(Ordering::SeqCst) || Instant::now() > deadline {
                    return Ok(None);
                }
                if down(vk::ESCAPE) {
                    return Ok(None);
                }
                let held: Vec<u16> = vk::KEYS.filter(|code| down(*code)).collect();
                match win_captured_key(&held) {
                    Some(now) => {
                        seen = match (seen, now) {
                            (None, now) => Some(now),
                            (Some(Ok(a)), Ok(b)) if a == b => Some(Ok(a)),
                            _ => Some(Err(())),
                        };
                    }
                    None => {
                        if let Some(pressed) = seen {
                            return pressed
                                .map(Some)
                                .map_err(|()| crate::i18n::t("errors.talkKeyUnsupportedWindows"));
                        }
                    }
                }
                std::thread::sleep(POLL);
            }
        })();
        CAPTURING.store(false, Ordering::SeqCst);
        result
    }

    pub(super) fn cancel_capture() {
        CAPTURE_CANCEL.store(true, Ordering::SeqCst);
    }

    fn run(app: AppHandle) {
        let clock = Instant::now();
        // One tracker per kind of take: [show, dictate].
        let mut trackers = [TalkTracker::default(), TalkTracker::default()];
        let kinds = [TalkKind::Show, TalkKind::Dictate];
        let mut keys = [TalkKey::Off, TalkKey::Off];
        let mut key_read_at: Option<Instant> = None;
        loop {
            if key_read_at.is_none_or(|at| at.elapsed() >= Duration::from_secs(1)) {
                let (show, dictate) = talk_keys(&app);
                keys = [show, dictate];
                key_read_at = Some(Instant::now());
            }
            let all_off = keys.iter().all(|k| *k == TalkKey::Off);
            if (all_off || CAPTURING.load(Ordering::SeqCst)) && !session_active() {
                trackers = [TalkTracker::default(), TalkTracker::default()];
                std::thread::sleep(POLL_OFF);
                continue;
            }
            std::thread::sleep(POLL);
            // While the words are pasted, the keys are not read: the paste
            // itself presses Ctrl, which must not look like a tap of a Ctrl
            // talk key. A key still held then is ignored until let go.
            if session_phase() == Some(Phase::Finishing) {
                for tracker in &mut trackers {
                    tracker.hold_off();
                }
                continue;
            }
            let running = session_kind();
            for i in 0..2 {
                let kind = kinds[i];
                // While a take runs, only its own key acts; the other is
                // ignored until let go (Ctrl pointing during a show take).
                if running.is_some_and(|k| k != kind) {
                    trackers[i].hold_off();
                    continue;
                }
                reconcile(&app, &mut trackers[i]);
                let in_take = session_kind() == Some(kind);
                let now_ms = clock.elapsed().as_millis() as u64;
                match trackers[i].update(win_read_keys(keys[i], in_take, down), now_ms) {
                    Some(TalkAction::Start(mode)) => {
                        if try_begin(&app, kind) {
                            tracing::info!(?mode, ?kind, "talk take starting");
                            trackers[1 - i].hold_off();
                            break;
                        }
                        trackers[i].clear_active();
                    }
                    Some(TalkAction::Stop) => request_end(&app, End::Stop),
                    Some(TalkAction::Cancel) => request_end(&app, End::Cancel),
                    None => {}
                }
            }
        }
    }

    /// Keeps the tracker and the session in step with what happened outside
    /// the keys: a show take stopped from the recording controls, the time
    /// limit, a recording that started during a dictation.
    fn reconcile(app: &AppHandle, tracker: &mut TalkTracker) {
        let mut stop_now = false;
        let mut external_stop = false;
        let mut interrupted = false;
        {
            let guard = SESSION.lock();
            match guard.as_ref() {
                None => tracker.clear_active(),
                Some(session) if session.phase == Phase::Recording => match session.kind {
                    TalkKind::Show => {
                        let ours = session.recording_id.as_deref();
                        let still = app
                            .state::<RecordingController>()
                            .active_recording_id()
                            .is_some_and(|id| Some(id.as_str()) == ours);
                        if !still {
                            external_stop = true;
                        } else if session.started.elapsed() >= MAX_TAKE {
                            stop_now = true;
                        }
                    }
                    TalkKind::Dictate => {
                        if app.state::<RecordingController>().dto().phase != RecordingPhase::Idle {
                            interrupted = true;
                        } else if session.started.elapsed() >= MAX_TAKE {
                            stop_now = true;
                        }
                    }
                },
                Some(_) => {}
            }
        }
        if interrupted {
            tracker.clear_active();
            end(app, End::Interrupted, false);
        } else if external_stop {
            tracker.clear_active();
            end(app, End::Stop, true);
        } else if stop_now {
            tracker.clear_active();
            end(app, End::Stop, false);
        }
    }

    fn try_begin(app: &AppHandle, kind: TalkKind) -> bool {
        // Windows has no built-in engine for dictation: without a downloaded
        // model there is nothing to turn the audio into words. Show does not
        // need one (Clipy transcribes the take when no model is chosen).
        let model = crate::transcription_models::chosen_model(app);
        if kind == TalkKind::Dictate && model.is_none() {
            notify(app, &crate::i18n::t("notifications.dictateNeedsModelWindows"));
            return false;
        }
        {
            let mut guard = SESSION.lock();
            if guard.is_some() {
                return false;
            }
            if app.state::<RecordingController>().dto().phase != RecordingPhase::Idle {
                return false;
            }
            // A Ctrl dictate key would otherwise paint Flare.
            crate::commands::FLARE_SUPPRESSED.store(kind == TalkKind::Dictate, Ordering::SeqCst);
            *guard = Some(Session {
                kind,
                phase: Phase::Starting,
                recording_id: None,
                dir: None,
                capture: None,
                model,
                // Read before anything can take focus.
                target: crate::clipboard_history::frontmost_target(),
                released_in: None,
                started: Instant::now(),
                pending: None,
            });
        }
        if kind == TalkKind::Dictate {
            crate::dictation::pill::show(app);
        }
        let app = app.clone();
        tauri::async_runtime::spawn(async move {
            let started = match kind {
                TalkKind::Show => begin_show(&app).await.map(Some),
                TalkKind::Dictate => begin_dictation(&app).await.map(|()| None),
            };
            match started {
                Ok(show) => {
                    let pending = {
                        let mut guard = SESSION.lock();
                        guard.as_mut().map(|session| {
                            if let Some((id, dir)) = show {
                                session.recording_id = Some(id);
                                session.dir = Some(dir);
                                session.started = Instant::now();
                            }
                            session.phase = Phase::Recording;
                            session.pending.take()
                        })
                    };
                    if let Some(Some(how)) = pending {
                        end(&app, how, false);
                    }
                }
                Err(err) => {
                    tracing::warn!(?kind, "talk take did not start: {err:#}");
                    clear_session(&app);
                    let key = match kind {
                        TalkKind::Show => "notifications.talkStartFailed",
                        TalkKind::Dictate => "notifications.dictateStartFailed",
                    };
                    notify(
                        &app,
                        &crate::i18n::t_with(key, &[("reason", crate::api_error::user_message(&err))]),
                    );
                }
            }
        });
        true
    }

    /// A Local take of the display under the pointer, the saved mic forced
    /// on and system audio off (it would muddy the words), no countdown.
    async fn begin_show(app: &AppHandle) -> anyhow::Result<(String, PathBuf)> {
        prewarm_model(app);
        crate::local::preflight_new_recording(app).await?;
        let settings = crate::commands::get_recording_settings(app.clone()).unwrap_or_default();
        let mut audio = settings.audio;
        audio.include_mic = true;
        audio.include_system_audio = false;
        let source = Some(CaptureSourceDto::Display {
            id: display_under_pointer().await?,
        });
        let recording_id = app
            .state::<RecordingController>()
            .start(
                app,
                String::new(),
                source,
                Some(audio),
                None,
                None,
                None,
                RecordingMode::Local,
                0,
            )
            .await?;
        let recording_id = recording_id.to_string();
        let dir = crate::local::directory(app, &recording_id)?;
        if let Err(err) = crate::local::mark_talk_take(&dir) {
            tracing::warn!("talk take marker could not be written: {err:#}");
        }
        Ok((recording_id, dir))
    }

    /// The id of the display the pointer is on. The recorder's display list
    /// is refreshed first (`list_sources` updates the ids the recorder
    /// resolves), so a display connected since the picker last opened is
    /// found. Positions and the pointer are both physical pixels. A pointer
    /// on no listed display is an error: recording another display instead
    /// would be a silent wrong capture.
    async fn display_under_pointer() -> anyhow::Result<u32> {
        let sources = crate::capture::windows::ScreenCapturer::list_sources().await?;
        let displays: Vec<(u32, f64, f64, u32, u32)> = sources
            .displays
            .iter()
            .map(|d| (d.id, d.x, d.y, d.width, d.height))
            .collect();
        let (x, y) = crate::cursor_track::current_cursor_position()
            .ok_or_else(|| anyhow::anyhow!("Clipy could not tell which screen the pointer is on."))?;
        display_at(&displays, x, y)
            .ok_or_else(|| anyhow::anyhow!("Clipy could not tell which screen the pointer is on."))
    }

    /// Opens the saved microphone while the account check runs alongside,
    /// so no words are lost to it. The capture goes into the session as
    /// soon as it opens, so a release or Esc during the check stops the
    /// microphone at once.
    async fn begin_dictation(app: &AppHandle) -> anyhow::Result<()> {
        prewarm_model(app);
        let check_app = app.clone();
        let checks = tauri::async_runtime::spawn(async move {
            crate::local::preflight_new_recording(&check_app).await
        });
        let settings = crate::commands::get_recording_settings(app.clone()).unwrap_or_default();
        let device = settings.audio.mic_device_id;
        let model = SESSION.lock().as_ref().and_then(|session| session.model);
        let capture_app = app.clone();
        let capture = tauri::async_runtime::spawn_blocking(move || {
            let words = crate::transcription_dictionary::saved_prompt_words();
            let ahead = model.and_then(|model| {
                crate::dictation::ahead::Ahead::start(model, words)
                    .map_err(|error| tracing::warn!("dictation transcriber did not start: {error}"))
                    .ok()
            });
            crate::dictation::start(&capture_app, device, ahead)
        })
        .await
        .map_err(|e| anyhow::anyhow!("dictation capture task: {e}"))??;
        let orphan = {
            let mut guard = SESSION.lock();
            match guard.as_mut() {
                Some(session) => {
                    if session.pending.is_some() {
                        capture.release();
                    }
                    session.capture = Some(capture);
                    None
                }
                None => Some(capture),
            }
        };
        if let Some(capture) = orphan {
            let _ = tauri::async_runtime::spawn_blocking(move || capture.abort()).await;
            return Ok(());
        }
        let checked = checks
            .await
            .map_err(|e| anyhow::anyhow!("dictation checks task: {e}"))
            .and_then(|checked| checked);
        if let Err(err) = checked {
            let capture = SESSION.lock().as_mut().and_then(|s| s.capture.take());
            if let Some(capture) = capture {
                let _ = tauri::async_runtime::spawn_blocking(move || capture.abort()).await;
            }
            return Err(err);
        }
        Ok(())
    }

    fn request_end(app: &AppHandle, how: End) {
        let frontmost = crate::clipboard_history::frontmost_target();
        {
            let mut guard = SESSION.lock();
            let Some(session) = guard.as_mut() else {
                return;
            };
            if session.phase != Phase::Finishing {
                session.released_in.get_or_insert(frontmost);
            }
            match session.phase {
                Phase::Starting => {
                    session.pending = Some(how);
                    if let Some(capture) = session.capture.as_ref() {
                        capture.release();
                    }
                    return;
                }
                Phase::Finishing => return,
                Phase::Recording => {}
            }
        }
        end(app, how, false);
    }

    /// Stops (unless it already stopped elsewhere), then pastes or discards.
    fn end(app: &AppHandle, how: End, already_stopped: bool) {
        let frontmost = crate::clipboard_history::frontmost_target();
        enum Ending {
            Show(String, PathBuf),
            Dictate(crate::dictation::Capture),
        }
        let (ending, model, target, released_in, started) = {
            let mut guard = SESSION.lock();
            let Some(session) = guard.as_mut() else {
                return;
            };
            if session.phase == Phase::Finishing {
                return;
            }
            session.phase = Phase::Finishing;
            let ending = match session.kind {
                TalkKind::Show => session
                    .recording_id
                    .clone()
                    .zip(session.dir.clone())
                    .map(|(id, dir)| Ending::Show(id, dir)),
                TalkKind::Dictate => session.capture.take().map(Ending::Dictate),
            };
            match ending {
                Some(ending) => (
                    ending,
                    session.model,
                    session.target,
                    session.released_in.unwrap_or(frontmost),
                    session.started,
                ),
                None => {
                    drop(guard);
                    clear_session(app);
                    return;
                }
            }
        };
        let app = app.clone();
        tauri::async_runtime::spawn(async move {
            match ending {
                Ending::Show(recording_id, dir) => {
                    finish_show(&app, how, already_stopped, &recording_id, &dir, target, released_in, started)
                        .await
                }
                Ending::Dictate(capture) => {
                    finish_dictation(&app, how, capture, model, target, released_in, started).await
                }
            }
            clear_session(&app);
        });
    }

    #[allow(clippy::too_many_arguments)]
    async fn finish_show(
        app: &AppHandle,
        how: End,
        already_stopped: bool,
        recording_id: &str,
        dir: &Path,
        target: Option<PasteTarget>,
        released_in: Option<PasteTarget>,
        started: Instant,
    ) {
        let rec = app.state::<RecordingController>();
        let ours = || {
            rec.active_recording_id()
                .is_some_and(|id| id.as_str() == recording_id)
        };
        let accidental = !already_stopped && started.elapsed() < MIN_TAKE;
        if how != End::Stop || accidental {
            if ours() {
                if let Err(err) = rec.stop(app).await {
                    tracing::warn!("talk take could not be stopped for discard: {err:#}");
                }
            }
            if let Err(err) = crate::local::discard(app, dir.to_path_buf()).await {
                tracing::warn!("talk take could not be discarded: {err:#}");
            }
            return;
        }
        if already_stopped {
            // Stopped from the recording controls: Stop keeps the take,
            // Discard throws it away and must paste nothing.
            if !kept_after_external_stop(dir).await {
                return;
            }
        } else if ours() {
            if let Err(err) = rec.stop(app).await {
                tracing::warn!("talk take did not stop cleanly: {err:#}");
                notify(app, &crate::i18n::t("notifications.talkStopFailed"));
                return;
            }
        }
        let words = match wait_for_words(dir, WORDS_WAIT).await {
            Words::Done(words) => words,
            // The path is pasted without the words; the AREC fills in.
            Words::NotReady => None,
        };
        if let Some(text) = compose_paste(TalkKind::Show, words.as_deref(), &arec_of(dir)) {
            crate::paste_fallback::deliver(app, TalkKind::Show, &text, target, released_in).await;
        }
    }

    /// From the release to the paste: stop the microphone, transcribe the
    /// audio in memory with the downloaded model, clean the words and paste
    /// them. Nothing touches disk.
    async fn finish_dictation(
        app: &AppHandle,
        how: End,
        capture: crate::dictation::Capture,
        model: Option<crate::transcription_models::ChosenModel>,
        target: Option<PasteTarget>,
        released_in: Option<PasteTarget>,
        started: Instant,
    ) {
        use crate::dictation::{ModelHeard, Outcome};
        let accidental = started.elapsed() < MIN_TAKE;
        if how != End::Stop || accidental {
            crate::dictation::pill::hide(app);
            let _ = tauri::async_runtime::spawn_blocking(move || capture.abort()).await;
            if how == End::Interrupted {
                notify(app, &crate::i18n::t("notifications.dictateInterrupted"));
            }
            return;
        }
        let released = Instant::now();
        crate::dictation::pill::working(app);
        let crate::dictation::Heard { pcm, ahead } =
            tauri::async_runtime::spawn_blocking(move || capture.stop())
                .await
                .unwrap_or_default();
        let audio_ms = pcm.len() as u64 * 1000 / u64::from(crate::dictation::PCM_RATE);
        // The model chosen when the key went down, if it is still installed.
        let model = model
            .filter(|_| !pcm.is_empty())
            .filter(|chosen| crate::transcription_models::chosen_model(app) == Some(*chosen));
        let heard = match model {
            None => ModelHeard::NotChosen,
            Some(model) => {
                let run = tauri::async_runtime::spawn_blocking(move || {
                    let started = Instant::now();
                    let whole = |pcm: &[f32]| {
                        let words = crate::transcription_dictionary::saved_prompt_words();
                        crate::transcription_models::transcribe(model, pcm, &AtomicBool::new(false), &words)
                    };
                    let result = match ahead.filter(|ahead| ahead.model() == model) {
                        Some(ahead) => ahead.finish(&pcm).or_else(|error| {
                            tracing::warn!("dictation pieces failed, transcribing it whole: {error}");
                            whole(&pcm)
                        }),
                        None => whole(&pcm),
                    };
                    (result, started.elapsed())
                })
                .await;
                match run {
                    Ok((Ok(transcript), took)) => {
                        tracing::info!(
                            model = model.as_str(),
                            took_ms = took.as_millis() as u64,
                            segments = transcript.segments.len(),
                            "dictation model transcript"
                        );
                        let (segments, _gaps) = crate::local::merge_model_transcript(&[], &transcript);
                        if segments.is_empty() {
                            ModelHeard::Empty
                        } else {
                            ModelHeard::Heard {
                                segments,
                                language: transcript.language.clone(),
                            }
                        }
                    }
                    Ok((Err(error), _)) => {
                        tracing::warn!(model = model.as_str(), "dictation model failed: {error}");
                        ModelHeard::Failed
                    }
                    Err(error) => {
                        tracing::warn!(model = model.as_str(), "dictation model task failed: {error}");
                        ModelHeard::Failed
                    }
                }
            }
        };
        let picked = crate::dictation::pick(heard, None, None);
        let mut segments = picked.segments;
        crate::transcript_cleanup::clean_segments(&mut segments, picked.language.as_deref(), |_| false);
        crate::transcription_dictionary::correct_saved_segments(&mut segments);
        let words = crate::local::segments_words(&segments);
        let outcome = crate::dictation::outcome(words, picked.failed);
        // Counts and milliseconds only, never words.
        tracing::info!(
            source = picked.source,
            audio_ms,
            segments = segments.len(),
            release_to_words_ms = released.elapsed().as_millis() as u64,
            pasted = matches!(outcome, Outcome::Paste(_)),
            "dictation finished"
        );
        crate::dictation::pill::hide(app);
        match outcome {
            Outcome::Paste(words) => {
                if let Some(text) = compose_paste(TalkKind::Dictate, Some(words.as_str()), Path::new("")) {
                    crate::paste_fallback::deliver(app, TalkKind::Dictate, &text, target, released_in)
                        .await;
                    tracing::info!(
                        release_to_paste_ms = released.elapsed().as_millis() as u64,
                        "dictation pasted"
                    );
                }
            }
            Outcome::NothingHeard => notify(app, &crate::i18n::t("notifications.dictateNoWords")),
            Outcome::Failed => notify(app, &crate::i18n::t("notifications.dictateFailed")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn keys(trigger: bool) -> TalkKeys {
        TalkKeys {
            trigger,
            ..TalkKeys::default()
        }
    }

    /// Feeds (trigger, at_ms) readings and collects the actions.
    fn run(steps: &[(bool, u64)]) -> Vec<TalkAction> {
        let mut tracker = TalkTracker::default();
        steps
            .iter()
            .filter_map(|&(down, at)| tracker.update(keys(down), at))
            .collect()
    }

    #[test]
    fn a_hold_starts_after_the_grace_and_release_stops() {
        assert_eq!(
            run(&[
                (true, 0),
                (true, 100),
                (true, HOLD_START_MS),
                (true, 2_000),
                (false, 2_100)
            ]),
            vec![TalkAction::Start(TalkMode::Hold), TalkAction::Stop]
        );
    }

    #[test]
    fn a_short_tap_does_nothing() {
        assert!(run(&[(true, 0), (true, 100), (false, 150)]).is_empty());
    }

    #[test]
    fn a_double_tap_starts_hands_free_and_the_next_tap_stops() {
        assert_eq!(
            run(&[
                (true, 0),
                (false, 120),
                (true, 300),
                // Held past the hold grace: still hands-free, no second start.
                (true, 900),
                (false, 950),
                (false, 5_000),
                (true, 5_100),
                (false, 5_200),
                (false, 6_000),
            ]),
            vec![TalkAction::Start(TalkMode::HandsFree), TalkAction::Stop]
        );
    }

    #[test]
    fn a_slow_second_tap_is_not_a_double_tap() {
        assert!(run(&[
            (true, 0),
            (false, 100),
            (true, 100 + DOUBLE_TAP_GAP_MS + 50),
            (false, 600)
        ])
        .is_empty());
    }

    #[test]
    fn a_shortcut_never_starts() {
        let mut tracker = TalkTracker::default();
        assert_eq!(tracker.update(keys(true), 0), None);
        let chord = TalkKeys {
            trigger: true,
            other_key: true,
            escape: false,
        };
        assert_eq!(tracker.update(chord, 50), None);
        assert_eq!(tracker.update(keys(true), 1_000), None);
        assert_eq!(tracker.update(keys(false), 1_100), None);
        // And it does not count as the first half of a double tap.
        assert_eq!(tracker.update(keys(true), 1_200), None);
        assert_eq!(tracker.update(keys(false), 1_250), None);
    }

    #[test]
    fn escape_cancels_and_the_release_does_nothing() {
        let mut tracker = TalkTracker::default();
        tracker.update(keys(true), 0);
        assert_eq!(
            tracker.update(keys(true), HOLD_START_MS),
            Some(TalkAction::Start(TalkMode::Hold))
        );
        let esc = TalkKeys {
            trigger: true,
            other_key: false,
            escape: true,
        };
        assert_eq!(tracker.update(esc, 1_000), Some(TalkAction::Cancel));
        assert_eq!(tracker.update(keys(false), 1_100), None);
        assert_eq!(tracker.active(), None);
    }

    #[test]
    fn escape_while_idle_blocks_hold_and_clears_double_tap() {
        let mut tracker = TalkTracker::default();
        let trigger_with_esc = TalkKeys {
            trigger: true,
            other_key: false,
            escape: true,
        };
        assert_eq!(tracker.update(trigger_with_esc, 0), None);
        assert_eq!(tracker.update(keys(true), HOLD_START_MS + 50), None);
        assert_eq!(tracker.active(), None);
        assert_eq!(tracker.update(keys(false), HOLD_START_MS + 100), None);

        // Quick trigger+Esc tap must not arm a double-tap either.
        assert_eq!(tracker.update(trigger_with_esc, 1_000), None);
        assert_eq!(tracker.update(keys(false), 1_050), None);
        assert_eq!(tracker.update(keys(true), 1_200), None);
        assert_eq!(tracker.active(), None);
    }

    #[test]
    fn escape_between_taps_clears_pending_double_tap() {
        let mut tracker = TalkTracker::default();
        assert_eq!(tracker.update(keys(true), 0), None);
        assert_eq!(tracker.update(keys(false), 100), None);
        assert_eq!(
            tracker.update(
                TalkKeys {
                    trigger: false,
                    other_key: false,
                    escape: true,
                },
                150
            ),
            None
        );
        assert_eq!(tracker.update(keys(true), 250), None);
        assert_eq!(tracker.active(), None);
    }

    #[test]
    fn trigger_and_escape_same_poll_cancels_hands_free_without_restarting() {
        let mut tracker = TalkTracker::default();
        assert_eq!(tracker.update(keys(true), 0), None);
        assert_eq!(tracker.update(keys(false), 100), None);
        assert_eq!(
            tracker.update(keys(true), 200),
            Some(TalkAction::Start(TalkMode::HandsFree))
        );
        assert_eq!(tracker.update(keys(false), 250), None);

        // Esc and trigger land on the same poll; Esc lifts while trigger is still held.
        let both = TalkKeys {
            trigger: true,
            other_key: false,
            escape: true,
        };
        assert_eq!(tracker.update(both, 1_000), Some(TalkAction::Cancel));
        assert_eq!(tracker.update(keys(true), 1_000 + HOLD_START_MS + 50), None);
        assert_eq!(tracker.active(), None);
        assert_eq!(tracker.update(keys(false), 1_400), None);
        // Clean next tap does not read as a double-tap.
        assert_eq!(tracker.update(keys(true), 1_500), None);
        assert_eq!(tracker.active(), None);
    }

    #[test]
    fn a_take_ended_elsewhere_ignores_the_held_key() {
        let mut tracker = TalkTracker::default();
        tracker.update(keys(true), 0);
        tracker.update(keys(true), HOLD_START_MS);
        tracker.clear_active();
        assert_eq!(tracker.update(keys(true), 2_000), None);
        assert_eq!(tracker.update(keys(false), 2_100), None);
    }

    #[test]
    fn show_pastes_the_words_then_the_path_and_dictate_only_the_words() {
        let arec = Path::new("/r/recording.arec");
        assert_eq!(
            compose_paste(TalkKind::Show, Some("  make this blue "), arec).unwrap(),
            "make this blue\n\nClipy recording: /r/recording.arec"
        );
        assert_eq!(
            compose_paste(TalkKind::Show, None, arec).unwrap(),
            "Clipy recording: /r/recording.arec"
        );
        assert_eq!(compose_paste(TalkKind::Dictate, Some(" hi "), arec).unwrap(), "hi");
        assert_eq!(compose_paste(TalkKind::Dictate, Some("  "), arec), None);
        assert_eq!(compose_paste(TalkKind::Dictate, None, arec), None);
    }

    #[test]
    fn windows_shows_with_right_shift_and_dictates_with_right_ctrl() {
        let defaults = (TalkKey::RightShift, TalkKey::RightControl);
        assert_eq!(windows_keys(None, None), defaults);
        assert_eq!(
            windows_keys(None, Some(TalkKey::Function(9))),
            (TalkKey::RightShift, TalkKey::Function(9))
        );
        // Mac keys in the settings read as the Windows defaults.
        assert_eq!(windows_keys(Some(TalkKey::Option), Some(TalkKey::Control)), (TalkKey::RightShift, TalkKey::Control));
        assert_eq!(windows_keys(Some(TalkKey::Fn), Some(TalkKey::Fn)), defaults);
        assert_eq!(
            windows_keys(Some(TalkKey::Off), Some(TalkKey::Off)),
            (TalkKey::Off, TalkKey::Off)
        );
        // Ctrl to show takes the dictate key's Right Ctrl: dictation steps aside.
        assert_eq!(
            windows_keys(Some(TalkKey::Control), None),
            (TalkKey::Control, TalkKey::Off)
        );
    }

    #[test]
    fn windows_allows_ctrl_right_ctrl_right_shift_and_function_keys_only() {
        for key in [
            TalkKey::Off,
            TalkKey::Control,
            TalkKey::RightControl,
            TalkKey::RightShift,
            TalkKey::Function(1),
            TalkKey::Function(20),
        ] {
            assert!(win_allowed(key), "{key:?}");
        }
        for key in [TalkKey::Option, TalkKey::RightOption, TalkKey::Fn] {
            assert!(!win_allowed(key), "{key:?}");
        }
        assert_eq!(TalkKey::parse("right_control"), Some(TalkKey::RightControl));
        assert_eq!(TalkKey::RightControl.as_str(), "right_control");
        assert!(TalkKey::Control.overlaps(TalkKey::RightControl));
        assert!(TalkKey::RightControl.overlaps(TalkKey::Control));
        assert!(!TalkKey::RightControl.overlaps(TalkKey::RightShift));
    }

    fn held(codes: &'static [u16]) -> impl Fn(u16) -> bool {
        move |code| codes.contains(&code)
    }

    #[test]
    fn windows_right_ctrl_alone_is_the_trigger() {
        let reading = win_read_keys(TalkKey::RightControl, false, held(&[vk::CONTROL, vk::RCONTROL]));
        assert_eq!(
            reading,
            TalkKeys {
                trigger: true,
                other_key: false,
                escape: false
            }
        );
        // Left Ctrl is not Right Ctrl.
        assert_eq!(
            win_read_keys(TalkKey::RightControl, false, held(&[vk::CONTROL, vk::LCONTROL])),
            TalkKeys::default()
        );
    }

    #[test]
    fn windows_any_other_key_or_ctrl_click_makes_a_shortcut() {
        // Ctrl+C.
        let copy = win_read_keys(TalkKey::Control, false, held(&[vk::CONTROL, vk::LCONTROL, 0x43]));
        assert!(copy.trigger && copy.other_key);
        // AltGr: a fake left Ctrl plus right Alt.
        let altgr = win_read_keys(
            TalkKey::Control,
            false,
            held(&[vk::CONTROL, vk::LCONTROL, vk::MENU, 0xA5]),
        );
        assert!(altgr.trigger && altgr.other_key);
        // Both Ctrl keys with a Right Ctrl talk key: the left one is another key.
        let both = win_read_keys(
            TalkKey::RightControl,
            false,
            held(&[vk::CONTROL, vk::LCONTROL, vk::RCONTROL]),
        );
        assert!(both.trigger && both.other_key);
        // Ctrl-click.
        let click = win_read_keys(TalkKey::Control, false, held(&[vk::CONTROL, vk::RCONTROL, 0x01]));
        assert!(click.trigger && click.other_key);
        // A click without Ctrl held means nothing to a Right Shift key.
        let shift_click = win_read_keys(TalkKey::RightShift, true, held(&[vk::SHIFT, vk::RSHIFT, 0x01]));
        assert!(shift_click.trigger && !shift_click.other_key);
    }

    #[test]
    fn windows_ctrl_points_during_a_show_take_but_is_a_shortcut_before_it() {
        // Right Shift held to show, then Ctrl held to point with Flare.
        let pointing = win_read_keys(
            TalkKey::RightShift,
            true,
            held(&[vk::SHIFT, vk::RSHIFT, vk::CONTROL, vk::LCONTROL]),
        );
        assert!(pointing.trigger && !pointing.other_key);
        // A letter during the take still cancels it.
        let typed = win_read_keys(
            TalkKey::RightShift,
            true,
            held(&[vk::SHIFT, vk::RSHIFT, vk::CONTROL, vk::LCONTROL, 0x43]),
        );
        assert!(typed.other_key);
        // Before a take starts, Right Shift with Ctrl is a shortcut.
        let shortcut = win_read_keys(
            TalkKey::RightShift,
            false,
            held(&[vk::SHIFT, vk::RSHIFT, vk::CONTROL, vk::RCONTROL]),
        );
        assert!(shortcut.trigger && shortcut.other_key);
    }

    #[test]
    fn the_show_display_is_the_one_under_the_pointer_or_none() {
        // A primary display and one to its left, at a negative origin.
        let displays = [(0, 0.0, 0.0, 1920, 1080), (3, -2560.0, 0.0, 2560, 1440)];
        assert_eq!(display_at(&displays, 100, 100), Some(0));
        assert_eq!(display_at(&displays, -10, 1200), Some(3));
        // Right and bottom edges belong to the next pixel, not this display.
        assert_eq!(display_at(&displays, 1920, 10), None);
        assert_eq!(display_at(&displays, 10, 1080), None);
        assert_eq!(display_at(&[], 0, 0), None);
    }

    #[test]
    fn windows_escape_is_reported_during_a_take() {
        let esc = win_read_keys(TalkKey::RightControl, true, held(&[vk::ESCAPE]));
        assert!(!esc.trigger && esc.escape && !esc.other_key);
        // Outside a take nothing is read until the key goes down.
        assert_eq!(
            win_read_keys(TalkKey::RightControl, false, held(&[vk::ESCAPE])),
            TalkKeys::default()
        );
        let f9 = win_read_keys(TalkKey::Function(9), false, held(&[0x78]));
        assert!(f9.trigger && !f9.other_key);
    }

    #[test]
    fn windows_settings_capture_names_one_key_and_refuses_the_rest() {
        assert_eq!(win_captured_key(&[]), None);
        assert_eq!(win_captured_key(&[vk::CONTROL, vk::RCONTROL]), Some(Ok(TalkKey::RightControl)));
        assert_eq!(win_captured_key(&[vk::CONTROL, vk::LCONTROL]), Some(Ok(TalkKey::Control)));
        assert_eq!(win_captured_key(&[vk::SHIFT, vk::RSHIFT]), Some(Ok(TalkKey::RightShift)));
        assert_eq!(win_captured_key(&[0x70]), Some(Ok(TalkKey::Function(1))));
        assert_eq!(win_captured_key(&[vk::F20]), Some(Ok(TalkKey::Function(20))));
        // F21 and up, left Shift, Alt, the Windows key, a letter, a combination.
        for held in [
            &[0x84u16][..],
            &[vk::SHIFT, vk::LSHIFT],
            &[vk::MENU, 0xA4],
            &[0x5B],
            &[0x41],
            &[vk::CONTROL, vk::RCONTROL, vk::RSHIFT, vk::SHIFT],
        ] {
            assert_eq!(win_captured_key(held), Some(Err(())), "{held:?}");
        }
    }

    #[test]
    fn option_shows_and_control_dictates_by_default() {
        assert_eq!(
            resolve_keys_from(None, None, MAC_DEFAULT_KEYS),
            (TalkKey::Option, TalkKey::Control)
        );
        #[cfg(not(target_os = "windows"))]
        assert_eq!(resolve_keys(None, None), (TalkKey::Option, TalkKey::Control));
        // Someone who made Control their show key keeps it; dictation steps aside.
        assert_eq!(
            resolve_keys(Some(TalkKey::Control), None),
            (TalkKey::Control, TalkKey::Off)
        );
        assert_eq!(
            resolve_keys(Some(TalkKey::Fn), Some(TalkKey::Fn)),
            (TalkKey::Fn, TalkKey::Off)
        );
        assert_eq!(
            resolve_keys(Some(TalkKey::Off), Some(TalkKey::Off)),
            (TalkKey::Off, TalkKey::Off)
        );
        assert_eq!(
            resolve_keys(Some(TalkKey::RightOption), Some(TalkKey::Fn)),
            (TalkKey::RightOption, TalkKey::Fn)
        );
    }

    #[test]
    fn option_and_right_option_cannot_split_between_show_and_dictate() {
        assert!(TalkKey::Option.overlaps(TalkKey::RightOption));
        assert!(TalkKey::RightOption.overlaps(TalkKey::Option));
        assert!(TalkKey::Control.overlaps(TalkKey::Control));
        assert!(!TalkKey::Off.overlaps(TalkKey::Off));
        assert!(!TalkKey::Option.overlaps(TalkKey::Control));
        assert!(!TalkKey::RightShift.overlaps(TalkKey::Fn));
        // Option and Right Option are Mac keys, so this uses the Mac's
        // defaults whatever platform the tests run on.
        assert_eq!(
            resolve_keys_from(None, Some(TalkKey::RightOption), MAC_DEFAULT_KEYS),
            (TalkKey::Option, TalkKey::Off)
        );
        assert_eq!(
            resolve_keys_from(Some(TalkKey::RightOption), Some(TalkKey::Option), MAC_DEFAULT_KEYS),
            (TalkKey::RightOption, TalkKey::Off)
        );
    }

    #[test]
    fn show_words_are_settled_only_after_transcription() {
        assert_eq!(words_settled("recording"), None);
        assert_eq!(words_settled("transcribing"), None);
        assert_eq!(words_settled("failed"), Some(false));
        for stage in ["selecting", "extracting", "ready"] {
            assert_eq!(words_settled(stage), Some(true));
        }
    }

    #[test]
    fn a_key_held_through_the_other_take_waits_to_be_let_go() {
        let mut tracker = TalkTracker::default();
        // Control held to point while a show take ran.
        tracker.hold_off();
        assert_eq!(tracker.update(keys(true), 0), None);
        assert_eq!(tracker.update(keys(true), 2_000), None);
        assert_eq!(tracker.update(keys(false), 2_100), None);
        // A fresh hold afterwards starts as usual.
        assert_eq!(tracker.update(keys(true), 3_000), None);
        assert_eq!(
            tracker.update(keys(true), 3_000 + HOLD_START_MS),
            Some(TalkAction::Start(TalkMode::Hold))
        );
    }

    #[test]
    fn a_take_stopped_elsewhere_pastes_only_once_it_was_kept() {
        let dir = std::env::temp_dir().join(format!("clipy-talk-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        // Discard has emptied the active recording but not marked the take yet.
        assert_eq!(external_outcome(&dir), None);
        std::fs::write(dir.join("metadata.json"), b"{}").unwrap();
        assert_eq!(external_outcome(&dir), Some(true));
        // A cancel marker wins even when the take was sealed first.
        std::fs::write(dir.join("cancelled"), b"cancelled").unwrap();
        assert_eq!(external_outcome(&dir), Some(false));
        std::fs::remove_dir_all(&dir).unwrap();
        // Trashed.
        assert_eq!(external_outcome(&dir), Some(false));
    }

    #[test]
    fn option_sides_come_from_the_device_flags() {
        // Flags read on a MacBook Pro keyboard, 2026-11-28: Right Option
        // 0x80140, left Option 0x80120.
        assert_eq!(modifier_keys(TalkKey::RightOption, 0x80140), Some((true, false)));
        assert_eq!(modifier_keys(TalkKey::RightOption, 0x80120), Some((false, false)));
        assert_eq!(modifier_keys(TalkKey::Option, 0x80120), Some((true, false)));
        assert_eq!(modifier_keys(TalkKey::Option, 0x80140), Some((true, false)));
        assert_eq!(modifier_keys(TalkKey::Option, 0x100), Some((false, false)));
    }

    #[test]
    fn another_modifier_makes_the_press_a_shortcut() {
        // Option with Shift or Command is a shortcut; with Control it is
        // Flare pointing during the take.
        assert_eq!(modifier_keys(TalkKey::Option, 0xA0120), Some((true, true)));
        assert_eq!(modifier_keys(TalkKey::Option, 0x180128), Some((true, true)));
        assert_eq!(modifier_keys(TalkKey::Option, 0xC0121), Some((true, false)));
        // Control+Shift is the pointer outside a recording.
        assert_eq!(modifier_keys(TalkKey::Control, 0x60103), Some((true, true)));
        assert_eq!(modifier_keys(TalkKey::Control, 0x40101), Some((true, false)));
        // Control points during a Right Shift take.
        assert_eq!(modifier_keys(TalkKey::RightShift, 0x60105), Some((true, false)));
        assert_eq!(modifier_keys(TalkKey::RightShift, 0x120104), Some((true, true)));
        assert_eq!(modifier_keys(TalkKey::Fn, 0x800100), None);
    }

    #[test]
    fn a_single_key_press_is_captured_by_name() {
        assert_eq!(captured_key(0x80120, false, &[]), Some(Ok(TalkKey::Option)));
        assert_eq!(captured_key(0x80140, false, &[]), Some(Ok(TalkKey::RightOption)));
        assert_eq!(captured_key(0x40101, false, &[]), Some(Ok(TalkKey::Control)));
        assert_eq!(captured_key(0x100110, false, &[]), Some(Err(())));
        assert_eq!(captured_key(0x20104, false, &[]), Some(Ok(TalkKey::RightShift)));
        assert_eq!(captured_key(0x800100, false, &[]), Some(Ok(TalkKey::Fn)));
        assert_eq!(captured_key(0x100, false, &[96]), Some(Ok(TalkKey::Function(5))));
        assert_eq!(captured_key(0x100, false, &[]), None);
    }

    #[test]
    fn letters_combinations_and_left_command_are_refused() {
        // A letter.
        assert_eq!(captured_key(0x100, false, &[0]), Some(Err(())));
        // Option+A.
        assert_eq!(captured_key(0x80120, false, &[0]), Some(Err(())));
        // Left Command and left Shift alone.
        assert_eq!(captured_key(0x100108, false, &[]), Some(Err(())));
        assert_eq!(captured_key(0x20102, false, &[]), Some(Err(())));
    }

    fn run_with_chords(steps: &[(bool, bool, u64)]) -> Vec<TalkAction> {
        let mut tracker = TalkTracker::default();
        steps
            .iter()
            .filter_map(|&(trigger, other_key, at)| {
                tracker.update(
                    TalkKeys {
                        trigger,
                        other_key,
                        ..TalkKeys::default()
                    },
                    at,
                )
            })
            .collect()
    }

    #[test]
    fn holding_the_key_during_hands_free_points_and_only_a_tap_stops() {
        assert_eq!(
            run(&[
                (true, 0),
                (false, 120),
                (true, 300),
                (false, 400),
                // Held for two seconds to point (Flare): the take goes on.
                (true, 2_000),
                (true, 4_000),
                (false, 4_100),
                // A quick tap ends it.
                (true, 6_000),
                (false, 6_100),
            ]),
            vec![TalkAction::Start(TalkMode::HandsFree), TalkAction::Stop]
        );
    }

    #[test]
    fn a_key_pressed_while_holding_to_talk_cancels_the_take() {
        assert_eq!(
            run_with_chords(&[
                (true, false, 0),
                (true, false, 400),
                // Ctrl+C after a slow press.
                (true, true, 900),
                (true, false, 1_000),
                (false, false, 1_100),
            ]),
            vec![TalkAction::Start(TalkMode::Hold), TalkAction::Cancel]
        );
    }

    #[test]
    fn option_is_the_default_talk_key() {
        assert_eq!(TalkKey::default(), TalkKey::Option);
    }

    #[test]
    fn settings_round_trip() {
        for key in [
            TalkKey::Off,
            TalkKey::Option,
            TalkKey::RightOption,
            TalkKey::Control,
            TalkKey::Fn,
            TalkKey::RightShift,
            TalkKey::Function(1),
            TalkKey::Function(20),
        ] {
            assert_eq!(TalkKey::parse(key.as_str()), Some(key));
        }
        assert_eq!(TalkKey::parse("f21"), None);
        assert_eq!(TalkKind::parse("show"), Some(TalkKind::Show));
        assert_eq!(TalkKind::parse("dictate"), Some(TalkKind::Dictate));
        assert_eq!(TalkKind::parse("words"), None);
    }
}