diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c80d42..8d07020 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.1.0 — v1.1.0 · The right microphone, one click away + +- Add **Microphone** to the tray menu: **System default (name)** and every microphone, the one in use checked. A click makes it the microphone for the next recordings — the laptop's own while the headset for calls stays plugged in. It is the same setting as Settings → Recording → Microphone, saved at once, and the window follows. +- Read the microphones again as they come and go: at startup, when the window lists them, and on Windows and macOS when the pointer reaches the tray icon. A chosen microphone that is unplugged stays in the menu greyed out; recordings use the system default until it is back. +- On Linux the same submenu is served through Utterform's own StatusNotifierItem. +- The first stable release since 0.8.0: everything of 1.0.0-rc.1 (stages 0.9.0 to 0.14.0) ships with it. 1.0.0 was not released separately. +- App version 1.1.0; the installers install v1.1.0 by default. + +See [1.1.0 release notes](docs/releases/v1.1.0.md). + ## 1.0.0-rc.1 — v1.0.0-rc.1 · Say it, it's done (prerelease) - First installed build of everything since 0.8.0: the stages 0.9.0 to 0.14.0 below — Settings with search and no Save button, text actions on the ChatGPT subscription, the Context action, an action per application, audio files and the first-run assistant. diff --git a/README.md b/README.md index c283ae7..e38d17c 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Utterform records a short voice clip, transcribes it with **OpenAI GPT Transcrib the cursor. The window can stay out of the way while a global shortcut controls the whole flow. -> Utterform is under active development. **0.8.0 — Omarchy's dictation key** makes Utterform a dictation backend for Omarchy: choose it in Setup → Defaults → Dictation, then press Alt + Space or hold Right Alt. The Apple-Silicon build is Developer ID signed and notarized; Windows remains unsigned. See the [release notes](docs/releases/v0.8.0.md) and [downloads](https://github.com/jli-software/utterform/releases/tag/v0.8.0). **1.0.0 release candidate 1** brings everything since — first-run assistant, Settings with search, ChatGPT text actions, Context, an action per app and audio files — and waits for acceptance on all three platforms: [release notes](docs/releases/v1.0.0-rc.1.md), [downloads](https://github.com/jli-software/utterform/releases/tag/v1.0.0-rc.1). +> **1.1.0 — The right microphone, one click away** switches the microphone from the tray menu and brings everything since 0.8.0: a first-run assistant, Settings with search, ChatGPT text actions, Context, an action per app and audio files. The Apple-Silicon build is Developer ID signed and notarized; Windows remains unsigned. See the [release notes](docs/releases/v1.1.0.md) and [downloads](https://github.com/jli-software/utterform/releases/tag/v1.1.0). ## How it works @@ -332,7 +332,7 @@ Push/PR CI runs Linux validation without release compilation. For a test binary - An action per app for the dictation key: Email in the mail client, Plain in the terminal - A vocabulary of your own terms, and a reasoning effort for the text step - Clipboard, TXT, Markdown, or combined output -- Selectable microphone with a system-default fallback +- Selectable microphone with a system-default fallback, in Settings and in the tray menu - Global dictation with a reserved key combination on Windows, macOS and X11, or a compositor binding on Wayland: either way without raising the window - Optional typing of the finished text into the focused window, next to clipboard and file, as one paste or as keystrokes (Linux and Windows) - A dictation key recorded by pressing it, read by physical key so the layout cannot change it diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1c05d5c..c2d2e00 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -266,6 +266,34 @@ Ghostty); macOS uses the localized name. `recording.app_action` (action) when a rule takes over. The application is never logged: which program someone dictates into says as much as a window title. +## Microphone in the tray (1.1.0) + +**One setting, two places.** The tray's **Microphone** submenu writes +`settings.input_device`, the field Settings → Recording → Microphone writes; `None` is the +system default. `tray_microphones::choose` loads `settings.json`, changes only that field, +saves it, and then emits `microphone-chosen` with the id. The window copies it into its +settings without saving; a pending or later save already carries it. The backend saves +first so the choice holds even if no window ever loaded. A recording that is running +keeps its microphone; the choice applies to the next `start_recording`. + +**The menu.** `tray_microphones::entries` turns the known devices and the choice into +lines: **System default (name of the default device)**, then every device, exactly one +checked. A chosen id that is not connected gets a greyed, checked line "Chosen microphone +(not connected, using system default)", because `audio::select_device` falls back to the +default then. Menu ids are `microphone:default` and `microphone:device:`. +Windows and macOS rebuild Tauri's native menu with `tray.set_menu` (labels escape `&`); +Linux updates the `SubMenu` of its own StatusNotifierItem through the ksni handle (labels +escape `_`). + +**Staying current.** The devices are read at startup (off the event loop), whenever the +window calls `list_input_devices` (its copy is reused), and on Windows and macOS on +`TrayIconEvent::Enter`, at most every two seconds, so a microphone plugged in since shows +up before the menu opens. `save_settings` and `complete_onboarding` move the checkmark. +Linux has no such hover event; there the list follows the window. + +**Diagnostics.** `tray.microphone_chosen` (`default` or `device`) and +`tray.microphones_failed` (step). Device names are not logged. + ## First-run assistant (0.14.0) **Who sees it.** `settings.onboarding_completed`. `AppSettings::default()` — what `load` diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5c3432f..fdfec1b 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -19,7 +19,22 @@ proposals are in [plans/v1.0-roadmap.md](plans/v1.0-roadmap.md). The plan of 202 (reliability, assistant, finish) is superseded; 0.7.13 shipped, 0.7.14 (`feat/simple-settings`) was rejected and will not be merged. -## Current handoff — 1.0.0 Finish +## Current handoff — 1.1.0 Microphone in the tray + +Branch `work/utterform-1.1.0-tray-microphone`. Jonas asked on 2026-11-13 for a quick +microphone switch in the tray (headset plugged in for calls, but dictating into the +laptop's microphone), Windows first, then macOS and Linux, released directly as 1.1.0 +without a release candidate; nobody else uses Utterform yet. He chose "release 1.1.0 +straight away" over first releasing 1.0.0: 1.1.0 is the first stable release since +0.8.0 and contains all of 1.0.0-rc.1. Design in +[ARCHITECTURE.md → Microphone in the tray](ARCHITECTURE.md#microphone-in-the-tray-110). +CBZIT007 (Windows) has no Visual C++ Build Tools; Rust was compiled and tested by the +`Desktop builds` workflow, the frontend locally. Open after the release: a real check of +the tray submenu on each desktop, the open points of +[plans/v1.0-acceptance.md](plans/v1.0-acceptance.md), and a new WinGet submission +(PR #27 is the last one, at 0.7.11). + +## Previous handoff — 1.0.0 Finish Stage 1.0.0 of [the roadmap](plans/v1.0-roadmap.md), branch `work/utterform-1.0.0-finish`. Jonas decided on 2026-11-08 to accept a real signed prerelease: the app is 1.0.0, the diff --git a/docs/plans/v1.0-roadmap.md b/docs/plans/v1.0-roadmap.md index 2a573af..4ac30e6 100644 --- a/docs/plans/v1.0-roadmap.md +++ b/docs/plans/v1.0-roadmap.md @@ -77,7 +77,8 @@ Proposals not yet confirmed by Jonas are marked **Proposal**. | 0.12.0 | Action per application | merged, ships with 1.0 | | 0.13.0 | Audio files | merged, ships with 1.0 | | 0.14.0 | First-run assistant | merged, ships with 1.0 | -| 1.0.0 | Acceptance on Linux, Windows, macOS; release; WinGet | in progress: rc.1 out for acceptance | +| 1.0.0 | Acceptance on Linux, Windows, macOS; release; WinGet | rc.1 published; not released on its own — ships as 1.1.0 | +| 1.1.0 | Microphone in the tray; first stable release since 0.8.0 | released (2026-11-13) | **Proposal (order):** the Omarchy backend first because it is small and the CLI already exists; Settings next so every later feature gets a fixed place; Codex before context diff --git a/docs/releases/v1.1.0.md b/docs/releases/v1.1.0.md new file mode 100644 index 0000000..3b6f575 --- /dev/null +++ b/docs/releases/v1.1.0.md @@ -0,0 +1,37 @@ +# Utterform 1.1.0 — The right microphone, one click away + +*The first stable release since 0.8.0. It brings everything of the 1.0.0 release +candidate and adds the microphone to the tray menu. There is no separate 1.0.0.* + +**Switch the microphone from the tray.** The headset for calls is plugged in, but you +want to talk to the laptop. Right-click the Utterform icon, open **Microphone** and pick +the laptop's microphone. The next dictation uses it, and it stays chosen until you pick +another one. **System default** follows the microphone your system uses and names it, so +you see at a glance which one that is. It is the same setting as Settings → Recording → +Microphone; both always agree. + +Plugging a microphone in or out is noticed: on Windows and macOS the list is read again +as the pointer reaches the tray icon, and everywhere when the window opens. A chosen +microphone that is unplugged stays in the menu, greyed out, and recordings fall back to +the system default until it is back. + +**Everything from 1.0.** A first-run assistant, Settings with search and no Save button, +text actions on your ChatGPT subscription (experimental), the Context action for the +selected text or the clipboard, an action per application and transcription of voice +messages and audio files. The details are in the +[1.0.0 release candidate notes](v1.0.0-rc.1.md) and in the changelog under 0.9.0 to +0.14.0. + +## Install + +Quit Utterform first. + +- **Linux (Omarchy / Arch):** + `curl -fsSL https://github.com/jli-software/utterform/releases/download/v1.1.0/install-linux.sh | sh` +- **Windows (PowerShell):** + `irm https://github.com/jli-software/utterform/releases/download/v1.1.0/install-windows.ps1 | iex` +- **macOS:** the [DMG](https://github.com/jli-software/utterform/releases/download/v1.1.0/utterform-macos-aarch64.dmg), + Developer ID signed and notarized. + +Windows builds remain unsigned and may trigger SmartScreen. Verify downloads against +`SHA256SUMS.txt`. diff --git a/package-lock.json b/package-lock.json index babbc03..b7b282e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "utterform", - "version": "1.0.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "utterform", - "version": "1.0.0", + "version": "1.1.0", "dependencies": { "@tauri-apps/api": "^2.11.1", "@tauri-apps/plugin-dialog": "^2.4.0", diff --git a/package.json b/package.json index c5d672d..89af544 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "utterform", "private": true, - "version": "1.0.0", + "version": "1.1.0", "type": "module", "scripts": { "dev": "vite", diff --git a/scripts/install-linux.sh b/scripts/install-linux.sh index f95f89a..6891cf6 100755 --- a/scripts/install-linux.sh +++ b/scripts/install-linux.sh @@ -2,7 +2,7 @@ set -eu -version="${UTTERFORM_VERSION:-v1.0.0-rc.1}" +version="${UTTERFORM_VERSION:-v1.1.0}" release_base="${UTTERFORM_RELEASE_BASE_URL:-https://github.com/jli-software/utterform/releases/download/${version}}" asset="utterform-linux-x86_64-system.tar.gz" prefix="${UTTERFORM_PREFIX:-${HOME}/.local}" diff --git a/scripts/install-windows.ps1 b/scripts/install-windows.ps1 index 358179b..3ccabcd 100644 --- a/scripts/install-windows.ps1 +++ b/scripts/install-windows.ps1 @@ -1,6 +1,6 @@ # Verify the NSIS setup before opening it; no elevation or forced app shutdown. param( - [string]$Version = 'v1.0.0-rc.1', + [string]$Version = 'v1.1.0', [switch]$VerifyOnly ) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 4676cee..e8270af 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5904,7 +5904,7 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "utterform" -version = "1.0.0" +version = "1.1.0" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 980e2d5..69c56e0 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "utterform" -version = "1.0.0" +version = "1.1.0" description = "Fast, lightweight voice-to-text transformation for the desktop" authors = ["Jonas"] edition = "2024" diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 923b4ef..a445553 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -113,6 +113,7 @@ pub fn save_settings(app: AppHandle, value: AppSettings) -> Result<(), String> { Ok(()) => { app.state::() .set(!value.onboarding_completed); + crate::tray_microphones::set_selected(&app, value.input_device.clone()); diagnostics::info!( "settings.saved", engine = value.engine.as_str(), @@ -150,6 +151,7 @@ pub fn complete_onboarding( )); } app.state::().set(false); + crate::tray_microphones::set_selected(&app, value.input_device.clone()); if skipped { diagnostics::info!("onboarding.skipped"); } else { @@ -168,9 +170,12 @@ pub fn complete_onboarding( } #[tauri::command] -pub fn list_input_devices() -> Result, String> { - audio::list_input_devices() - .map_err(|failure| diagnostics::failure!("audio.devices_failed", &failure)) +pub fn list_input_devices(app: AppHandle) -> Result, String> { + let devices = audio::list_input_devices() + .map_err(|failure| diagnostics::failure!("audio.devices_failed", &failure))?; + // The window has just looked; the tray's Microphone menu shows the same. + crate::tray_microphones::set_devices(&app, devices.clone()); + Ok(devices) } /// Open the microphone and play the start cue. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cb4c743..5c34184 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -23,6 +23,7 @@ mod secrets; mod settings; mod transcription; mod tray; +mod tray_microphones; mod typing; use tauri::Manager; @@ -269,6 +270,7 @@ fn setup(app: &mut tauri::App, startup_intent: Intent) -> Result<(), Box(app: &AppHandle) { /// Install the tray icon, preferring the implementation that gives this /// platform a working click. -pub fn install(app: &AppHandle) -> tauri::Result<()> { +pub fn install(app: &AppHandle) -> tauri::Result<()> { #[cfg(target_os = "linux")] match status_notifier_item::install(app) { Ok(()) => { @@ -349,11 +350,10 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> { } /// Tauri's own tray. Left click and double click open the window where the -/// platform reports them. -fn native(app: &AppHandle) -> tauri::Result<()> { - let show = MenuItem::with_id(app, "show", "Show Utterform", true, None::<&str>)?; - let quit_item = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; - let menu = Menu::with_items(app, &[&show, &quit_item])?; +/// platform reports them; the pointer arriving on the icon reads the +/// microphones again, so the menu it is about to open is current. +fn native(app: &AppHandle) -> tauri::Result<()> { + let menu = native_menu(app, &tray_microphones::current(app))?; let mut tray = TrayIconBuilder::with_id(NATIVE_TRAY) .menu(&menu) .show_menu_on_left_click(false); @@ -363,9 +363,16 @@ fn native(app: &AppHandle) -> tauri::Result<()> { tray.on_menu_event(|app, event| match event.id.as_ref() { "show" => reveal_main_window(app, "tray_menu"), "quit" => quit(app), - _ => {} + id => { + if let Some(choice) = tray_microphones::choice(id) { + tray_microphones::choose(app, choice); + } + } }) .on_tray_icon_event(|tray, event| { + if matches!(event, TrayIconEvent::Enter { .. }) { + tray_microphones::refresh(tray.app_handle(), true); + } if opens_main_window(&event) { reveal_main_window(tray.app_handle(), "tray_click"); } @@ -374,24 +381,95 @@ fn native(app: &AppHandle) -> tauri::Result<()> { Ok(()) } +/// Show Utterform, Microphone (submenu), Quit. +fn native_menu(app: &AppHandle, microphones: &[Entry]) -> tauri::Result> { + let show = MenuItem::with_id(app, "show", "Show Utterform", true, None::<&str>)?; + let lines = microphones + .iter() + .map(|entry| { + CheckMenuItem::with_id( + app, + entry.id.as_str(), + native_label(&entry.label), + entry.enabled, + entry.checked, + None::<&str>, + ) + }) + .collect::>>()?; + let lines: Vec<&dyn IsMenuItem> = lines + .iter() + .map(|line| line as &dyn IsMenuItem) + .collect(); + let microphone = Submenu::with_items(app, "Microphone", true, &lines)?; + let separator = PredefinedMenuItem::separator(app)?; + let quit_item = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; + Menu::with_items(app, &[&show, µphone, &separator, &quit_item]) +} + +/// Windows reads `&` in a menu label as an access key; a device called +/// "Mic & Line" must keep its ampersand. +fn native_label(label: &str) -> String { + if cfg!(windows) { + label.replace('&', "&&") + } else { + label.to_owned() + } +} + +/// Redraw the Microphone submenu from what [`tray_microphones`] knows. +pub fn show_microphones(app: &AppHandle) { + let queued = app.clone(); + if app + .run_on_main_thread(move || { + let entries = tray_microphones::current(&queued); + #[cfg(target_os = "linux")] + if status_notifier_item::set_microphones(&queued, entries.clone()) { + return; + } + let Some(tray) = queued.tray_by_id(NATIVE_TRAY) else { + return; + }; + match native_menu(&queued, &entries) { + Ok(menu) => { + if tray.set_menu(Some(menu)).is_err() { + diagnostics::warning!("tray.microphones_failed", step = "set_menu"); + } + } + Err(_) => diagnostics::warning!("tray.microphones_failed", step = "build_menu"), + } + }) + .is_err() + { + diagnostics::warning!("tray.microphones_failed", step = "queue"); + } +} + #[cfg(target_os = "linux")] mod status_notifier_item { - use ksni::{Icon, MenuItem, blocking::TrayMethods, menu::StandardItem}; + use ksni::{ + Icon, MenuItem, + blocking::TrayMethods, + menu::{CheckmarkItem, StandardItem, SubMenu}, + }; use tauri::{AppHandle, Manager, Runtime}; use super::Status; use crate::activation::reveal_main_window; + use crate::tray_microphones::{self, Entry}; /// What the tray can ask Utterform to do. Keeping this behind a trait lets /// the D-Bus behaviour be tested without a running desktop application. pub trait TrayActions: Send + 'static { fn show(&self); fn quit(&self); + /// `None` is the system default. + fn choose_microphone(&self, microphone: Option); } - struct AppActions(AppHandle); + struct AppActions(AppHandle); - impl TrayActions for AppActions { + impl TrayActions for AppActions { fn show(&self) { reveal_main_window(&self.0, "tray"); } @@ -399,6 +477,10 @@ mod status_notifier_item { fn quit(&self) { super::quit(&self.0); } + + fn choose_microphone(&self, microphone: Option) { + tray_microphones::choose(&self.0, microphone); + } } pub struct UtterformTray { @@ -408,6 +490,7 @@ mod status_notifier_item { success_icon: Vec, failed_icon: Vec, status: Status, + microphones: Vec, } impl ksni::Tray for UtterformTray { @@ -448,6 +531,12 @@ mod status_notifier_item { ..Default::default() } .into(), + SubMenu { + label: "Microphone".into(), + submenu: self.microphones.iter().map(microphone_item).collect(), + ..Default::default() + } + .into(), MenuItem::Separator, StandardItem { label: "Quit".into(), @@ -459,6 +548,24 @@ mod status_notifier_item { } } + /// One microphone line. DBusMenu reads `_` as an access key, so a device + /// name keeps its underscores by doubling them. + fn microphone_item(entry: &Entry) -> MenuItem> { + let choice = tray_microphones::choice(&entry.id); + CheckmarkItem { + label: entry.label.replace('_', "__"), + checked: entry.checked, + enabled: entry.enabled, + activate: Box::new(move |tray: &mut UtterformTray| { + if let Some(choice) = choice.clone() { + tray.actions.choose_microphone(choice); + } + }), + ..Default::default() + } + .into() + } + /// Convert Tauri's RGBA icon bytes to the ARGB32 network byte order that the /// StatusNotifierItem specification asks for. fn rgba_to_argb32(rgba: &[u8]) -> Vec { @@ -483,6 +590,7 @@ mod status_notifier_item { success_icon, failed_icon, status: Status::Idle, + microphones: tray_microphones::entries(&[], None), } .spawn() } @@ -495,7 +603,7 @@ mod status_notifier_item { }] } - pub fn install(app: &AppHandle) -> Result<(), ksni::Error> { + pub fn install(app: &AppHandle) -> Result<(), ksni::Error> { let (icon, recording_icon, success_icon, failed_icon) = app .default_window_icon() .map(|image| { @@ -536,7 +644,7 @@ mod status_notifier_item { /// Swap the icon; `update` has ksni tell the host it changed. False when /// this session fell back to the native tray instead. pub(super) fn set_status(app: &AppHandle, status: Status) -> bool { - let Some(handle) = app.try_state::>>>() + let Some(handle) = app.try_state::>>() else { return false; }; @@ -547,6 +655,25 @@ mod status_notifier_item { true } + /// Replace the Microphone submenu. False when this session fell back to + /// the native tray instead. + pub(super) fn set_microphones(app: &AppHandle, microphones: Vec) -> bool { + let Some(handle) = app.try_state::>>() + else { + return false; + }; + if handle + .update(|tray| tray.microphones = microphones) + .is_none() + { + crate::diagnostics::warning!( + "tray.update_failed", + step = "status_notifier_microphones" + ); + } + true + } + #[cfg(test)] mod tests { use std::sync::Arc; @@ -567,6 +694,8 @@ mod status_notifier_item { } fn quit(&self) {} + + fn choose_microphone(&self, _microphone: Option) {} } /// The smallest watcher a StatusNotifierItem needs to find: it only has diff --git a/src-tauri/src/tray_microphones.rs b/src-tauri/src/tray_microphones.rs new file mode 100644 index 0000000..05f09a6 --- /dev/null +++ b/src-tauri/src/tray_microphones.rs @@ -0,0 +1,274 @@ +//! The tray's microphone menu: switch the microphone for the next recording +//! without opening Utterform — the laptop's own microphone while the Teams +//! headset lies on the desk, say. +//! +//! The choice is the same setting as Settings → Recording → Microphone. A +//! click writes it to the settings file here, so it holds even if the window +//! never loaded, and then tells the window so its copy of the settings agrees. +//! "System default" follows whatever the operating system calls its default +//! input; a chosen microphone that is unplugged falls back to it, as it always +//! has. +//! +//! Microphones come and go, so the list is read again whenever it might have +//! changed: at startup, when the window lists microphones, and on Windows and +//! macOS whenever the pointer moves onto the tray icon — that is, just before +//! its menu can be opened. + +use std::{ + sync::Mutex, + time::{Duration, Instant}, +}; + +use tauri::{AppHandle, Emitter, Manager}; + +use crate::{audio, diagnostics, domain::AudioDeviceInfo, settings}; + +/// What the window hears when the tray changed the microphone; the payload is +/// the device id, or `null` for the system default. +pub const CHOSEN_EVENT: &str = "microphone-chosen"; + +const DEFAULT_ID: &str = "microphone:default"; +const DEVICE_PREFIX: &str = "microphone:device:"; +const MISSING_ID: &str = "microphone:missing"; + +/// Hovering the tray icon fires many events; one look per this long is enough. +const REFRESH_INTERVAL: Duration = Duration::from_secs(2); + +/// One line of the Microphone submenu, the same on every platform. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + pub id: String, + pub label: String, + pub checked: bool, + pub enabled: bool, +} + +/// The submenu for these microphones with `selected` chosen (`None`: system +/// default). A chosen microphone that is not connected stays visible as a +/// greyed line, so the menu never claims the system default was chosen. +pub fn entries(devices: &[AudioDeviceInfo], selected: Option<&str>) -> Vec { + let default_label = match devices.iter().find(|device| device.is_default) { + Some(device) => format!("System default ({})", device.name), + None => "System default".into(), + }; + let mut entries = vec![Entry { + id: DEFAULT_ID.into(), + label: default_label, + checked: selected.is_none(), + enabled: true, + }]; + if let Some(selected) = selected + && !devices.iter().any(|device| device.id == selected) + { + entries.push(Entry { + id: MISSING_ID.into(), + label: "Chosen microphone (not connected, using system default)".into(), + checked: true, + enabled: false, + }); + } + entries.extend(devices.iter().map(|device| Entry { + id: format!("{DEVICE_PREFIX}{}", device.id), + label: device.name.clone(), + checked: selected == Some(device.id.as_str()), + enabled: true, + })); + entries +} + +/// The choice a menu id stands for: `Some(None)` is the system default, +/// `Some(Some(id))` a microphone, `None` not a microphone line at all. +pub fn choice(menu_id: &str) -> Option> { + if menu_id == DEFAULT_ID { + return Some(None); + } + menu_id + .strip_prefix(DEVICE_PREFIX) + .map(|device| Some(device.to_owned())) +} + +#[derive(Default)] +struct Known { + devices: Vec, + selected: Option, + refreshed: Option, +} + +/// What the tray menu currently shows. +#[derive(Default)] +pub struct MicrophoneMenu(Mutex); + +/// The submenu as it should look now. +pub fn current(app: &AppHandle) -> Vec { + let state = app.state::(); + let Ok(known) = state.0.lock() else { + return entries(&[], None); + }; + entries(&known.devices, known.selected.as_deref()) +} + +fn update(app: &AppHandle, apply: impl FnOnce(&mut Known)) { + { + let state = app.state::(); + let Ok(mut known) = state.0.lock() else { + diagnostics::warning!("tray.microphones_failed", step = "state"); + return; + }; + apply(&mut known); + } + crate::tray::show_microphones(app); +} + +/// Load the saved choice and read the microphones once, at startup. +pub fn init(app: &AppHandle) { + match settings::load(app) { + Ok(saved) => update(app, |known| known.selected = saved.input_device), + Err(failure) => { + diagnostics::warning!( + "tray.microphones_failed", + step = "settings", + class = failure.class() + ) + } + } + refresh(app, false); +} + +/// The settings were saved: show their microphone as chosen. +pub fn set_selected(app: &AppHandle, selected: Option) { + update(app, |known| known.selected = selected); +} + +/// The microphones were just read elsewhere; no need to read them again. +pub fn set_devices(app: &AppHandle, devices: Vec) { + update(app, |known| { + known.devices = devices; + known.refreshed = Some(Instant::now()); + }); +} + +/// Read the microphones again, off the event loop. `throttled` skips the read +/// when one happened moments ago. +pub fn refresh(app: &AppHandle, throttled: bool) { + { + let state = app.state::(); + let Ok(mut known) = state.0.lock() else { + return; + }; + if throttled + && known + .refreshed + .is_some_and(|last| last.elapsed() < REFRESH_INTERVAL) + { + return; + } + known.refreshed = Some(Instant::now()); + } + let app = app.clone(); + std::thread::spawn(move || match audio::list_input_devices() { + Ok(devices) => set_devices(&app, devices), + Err(failure) => { + diagnostics::warning!( + "tray.microphones_failed", + step = "list", + class = failure.class() + ) + } + }); +} + +/// A microphone line was clicked: save it as the microphone for recordings and +/// tell the window. A recording already running keeps its microphone. +pub fn choose(app: &AppHandle, selected: Option) { + let saved = settings::load(app).and_then(|mut value| { + value.input_device = selected.clone(); + settings::save(app, &value) + }); + if let Err(failure) = saved { + diagnostics::warning!("tray.microphone_choice_failed", class = failure.class()); + // Show the choice that is still in force. + update(app, |_| {}); + return; + } + diagnostics::info!( + "tray.microphone_chosen", + microphone = if selected.is_some() { + "device" + } else { + "default" + } + ); + set_selected(app, selected.clone()); + if app.emit(CHOSEN_EVENT, selected).is_err() { + diagnostics::warning!("tray.microphone_choice_failed", step = "emit"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn device(id: &str, name: &str, is_default: bool) -> AudioDeviceInfo { + AudioDeviceInfo { + id: id.into(), + name: name.into(), + is_default, + } + } + + fn devices() -> Vec { + vec![ + device("headset", "Headset (Jabra)", true), + device("laptop", "Microphone Array (Realtek)", false), + ] + } + + #[test] + fn the_system_default_is_checked_and_names_the_device_it_means() { + let entries = entries(&devices(), None); + assert_eq!(entries[0].label, "System default (Headset (Jabra))"); + assert!(entries[0].checked); + assert!(entries[1..].iter().all(|entry| !entry.checked)); + assert_eq!(entries.len(), 3); + } + + #[test] + fn a_chosen_microphone_is_the_only_line_checked() { + let entries = entries(&devices(), Some("laptop")); + let checked: Vec<_> = entries.iter().filter(|entry| entry.checked).collect(); + assert_eq!(checked.len(), 1); + assert_eq!(checked[0].label, "Microphone Array (Realtek)"); + } + + #[test] + fn an_unplugged_choice_stays_visible_but_cannot_be_clicked() { + let entries = entries(&devices(), Some("gone")); + assert!(!entries[0].checked); + assert_eq!(entries[1].id, MISSING_ID); + assert!(entries[1].checked && !entries[1].enabled); + assert_eq!(choice(&entries[1].id), None); + } + + #[test] + fn without_microphones_only_the_system_default_remains() { + let entries = entries(&[], None); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].label, "System default"); + } + + #[test] + fn menu_ids_round_trip_to_the_choice_they_stand_for() { + for entry in entries(&devices(), None) { + match entry.id.as_str() { + DEFAULT_ID => assert_eq!(choice(&entry.id), Some(None)), + _ => assert!(matches!(choice(&entry.id), Some(Some(_)))), + } + } + assert_eq!( + choice("microphone:device:{0.0.1.00000000}.{abc}"), + Some(Some("{0.0.1.00000000}.{abc}".into())) + ); + assert_eq!(choice("show"), None); + assert_eq!(choice("quit"), None); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 4e0600c..d323c24 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Utterform", - "version": "1.0.0", + "version": "1.1.0", "identifier": "software.jli.utterform", "build": { "beforeDevCommand": "npm run dev", diff --git a/src/App.svelte b/src/App.svelte index c1a23bc..2e2cae5 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -348,6 +348,11 @@ }); unlistenFiles = await Promise.all([ listen("file-waiting", () => { filesWaiting = true; }), + // The tray has already saved the choice; only this copy has to agree, + // so the next save or recording does not undo it. + listen("microphone-chosen", (event) => { + settings = { ...settings, input_device: event.payload }; + }), listen<{ paths: string[] }>("tauri://drag-enter", (event) => { dragActive = canTakeFile && event.payload.paths.length > 0; }), diff --git a/src/App.test.ts b/src/App.test.ts index e5a54b2..98b894b 100644 --- a/src/App.test.ts +++ b/src/App.test.ts @@ -1941,3 +1941,28 @@ describe("first-run assistant", () => { expect(view.queryByRole("dialog")).not.toBeNull(); }); }); + +describe("the tray's Microphone menu", () => { + it("records the next dictation with the microphone chosen in the tray, and never saves the old one back", async () => { + vi.mocked(api.startRecording).mockResolvedValue(undefined); + render(App); + await waitFor(() => expect(listeners.has("microphone-chosen")).toBe(true)); + // The backend has already written the choice to settings.json. + listeners.get("microphone-chosen")!({ payload: "laptop-microphone" }); + await remoteIntent("toggle"); + await waitFor(() => expect(api.startRecording).toHaveBeenCalledOnce()); + expect(vi.mocked(api.startRecording).mock.calls[0][0]).toBe("laptop-microphone"); + for (const [saved] of vi.mocked(api.saveSettings).mock.calls) expect(saved.input_device).toBe("laptop-microphone"); + }); + + it("goes back to the system default when the tray says so", async () => { + vi.mocked(api.getSettings).mockResolvedValue({ ...structuredClone(DEFAULT_SETTINGS), input_device: "headset" }); + vi.mocked(api.startRecording).mockResolvedValue(undefined); + render(App); + await waitFor(() => expect(listeners.has("microphone-chosen")).toBe(true)); + listeners.get("microphone-chosen")!({ payload: null }); + await remoteIntent("toggle"); + await waitFor(() => expect(api.startRecording).toHaveBeenCalledOnce()); + expect(vi.mocked(api.startRecording).mock.calls[0][0]).toBeNull(); + }); +});