diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md index 6c672475..3b1897ed 100644 --- a/docs/WINDOWS.md +++ b/docs/WINDOWS.md @@ -40,9 +40,9 @@ calendar matching can then be added back with Windows-native implementations. Minimum porting checklist: 1. Move macOS-only dependencies behind `cfg(target_os = "macos")`. -2. Add Windows equivalents or feature fallbacks for global hotkeys, focus context, - microphone permission UX, meeting audio capture, screen recording, calendar - lookup, and credential storage. +2. Add Windows equivalents or feature fallbacks for focus context, microphone + permission UX, meeting audio capture, screen recording, calendar lookup, and + credential storage. (Global hotkeys are done — see "Hotkeys on Windows" below.) 3. Replace the unconditional Metal LLM build with a Windows-compatible llama.cpp backend, likely CPU first, then optional CUDA/Vulkan later. 4. Add Windows sidecar binaries or disable the features that require the current @@ -51,6 +51,26 @@ Minimum porting checklist: 6. Publish a Windows installer from Tauri, typically an NSIS `*-setup.exe` or an MSI package. +## Hotkeys on Windows + +Windows has no CGEventTap, so the configured bindings are registered with the +global-shortcut plugin (`RegisterHotKey`) instead of the macOS event tap. Two +consequences the UI has to live with: + +- **A shortcut must contain a regular key.** `RegisterHotKey` cannot register a + bare modifier, so the macOS default (Right Control on its own) is not + expressible. Settings reports this rather than silently doing nothing. +- **Left/right modifiers are not distinguished.** "Right Alt + Slash" registers + as "Alt + Slash". +- **Registration is first-come-first-served across the whole system.** If another + running application already owns the combination, registration fails and Echo + Scribe surfaces the problem in Settings next to that shortcut. + +Because a second instance of the app would lose that race against the first and +end up with no working hotkey at all, the app registers +`tauri-plugin-single-instance` and focuses the existing window instead of +starting a second process. + ## Validation commands for a Windows developer On a Windows development machine: diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 51e00374..f7e9d11f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -46,6 +46,8 @@ tauri-plugin-store = "2" tauri-plugin-autostart = "2" tauri-plugin-notification = "2" tauri-plugin-global-shortcut = "2" +# Keeps a second launch from stealing/losing the global hotkey registration. +tauri-plugin-single-instance = "2" # ASR / Parakeet via ONNX Runtime. CPU-only — `ort-coreml` was dropped after # logs showed CoreML accepted only 15/39 encoder ops and 4/35 decoder ops, and # spent ~50s on first-run graph compilation while still running most of the diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index f76e117e..5b1f080e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -31,6 +31,7 @@ use crate::input::binding::{ code_from_key, key_from_code, Binding, ModifierKind, ModifierSide, SerKey, }; use crate::input::hotkeys::{spawn_listener, HotkeyEvent}; +use crate::input::trigger::HotkeyProblem; use crate::llm::{self, rag, GenerateRequest, Llm, LlmDownloadProgress, LlmModelEntry}; use crate::permissions::{self, CameraAccessOutcome, MicAccessOutcome, PermissionsStatus, SettingsPane}; use crate::settings::SettingsStore; @@ -62,6 +63,12 @@ pub struct AppState { pub action_binding: Arc>, pub edit_selection_binding: Arc>, pub hotkey_started: AtomicBool, + /// Friendly, user-facing reasons the configured hotkeys couldn't be + /// registered (Windows/Linux only — macOS uses the event tap and never + /// registers anything). Refreshed on every `sync_hotkeys` call and read by + /// the settings UI via [`get_hotkey_problems`], so a shortcut that another + /// app already owns shows up in the UI instead of only in the log. + pub hotkey_problems: Arc>>, /// When `true`, the coordinator drops Pressed/Released events. Toggled /// from the tray menu (Pause/Resume hotkeys). The hotkey listeners stay /// running so the toggle is instant — only the coordinator filters. @@ -344,6 +351,36 @@ pub fn request_screen_recording_access() -> Result { Ok(granted) } +/// Re-register the global shortcuts from the current bindings and store any +/// user-facing problems for [`get_hotkey_problems`]. +/// +/// No-op on macOS, where the CGEventTap listeners read the shared `Binding` +/// directly on every key event and so pick up rebinds with nothing to re-register. +pub fn sync_hotkeys(state: &AppState, app: &AppHandle) { + #[cfg(not(target_os = "macos"))] + { + let problems = crate::input::trigger::sync_shortcuts(app, state); + if let Ok(mut guard) = state.hotkey_problems.write() { + *guard = problems; + } + } + #[cfg(target_os = "macos")] + { + let _ = (state, app); + } +} + +/// Hotkeys that could not be registered (empty on macOS, and empty on +/// Windows/Linux when everything registered cleanly). +#[tauri::command] +pub fn get_hotkey_problems(state: State<'_, AppState>) -> Vec { + state + .hotkey_problems + .read() + .map(|g| g.clone()) + .unwrap_or_default() +} + #[tauri::command] pub fn get_voice_at_cursor_binding(state: State<'_, AppState>) -> JsBinding { let b = state @@ -357,6 +394,7 @@ pub fn get_voice_at_cursor_binding(state: State<'_, AppState>) -> JsBinding { #[tauri::command] pub fn update_voice_at_cursor_binding( state: State<'_, AppState>, + app: AppHandle, binding: JsBinding, ) -> Result<(), String> { let parsed: Binding = binding @@ -366,11 +404,14 @@ pub fn update_voice_at_cursor_binding( .settings .set_voice_at_cursor_binding(parsed.clone()) .map_err(|e| e.to_string())?; - let mut guard = state - .binding - .write() - .map_err(|_| "binding lock poisoned".to_string())?; - *guard = parsed; + { + let mut guard = state + .binding + .write() + .map_err(|_| "binding lock poisoned".to_string())?; + *guard = parsed; + } + sync_hotkeys(&state, &app); Ok(()) } @@ -387,6 +428,7 @@ pub fn get_log_capture_binding(state: State<'_, AppState>) -> JsBinding { #[tauri::command] pub fn update_log_capture_binding( state: State<'_, AppState>, + app: AppHandle, binding: JsBinding, ) -> Result<(), String> { let parsed: Binding = binding @@ -396,11 +438,14 @@ pub fn update_log_capture_binding( .settings .set_log_capture_binding(parsed.clone()) .map_err(|e| e.to_string())?; - let mut guard = state - .log_capture_binding - .write() - .map_err(|_| "binding lock poisoned".to_string())?; - *guard = parsed; + { + let mut guard = state + .log_capture_binding + .write() + .map_err(|_| "binding lock poisoned".to_string())?; + *guard = parsed; + } + sync_hotkeys(&state, &app); Ok(()) } @@ -415,7 +460,11 @@ pub fn get_action_binding(state: State<'_, AppState>) -> JsBinding { } #[tauri::command] -pub fn update_action_binding(state: State<'_, AppState>, binding: JsBinding) -> Result<(), String> { +pub fn update_action_binding( + state: State<'_, AppState>, + app: AppHandle, + binding: JsBinding, +) -> Result<(), String> { let parsed: Binding = binding .try_into() .map_err(|e: BindingConversionError| e.to_string())?; @@ -423,11 +472,14 @@ pub fn update_action_binding(state: State<'_, AppState>, binding: JsBinding) -> .settings .set_action_binding(parsed.clone()) .map_err(|e| e.to_string())?; - let mut guard = state - .action_binding - .write() - .map_err(|_| "action_binding lock poisoned".to_string())?; - *guard = parsed; + { + let mut guard = state + .action_binding + .write() + .map_err(|_| "action_binding lock poisoned".to_string())?; + *guard = parsed; + } + sync_hotkeys(&state, &app); Ok(()) } @@ -444,6 +496,7 @@ pub fn get_edit_selection_binding(state: State<'_, AppState>) -> JsBinding { #[tauri::command] pub fn update_edit_selection_binding( state: State<'_, AppState>, + app: AppHandle, binding: JsBinding, ) -> Result<(), String> { let parsed: Binding = binding @@ -453,11 +506,14 @@ pub fn update_edit_selection_binding( .settings .set_edit_selection_binding(parsed.clone()) .map_err(|e| e.to_string())?; - let mut guard = state - .edit_selection_binding - .write() - .map_err(|_| "edit_selection_binding lock poisoned".to_string())?; - *guard = parsed; + { + let mut guard = state + .edit_selection_binding + .write() + .map_err(|_| "edit_selection_binding lock poisoned".to_string())?; + *guard = parsed; + } + sync_hotkeys(&state, &app); Ok(()) } @@ -705,16 +761,10 @@ pub fn ensure_pipeline_started(state: &AppState, app: &AppHandle) { spawn_listener(Arc::clone(&state.edit_selection_binding), es_tx, Arc::clone(&state.rebinding)); // macOS drives the coordinator from the CGEventTap listeners above. - // Non-macOS has no tap, so register the global-shortcut trigger. - #[cfg(not(target_os = "macos"))] - { - if let Err(e) = crate::input::trigger::register_default_dictation_shortcut( - app, - coord_tx.clone(), - ) { - tracing::warn!(target: "trigger", %e, "dictation hotkey unavailable"); - } - } + // Non-macOS has no tap, so register the configured bindings as global + // shortcuts. Must run after `coord_tx` is stored in state — the shortcut + // handlers forward into that channel. + sync_hotkeys(state, app); // Adapter tasks: tag + forward into the coordinator channel. We use // `tokio::spawn` rather than a dedicated thread because these are pure diff --git a/src-tauri/src/input/focus.rs b/src-tauri/src/input/focus.rs index 5156aadc..b8c4c995 100644 --- a/src-tauri/src/input/focus.rs +++ b/src-tauri/src/input/focus.rs @@ -260,8 +260,19 @@ pub fn capture_selection(element: Option<&FocusElement>) -> Option) -> Option { + if let Some(text) = crate::input::paste::capture_selection_via_copy() { + tracing::info!(target: "edit", chars = text.len(), "capture_selection: via Ctrl+C fallback"); + return Some(SelectionSnapshot { text, method: SelectionMethod::Copy }); + } + tracing::info!(target: "edit", "capture_selection: no selection found (clipboard unchanged)"); None } diff --git a/src-tauri/src/input/paste.rs b/src-tauri/src/input/paste.rs index da379eb1..0bd74bfe 100644 --- a/src-tauri/src/input/paste.rs +++ b/src-tauri/src/input/paste.rs @@ -139,10 +139,13 @@ pub fn selection_from_clipboard_delta(before: Option<&str>, after: Option<&str>) } } -/// Fallback selection capture: synthesize Cmd+C, read the clipboard, then -/// restore the user's original clipboard. Returns the selected text, or `None` -/// if nothing changed / the copy failed. macOS-only. -#[cfg(target_os = "macos")] +/// Fallback selection capture: synthesize the platform copy chord, read the +/// clipboard, then restore the user's original clipboard. Returns the selected +/// text, or `None` if nothing changed / the copy failed. +/// +/// Platform-neutral: only [`synthesize_cmd_c`] differs per OS (CoreGraphics on +/// macOS, enigo elsewhere). On Windows this is the *only* selection path, since +/// the AX-based `focus::capture_selection` has no Win32 equivalent yet. pub fn capture_selection_via_copy() -> Option { use arboard::Clipboard; let mut clipboard = match Clipboard::new() { @@ -170,10 +173,6 @@ pub fn capture_selection_via_copy() -> Option { result } -#[cfg(not(target_os = "macos"))] -pub fn capture_selection_via_copy() -> Option { - None -} /// Synthesize Cmd+C via CoreGraphics (same deterministic approach as /// [`synthesize_cmd_v`], with the Command flag set directly on the keydown). @@ -200,6 +199,25 @@ fn synthesize_cmd_c() -> Result<(), PasteError> { Ok(()) } +/// Synthesize Ctrl+C. Mirrors [`synthesize_cmd_v`]'s non-macOS enigo path so +/// the two chords behave identically on Windows/Linux. +#[cfg(not(target_os = "macos"))] +fn synthesize_cmd_c() -> Result<(), PasteError> { + use enigo::{Direction, Enigo, Key, Keyboard, Settings}; + let mut enigo = + Enigo::new(&Settings::default()).map_err(|e| PasteError::Init(e.to_string()))?; + enigo + .key(Key::Control, Direction::Press) + .map_err(|e| PasteError::Keystroke(e.to_string()))?; + enigo + .key(Key::Unicode('c'), Direction::Click) + .map_err(|e| PasteError::Keystroke(e.to_string()))?; + enigo + .key(Key::Control, Direction::Release) + .map_err(|e| PasteError::Keystroke(e.to_string()))?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/input/trigger.rs b/src-tauri/src/input/trigger.rs index 1b77e0e8..e32b6326 100644 --- a/src-tauri/src/input/trigger.rs +++ b/src-tauri/src/input/trigger.rs @@ -1,10 +1,17 @@ //! Cross-platform dictation trigger helpers. //! //! macOS uses the CGEventTap listener in `hotkeys.rs`. Windows/Linux have no -//! event tap, so we drive the coordinator from the global-shortcut plugin and -//! the in-app Record button. Both funnel into `CoordinatorMsg::Hotkey`. +//! event tap, so we drive the coordinator from the global-shortcut plugin. +//! Both funnel into `CoordinatorMsg::Hotkey`. +//! +//! On Windows/Linux the shortcuts are derived from the *user's configured +//! bindings* (the same ones the Settings UI edits), not a hardcoded default. +//! [`sync_shortcuts`] is idempotent: it clears every registration and rebuilds +//! it from the current bindings, so it can be called at pipeline start and +//! again after any rebind. -use crate::input::hotkeys::HotkeyEvent; +use crate::input::binding::{code_from_key, Binding, ModifierKind}; +use crate::input::hotkeys::{is_modifier, HotkeyEvent}; /// Map a "is the trigger currently active?" boolean to a coordinator hotkey /// transition. `true` => `Pressed` (start capture), `false` => `Released` @@ -17,45 +24,415 @@ pub fn shortcut_state_to_hotkey(pressed: bool) -> HotkeyEvent { } } -/// Register the default Windows/Linux dictation hotkey (Ctrl+Alt+Space, -/// push-to-talk) with the global-shortcut plugin, forwarding Pressed/Released -/// into the coordinator as `Action::VoiceAtCursor`. +/// A hotkey that could not be registered, tagged with the action it belongs to +/// so the settings UI can show the message next to the shortcut that caused it +/// instead of dumping every problem under all four rebinders. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct HotkeyProblem { + /// Stable action slug: "voice-at-cursor" | "log-capture" | "action" | + /// "edit-selection". Matches the `action` prop of `HotkeyRebinder`. + pub action: String, + /// Friendly, already-formatted explanation for the user. + pub message: String, +} + +/// Why a configured binding cannot become a Windows/Linux global shortcut. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UnsupportedBinding { + /// The primary key is a bare modifier (the macOS default is Right Control + /// on its own). `RegisterHotKey` requires a non-modifier key, so this + /// shape is unrepresentable on Windows. + ModifierOnly, + /// Another Echo Scribe action already claimed this exact combination. + /// The macOS event tap happily lets two actions share a binding; + /// `RegisterHotKey` rejects the duplicate, so we have to say which of our + /// own shortcuts is in the way rather than blaming another app. + DuplicateOf(&'static str), + /// The key has no DOM-code mapping, so we can't translate it. + UnmappableKey, +} + +impl UnsupportedBinding { + /// A short, human-readable explanation for the settings UI. `label` names + /// the action, e.g. "voice-at-cursor". + pub fn message(self, label: &str) -> String { + match self { + Self::ModifierOnly => format!( + "The {label} shortcut is a single modifier key. Windows can only \ + register a shortcut that includes a regular key — add a letter, \ + digit or function key to the combination." + ), + Self::UnmappableKey => { + format!("The {label} shortcut uses a key Windows can't register. Pick another key.") + } + Self::DuplicateOf(other) => format!( + "The {label} shortcut is the same combination as the {other} shortcut. Windows \ + needs a different combination for each action." + ), + } + } +} + +/// Split a binding into the DOM `KeyboardEvent.code` of its primary key plus +/// the distinct modifier kinds it requires. /// -/// Windows can't swallow the keystroke the way the macOS CGEventTap does, so -/// the default is a deliberately non-conflicting combo. Rebinding on Windows is -/// deferred; v1 ships this fixed default. +/// Pure and platform-independent so it unit-tests on every host, including the +/// macOS CI runner. Note that `ModifierSide` is deliberately discarded: +/// Windows' `RegisterHotKey` has no notion of left-vs-right modifiers, so a +/// binding of "Right Alt + Slash" registers as "Alt + Slash" there. +pub fn shortcut_parts( + binding: &Binding, +) -> Result<(&'static str, Vec), UnsupportedBinding> { + if is_modifier(binding.primary.0) { + return Err(UnsupportedBinding::ModifierOnly); + } + let code = code_from_key(binding.primary.0).ok_or(UnsupportedBinding::UnmappableKey)?; + + let mut kinds: Vec = Vec::new(); + for (kind, _side) in &binding.modifiers { + if !kinds.contains(kind) { + kinds.push(*kind); + } + } + // Canonical order, so two bindings that require the same modifiers compare + // equal regardless of the order the user pressed them in. Duplicate + // detection in `sync_shortcuts` relies on this. + kinds.sort_by_key(|k| modifier_rank(*k)); + Ok((code, kinds)) +} + +fn modifier_rank(kind: ModifierKind) -> u8 { + match kind { + ModifierKind::Control => 0, + ModifierKind::Shift => 1, + ModifierKind::Alt => 2, + ModifierKind::Meta => 3, + } +} + #[cfg(not(target_os = "macos"))] -pub fn register_default_dictation_shortcut( - app: &tauri::AppHandle, - coord_tx: tokio::sync::mpsc::UnboundedSender, -) -> Result<(), String> { - use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState}; - - let shortcut = Shortcut::new(Some(Modifiers::CONTROL | Modifiers::ALT), Code::Space); - - app.global_shortcut() - .on_shortcut(shortcut, move |_app, _shortcut, event| { - let ev = shortcut_state_to_hotkey(matches!(event.state(), ShortcutState::Pressed)); - if let Err(e) = coord_tx.send(crate::coordinator::CoordinatorMsg::Hotkey( - crate::coordinator::Action::VoiceAtCursor, - ev, - )) { - tracing::warn!(target: "trigger", ?e, "failed to forward global shortcut to coordinator"); - } +pub use platform::sync_shortcuts; + +#[cfg(not(target_os = "macos"))] +mod platform { + use tauri::AppHandle; + use tauri_plugin_global_shortcut::{ + Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState, + }; + + use super::{shortcut_parts, shortcut_state_to_hotkey, HotkeyProblem}; + use crate::commands::AppState; + use crate::coordinator::{Action, CoordinatorMsg}; + use crate::input::binding::{Binding, ModifierKind}; + + /// The bindings we register, paired with the action they drive and the + /// label used in user-facing problem messages. + fn configured(state: &AppState) -> Vec<(Action, &'static str, Binding)> { + let read = |lock: &std::sync::RwLock| lock.read().ok().map(|g| g.clone()); + let mut out = Vec::new(); + if let Some(b) = read(&state.binding) { + out.push((Action::VoiceAtCursor, "voice-at-cursor", b)); + } + if let Some(b) = read(&state.log_capture_binding) { + out.push((Action::LogCapture, "log-capture", b)); + } + if let Some(b) = read(&state.action_binding) { + out.push((Action::ActionCommand, "action", b)); + } + if let Some(b) = read(&state.edit_selection_binding) { + out.push((Action::EditSelection, "edit-selection", b)); + } + out + } + + fn modifiers_for(kinds: &[ModifierKind]) -> Modifiers { + let mut mods = Modifiers::empty(); + for kind in kinds { + mods |= match kind { + ModifierKind::Control => Modifiers::CONTROL, + ModifierKind::Shift => Modifiers::SHIFT, + ModifierKind::Alt => Modifiers::ALT, + ModifierKind::Meta => Modifiers::META, + }; + } + mods + } + + /// DOM `KeyboardEvent.code` string -> `Code`. + /// + /// Explicit rather than `Code::from_str` so an unmappable key is a + /// `None` we report, never a panic or a silently-wrong key. The input + /// strings come from `binding::code_from_key`, so this table mirrors it. + fn code_for(code: &str) -> Option { + Some(match code { + "Space" => Code::Space, + "Tab" => Code::Tab, + "Escape" => Code::Escape, + "Enter" => Code::Enter, + "Backspace" => Code::Backspace, + "KeyA" => Code::KeyA, + "KeyB" => Code::KeyB, + "KeyC" => Code::KeyC, + "KeyD" => Code::KeyD, + "KeyE" => Code::KeyE, + "KeyF" => Code::KeyF, + "KeyG" => Code::KeyG, + "KeyH" => Code::KeyH, + "KeyI" => Code::KeyI, + "KeyJ" => Code::KeyJ, + "KeyK" => Code::KeyK, + "KeyL" => Code::KeyL, + "KeyM" => Code::KeyM, + "KeyN" => Code::KeyN, + "KeyO" => Code::KeyO, + "KeyP" => Code::KeyP, + "KeyQ" => Code::KeyQ, + "KeyR" => Code::KeyR, + "KeyS" => Code::KeyS, + "KeyT" => Code::KeyT, + "KeyU" => Code::KeyU, + "KeyV" => Code::KeyV, + "KeyW" => Code::KeyW, + "KeyX" => Code::KeyX, + "KeyY" => Code::KeyY, + "KeyZ" => Code::KeyZ, + "Digit0" => Code::Digit0, + "Digit1" => Code::Digit1, + "Digit2" => Code::Digit2, + "Digit3" => Code::Digit3, + "Digit4" => Code::Digit4, + "Digit5" => Code::Digit5, + "Digit6" => Code::Digit6, + "Digit7" => Code::Digit7, + "Digit8" => Code::Digit8, + "Digit9" => Code::Digit9, + "F1" => Code::F1, + "F2" => Code::F2, + "F3" => Code::F3, + "F4" => Code::F4, + "F5" => Code::F5, + "F6" => Code::F6, + "F7" => Code::F7, + "F8" => Code::F8, + "F9" => Code::F9, + "F10" => Code::F10, + "F11" => Code::F11, + "F12" => Code::F12, + "Period" => Code::Period, + "Comma" => Code::Comma, + "Semicolon" => Code::Semicolon, + "Quote" => Code::Quote, + "BracketLeft" => Code::BracketLeft, + "BracketRight" => Code::BracketRight, + "Backslash" => Code::Backslash, + "Slash" => Code::Slash, + "Minus" => Code::Minus, + "Equal" => Code::Equal, + "Backquote" => Code::Backquote, + _ => return None, }) - .map_err(|e| format!("failed to register dictation hotkey: {e}"))?; + } + + /// Re-register every global shortcut from the user's current bindings. + /// + /// Returns one friendly message per binding that could NOT be registered — + /// either because Windows can't express it, or because another running + /// application already owns the combination. The caller stores these so the + /// settings UI can show them; the technical detail goes to the log. + /// + /// Safe to call repeatedly: it unregisters everything first. + pub fn sync_shortcuts(app: &AppHandle, state: &AppState) -> Vec { + let mut problems: Vec = Vec::new(); + let problem = |action: &str, message: String| HotkeyProblem { + action: action.to_string(), + message, + }; + + if let Err(e) = app.global_shortcut().unregister_all() { + tracing::warn!(target: "trigger", ?e, "failed to clear existing global shortcuts"); + } + + let coord_tx = match state.coord_tx.lock() { + Ok(guard) => guard.clone(), + Err(_) => { + tracing::warn!(target: "trigger", "coordinator channel lock poisoned"); + None + } + }; + let Some(coord_tx) = coord_tx else { + // The pipeline hasn't started yet; ensure_pipeline_started will + // call us again once the channel exists. + tracing::info!(target: "trigger", "no coordinator channel yet; skipping shortcut sync"); + return problems; + }; + + // (code, modifiers) pairs already taken, with the action that took + // them — so a self-collision reports the real culprit. + let mut claimed: Vec<(&'static str, Vec, &'static str)> = Vec::new(); + + for (action, label, binding) in configured(state) { + let (code, kinds) = match shortcut_parts(&binding) { + Ok(parts) => parts, + Err(e) => { + tracing::warn!(target: "trigger", %label, ?e, "binding unsupported on this platform"); + problems.push(problem(label, e.message(label))); + continue; + } + }; + // Reject a duplicate before asking the OS, so the message names our + // own conflicting shortcut instead of implying a foreign app. + if let Some((_, _, other)) = claimed + .iter() + .find(|(c, k, _)| *c == code && *k == kinds) + { + let e = super::UnsupportedBinding::DuplicateOf(other); + tracing::warn!(target: "trigger", %label, %other, "two actions share one binding"); + problems.push(problem(label, e.message(label))); + continue; + } + claimed.push((code, kinds.clone(), label)); + + let Some(code) = code_for(code) else { + let e = super::UnsupportedBinding::UnmappableKey; + tracing::warn!(target: "trigger", %label, %code, "no Code mapping for key"); + problems.push(problem(label, e.message(label))); + continue; + }; + + let shortcut = Shortcut::new(Some(modifiers_for(&kinds)), code); + // Rendered before `shortcut` is handed to the plugin so the log + // lines below don't depend on it still being ours to borrow. + let desc = format!("{shortcut:?}"); + let tx = coord_tx.clone(); + let result = app + .global_shortcut() + .on_shortcut(shortcut, move |_app, _shortcut, event| { + let ev = shortcut_state_to_hotkey(matches!(event.state(), ShortcutState::Pressed)); + if let Err(e) = tx.send(CoordinatorMsg::Hotkey(action, ev)) { + tracing::warn!(target: "trigger", ?e, "failed to forward global shortcut to coordinator"); + } + }); + + match result { + Ok(()) => { + tracing::info!(target: "trigger", %label, %desc, "registered global shortcut"); + } + Err(e) => { + // The overwhelmingly common cause on Windows is another + // running app already owning the combination — + // RegisterHotKey is first-come-first-served process-wide. + tracing::error!(target: "trigger", %label, %desc, %e, "failed to register global shortcut"); + problems.push(problem( + label, + format!( + "Couldn't register the {label} shortcut. Another application is \ + probably already using that key combination — pick a different one." + ), + )); + } + } + } - tracing::info!(target: "trigger", "registered default dictation hotkey Ctrl+Alt+Space"); - Ok(()) + problems + } } #[cfg(test)] mod tests { use super::*; + use crate::input::binding::{ModifierSide, SerKey}; + use rdev::Key; #[test] fn maps_pressed_and_released() { assert_eq!(shortcut_state_to_hotkey(true), HotkeyEvent::Pressed); assert_eq!(shortcut_state_to_hotkey(false), HotkeyEvent::Released); } + + #[test] + fn combo_splits_into_code_and_modifiers() { + let b = Binding { + primary: SerKey(Key::Slash), + modifiers: vec![(ModifierKind::Alt, ModifierSide::Right)], + }; + let (code, kinds) = shortcut_parts(&b).expect("combo should be supported"); + assert_eq!(code, "Slash"); + assert_eq!(kinds, vec![ModifierKind::Alt]); + } + + /// Left/right is meaningless to RegisterHotKey, so the same modifier bound + /// on both sides must collapse to one entry rather than being applied twice. + #[test] + fn duplicate_modifier_kinds_collapse() { + let b = Binding { + primary: SerKey(Key::KeyK), + modifiers: vec![ + (ModifierKind::Control, ModifierSide::Left), + (ModifierKind::Control, ModifierSide::Right), + ], + }; + let (_, kinds) = shortcut_parts(&b).expect("supported"); + assert_eq!(kinds, vec![ModifierKind::Control]); + } + + /// THE Windows gap: the shipped macOS default (bare Right Control) can't + /// be a global shortcut, so it must be reported rather than silently + /// dropped — that silence is what made the mic look dead on Windows. + #[test] + fn bare_modifier_primary_is_unsupported() { + assert_eq!( + shortcut_parts(&Binding::single(Key::ControlRight)), + Err(UnsupportedBinding::ModifierOnly) + ); + assert_eq!( + shortcut_parts(&Binding::single(Key::AltGr)), + Err(UnsupportedBinding::ModifierOnly) + ); + } + + #[test] + fn single_non_modifier_key_is_supported() { + let (code, kinds) = shortcut_parts(&Binding::single(Key::F8)).expect("supported"); + assert_eq!(code, "F8"); + assert!(kinds.is_empty()); + } + + /// Modifier order must not affect equality: Echo Scribe's own default + /// bindings collided on Windows (`RegisterHotKey` rejects duplicates where + /// the macOS event tap allowed them), and duplicate detection compares + /// these vectors. + #[test] + fn modifier_order_is_canonical() { + let ctrl_shift = Binding { + primary: SerKey(Key::KeyD), + modifiers: vec![ + (ModifierKind::Shift, ModifierSide::Either), + (ModifierKind::Control, ModifierSide::Either), + ], + }; + let shift_ctrl = Binding { + primary: SerKey(Key::KeyD), + modifiers: vec![ + (ModifierKind::Control, ModifierSide::Either), + (ModifierKind::Shift, ModifierSide::Either), + ], + }; + assert_eq!( + shortcut_parts(&ctrl_shift).unwrap(), + shortcut_parts(&shift_ctrl).unwrap() + ); + } + + #[test] + fn duplicate_message_names_the_conflicting_action() { + let msg = UnsupportedBinding::DuplicateOf("log-capture").message("voice-at-cursor"); + assert!(msg.contains("log-capture"), "got {msg}"); + assert!(msg.contains("voice-at-cursor"), "got {msg}"); + } + + #[test] + fn messages_name_the_action() { + let msg = UnsupportedBinding::ModifierOnly.message("voice-at-cursor"); + assert!(msg.contains("voice-at-cursor"), "got {msg}"); + } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index e302bd3b..47de7c12 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -59,6 +59,7 @@ use crate::commands::{ get_format_templates, get_item, get_llm_unload_secs, get_log_capture_binding, get_mute_while_recording, get_onboarding_completed, get_project_auto_tagging_enabled, get_recording_project, get_screenrec_audio_prefs, get_trigger_word_routing_enabled, + get_hotkey_problems, get_voice_at_cursor_binding, hide_countdown_overlay, import_editor_background, @@ -107,16 +108,28 @@ use crate::ui::tray::TrayHandle; /// Resolve the directory crash logs are rotated into. Public so that the /// `diagnostics_log_dir` Tauri command (Settings → Diagnostics) can return /// the same path the appender writes to. +#[cfg(target_os = "macos")] pub fn log_dir() -> std::path::PathBuf { dirs::home_dir() .map(|h| h.join("Library/Logs/EchoScribe")) .unwrap_or_else(std::env::temp_dir) } +/// Non-macOS hosts have no `~/Library`; use the platform's local-data dir +/// (`%LOCALAPPDATA%\EchoScribe\logs` on Windows) so logs land somewhere the +/// OS actually expects rather than in a macOS-shaped path under the home dir. +#[cfg(not(target_os = "macos"))] +pub fn log_dir() -> std::path::PathBuf { + dirs::data_local_dir() + .map(|d| d.join("EchoScribe").join("logs")) + .unwrap_or_else(std::env::temp_dir) +} + #[cfg(test)] mod tests { use super::*; + #[cfg(target_os = "macos")] #[test] fn log_dir_resolves_under_library_logs_when_home_present() { // We can't easily mock `dirs::home_dir()`, but on the host where @@ -136,6 +149,24 @@ mod tests { assert_eq!(p, std::env::temp_dir()); } } + + /// Windows/Linux must not put logs in a macOS-shaped `~/Library` path. + #[cfg(not(target_os = "macos"))] + #[test] + fn log_dir_resolves_under_local_data_dir() { + let p = log_dir(); + let s = p.to_string_lossy(); + if let Some(local) = dirs::data_local_dir() { + assert!( + s.starts_with(local.to_string_lossy().as_ref()), + "log dir {s} should sit under local data dir {}", + local.display() + ); + assert!(!s.contains("Library"), "got a macOS-shaped path: {s}"); + } else { + assert_eq!(p, std::env::temp_dir()); + } + } } #[cfg_attr(mobile, tauri::mobile_entry_point)] @@ -176,6 +207,19 @@ pub fn run() { info!(accelerator = %OrtAccelerator::CpuOnly, "ORT accelerator selected"); tauri::Builder::default() + // Must be registered first (plugin requirement). Without it a second + // launch starts a second process that loses the global-shortcut race + // against the first — on Windows `RegisterHotKey` is first-come- + // first-served, so the new instance silently has NO working hotkey. + // Focus the existing window instead. + .plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| { + use tauri::Manager; + if let Some(window) = app.get_webview_window("main") { + let _ = window.show(); + let _ = window.unminimize(); + let _ = window.set_focus(); + } + })) .on_window_event(|window, event| { if window.label() == "main" { if let tauri::WindowEvent::CloseRequested { api, .. } = event { @@ -230,6 +274,7 @@ pub fn run() { request_screen_recording_access, get_voice_at_cursor_binding, update_voice_at_cursor_binding, + get_hotkey_problems, get_log_capture_binding, update_log_capture_binding, get_action_binding, @@ -678,6 +723,7 @@ pub fn run() { action_binding, edit_selection_binding, hotkey_started: AtomicBool::new(false), + hotkey_problems: Arc::new(std::sync::RwLock::new(Vec::new())), paused_hotkeys: Arc::clone(&paused_hotkeys), rebinding, coord_tx: Mutex::new(None), diff --git a/src/components/HotkeyRebinder.tsx b/src/components/HotkeyRebinder.tsx index 754a9c6b..c20b5ab7 100644 --- a/src/components/HotkeyRebinder.tsx +++ b/src/components/HotkeyRebinder.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from "react"; import { invoke } from "@tauri-apps/api/core"; import { + getHotkeyProblems, getVoiceAtCursorBinding, updateVoiceAtCursorBinding, type JsBinding, @@ -25,6 +26,9 @@ type Props = { /// voice-at-cursor binding for backwards compatibility. load?: () => Promise; save?: (b: JsBinding) => Promise; + /// Action slug used to match this rebinder against `getHotkeyProblems()` + /// entries. Defaults to voice-at-cursor, matching `load`/`save`. + action?: string; }; function buildBinding( @@ -58,16 +62,34 @@ function buildBinding( return { primary: primaryCode, modifiers }; } -export default function HotkeyRebinder({ onChange, load, save }: Props) { +export default function HotkeyRebinder({ + onChange, + load, + save, + action = "voice-at-cursor", +}: Props) { const [current, setCurrent] = useState(null); const [loadError, setLoadError] = useState(null); const [capture, setCapture] = useState({ kind: "idle" }); const [saveError, setSaveError] = useState(null); const [saving, setSaving] = useState(false); + const [problem, setProblem] = useState(null); const loader = load ?? getVoiceAtCursorBinding; const saver = save ?? updateVoiceAtCursorBinding; + // Whether the OS accepted this shortcut. On Windows a combination another + // app already owns fails to register, and without this the app looks healthy + // while the hotkey does nothing at all. + const refreshProblem = async () => { + try { + const problems = await getHotkeyProblems(); + setProblem(problems.find((p) => p.action === action)?.message ?? null); + } catch { + // Diagnostics only — never block the rebinder on this. + } + }; + // Load current binding on mount useEffect(() => { let cancelled = false; @@ -79,6 +101,7 @@ export default function HotkeyRebinder({ onChange, load, save }: Props) { if (!cancelled) setLoadError(e instanceof Error ? e.message : String(e)); } + if (!cancelled) await refreshProblem(); })(); return () => { cancelled = true; @@ -152,6 +175,9 @@ export default function HotkeyRebinder({ onChange, load, save }: Props) { setCurrent(capture.binding); onChange?.(capture.binding); setCapture({ kind: "idle" }); + // The backend re-registers on save, so ask whether the new combination + // was actually accepted by the OS. + await refreshProblem(); } catch (e) { const msg = e instanceof Error ? e.message : String(e); setSaveError(`Unsupported key — try a different one. (${msg})`); @@ -229,6 +255,9 @@ export default function HotkeyRebinder({ onChange, load, save }: Props) { )} + {problem && capture.kind === "idle" ? ( +

{problem}

+ ) : null} {saveError ? (

{saveError}

) : null} diff --git a/src/lib/api.ts b/src/lib/api.ts index f274f5fc..027a30f5 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -70,6 +70,14 @@ export const requestScreenRecordingAccess = (): Promise => export const getVoiceAtCursorBinding = (): Promise => invoke("get_voice_at_cursor_binding"); +/** A configured hotkey the OS refused to register, tagged by action slug. */ +export type HotkeyProblem = { action: string; message: string }; + +// Always empty on macOS (the event tap registers nothing); on Windows/Linux a +// combination another app already owns shows up here. +export const getHotkeyProblems = (): Promise => + invoke("get_hotkey_problems"); + export const updateVoiceAtCursorBinding = (binding: JsBinding): Promise => invoke("update_voice_at_cursor_binding", { binding }); diff --git a/src/views/Settings.tsx b/src/views/Settings.tsx index ce8e15ce..c0f415de 100644 --- a/src/views/Settings.tsx +++ b/src/views/Settings.tsx @@ -336,6 +336,7 @@ function LogCapturePage() { subtitle="Hold this key combination to capture a thought, idea, or task — classified locally and saved to your log." > @@ -1773,6 +1774,7 @@ function AppLauncherSettingsSection() {
@@ -1789,6 +1791,7 @@ function AppLauncherSettingsSection() {