diff --git a/crates/voelin-ui-vm/src/host.rs b/crates/voelin-ui-vm/src/host.rs index 0f99c3a..c1209f4 100644 --- a/crates/voelin-ui-vm/src/host.rs +++ b/crates/voelin-ui-vm/src/host.rs @@ -114,6 +114,10 @@ pub enum Persist { }, /// The UI's own settings changed (`AppState::settings`). Settings, + /// The audio settings changed (`AppState::audio`). + Audio, + /// The clients' local volumes changed (`AppState::playback`). + Playback, } /// The password dialog of a locked channel is to open diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index 7ba361a..d2a41fe 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -24,6 +24,7 @@ pub mod list; pub mod previews; pub mod servers; pub mod settings; +pub mod settings_page; pub mod settings_pages; pub mod social; pub mod state; diff --git a/crates/voelin-ui-vm/src/settings_page/logic.rs b/crates/voelin-ui-vm/src/settings_page/logic.rs new file mode 100644 index 0000000..082b04d --- /dev/null +++ b/crates/voelin-ui-vm/src/settings_page/logic.rs @@ -0,0 +1,412 @@ +//! The audio settings page and the local volume of clients: the device +//! lists and the form, what a change of the form sends to the engine, the +//! microphone test, the push-to-talk and H.264 switches, the crash notice +//! and the volume dialog. The functions change the +//! [`AppState`](crate::state::AppState) and say in the [`Cx`]'s update what +//! to send and keep; the devices, the hotkey, the store and the window are +//! the front end's. + +use voelin_core::Command; + +use crate::bridge::{AudioForm, ClientAudio}; +use crate::host::{Cx, Persist}; +use crate::settings::{ClientPlayback, DeviceChoices, apply_audio_form, audio_form}; +use crate::state::AppState; + +/// What the settings page shows when it opens ([`open_settings`]). +#[derive(Clone, Debug, PartialEq)] +pub struct SettingsView { + /// The input devices' names, the system default first. + pub input_devices: Vec, + /// The output devices' names, the system default first. + pub output_devices: Vec, + /// The form of the audio settings. + pub audio: AudioForm, + /// The push-to-talk key works in every window. + pub global_ptt: bool, + /// The push-to-talk key. + pub ptt_key: String, + /// H.264 through the downloaded OpenH264 is on. + pub h264_enabled: bool, +} + +/// An audio device the system lists: its id, its name and whether it is the +/// system's default of its direction. +pub type Device = (String, String, bool); + +/// The settings page opens: the devices the system lists become the choices +/// (a device that is stored but not there stays in the list), and the form +/// and the switches are those of the state. +pub fn open_settings( + state: &mut AppState, + inputs: &[Device], + outputs: &[Device], +) -> SettingsView { + state.inputs = DeviceChoices::new(inputs, state.audio.input_device.as_deref()); + state.outputs = DeviceChoices::new(outputs, state.audio.output_device.as_deref()); + SettingsView { + input_devices: state.inputs.names.clone(), + output_devices: state.outputs.names.clone(), + audio: audio_form(&state.audio, &state.inputs, &state.outputs), + global_ptt: state.settings.global_ptt, + ptt_key: state.settings.ptt_key.clone(), + h264_enabled: state.settings.openh264, + } +} + +/// The form changed: the engine gets the new audio settings, and they are +/// kept later ([`save_audio`]), if the form changed anything. +pub fn audio_changed(state: &mut AppState, cx: &mut Cx<'_>, form: &AudioForm) { + let audio = apply_audio_form(form, &state.audio, &state.inputs, &state.outputs); + if audio == state.audio { + return; + } + state.audio = audio; + state.audio_dirty = true; + cx.send(Command::SetAudioSettings(Box::new(state.audio.clone()))); +} + +/// Keep the audio settings, if they changed since they were kept. +pub fn save_audio(state: &mut AppState, cx: &mut Cx<'_>) { + if state.audio_dirty { + state.audio_dirty = false; + cx.persist(Persist::Audio); + } +} + +/// The settings page closes: the microphone test stops and the audio +/// settings are kept. Whether the test was on. +pub fn close_settings(state: &mut AppState, cx: &mut Cx<'_>) -> bool { + let was_on = set_mic_test(state, cx, false); + save_audio(state, cx); + was_on +} + +/// Start or stop the microphone test: whether that changed anything. +pub fn set_mic_test(state: &mut AppState, cx: &mut Cx<'_>, on: bool) -> bool { + if state.mic_test == on { + return false; + } + state.mic_test = on; + cx.send(Command::TestMicrophone { on }); + true +} + +/// The push-to-talk switch and key: kept, and the key to register as a +/// hotkey of the whole desktop, none to unregister it. A blank key leaves +/// the one that was set. +pub fn apply_ptt( + state: &mut AppState, + cx: &mut Cx<'_>, + enabled: bool, + key: &str, +) -> Option { + let key = key.trim().to_owned(); + state.settings.global_ptt = enabled; + if !key.is_empty() { + state.settings.ptt_key = key.clone(); + } + cx.persist(Persist::Settings); + (enabled && !key.is_empty()).then_some(key) +} + +/// The H.264 switch: kept; the front end tells the encoder. +pub fn set_h264(state: &mut AppState, cx: &mut Cx<'_>, enabled: bool) { + state.settings.openh264 = enabled; + cx.persist(Persist::Settings); +} + +/// What the H.264 rows show ([`h264_view`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct H264View { + /// The library is loaded. + pub loaded: bool, + /// It is being downloaded. + pub busy: bool, + /// What the front end's codec says. + pub status: String, +} + +/// The H.264 rows for the codec's state: `loaded`, and its `status` text +/// ("Downloading …" while it is being fetched). +pub fn h264_view(loaded: bool, status: String) -> H264View { + H264View { loaded, busy: status.starts_with("Downloading"), status } +} + +/// The crash reports switch: kept (the front end also tells the crash +/// handler and the settings service). +pub fn set_crash_reports(state: &mut AppState, cx: &mut Cx<'_>, enabled: bool) { + state.settings.crash_reports = enabled; + // Also in the blob, for older versions. + cx.persist(Persist::Settings); +} + +/// The notice while crash reports are on disk: `summaries` are the first +/// lines of their panic messages, oldest first. Empty without reports. +pub fn crash_notice(summaries: &[String]) -> String { + let Some(newest) = summaries.last() else { return String::new() }; + let saved = match summaries.len() { + 1 => "1 crash report is saved".to_owned(), + n => format!("{n} crash reports are saved"), + }; + format!("The app crashed earlier ({newest}). {saved} on this device.") +} + +// Local volume and mute of clients. + +/// Fill the volume dialog for `client` of the current session; none when +/// there is no such client. +pub fn open_client(state: &mut AppState, client: u16) -> Option { + let id = state.current?; + let info = state.sessions.get(&id)?.presence.clients.get(&client)?.clone(); + let playback = + info.uid.as_ref().and_then(|uid| state.playback.get(uid)).copied().unwrap_or_default(); + state.playback_dialog = Some((id, client, info.uid.clone())); + Some(ClientAudio { + id: i32::from(client), + name: info.nickname.into(), + volume: playback.volume * 100.0, + muted: playback.muted, + streaming: info.streaming == Some(true), + }) +} + +/// The volume dialog changed: the engine plays the client so, and the +/// choice is kept by the client's unique id (a client without one only for +/// this connection), the default as no choice. The tree shows who is muted. +pub fn client_playback_changed(state: &mut AppState, cx: &mut Cx<'_>, form: &ClientAudio) { + let Some((session, client, uid)) = state.playback_dialog.clone() else { return }; + let playback = + ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted }; + let session = session as u64; + cx.send(Command::SetClientVolume { session, client, volume: playback.volume }); + cx.send(Command::SetClientMuted { session, client, muted: playback.muted }); + if let Some(uid) = uid { + if playback.is_default() { + state.playback.remove(&uid); + } else { + state.playback.insert(uid, playback); + } + cx.persist(Persist::Playback); + } + cx.update.refresh.tree = true; +} + +/// The first client of the current session that is not us nor a query +/// client (`VOELIN_OPEN=client`): its id, when we are in the session. +pub fn first_client(state: &AppState) -> Option { + let view = state.current.and_then(|id| state.sessions.get(&id))?; + let own = view.state.own_client?; + view.presence.clients.values().filter(|c| c.id != own && !c.is_query).map(|c| c.id).min() +} + +#[cfg(test)] +mod tests { + use voelin_core::VoiceState; + + use super::*; + use crate::host::testing::{Fake, State, presence, session, state}; + + fn device(id: &str, name: &str, default: bool) -> Device { + (id.into(), name.into(), default) + } + + #[test] + fn the_page_opens_with_the_devices_and_a_stored_one_stays() { + let mut st = state(); + st.audio.input_device = Some("gone".into()); + st.settings.global_ptt = true; + st.settings.ptt_key = "F9".into(); + let inputs = [device("a", "Built-in", true), device("b", "Headset", false)]; + let outputs = [device("a", "Built-in", false), device("b", "Headset", true)]; + let view = open_settings(&mut st, &inputs, &outputs); + // The system default first, named after the one that is the default. + assert_eq!( + view.input_devices, + ["System default (Built-in)", "Built-in", "Headset", "gone (not connected)"] + ); + // Outputs have the other as the default, and no stored device. + assert_eq!(view.output_devices, ["System default (Headset)", "Built-in", "Headset"]); + assert_eq!(view.audio.input_index, 3, "the stored device is selected"); + assert_eq!(view.audio.output_index, 0, "no stored output: the default"); + assert!(view.global_ptt && view.ptt_key == "F9" && !view.h264_enabled); + assert_eq!(st.inputs.names, view.input_devices); + } + + #[test] + fn a_change_of_the_form_goes_to_the_engine_once_and_is_kept_later() { + let mut st = state(); + let host = Fake::default(); + open_settings(&mut st, &[], &[]); + let mut form = audio_form(&st.audio, &st.inputs, &st.outputs); + // Nothing changed: nothing sent. + let mut cx = Cx::new(&host); + audio_changed(&mut st, &mut cx, &form); + assert!(cx.update.commands.is_empty() && !st.audio_dirty); + form.output_volume = 50.0; + audio_changed(&mut st, &mut cx, &form); + assert!(matches!( + cx.update.commands.as_slice(), + [Command::SetAudioSettings(audio)] if audio.output_volume == 0.5 + )); + assert!(st.audio_dirty); + // The same form again changes nothing. + audio_changed(&mut st, &mut cx, &form); + assert_eq!(cx.update.commands.len(), 1); + // Kept once, when the page closes or the clock ticks. + save_audio(&mut st, &mut cx); + save_audio(&mut st, &mut cx); + assert_eq!(cx.update.persist, [Persist::Audio]); + assert!(!st.audio_dirty); + } + + #[test] + fn the_microphone_test_stops_with_the_page() { + let mut st = state(); + let host = Fake::default(); + let mut cx = Cx::new(&host); + assert!(!close_settings(&mut st, &mut cx), "it was not on"); + assert!(cx.update.commands.is_empty()); + assert!(set_mic_test(&mut st, &mut cx, true)); + assert!(!set_mic_test(&mut st, &mut cx, true), "already on"); + st.audio_dirty = true; + assert!(close_settings(&mut st, &mut cx), "it was on"); + assert!(!st.mic_test); + assert!(matches!( + cx.update.commands.as_slice(), + [Command::TestMicrophone { on: true }, Command::TestMicrophone { on: false }] + )); + assert_eq!(cx.update.persist, [Persist::Audio]); + } + + #[test] + fn the_push_to_talk_key_is_registered_when_it_is_on_and_set() { + let mut st = state(); + let host = Fake::default(); + let mut cx = Cx::new(&host); + assert_eq!(apply_ptt(&mut st, &mut cx, true, " F9 ").as_deref(), Some("F9")); + assert!(st.settings.global_ptt); + assert_eq!(st.settings.ptt_key, "F9"); + // Off: unregistered, the key stays for later. + assert_eq!(apply_ptt(&mut st, &mut cx, false, "F10"), None); + assert_eq!(st.settings.ptt_key, "F10"); + // A blank key leaves the one that was set, and registers nothing. + assert_eq!(apply_ptt(&mut st, &mut cx, true, " "), None); + assert_eq!(st.settings.ptt_key, "F10"); + assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings, Persist::Settings]); + } + + #[test] + fn the_switches_are_kept() { + let mut st = state(); + let host = Fake::default(); + let mut cx = Cx::new(&host); + set_h264(&mut st, &mut cx, true); + set_crash_reports(&mut st, &mut cx, true); + assert!(st.settings.openh264 && st.settings.crash_reports); + assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings]); + assert_eq!( + h264_view(false, "Downloading OpenH264… 40%".into()), + H264View { loaded: false, busy: true, status: "Downloading OpenH264… 40%".into() } + ); + assert!(!h264_view(true, "Loaded".into()).busy); + } + + #[test] + fn the_crash_notice_counts_the_reports() { + assert_eq!(crash_notice(&[]), ""); + assert_eq!( + crash_notice(&["index out of bounds".into()]), + "The app crashed earlier (index out of bounds). 1 crash report is saved on this device." + ); + assert_eq!( + crash_notice(&["old".into(), "new".into()]), + "The app crashed earlier (new). 2 crash reports are saved on this device." + ); + } + + /// Connected, with Alice (11) in Games next to us (10), a query client + /// (12) and Zed (9, a lower id). + fn with_clients() -> State { + let mut st = state(); + let mut p = (*presence()).clone(); + p.clients.get_mut(&11).unwrap().streaming = Some(true); + for (id, name, query) in [(12, "serveradmin", true), (9, "Zed", false)] { + p.clients.insert( + id, + voelin_model::ClientInfo { + id, + channel: 2, + nickname: name.into(), + is_query: query, + ..Default::default() + }, + ); + } + let view = st.sessions.entry(1).or_default(); + view.presence = std::sync::Arc::new(p); + view.state = session(VoiceState::Connected, Some(2)); + st + } + + #[test] + fn the_volume_dialog_fills_from_what_was_kept() { + let mut st = with_clients(); + assert_eq!(open_client(&mut st, 99), None, "no such client"); + let form = open_client(&mut st, 11).unwrap(); + assert_eq!((form.id, &*form.name, form.volume, form.muted), (11, "Alice", 100.0, false)); + assert!(form.streaming); + assert_eq!(st.playback_dialog, Some((1, 11, Some("alice=".into())))); + st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true }); + let form = open_client(&mut st, 11).unwrap(); + assert_eq!((form.volume, form.muted), (50.0, true)); + st.current = None; + assert_eq!(open_client(&mut st, 11), None, "no server shown"); + } + + #[test] + fn a_client_is_played_as_the_dialog_says_and_the_default_is_forgotten() { + let mut st = with_clients(); + let host = Fake::default(); + let mut cx = Cx::new(&host); + // No dialog open: nothing. + client_playback_changed(&mut st, &mut cx, &ClientAudio::default()); + assert!(cx.update.commands.is_empty()); + let mut form = open_client(&mut st, 11).unwrap(); + form.volume = 900.0; + form.muted = true; + client_playback_changed(&mut st, &mut cx, &form); + // Clamped to four times, sent, kept by unique id, the tree shows it. + assert!(matches!( + cx.update.commands.as_slice(), + [ + Command::SetClientVolume { session: 1, client: 11, volume: 4.0 }, + Command::SetClientMuted { session: 1, client: 11, muted: true }, + ] + )); + assert_eq!(st.playback["alice="], ClientPlayback { volume: 4.0, muted: true }); + assert_eq!(cx.update.persist, [Persist::Playback]); + assert!(cx.update.refresh.tree); + // Back to the default: no entry. + form.volume = 100.0; + form.muted = false; + client_playback_changed(&mut st, &mut cx, &form); + assert!(st.playback.is_empty()); + // A client without a unique id is played so only for now. + st.playback_dialog = Some((1, 9, None)); + let before = cx.update.persist.len(); + client_playback_changed(&mut st, &mut cx, &form); + assert!(st.playback.is_empty()); + assert_eq!(cx.update.persist.len(), before); + } + + #[test] + fn the_first_client_is_the_lowest_id_that_is_not_us() { + let mut st = with_clients(); + assert_eq!(first_client(&st), Some(9), "not us (10), not the query client"); + st.sessions.get_mut(&1).unwrap().state.own_client = None; + assert_eq!(first_client(&st), None, "not in the session"); + st.current = None; + assert_eq!(first_client(&st), None); + } +} diff --git a/crates/voelin-ui-vm/src/settings_page/mod.rs b/crates/voelin-ui-vm/src/settings_page/mod.rs new file mode 100644 index 0000000..47f873c --- /dev/null +++ b/crates/voelin-ui-vm/src/settings_page/mod.rs @@ -0,0 +1,6 @@ +//! The settings page of the audio devices and the voice controls, the push +//! to talk key, the H.264 switch, the crash reports and the volume of a +//! client. [`logic`] has what the page shows and what its controls change; +//! the engine, the store, the hotkey and the window are the front end's. + +pub mod logic; diff --git a/crates/voelin-ui/src/host.rs b/crates/voelin-ui/src/host.rs index e314ef9..4e5f32d 100644 --- a/crates/voelin-ui/src/host.rs +++ b/crates/voelin-ui/src/host.rs @@ -7,11 +7,11 @@ use slint::ComponentHandle; use tracing::{debug, warn}; use voelin_core::Event; -use voelin_core::settings::{CACHE_FETCH_IMAGES, Settings}; +use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings}; use voelin_store::{ChatRead, ChatTarget as StoredTarget, Store}; use crate::app::{App, AppState, Bridge, MainWindow, Nav}; -use crate::settings::UI_IMAGE_PREVIEW_KB; +use crate::settings::{CLIENT_PLAYBACK, UI_IMAGE_PREVIEW_KB}; use crate::studio::StudioState; use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update}; @@ -213,6 +213,16 @@ impl App { } } Persist::Settings => self.store_settings(), + Persist::Audio => { + if let Err(e) = self.prefs.set(&AUDIO, self.state.audio.clone()) { + warn!(%e, "could not store audio settings"); + } + } + Persist::Playback => { + if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.state.playback.clone()) { + warn!(%e, "could not store client volumes"); + } + } } } diff --git a/crates/voelin-ui/src/settings_page.rs b/crates/voelin-ui/src/settings_page.rs deleted file mode 100644 index 7d612f1..0000000 --- a/crates/voelin-ui/src/settings_page.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! The settings page (audio, push-to-talk, H.264, crash reports), the -//! About page's notices, and the local volume of clients. - -use slint::{ComponentHandle, SharedString}; -use tracing::warn; -use voelin_core::Command; -use voelin_core::settings::{AUDIO, CRASH_REPORTS}; -use voelin_platform::{crash, notices}; - -use crate::app::{App, Bridge, later, model}; -use crate::settings::{self, CLIENT_PLAYBACK, ClientPlayback, DeviceChoices}; -use crate::vm::bridge::{AudioForm, ClientAudio}; - -impl App { - pub(crate) fn open_settings(&mut self) { - let list = |devices: voelin_audio::Result>, - input: bool| { - let devices = devices.unwrap_or_else(|e| { - warn!("cannot list audio devices: {e}"); - Vec::new() - }); - devices - .into_iter() - .map(|d| { - let default = if input { d.default_input } else { d.default_output }; - (d.id, d.name, default) - }) - .collect::>() - }; - let inputs = list(voelin_audio::device::input_devices(), true); - let outputs = list(voelin_audio::device::output_devices(), false); - self.state.inputs = DeviceChoices::new(&inputs, self.state.audio.input_device.as_deref()); - self.state.outputs = - DeviceChoices::new(&outputs, self.state.audio.output_device.as_deref()); - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let names = |c: &DeviceChoices| model(c.names.iter().map(SharedString::from).collect()); - bridge.set_input_devices(names(&self.state.inputs)); - bridge.set_output_devices(names(&self.state.outputs)); - bridge.set_audio( - settings::audio_form(&self.state.audio, &self.state.inputs, &self.state.outputs).into(), - ); - bridge.set_global_ptt(self.state.settings.global_ptt); - bridge.set_ptt_key(self.state.settings.ptt_key.clone().into()); - bridge.set_h264_enabled(self.state.settings.openh264); - bridge.set_image_cache_usage(crate::images::usage_text().into()); - self.refresh_h264(); - self.refresh_identities(); - } - - pub(crate) fn close_settings(&mut self) { - self.set_mic_test(false); - self.save_audio(); - } - - pub(crate) fn audio_changed(&mut self, form: &AudioForm) { - let audio = settings::apply_audio_form( - form, - &self.state.audio, - &self.state.inputs, - &self.state.outputs, - ); - if audio == self.state.audio { - return; - } - self.state.audio = audio; - self.state.audio_dirty = true; - self.engine.send(Command::SetAudioSettings(Box::new(self.state.audio.clone()))); - } - - pub(crate) fn save_audio(&mut self) { - if !self.state.audio_dirty { - return; - } - self.state.audio_dirty = false; - if let Err(e) = self.prefs.set(&AUDIO, self.state.audio.clone()) { - warn!(%e, "could not store audio settings"); - } - } - - pub(crate) fn set_mic_test(&mut self, on: bool) { - if self.state.mic_test == on { - return; - } - self.state.mic_test = on; - self.engine.send(Command::TestMicrophone { on }); - if let Some(ui) = self.ui.upgrade() { - let bridge = ui.global::(); - bridge.set_mic_test(on); - if !on { - bridge.set_input_level(-100.0); - } - } - } - - pub(crate) fn apply_ptt(&mut self, enabled: bool, key: String) { - let key = key.trim().to_owned(); - self.state.settings.global_ptt = enabled; - if !key.is_empty() { - self.state.settings.ptt_key = key.clone(); - } - self.store_settings(); - self.ptt.set((enabled && !key.is_empty()).then_some(key)); - } - - pub(crate) fn set_ptt_status(&mut self, status: String) { - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_ptt_status(status.into()); - } - } - - pub(crate) fn set_h264(&mut self, enabled: bool) { - self.state.settings.openh264 = enabled; - self.store_settings(); - self.video.set_h264(enabled); - self.refresh_h264(); - } - - pub(crate) fn download_h264(&mut self) { - let runtime = self.engine.runtime().clone(); - self.video.download_h264(&runtime, |download| { - later(move |app| { - app.video.downloaded(download, app.state.settings.openh264); - app.refresh_h264(); - }); - }); - self.refresh_h264(); - } - - fn refresh_h264(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let (loaded, status) = self.video.h264_status(); - bridge.set_h264_loaded(loaded); - bridge.set_h264_busy(status.starts_with("Downloading")); - bridge.set_h264_status(status.into()); - } - - /// Switches the About page and the settings show. - pub(crate) fn refresh_settings_flags(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - bridge.set_h264_enabled(self.state.settings.openh264); - bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into()); - bridge.set_crash_reports(self.state.settings.crash_reports); - } - - /// The transmit mode for the voice controls (Hold to talk shows for - /// push-to-talk) before the settings page fills the whole form: only - /// `transmit` changes, as the device lists are not read yet. - pub(crate) fn refresh_transmit(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let mut form = bridge.get_audio(); - form.transmit = settings::transmit_index(self.state.audio.transmit); - bridge.set_audio(form); - } - - pub(crate) fn set_crash_reports(&mut self, enabled: bool) { - self.state.settings.crash_reports = enabled; - // Also in the blob, for older versions. - self.store_settings(); - if let Err(e) = self.prefs.set(&CRASH_REPORTS, enabled) { - warn!(%e, "could not store the crash report setting"); - } - crash::set_enabled(enabled); - } - - /// A notice while crash reports are on disk. - pub(crate) fn refresh_crash_notice(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let text = match crash::pending_reports() { - Ok(reports) if !reports.is_empty() => { - let newest = &reports[reports.len() - 1]; - let saved = match reports.len() { - 1 => "1 crash report is saved".to_owned(), - n => format!("{n} crash reports are saved"), - }; - format!("The app crashed earlier ({}). {saved} on this device.", newest.summary) - } - _ => String::new(), - }; - ui.global::().set_crash_notice(text.into()); - } - - pub(crate) fn open_crash_folder(&mut self) { - let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned()); - if let Err(e) = - result.and_then(|dir| crate::app::open_path(&dir).map_err(|e| e.to_string())) - { - self.set_status(format!("Cannot open the crash report folder: {e}")); - } - } - - pub(crate) fn delete_crash_reports(&mut self) { - match crash::clear() { - Ok(n) => self.set_status(format!("Deleted {n} crash reports")), - Err(e) => self.set_status(format!("Cannot delete the crash reports: {e}")), - } - self.refresh_crash_notice(); - } - - /// The third-party notices, one model entry per line. - pub(crate) fn load_notices(&mut self) { - if self.notices_loaded { - return; - } - let Some(ui) = self.ui.upgrade() else { return }; - let lines: Vec = notices::text().lines().map(SharedString::from).collect(); - ui.global::().set_notices(model(lines)); - self.notices_loaded = true; - } - - // Local volume and mute of clients. - - /// Fill the volume dialog for `client` of the current session. - pub(crate) fn open_client(&mut self, client: u16) -> bool { - let Some(id) = self.state.current else { return false }; - let Some(info) = self.view().and_then(|v| v.presence.clients.get(&client)).cloned() else { - return false; - }; - let playback = info - .uid - .as_ref() - .and_then(|uid| self.state.playback.get(uid)) - .copied() - .unwrap_or_default(); - self.state.playback_dialog = Some((id, client, info.uid.clone())); - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_client_audio( - ClientAudio { - id: client as i32, - name: info.nickname.into(), - volume: playback.volume * 100.0, - muted: playback.muted, - streaming: info.streaming == Some(true), - } - .into(), - ); - } - true - } - - pub(crate) fn client_playback_changed(&mut self, form: &ClientAudio) { - let Some((session, client, uid)) = self.state.playback_dialog.clone() else { return }; - let playback = - ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted }; - let session = session as u64; - self.engine.send(Command::SetClientVolume { session, client, volume: playback.volume }); - self.engine.send(Command::SetClientMuted { session, client, muted: playback.muted }); - // Kept by unique id; clients without one only for this connection. - if let Some(uid) = uid { - if playback.is_default() { - self.state.playback.remove(&uid); - } else { - self.state.playback.insert(uid, playback); - } - if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.state.playback.clone()) { - warn!(%e, "could not store client volumes"); - } - } - self.refresh_tree(); - } - - /// `VOELIN_OPEN=client`: the volume dialog of the first client that is not us. - pub(crate) fn open_first_client(&mut self) { - let Some(view) = self.view().filter(|v| v.state.own_client.is_some()) else { return }; - let own = view.state.own_client; - let mut others: Vec<_> = - view.presence.clients.values().filter(|c| Some(c.id) != own && !c.is_query).collect(); - others.sort_by_key(|c| c.id); - let Some(id) = others.first().map(|c| c.id) else { return }; - self.open_client_pending = false; - if self.open_client(id) - && let Some(ui) = self.ui.upgrade() - { - ui.global::().set_client_open(true); - } - } -} diff --git a/crates/voelin-ui/src/settings_page/bind.rs b/crates/voelin-ui/src/settings_page/bind.rs new file mode 100644 index 0000000..ee25e81 --- /dev/null +++ b/crates/voelin-ui/src/settings_page/bind.rs @@ -0,0 +1,222 @@ +//! The Slint side of the settings page: the system's audio devices, the +//! hotkey, the codec download and the crash reports, the Bridge writes, and +//! the callbacks' ways into the transitions of +//! `voelin_ui_vm::settings_page::logic`. + +use slint::{ComponentHandle, SharedString}; +use tracing::warn; +use voelin_core::settings::CRASH_REPORTS; +use voelin_platform::{crash, notices}; + +use crate::app::{App, Bridge, Nav, later, model}; +use crate::settings; +use crate::vm::bridge::{AudioForm, ClientAudio}; +use crate::vm::settings_page::logic::{self, Device}; + +/// The audio devices the system lists in one direction, as `(id, name, +/// is the default)`; none, and a warning, when it cannot list them. +fn devices( + list: voelin_audio::Result>, + input: bool, +) -> Vec { + list.unwrap_or_else(|e| { + warn!("cannot list audio devices: {e}"); + Vec::new() + }) + .into_iter() + .map(|d| { + let default = if input { d.default_input } else { d.default_output }; + (d.id, d.name, default) + }) + .collect() +} + +impl App { + pub(crate) fn open_settings(&mut self) { + let inputs = devices(voelin_audio::device::input_devices(), true); + let outputs = devices(voelin_audio::device::output_devices(), false); + let page = logic::open_settings(&mut self.state, &inputs, &outputs); + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let names = |names: Vec| model(names.into_iter().map(SharedString::from).collect()); + bridge.set_input_devices(names(page.input_devices)); + bridge.set_output_devices(names(page.output_devices)); + bridge.set_audio(page.audio.into()); + bridge.set_global_ptt(page.global_ptt); + bridge.set_ptt_key(page.ptt_key.into()); + bridge.set_h264_enabled(page.h264_enabled); + bridge.set_image_cache_usage(crate::images::usage_text().into()); + self.refresh_h264(); + self.refresh_identities(); + } + + pub(crate) fn close_settings(&mut self) { + if self.transition(logic::close_settings) { + self.mic_test_stopped(); + } + } + + pub(crate) fn audio_changed(&mut self, form: &AudioForm) { + self.transition(|state, cx| logic::audio_changed(state, cx, form)); + } + + pub(crate) fn save_audio(&mut self) { + self.transition(logic::save_audio); + } + + pub(crate) fn set_mic_test(&mut self, on: bool) { + if self.transition(|state, cx| logic::set_mic_test(state, cx, on)) { + if on { + self.mic_test_started(); + } else { + self.mic_test_stopped(); + } + } + } + + /// The Bridge shows the microphone test running. + fn mic_test_started(&self) { + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_mic_test(true); + } + } + + /// The Bridge shows the microphone test over, and its level gone. + fn mic_test_stopped(&self) { + if let Some(ui) = self.ui.upgrade() { + let bridge = ui.global::(); + bridge.set_mic_test(false); + bridge.set_input_level(-100.0); + } + } + + pub(crate) fn apply_ptt(&mut self, enabled: bool, key: String) { + let hotkey = self.transition(|state, cx| logic::apply_ptt(state, cx, enabled, &key)); + self.ptt.set(hotkey); + } + + pub(crate) fn set_ptt_status(&mut self, status: String) { + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_ptt_status(status.into()); + } + } + + pub(crate) fn set_h264(&mut self, enabled: bool) { + self.transition(|state, cx| logic::set_h264(state, cx, enabled)); + self.video.set_h264(enabled); + self.refresh_h264(); + } + + pub(crate) fn download_h264(&mut self) { + let runtime = self.engine.runtime().clone(); + self.video.download_h264(&runtime, |download| { + later(move |app| { + app.video.downloaded(download, app.state.settings.openh264); + app.refresh_h264(); + }); + }); + self.refresh_h264(); + } + + fn refresh_h264(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let (loaded, status) = self.video.h264_status(); + let view = logic::h264_view(loaded, status); + bridge.set_h264_loaded(view.loaded); + bridge.set_h264_busy(view.busy); + bridge.set_h264_status(view.status.into()); + } + + /// Switches the About page and the settings show. + pub(crate) fn refresh_settings_flags(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + bridge.set_h264_enabled(self.state.settings.openh264); + bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into()); + bridge.set_crash_reports(self.state.settings.crash_reports); + } + + /// The transmit mode for the voice controls (Hold to talk shows for + /// push-to-talk) before the settings page fills the whole form: only + /// `transmit` changes, as the device lists are not read yet. + pub(crate) fn refresh_transmit(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let mut form = bridge.get_audio(); + form.transmit = settings::transmit_index(self.state.audio.transmit); + bridge.set_audio(form); + } + + pub(crate) fn set_crash_reports(&mut self, enabled: bool) { + self.transition(|state, cx| logic::set_crash_reports(state, cx, enabled)); + if let Err(e) = self.prefs.set(&CRASH_REPORTS, enabled) { + warn!(%e, "could not store the crash report setting"); + } + crash::set_enabled(enabled); + } + + /// A notice while crash reports are on disk ([`logic::crash_notice`]). + pub(crate) fn refresh_crash_notice(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let summaries: Vec = crash::pending_reports() + .map(|reports| reports.into_iter().map(|r| r.summary).collect()) + .unwrap_or_default(); + ui.global::().set_crash_notice(logic::crash_notice(&summaries).into()); + } + + pub(crate) fn open_crash_folder(&mut self) { + let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned()); + if let Err(e) = + result.and_then(|dir| crate::app::open_path(&dir).map_err(|e| e.to_string())) + { + self.set_status(format!("Cannot open the crash report folder: {e}")); + } + } + + pub(crate) fn delete_crash_reports(&mut self) { + match crash::clear() { + Ok(n) => self.set_status(format!("Deleted {n} crash reports")), + Err(e) => self.set_status(format!("Cannot delete the crash reports: {e}")), + } + self.refresh_crash_notice(); + } + + /// The third-party notices, one model entry per line. + pub(crate) fn load_notices(&mut self) { + if self.notices_loaded { + return; + } + let Some(ui) = self.ui.upgrade() else { return }; + let lines: Vec = notices::text().lines().map(SharedString::from).collect(); + ui.global::().set_notices(model(lines)); + self.notices_loaded = true; + } + + // Local volume and mute of clients. + + /// Fill the volume dialog for `client` of the current session + /// ([`logic::open_client`]). + pub(crate) fn open_client(&mut self, client: u16) -> bool { + let Some(form) = logic::open_client(&mut self.state, client) else { return false }; + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_client_audio(form.into()); + } + true + } + + pub(crate) fn client_playback_changed(&mut self, form: &ClientAudio) { + self.transition(|state, cx| logic::client_playback_changed(state, cx, form)); + } + + /// `VOELIN_OPEN=client`: the volume dialog of the first client that is not us. + pub(crate) fn open_first_client(&mut self) { + let Some(id) = logic::first_client(&self.state) else { return }; + self.open_client_pending = false; + if self.open_client(id) + && let Some(ui) = self.ui.upgrade() + { + ui.global::