feat #14740: settings, keyring, tray and manual recording

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-05 14:58:36 +01:00
co-authored by Claude Opus 5.5
parent ef07ecab1e
commit 1a2fc518ab
21 changed files with 2804 additions and 59 deletions
+201
View File
@@ -0,0 +1,201 @@
//! Tauri commands and the UI side effects of recording (windows, events).
//!
//! The handlers stay thin: the work happens in [`AppState`]. Anything that
//! blocks (audio devices, stopping a recorder, the keyring) runs on the
//! blocking pool so the UI thread never waits on it.
use std::thread;
use std::time::Duration;
use recorder_core::capture::Devices;
use recorder_core::model::CallId;
use recorder_core::secrets::Service;
use recorder_core::settings::Settings;
use tauri::{AppHandle, Emitter, Manager, State};
use tauri_plugin_autostart::ManagerExt;
use crate::state::{AppState, DeviceLevels, RecordingState};
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
type CmdResult<T> = Result<T, String>;
#[tauri::command]
pub fn get_settings(state: State<'_, AppState>) -> Settings {
state.settings()
}
#[tauri::command]
pub fn save_settings(
app: AppHandle,
state: State<'_, AppState>,
settings: Settings,
) -> CmdResult<()> {
let autostart = settings.autostart;
state.save_settings(settings)?;
apply_autostart(&app, autostart);
Ok(())
}
/// Stores `key` in the keyring; an empty key deletes the entry.
#[tauri::command]
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
blocking(app, move |app| {
let secrets = &app.state::<AppState>().secrets;
let key = key.trim();
let result = if key.is_empty() {
secrets.delete(service)
} else {
secrets.set(service, key)
};
result.map_err(|e| e.to_string())
})
.await
}
/// Whether a key is stored. Never returns the key itself.
#[tauri::command]
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
blocking(app, move |app| {
let key = app.state::<AppState>().secrets.get(service);
Ok(key.is_some_and(|key| !key.is_empty()))
})
.await
}
#[tauri::command]
pub async fn list_devices() -> CmdResult<Devices> {
tauri::async_runtime::spawn_blocking(recorder_audio::list_devices)
.await
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn test_devices(app: AppHandle) -> CmdResult<DeviceLevels> {
blocking(app, |app| app.state::<AppState>().test_devices()).await
}
#[tauri::command]
pub fn get_recording_state(state: State<'_, AppState>) -> RecordingState {
state.recording_state()
}
#[tauri::command]
pub async fn start_manual_recording(app: AppHandle) -> CmdResult<CallId> {
blocking(app, start_manual).await
}
#[tauri::command]
pub async fn stop_recording(app: AppHandle) -> CmdResult<()> {
blocking(app, stop).await
}
#[tauri::command]
pub async fn discard_current_recording(app: AppHandle) -> CmdResult<()> {
blocking(app, discard).await
}
/// Starts a manual recording, shows the floating window and streams levels.
pub fn start_manual(app: &AppHandle) -> CmdResult<CallId> {
let state = app.state::<AppState>().start_manual_recording()?;
let RecordingState::Recording { call_id, .. } = state else {
return Err("Aufnahme wurde nicht gestartet".to_string());
};
spawn_level_emitter(app.clone(), call_id);
set_window_visible(app, "recorder", true);
emit_state(app, &state);
Ok(call_id)
}
/// Stops the current recording and hides the floating window.
pub fn stop(app: &AppHandle) -> CmdResult<()> {
let result = app.state::<AppState>().stop_recording();
set_window_visible(app, "recorder", false);
emit_state(app, &RecordingState::Idle);
result.map(|_| ())
}
/// Throws the current recording away and hides the floating window.
pub fn discard(app: &AppHandle) -> CmdResult<()> {
let result = app.state::<AppState>().discard_current_recording();
set_window_visible(app, "recorder", false);
emit_state(app, &RecordingState::Idle);
result
}
/// Enables or disables launching at login. Debug builds leave the login
/// items alone so `cargo tauri dev` never registers a dev binary.
pub fn apply_autostart(app: &AppHandle, enabled: bool) {
if cfg!(debug_assertions) {
log::info!("debug build: not changing autostart (wanted {enabled})");
return;
}
let autolaunch = app.autolaunch();
let result = if enabled {
autolaunch.enable()
} else {
autolaunch.disable()
};
if let Err(e) = result {
log::error!("could not apply autostart={enabled}: {e}");
}
}
pub fn show_main(app: &AppHandle) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}
/// Brings back the floating window if the user closed it mid-recording.
pub fn show_recorder_if_recording(app: &AppHandle) {
if matches!(
app.state::<AppState>().recording_state(),
RecordingState::Recording { .. }
) {
set_window_visible(app, "recorder", true);
}
}
/// Emits `levels` every 100 ms until `call_id` stops being the current
/// recording.
fn spawn_level_emitter(app: AppHandle, call_id: CallId) {
thread::spawn(move || loop {
thread::sleep(LEVELS_INTERVAL);
let Some(levels) = app.state::<AppState>().levels(call_id) else {
break;
};
let _ = app.emit("levels", levels);
});
}
fn emit_state(app: &AppHandle, state: &RecordingState) {
if let Err(e) = app.emit("recording-state", state) {
log::error!("could not emit recording-state: {e}");
}
}
fn set_window_visible(app: &AppHandle, label: &str, visible: bool) {
if let Some(window) = app.get_webview_window(label) {
let result = if visible {
window.show()
} else {
window.hide()
};
if let Err(e) = result {
log::error!("could not change visibility of window {label}: {e}");
}
}
}
async fn blocking<T, F>(app: AppHandle, f: F) -> CmdResult<T>
where
T: Send + 'static,
F: FnOnce(&AppHandle) -> CmdResult<T> + Send + 'static,
{
tauri::async_runtime::spawn_blocking(move || f(&app))
.await
.map_err(|e| e.to_string())?
}
+78 -13
View File
@@ -1,16 +1,81 @@
mod commands;
mod state;
mod tray;
use recorder_core::secrets::KeyringSecrets;
use recorder_core::store::Store;
use tauri::{Manager, WindowEvent};
use tauri_plugin_autostart::MacosLauncher;
use crate::state::AppState;
/// Command-line flag the login item starts the app with; the main window
/// then stays hidden in the tray.
const AUTOSTART_ARG: &str = "--autostart";
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while building tauri application");
tauri::Builder::default()
// Must be registered first: a second launch only focuses the first.
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
commands::show_main(app);
}))
.plugin(tauri_plugin_autostart::init(
MacosLauncher::LaunchAgent,
Some(vec![AUTOSTART_ARG]),
))
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
let data_dir = app.path().app_data_dir()?;
let config_dir = app.path().app_config_dir()?;
std::fs::create_dir_all(&data_dir)?;
let store = Store::open(&data_dir.join("calls.sqlite"))?;
let recovery = store.startup_recovery()?;
log::info!("startup recovery: {recovery:?}");
let state = AppState::new(
store,
Box::new(KeyringSecrets),
config_dir.join("settings.json"),
data_dir.join("recordings"),
);
let autostart = state.settings().autostart;
app.manage(state);
commands::apply_autostart(app.handle(), autostart);
tray::create(app.handle())?;
if !std::env::args().any(|arg| arg == AUTOSTART_ARG) {
commands::show_main(app.handle());
}
Ok(())
})
.on_window_event(|window, event| {
// Closing a window only hides it; the app keeps running in the
// tray (for call detection) until "Beenden".
if let WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
}
})
.invoke_handler(tauri::generate_handler![
commands::get_settings,
commands::save_settings,
commands::set_api_key,
commands::has_api_key,
commands::list_devices,
commands::test_devices,
commands::get_recording_state,
commands::start_manual_recording,
commands::stop_recording,
commands::discard_current_recording,
])
.run(tauri::generate_context!())
.expect("error while building tauri application");
}
+1 -1
View File
@@ -2,5 +2,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
call_recorder_lib::run();
call_recorder_lib::run();
}
+279
View File
@@ -0,0 +1,279 @@
//! Application state shared by commands, the tray and background threads.
//!
//! Holds the store, the settings, the secret store and the recording that is
//! currently running. Everything here is independent of windows and events;
//! the command layer turns results into UI updates.
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::thread;
use std::time::{Duration, Instant};
use chrono::{DateTime, Local};
use recorder_core::capture::OutputTarget;
use recorder_core::model::{CallId, CallStatus};
use recorder_core::recorder::Recorder;
use recorder_core::secrets::SecretStore;
use recorder_core::settings::Settings;
use recorder_core::store::Store;
use serde::Serialize;
/// `app` value of calls started from the tray or UI instead of detection.
const MANUAL_APP: &str = "Manuell";
/// How long [`AppState::test_devices`] records.
const TEST_DURATION: Duration = Duration::from_secs(5);
const TEST_POLL: Duration = Duration::from_millis(50);
/// Payload of the `recording-state` event.
#[derive(Serialize, Clone, Debug)]
#[serde(tag = "state", rename_all = "lowercase")]
pub enum RecordingState {
Idle,
Recording {
call_id: CallId,
app: String,
started_at: DateTime<Local>,
},
}
/// Payload of the `levels` event.
#[derive(Serialize, Clone, Debug)]
pub struct Levels {
pub mic: f32,
pub out: f32,
pub failed_tracks: Vec<&'static str>,
}
/// Result of [`AppState::test_devices`]: peak rms level per track.
#[derive(Serialize, Clone, Copy, Debug)]
pub struct DeviceLevels {
pub mic: f32,
pub out: f32,
}
struct CurrentRecording {
call_id: CallId,
app: String,
started_at: DateTime<Local>,
recorder: Recorder,
}
pub struct AppState {
pub store: Store,
pub secrets: Box<dyn SecretStore>,
settings: Mutex<Settings>,
settings_path: PathBuf,
recordings_dir: PathBuf,
current: Mutex<Option<CurrentRecording>>,
/// Set while a recording starts or the devices are tested, so neither
/// runs twice and `current` is never locked for longer than a moment.
devices_busy: AtomicBool,
}
/// Releases [`AppState::devices_busy`] when dropped.
struct DevicesClaim<'a>(&'a AtomicBool);
impl Drop for DevicesClaim<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
impl AppState {
pub fn new(
store: Store,
secrets: Box<dyn SecretStore>,
settings_path: PathBuf,
recordings_dir: PathBuf,
) -> Self {
let settings = Settings::load(&settings_path);
Self {
store,
secrets,
settings: Mutex::new(settings),
settings_path,
recordings_dir,
current: Mutex::new(None),
devices_busy: AtomicBool::new(false),
}
}
pub fn settings(&self) -> Settings {
lock(&self.settings).clone()
}
pub fn save_settings(&self, settings: Settings) -> Result<(), String> {
settings
.save(&self.settings_path)
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?;
*lock(&self.settings) = settings;
Ok(())
}
pub fn recording_state(&self) -> RecordingState {
match lock(&self.current).as_ref() {
Some(cur) => RecordingState::Recording {
call_id: cur.call_id,
app: cur.app.clone(),
started_at: cur.started_at,
},
None => RecordingState::Idle,
}
}
/// Levels of the recording `call_id`, or `None` once it is no longer
/// the current recording.
pub fn levels(&self, call_id: CallId) -> Option<Levels> {
let current = lock(&self.current);
let cur = current.as_ref().filter(|cur| cur.call_id == call_id)?;
let (mic, out) = cur.recorder.levels();
Some(Levels {
mic,
out,
failed_tracks: cur.recorder.failed_tracks(),
})
}
/// Creates a call row and starts recording the configured mic and
/// output device into `recordings/<id>-mic.wav` / `<id>-out.wav`.
pub fn start_manual_recording(&self) -> Result<RecordingState, String> {
let _claim = self.claim_devices("Es läuft bereits eine Aufnahme")?;
let settings = self.settings();
fs::create_dir_all(&self.recordings_dir)
.map_err(|e| format!("Aufnahmeordner konnte nicht angelegt werden: {e}"))?;
let started_at = Local::now();
let call_id = self
.store
.create_call(MANUAL_APP, started_at, Path::new(""), Path::new(""))
.map_err(|e| format!("Gespräch konnte nicht angelegt werden: {e}"))?;
let (mic_path, out_path) = self.track_paths(call_id);
let started = self
.store
.set_paths(call_id, &mic_path, &out_path)
.map_err(|e| e.to_string())
.and_then(|()| {
let mic = recorder_audio::mic_source(settings.mic_device.as_deref());
let out = recorder_audio::output_source(output_target(&settings));
Recorder::start(mic, out, &mic_path, &out_path).map_err(|e| e.to_string())
});
let recorder = match started {
Ok(recorder) => recorder,
Err(err) => {
if let Err(e) = self.store.delete_call(call_id) {
log::error!("could not delete call {call_id} after failed start: {e}");
}
return Err(format!("Aufnahme konnte nicht gestartet werden: {err}"));
}
};
*lock(&self.current) = Some(CurrentRecording {
call_id,
app: MANUAL_APP.to_string(),
started_at,
recorder,
});
Ok(self.recording_state())
}
/// Stops the current recording and finalizes its row. Returns `Ok(false)`
/// if nothing was recording. A recorder error still finishes the row and
/// marks the call as failed.
pub fn stop_recording(&self) -> Result<bool, String> {
let Some(cur) = lock(&self.current).take() else {
return Ok(false);
};
let result = cur.recorder.stop();
let id = cur.call_id;
self.store
.finish_recording(id, Local::now(), false)
.map_err(|e| format!("Gespräch konnte nicht gespeichert werden: {e}"))?;
if let Err(err) = result {
let msg = format!("Aufnahme fehlerhaft: {err}");
if let Err(e) = self.store.set_status(id, CallStatus::Failed, Some(&msg)) {
log::error!("could not mark call {id} as failed: {e}");
}
return Err(msg);
}
Ok(true)
}
/// Discards the current recording: deletes both WAVs and the call row.
pub fn discard_current_recording(&self) -> Result<(), String> {
let Some(cur) = lock(&self.current).take() else {
return Ok(());
};
cur.recorder.discard();
self.store
.delete_call(cur.call_id)
.map_err(|e| format!("Gespräch konnte nicht gelöscht werden: {e}"))
}
/// Records both configured devices into a temporary directory for five
/// seconds and returns the peak level of each track.
pub fn test_devices(&self) -> Result<DeviceLevels, String> {
let _claim = self.claim_devices("Während einer Aufnahme ist kein Test möglich")?;
let settings = self.settings();
let dir = tempfile::tempdir()
.map_err(|e| format!("Testordner konnte nicht angelegt werden: {e}"))?;
let mic = recorder_audio::mic_source(settings.mic_device.as_deref());
let out = recorder_audio::output_source(output_target(&settings));
let recorder = Recorder::start(
mic,
out,
&dir.path().join("test-mic.wav"),
&dir.path().join("test-out.wav"),
)
.map_err(|e| format!("Test fehlgeschlagen: {e}"))?;
let mut peak = DeviceLevels { mic: 0.0, out: 0.0 };
let until = Instant::now() + TEST_DURATION;
while Instant::now() < until {
thread::sleep(TEST_POLL);
let (mic, out) = recorder.levels();
peak.mic = peak.mic.max(mic);
peak.out = peak.out.max(out);
}
recorder.discard();
Ok(peak)
}
/// Reserves the audio devices for a recording start or a test. Fails
/// with `recording_msg` while a recording runs.
fn claim_devices(&self, recording_msg: &str) -> Result<DevicesClaim<'_>, String> {
if self.devices_busy.swap(true, Ordering::SeqCst) {
return Err("Die Audiogeräte werden gerade getestet oder gestartet".to_string());
}
let claim = DevicesClaim(&self.devices_busy);
// Checked after claiming: a start that just finished has already
// stored its recording before releasing the claim.
if lock(&self.current).is_some() {
return Err(recording_msg.to_string());
}
Ok(claim)
}
fn track_paths(&self, id: CallId) -> (PathBuf, PathBuf) {
(
self.recordings_dir.join(format!("{id}-mic.wav")),
self.recordings_dir.join(format!("{id}-out.wav")),
)
}
}
fn output_target(settings: &Settings) -> OutputTarget {
match &settings.output_device {
Some(id) => OutputTarget::Device(id.clone()),
None => OutputTarget::DefaultRender,
}
}
/// Locks ignoring poisoning: a panic in one command must not wedge the app.
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
+75
View File
@@ -0,0 +1,75 @@
//! Tray icon with "Öffnen", "Aufnahme manuell starten" and "Beenden".
use std::thread;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::{AppHandle, Manager};
use crate::commands;
use crate::state::AppState;
const OPEN: &str = "open";
const RECORD: &str = "record";
const QUIT: &str = "quit";
pub fn create(app: &AppHandle) -> tauri::Result<()> {
let menu = Menu::with_items(
app,
&[
&MenuItem::with_id(app, OPEN, "Öffnen", true, None::<&str>)?,
&MenuItem::with_id(app, RECORD, "Aufnahme manuell starten", true, None::<&str>)?,
&PredefinedMenuItem::separator(app)?,
&MenuItem::with_id(app, QUIT, "Beenden", true, None::<&str>)?,
],
)?;
let mut builder = TrayIconBuilder::with_id("main")
.tooltip("Gesprächsrekorder")
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id().as_ref() {
OPEN => {
commands::show_main(app);
commands::show_recorder_if_recording(app);
}
RECORD => {
// Opening the audio devices can take a moment; keep the
// event loop free.
let app = app.clone();
thread::spawn(move || {
if let Err(e) = commands::start_manual(&app) {
log::error!("manual recording from tray failed: {e}");
}
});
}
QUIT => quit(app),
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
commands::show_main(tray.app_handle());
}
});
if let Some(icon) = app.default_window_icon() {
builder = builder.icon(icon.clone());
}
builder.build(app)?;
Ok(())
}
/// Finalizes a running recording, then exits.
fn quit(app: &AppHandle) {
let app = app.clone();
thread::spawn(move || {
if let Err(e) = app.state::<AppState>().stop_recording() {
log::error!("stopping the recording on quit failed: {e}");
}
app.exit(0);
});
}