From 03f4a9216145efd3343afd164ec34810cbd96375 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 15:31:53 +0300 Subject: [PATCH] Split the settings pages: logic into voelin-ui-vm, the Bridge writes stay in bind.rs settings_pages.rs had 52 Bridge writes interleaved with what the pages show and change. The decisions now live in voelin_ui_vm::settings_pages::logic and work on the settings service, the AppState and the plain bridge rows: - the forms read from the settings (video, streaming, notifications, privacy, advanced), the layer and audio-source rows and the filtered list of all settings; - the settings written from the forms (apply_video, apply_streaming, layer, audio source, SRTP profile, notification, privacy and advanced edits), each returning the messages for the status line instead of writing them; - the Integrations rows (gateways, configuration keys, permission rules, encoders and decoders with their status texts) and the Profiles rows (identities, bookmark pickers, what an import found, the account form); - the pages' own state (PagesState, Improving), the layer, preset and codec helpers, allowed_index/of and origin_label, with the tests that went with them and tests for each of the above. voelin-ui keeps settings_pages/{mod,bind}.rs: Pages (PagesState plus the camera preview and the audio-app watcher), the Bridge and model writes, and what a change sets going (camera, engine, identity store, threads). A message the logic returns is logged and shown as before; the one visible difference is that the "A layer needs a size" hint is logged with it. serde_json becomes a regular dependency of voelin-ui-vm (the JSON typed into the Advanced list); the lock file is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-ui-vm/Cargo.toml | 3 +- crates/voelin-ui-vm/src/lib.rs | 1 + .../voelin-ui-vm/src/settings_pages/logic.rs | 1367 +++++++++++++++ crates/voelin-ui-vm/src/settings_pages/mod.rs | 7 + crates/voelin-ui/src/bind/pages.rs | 2 +- crates/voelin-ui/src/identities.rs | 25 +- crates/voelin-ui/src/settings_pages.rs | 1460 ----------------- crates/voelin-ui/src/settings_pages/bind.rs | 801 +++++++++ crates/voelin-ui/src/settings_pages/mod.rs | 27 + crates/voelin-ui/src/social.rs | 23 +- 10 files changed, 2208 insertions(+), 1508 deletions(-) create mode 100644 crates/voelin-ui-vm/src/settings_pages/logic.rs create mode 100644 crates/voelin-ui-vm/src/settings_pages/mod.rs delete mode 100644 crates/voelin-ui/src/settings_pages.rs create mode 100644 crates/voelin-ui/src/settings_pages/bind.rs create mode 100644 crates/voelin-ui/src/settings_pages/mod.rs diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml index b452210..6d903b0 100644 --- a/crates/voelin-ui-vm/Cargo.toml +++ b/crates/voelin-ui-vm/Cargo.toml @@ -20,6 +20,8 @@ chrono = { version = "0.4.45", default-features = false, features = ["clock"] } # front end's toolkit used to bring them. image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } serde = { version = "1", features = ["derive"] } +# JSON values of the settings and the gateway's configuration keys. +serde_json = "1" # The Twemoji archive's blocks (raw deflate). miniz_oxide = "0.8" # Grapheme clusters for emoji in chat text. @@ -32,7 +34,6 @@ voelin-store = { path = "../voelin-store" } [dev-dependencies] png = "0.18" -serde_json = "1" [lints] workspace = true diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index 7dc0382..fa25c8f 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -14,6 +14,7 @@ pub mod image; pub mod list; pub mod servers; pub mod settings; +pub mod settings_pages; pub mod social; pub mod state; pub mod streams; diff --git a/crates/voelin-ui-vm/src/settings_pages/logic.rs b/crates/voelin-ui-vm/src/settings_pages/logic.rs new file mode 100644 index 0000000..fd9e302 --- /dev/null +++ b/crates/voelin-ui-vm/src/settings_pages/logic.rs @@ -0,0 +1,1367 @@ +//! What the settings pages show and what their controls change, apart from +//! the toolkit: the forms read from the settings, the settings written from +//! the forms, and the lists of the Integrations and Profiles pages. +//! +//! The functions work on the settings service (`voelin_core::settings`), the +//! app's state ([`AppState`]) and the plain rows of [`crate::bridge`]. A +//! function that changes settings returns the messages for the status line +//! (what the service refused, what was typed wrong); the front end shows them +//! and fills its forms again. The Slint front end's side of this is +//! `voelin-ui`'s `settings_pages/bind.rs`. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use voelin_core::identity::Found; +use voelin_core::media::auto_bitrate; +use voelin_core::media::voelin_media::EncoderInfo; +use voelin_core::settings::{ + AudioSourceKindSetting, AudioSourceSetting, BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, + CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_RETENTION_DAYS, CHAT_STORE_HISTORY, + CaptureChoice, CodecChoice, FILES_PROGRESS_MS, Key, LayerSetting, PRIVACY_BLOCK_MODE, + PRIVACY_POKES, PRIVACY_PRIVATE_MESSAGES, SRTP_PROFILES, STREAM_AUDIO_SOURCES, + STREAM_BITRATE_KBPS, STREAM_CAPTURE_BACKEND, STREAM_CODEC, STREAM_DECODER_BACKEND, + STREAM_ENCODER_BACKEND, STREAM_FPS, STREAM_HARDWARE_ACCELERATION, STREAM_HARDWARE_DECODING, + STREAM_LAYERS, STREAM_PERMISSIONS, STREAM_SRTP_PROFILES, STUDIO_RECORDING_DIR, + STUDIO_REPLAY_MEMORY_MB, STUDIO_REPLAY_SECONDS, Settings, Source as SettingSource, + StreamPermissions, +}; +use voelin_gateway_proto::{ConfigSource, PermRule, feature}; +use voelin_store::{Bookmark, IdentityEntry, IdentityOrigin}; + +use crate::bridge::{ + AccountForm, AdvancedForm, AudioSourceItem, BookmarkIdentity, ConfigItem, EncoderItem, + FoundIdentity, GatewayItem, IdentityItem, LayerItem, NotifyForm, PermItem, PrivacyForm, + SettingItem, StreamingForm, VideoForm, +}; +use crate::settings::{ + NOTIFY_EVENTS, NOTIFY_FRIENDS, NOTIFY_MENTIONS, NOTIFY_MESSAGES, NOTIFY_POKES, NotifyLevel, + UI_IMAGE_PREVIEW_KB, VIDEO_BACKGROUND, VIDEO_CAMERA, VIDEO_MIRROR, VIDEO_RESOLUTION, + parse_positive, parse_size, +}; +use crate::state::{AppState, SessionExtra}; + +/// Sizes of the stream quality presets (Auto: the source's size). +const PRESETS: [(u32, u32); 5] = + [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2160), (7680, 4320)]; + +/// An identity whose level is being raised. +pub struct Improving { + /// The level aimed at. + pub target: u8, + /// The best level reached so far. + pub reached: u8, + /// Set to stop the search. + pub cancel: Arc, +} + +/// What the settings pages remember apart from the settings themselves. +#[derive(Default)] +pub struct PagesState { + /// The identities whose level is being raised, by store id. + pub improving: HashMap, + /// Identities found in other clients' files, picked for import. + pub found: Vec<(Found, bool)>, + /// What the list of all settings is filtered by. + pub settings_filter: String, + /// The gateway being administered (a bookmark id). + pub admin: Option, + /// Camera ids by the index of the cameras list. + pub cameras: Vec, + /// The encoders are being probed. + pub encoders_loading: bool, +} + +/// "1920x1080" or "0.5" for a layer. +fn layer_size(l: &LayerSetting) -> String { + match l.size { + Some((w, h)) => format!("{w}x{h}"), + None => format!("{}", l.scale), + } +} + +/// kbit/s of bit/s, as typed. +fn kbps(bits: u64) -> String { + (bits / 1000).to_string() +} + +/// A layer as the Streaming page's row shows it. +pub fn layer_item(l: &LayerSetting) -> LayerItem { + LayerItem { + size: layer_size(l).into(), + fps: l.max_fps.map(|f| f.to_string()).unwrap_or_default().into(), + bitrate: kbps(l.bitrate).into(), + min_bitrate: kbps(l.min_bitrate).into(), + max_bitrate: l.max_bitrate.map(kbps).unwrap_or_default().into(), + } +} + +/// A layer from what was typed; `None` when it is not a layer. +pub fn layer_of(item: &LayerItem, base: &LayerSetting) -> Option { + let mut l = base.clone(); + match parse_size(&item.size) { + Some(size) => l.size = Some(size), + None => { + l.size = None; + l.scale = item.size.trim().parse().ok().filter(|s: &f32| *s > 0.0)?; + } + } + let number = |t: &str| t.trim().parse::().ok(); + l.max_fps = number(&item.fps).map(|f| f as u32).filter(|f| *f > 0); + l.bitrate = number(&item.bitrate).filter(|b| *b > 0)? * 1000; + l.min_bitrate = number(&item.min_bitrate).unwrap_or(0) * 1000; + l.max_bitrate = number(&item.max_bitrate).map(|b| b * 1000).filter(|m| *m >= l.bitrate); + Some(l) +} + +/// The layers of quality preset `quality` (0: none, the source's size; +/// then [`PRESETS`]) at `kbps` (0: automatic, for the preset's size and +/// `fps`); `None` for no preset (layers of one's own). +pub fn preset_layers(quality: i32, kbps: u32, fps: u32) -> Option> { + match usize::try_from(quality).ok()? { + 0 => Some(Vec::new()), + q => PRESETS.get(q - 1).map(|&(width, height)| { + let bitrate = match kbps { + 0 => auto_bitrate(width, height, fps), + kbps => u64::from(kbps) * 1000, + }; + vec![LayerSetting { size: Some((width, height)), bitrate, ..LayerSetting::default() }] + }), + } +} + +/// The preset of a list of layers: 0 Auto (none), 1..5 a preset size, -1 +/// other layers. +pub fn quality_of(layers: &[LayerSetting]) -> i32 { + match layers { + [] => 0, + [one] => PRESETS.iter().position(|p| one.size == Some(*p)).map_or(-1, |i| i as i32 + 1), + _ => -1, + } +} + +/// An audio source of the stream as the Streaming page's row shows it +/// (`app_name`: the app's own name, for "Desktop without ..."). +pub fn source_item(s: &AudioSourceSetting, app_name: &str) -> AudioSourceItem { + let (kind, name, detail) = match &s.kind { + AudioSourceKindSetting::Desktop => { + ("desktop", format!("Desktop without {app_name}"), "Everything that plays".to_owned()) + } + AudioSourceKindSetting::App { name, pid } => ( + "app", + name.clone().unwrap_or_else(|| format!("Process {}", pid.unwrap_or_default())), + "Application".to_owned(), + ), + AudioSourceKindSetting::Window => { + ("window", "The shared window's app".to_owned(), "Where the system tells".to_owned()) + } + AudioSourceKindSetting::Microphone => { + ("microphone", "Microphone".to_owned(), "After noise suppression".to_owned()) + } + AudioSourceKindSetting::Synthetic { frequency } => { + ("synthetic", "Test tone".to_owned(), format!("{frequency} Hz")) + } + }; + AudioSourceItem { + kind: kind.into(), + name: name.into(), + detail: detail.into(), + gain: s.gain * 100.0, + muted: s.muted, + } +} + +/// Where a gateway's configuration value comes from, in words. +pub fn config_source(s: ConfigSource) -> &'static str { + match s { + ConfigSource::Db => "set at runtime", + ConfigSource::Cli => "command line", + ConfigSource::Env => "environment", + ConfigSource::File => "file", + ConfigSource::Default => "default", + ConfigSource::Unknown => "?", + } +} + +/// A permission rule in words. +pub fn rule_text(rule: &PermRule) -> String { + let mut parts = Vec::new(); + if rule.everyone { + parts.push("everyone".to_owned()); + } + let list = |ids: &[u64]| ids.iter().map(u64::to_string).collect::>().join(", "); + if !rule.server_groups.is_empty() { + parts.push(format!("server groups {}", list(&rule.server_groups))); + } + if !rule.channel_groups.is_empty() { + parts.push(format!("channel groups {}", list(&rule.channel_groups))); + } + if parts.is_empty() { "nobody".into() } else { parts.join("; ") } +} + +/// "6, 7" → [6, 7] (other words are left out). +pub fn group_ids(text: &str) -> Vec { + text.split([',', ' ']).filter_map(|t| t.trim().parse().ok()).collect() +} + +/// A value typed into a JSON field: JSON when it parses, else a string. +pub fn json_of(text: &str) -> serde_json::Value { + serde_json::from_str(text).unwrap_or_else(|_| serde_json::Value::String(text.to_owned())) +} + +/// The codec choice as the pages' lists index it. +pub fn codec_index(c: CodecChoice) -> i32 { + match c { + CodecChoice::Auto => 0, + CodecChoice::Vp8 => 1, + CodecChoice::Vp9 => 2, + CodecChoice::H264 => 3, + CodecChoice::Av1 => 4, + } +} + +/// The codec choice of an index of the pages' lists. +pub fn codec_of(i: i32) -> CodecChoice { + match i { + 1 => CodecChoice::Vp8, + 2 => CodecChoice::Vp9, + 3 => CodecChoice::H264, + 4 => CodecChoice::Av1, + _ => CodecChoice::Auto, + } +} + +/// Where an identity came from, as Profiles says it. +pub fn origin_label(origin: IdentityOrigin) -> &'static str { + match origin { + IdentityOrigin::Created => "Made in Voelin", + IdentityOrigin::Imported => "Imported", + IdentityOrigin::User => "Chosen by you", + } +} + +// The forms, from the settings. + +/// The Voice & Video form. `cameras`: the ids of the cameras list; +/// `preview`: the camera preview runs. +pub fn video_form(p: &Settings, cameras: &[String], preview: bool) -> VideoForm { + let camera = p.get(&VIDEO_CAMERA); + VideoForm { + camera: cameras.iter().position(|c| *c == camera).unwrap_or(0) as i32, + background: i32::from(p.get(&VIDEO_BACKGROUND) == "blur"), + resolution: p.get(&VIDEO_RESOLUTION).into(), + fps: p.get(&STREAM_FPS).to_string().into(), + codec: codec_index(p.get(&STREAM_CODEC)), + hardware: p.get(&STREAM_HARDWARE_ACCELERATION), + mirror: p.get(&VIDEO_MIRROR), + permissions: match p.get(&STREAM_PERMISSIONS) { + StreamPermissions::Everyone => 0, + StreamPermissions::Friends => 1, + StreamPermissions::Channel => 2, + StreamPermissions::Nobody => 3, + }, + quality: quality_of(&p.get(&STREAM_LAYERS)), + bitrate: p.get(&STREAM_BITRATE_KBPS) as f32, + preview, + } +} + +/// The Streaming page's defaults. +pub fn streaming_form(p: &Settings) -> StreamingForm { + StreamingForm { + fps: p.get(&STREAM_FPS).to_string().into(), + bitrate: p.get(&STREAM_BITRATE_KBPS).to_string().into(), + codec: codec_index(p.get(&STREAM_CODEC)), + capture: match p.get(&STREAM_CAPTURE_BACKEND) { + CaptureChoice::Auto => 0, + CaptureChoice::Portal => 1, + CaptureChoice::Wlroots => 2, + CaptureChoice::X11 => 3, + }, + replay_seconds: p.get(&STUDIO_REPLAY_SECONDS).to_string().into(), + replay_memory: p.get(&STUDIO_REPLAY_MEMORY_MB).to_string().into(), + recording_dir: p.get(&STUDIO_RECORDING_DIR).into(), + } +} + +/// The stream's layers, one row each. +pub fn layer_items(p: &Settings) -> Vec { + p.get(&STREAM_LAYERS).iter().map(layer_item).collect() +} + +/// The stream's audio sources, one row each (`app_name`: see +/// [`source_item`]). +pub fn audio_source_items(p: &Settings, app_name: &str) -> Vec { + p.get(&STREAM_AUDIO_SOURCES).iter().map(|s| source_item(s, app_name)).collect() +} + +/// The notification levels. +pub fn notify_form(p: &Settings) -> NotifyForm { + NotifyForm { + mentions: p.get(&NOTIFY_MENTIONS).index(), + pokes: p.get(&NOTIFY_POKES).index(), + messages: p.get(&NOTIFY_MESSAGES).index(), + events: p.get(&NOTIFY_EVENTS).index(), + friends: p.get(&NOTIFY_FRIENDS).index(), + } +} + +/// What a privacy or notification choice is as an index, and back. +pub fn allowed_index(a: voelin_core::settings::Allowed) -> i32 { + match a { + voelin_core::settings::Allowed::Everyone => 0, + voelin_core::settings::Allowed::Friends => 1, + voelin_core::settings::Allowed::Nobody => 2, + } +} + +/// The privacy or notification choice of an index. +pub fn allowed_of(index: i32) -> voelin_core::settings::Allowed { + match index { + 1 => voelin_core::settings::Allowed::Friends, + 2 => voelin_core::settings::Allowed::Nobody, + _ => voelin_core::settings::Allowed::Everyone, + } +} + +/// Privacy & Safety. +pub fn privacy_form(p: &Settings) -> PrivacyForm { + PrivacyForm { + block_mode: i32::from(p.get(&PRIVACY_BLOCK_MODE) == BlockMode::Flag), + messages: allowed_index(p.get(&PRIVACY_PRIVATE_MESSAGES)), + pokes: allowed_index(p.get(&PRIVACY_POKES)), + } +} + +/// Advanced. `logs` and `crash_dir` are the texts about where the logs and +/// crash reports go, which the front end knows. +pub fn advanced_form(p: &Settings, logs: &str, crash_dir: &str) -> AdvancedForm { + AdvancedForm { + encoder: p.get(&STREAM_ENCODER_BACKEND).into(), + hardware: p.get(&STREAM_HARDWARE_ACCELERATION), + decoder: p.get(&STREAM_DECODER_BACKEND).into(), + hardware_decoding: p.get(&STREAM_HARDWARE_DECODING), + store_history: p.get(&CHAT_STORE_HISTORY), + history_page: p.get(&CHAT_HISTORY_PAGE).to_string().into(), + dedupe_ms: p.get(&CHAT_DEDUPE_TOLERANCE_MS).to_string().into(), + retention_days: p.get(&CHAT_RETENTION_DAYS).to_string().into(), + cache_mb: p.get(&CACHE_MAX_MB).to_string().into(), + fetch_images: p.get(&CACHE_FETCH_IMAGES), + progress_ms: p.get(&FILES_PROGRESS_MS).to_string().into(), + preview_kb: p.get(&UI_IMAGE_PREVIEW_KB).to_string().into(), + logs: logs.into(), + crash_dir: crash_dir.into(), + } +} + +/// The SRTP profiles that are not offered (those that can be added). +pub fn srtp_unused(offered: &[String]) -> Vec<&'static str> { + SRTP_PROFILES.iter().filter(|n| !offered.iter().any(|s| s == *n)).copied().collect() +} + +/// Every registered setting (Advanced) whose name or description has +/// `filter` (lower case; empty: all). +pub fn setting_items(p: &Settings, filter: &str) -> Vec { + p.keys() + .into_iter() + .filter(|k| { + filter.is_empty() + || k.name().contains(filter) + || k.doc().to_lowercase().contains(filter) + }) + .map(|k| SettingItem { + key: k.name().into(), + doc: k.doc().into(), + value: p.get_json(k.name()).map(|v| v.to_string()).unwrap_or_default().into(), + source: match p.source(k.name()) { + Some(SettingSource::Runtime) => "set here", + Some(SettingSource::Override) => "command line", + Some(SettingSource::Config) => "config file", + _ => "default", + } + .into(), + }) + .collect() +} + +// The settings, from the forms. + +/// Stores settings, and keeps what is to be said about it. +struct Put<'a> { + prefs: &'a Settings, + said: Vec, +} + +impl<'a> Put<'a> { + fn new(prefs: &'a Settings) -> Self { + Self { prefs, said: Vec::new() } + } + + /// Store a setting; a refusal is something to say. + fn put(&mut self, key: &'static Key, value: T) + where + T: Serialize + DeserializeOwned + Send + Sync + 'static, + { + if let Err(e) = self.prefs.set(key, value) { + self.said.push(e.to_string()); + } + } + + /// Store a setting unless it is what it is already. + fn put_if_changed(&mut self, key: &'static Key, value: T) + where + T: Clone + PartialEq + Serialize + DeserializeOwned + Send + Sync + 'static, + { + if self.prefs.get(key) != value { + self.put(key, value); + } + } + + fn say(&mut self, text: impl Into) { + self.said.push(text.into()); + } + + fn done(self) -> Vec { + self.said + } +} + +/// The Voice & Video form was changed. `cameras`: the ids of the cameras +/// list. Returns what is to be said in the status line. +pub fn apply_video(prefs: &Settings, cameras: &[String], form: &VideoForm) -> Vec { + let mut p = Put::new(prefs); + if let Some(id) = usize::try_from(form.camera).ok().and_then(|i| cameras.get(i)).cloned() { + p.put_if_changed(&VIDEO_CAMERA, id); + } + let background = if form.background == 1 { "blur" } else { "none" }; + p.put_if_changed(&VIDEO_BACKGROUND, background.to_owned()); + p.put_if_changed(&VIDEO_RESOLUTION, form.resolution.to_string()); + if let Some(fps) = parse_positive(&form.fps) { + p.put_if_changed(&STREAM_FPS, fps); + } + p.put_if_changed(&STREAM_CODEC, codec_of(form.codec)); + p.put_if_changed(&STREAM_HARDWARE_ACCELERATION, form.hardware); + p.put_if_changed(&VIDEO_MIRROR, form.mirror); + let permissions = match form.permissions { + 0 => StreamPermissions::Everyone, + 1 => StreamPermissions::Friends, + 3 => StreamPermissions::Nobody, + _ => StreamPermissions::Channel, + }; + p.put_if_changed(&STREAM_PERMISSIONS, permissions); + // 0: automatic. + let bitrate = form.bitrate.round().max(0.0) as u32; + p.put_if_changed(&STREAM_BITRATE_KBPS, bitrate); + // A preset: one layer of that size at the bitrate (an automatic one + // for that size and the frame rate); Auto: none. + let layers = prefs.get(&STREAM_LAYERS); + let wanted = preset_layers(form.quality, bitrate, prefs.get(&STREAM_FPS)); + if let Some(wanted) = wanted.filter(|w| *w != layers) { + p.put(&STREAM_LAYERS, wanted); + } + p.done() +} + +/// The Streaming page's defaults were changed. +pub fn apply_streaming(prefs: &Settings, form: &StreamingForm) -> Vec { + let mut p = Put::new(prefs); + if let Some(fps) = parse_positive(&form.fps) { + p.put(&STREAM_FPS, fps); + } + // Nothing, 0 or "auto": automatic. + let bitrate = form.bitrate.trim(); + let auto = bitrate.is_empty() || bitrate == "0" || bitrate.eq_ignore_ascii_case("auto"); + if let Some(bitrate) = parse_positive(bitrate).or(auto.then_some(0)) { + p.put(&STREAM_BITRATE_KBPS, bitrate); + } + p.put(&STREAM_CODEC, codec_of(form.codec)); + p.put( + &STREAM_CAPTURE_BACKEND, + match form.capture { + 1 => CaptureChoice::Portal, + 2 => CaptureChoice::Wlroots, + 3 => CaptureChoice::X11, + _ => CaptureChoice::Auto, + }, + ); + if let Ok(seconds) = form.replay_seconds.trim().parse() { + p.put(&STUDIO_REPLAY_SECONDS, seconds); + } + if let Ok(mb) = form.replay_memory.trim().parse() { + p.put(&STUDIO_REPLAY_MEMORY_MB, mb); + } + p.put(&STUDIO_RECORDING_DIR, form.recording_dir.trim().to_owned()); + p.done() +} + +/// A row of the stream's layers was edited. `None`: there is no such layer, +/// nothing was done. +pub fn apply_layer(prefs: &Settings, index: i32, item: &LayerItem) -> Option> { + let mut layers = prefs.get(&STREAM_LAYERS); + let slot = usize::try_from(index).ok().filter(|i| *i < layers.len())?; + let mut p = Put::new(prefs); + match layer_of(item, &layers[slot]) { + Some(layer) => { + layers[slot] = layer; + p.put(&STREAM_LAYERS, layers); + } + None => p.say("A layer needs a size (1280x720) or scale (0.5) and a bitrate."), + } + Some(p.done()) +} + +/// Add a layer: half the size of the one before and a quarter of its +/// bitrate. +pub fn add_layer(prefs: &Settings) -> Vec { + let mut layers = prefs.get(&STREAM_LAYERS); + let bitrate = u64::from(prefs.get(&STREAM_BITRATE_KBPS)) * 1000; + let scale = 0.5f32.powi(layers.len() as i32); + layers.push(LayerSetting { + scale, + bitrate: (bitrate / 4u64.pow(layers.len() as u32)).max(100_000), + ..LayerSetting::default() + }); + let mut p = Put::new(prefs); + p.put(&STREAM_LAYERS, layers); + p.done() +} + +/// Remove a layer (no such one: nothing). +pub fn remove_layer(prefs: &Settings, index: i32) -> Vec { + let mut layers = prefs.get(&STREAM_LAYERS); + let mut p = Put::new(prefs); + if let Some(i) = usize::try_from(index).ok().filter(|i| *i < layers.len()) { + layers.remove(i); + p.put(&STREAM_LAYERS, layers); + } + p.done() +} + +/// The gain or the mute of an audio source of the stream was changed. +pub fn apply_audio_source(prefs: &Settings, index: i32, item: &AudioSourceItem) -> Vec { + let mut sources = prefs.get(&STREAM_AUDIO_SOURCES); + let mut p = Put::new(prefs); + if let Some(s) = usize::try_from(index).ok().and_then(|i| sources.get_mut(i)) { + s.gain = (item.gain / 100.0).max(0.0); + s.muted = item.muted; + p.put(&STREAM_AUDIO_SOURCES, sources); + } + p.done() +} + +/// Add an audio source of `kind` ("desktop", "window", "microphone", or +/// "app" with its `name`). `None`: not a source, nothing was done. +pub fn add_audio_source(prefs: &Settings, kind: &str, name: &str) -> Option> { + let kind = match kind { + "desktop" => AudioSourceKindSetting::Desktop, + "window" => AudioSourceKindSetting::Window, + "microphone" => AudioSourceKindSetting::Microphone, + "app" if !name.is_empty() => { + AudioSourceKindSetting::App { name: Some(name.to_owned()), pid: None } + } + _ => return None, + }; + let mut sources = prefs.get(&STREAM_AUDIO_SOURCES); + sources.push(AudioSourceSetting::new(kind)); + let mut p = Put::new(prefs); + p.put(&STREAM_AUDIO_SOURCES, sources); + Some(p.done()) +} + +/// Remove an audio source of the stream (no such one: nothing). +pub fn remove_audio_source(prefs: &Settings, index: i32) -> Vec { + let mut sources = prefs.get(&STREAM_AUDIO_SOURCES); + let mut p = Put::new(prefs); + if let Some(i) = usize::try_from(index).ok().filter(|i| *i < sources.len()) { + sources.remove(i); + p.put(&STREAM_AUDIO_SOURCES, sources); + } + p.done() +} + +/// The notification levels were changed. +pub fn apply_notify(prefs: &Settings, form: &NotifyForm) -> Vec { + let mut p = Put::new(prefs); + p.put(&NOTIFY_MENTIONS, NotifyLevel::from_index(form.mentions)); + p.put(&NOTIFY_POKES, NotifyLevel::from_index(form.pokes)); + p.put(&NOTIFY_MESSAGES, NotifyLevel::from_index(form.messages)); + p.put(&NOTIFY_EVENTS, NotifyLevel::from_index(form.events)); + p.put(&NOTIFY_FRIENDS, NotifyLevel::from_index(form.friends)); + p.done() +} + +/// Privacy & Safety was changed. +pub fn apply_privacy(prefs: &Settings, form: &PrivacyForm) -> Vec { + let mut p = Put::new(prefs); + p.put( + &PRIVACY_BLOCK_MODE, + if form.block_mode == 1 { BlockMode::Flag } else { BlockMode::Hide }, + ); + p.put(&PRIVACY_PRIVATE_MESSAGES, allowed_of(form.messages)); + p.put(&PRIVACY_POKES, allowed_of(form.pokes)); + p.done() +} + +/// Advanced was changed (a number that is not one leaves its setting alone). +pub fn apply_advanced(prefs: &Settings, form: &AdvancedForm) -> Vec { + let mut p = Put::new(prefs); + let number = |t: &Arc| t.trim().parse::().ok(); + if !form.encoder.trim().is_empty() { + p.put(&STREAM_ENCODER_BACKEND, form.encoder.trim().to_owned()); + } + p.put(&STREAM_HARDWARE_ACCELERATION, form.hardware); + if !form.decoder.trim().is_empty() { + p.put(&STREAM_DECODER_BACKEND, form.decoder.trim().to_owned()); + } + p.put(&STREAM_HARDWARE_DECODING, form.hardware_decoding); + p.put(&CHAT_STORE_HISTORY, form.store_history); + if let Some(v) = number(&form.history_page) { + p.put(&CHAT_HISTORY_PAGE, v as u32); + } + if let Some(v) = number(&form.dedupe_ms) { + p.put(&CHAT_DEDUPE_TOLERANCE_MS, v); + } + if let Some(v) = number(&form.retention_days) { + p.put(&CHAT_RETENTION_DAYS, v as u32); + } + if let Some(v) = number(&form.cache_mb) { + p.put(&CACHE_MAX_MB, v); + } + p.put(&CACHE_FETCH_IMAGES, form.fetch_images); + if let Some(v) = number(&form.progress_ms) { + p.put(&FILES_PROGRESS_MS, v as u32); + } + if let Some(v) = number(&form.preview_kb) { + p.put(&UI_IMAGE_PREVIEW_KB, v as u32); + } + p.done() +} + +/// Move an SRTP profile up (`by` -1) or down (1). `None`: it cannot be +/// moved there, nothing was done. +pub fn srtp_move(prefs: &Settings, index: i32, by: i32) -> Option> { + let mut list = prefs.get(&STREAM_SRTP_PROFILES); + let (Ok(from), Ok(to)) = (usize::try_from(index), usize::try_from(index + by)) else { + return None; + }; + let mut p = Put::new(prefs); + if from < list.len() && to < list.len() { + list.swap(from, to); + p.put(&STREAM_SRTP_PROFILES, list); + } + Some(p.done()) +} + +/// Offer a profile, or stop offering it (one stays). `None`: it is the one +/// that stays, nothing was done. +pub fn srtp_toggle(prefs: &Settings, name: &str) -> Option> { + let mut list = prefs.get(&STREAM_SRTP_PROFILES); + match list.iter().position(|p| p == name) { + Some(i) if list.len() > 1 => { + list.remove(i); + } + Some(_) => return None, + None => list.push(name.to_owned()), + } + let mut p = Put::new(prefs); + p.put(&STREAM_SRTP_PROFILES, list); + Some(p.done()) +} + +// Integrations. + +/// The gateways of our servers, one row each. +pub fn gateway_items(state: &AppState) -> Vec { + state + .bookmarks + .iter() + .filter_map(|b| { + let url = b.gateway_url.clone()?; + let view = state.sessions.get(&b.id); + let caps = view.map(|v| v.gateway_caps.clone()).unwrap_or_default(); + let status = match view.map(|v| v.state.observe) { + _ if !caps.is_empty() => "connected", + Some(voelin_core::ObserveState::Connecting) => "connecting", + _ => "off", + }; + Some(GatewayItem { + session: b.id as i32, + server: b.name.clone().into(), + url: url.into(), + status: status.into(), + admin: caps.iter().any(|c| c == feature::ADMIN), + features: caps.into_iter().map(Arc::::from).collect(), + }) + }) + .collect() +} + +/// The configuration keys of the gateway being administered. +pub fn config_items(extra: Option<&SessionExtra>) -> Vec { + extra + .map(|e| { + e.config + .iter() + .map(|c| ConfigItem { + key: c.key.clone().into(), + value: c.value.to_string().into(), + source: config_source(c.source).into(), + description: c.description.clone().into(), + kind: c.value_type.clone().into(), + bootstrap: c.bootstrap, + }) + .collect() + }) + .unwrap_or_default() +} + +/// The permission rules of the gateway being administered. +pub fn perm_items(extra: Option<&SessionExtra>) -> Vec { + extra + .map(|e| { + e.perms + .iter() + .map(|r| { + let rule = r.rule.clone().unwrap_or_default(); + let list = + |ids: &[u64]| ids.iter().map(u64::to_string).collect::>().join(", "); + PermItem { + action: r.action.as_str().into(), + rule: match &r.rule { + Some(rule) => rule_text(rule), + None => format!("Default: {}", r.default), + } + .into(), + source: config_source(r.source).into(), + everyone: rule.everyone, + server_groups: list(&rule.server_groups).into(), + channel_groups: list(&rule.channel_groups).into(), + } + }) + .collect() + }) + .unwrap_or_default() +} + +/// The encoders (or decoders) the probe found, one row each. A decoder's +/// entry is an encoder's (its rank: the place in its codec's ladder). +pub fn encoder_items(list: &[EncoderInfo]) -> Vec { + list.iter() + .map(|e| EncoderItem { + name: e.name.clone().into(), + api: e.api.clone().into(), + codec: format!("{:?}", e.codec).to_uppercase().into(), + hardware: e.hardware, + ok: e.status.is_ok(), + status: match (&e.status, e.rank) { + (Err(why), _) => why.clone(), + (Ok(()), Some(0)) => format!("{} · used first", e.api), + (Ok(()), Some(n)) => format!("{} · choice {}", e.api, n + 1), + (Ok(()), None) => format!("{} · not used", e.api), + } + .into(), + }) + .collect() +} + +/// What the probe says of FFmpeg. +pub fn ffmpeg_status(ffmpeg: &Result) -> String { + match ffmpeg { + Ok(v) => format!("FFmpeg: {v}"), + Err(e) => format!("FFmpeg is not used: {e}"), + } +} + +/// What the probe says of capture without a copy. +pub fn zero_copy_status(zero_copy: &Result<(), String>) -> String { + match zero_copy { + Ok(()) => "Screen capture goes to the GPU encoder without a copy.".to_owned(), + Err(e) => format!("No zero-copy capture: {e}"), + } +} + +/// The screens and windows that can be shared, as the list shows them (the +/// error for a list that could not be made). +pub fn capture_source_names(listed: Result, String>) -> Vec { + match listed { + Ok(list) => list + .into_iter() + .map(|(n, d)| if d.is_empty() { n } else { format!("{n} · {d}") }) + .collect(), + Err(e) => vec![e], + } +} + +// Identities. + +/// An identity of the store with what its key says: its unique id on +/// TeamSpeak 6 servers and its level (`None` when the key could not be read). +pub struct IdentityFacts<'a> { + /// The store's entry. + pub entry: &'a IdentityEntry, + /// The unique id on TeamSpeak 6 servers and the level of the key. + pub key: Option<(String, u8)>, +} + +/// The identities, one row each. `used`: each bookmark's name and the +/// identity it connects with; `improving`: the level aimed at and the best +/// one reached of an identity whose level is being raised. +pub fn identity_items( + identities: &[IdentityFacts<'_>], + default: Option, + used: &[(&str, Option)], + improving: impl Fn(i64) -> Option<(u8, u8)>, +) -> Vec { + identities + .iter() + .map(|IdentityFacts { entry: e, key }| { + let improving = improving(e.id); + let used: Vec<&str> = + used.iter().filter(|(_, id)| *id == Some(e.id)).map(|(name, _)| *name).collect(); + IdentityItem { + id: e.id as i32, + name: e.name.clone().into(), + uid: e.uid.clone().into(), + uid6: key.as_ref().map(|k| k.0.clone()).unwrap_or_default().into(), + level: i32::from(key.as_ref().map_or(e.level, |k| k.1)), + default: Some(e.id) == default, + origin: origin_label(e.origin).into(), + improving: improving.map_or(0, |i| i32::from(i.0)), + reached: improving.map_or(0, |i| i32::from(i.1)), + used_by: used.join(", ").into(), + } + }) + .collect() +} + +/// The names the bookmarks' identity pickers offer: the default first, then +/// every identity. +pub fn identity_names(entries: &[IdentityEntry]) -> Vec { + let mut names = vec!["Default identity".to_owned()]; + names.extend(entries.iter().map(|e| e.name.clone())); + names +} + +/// The bookmarks and the identity each connects with (an index into +/// [`identity_names`]). +pub fn bookmark_identities( + bookmarks: &[Bookmark], + entries: &[IdentityEntry], +) -> Vec { + bookmarks + .iter() + .map(|b| BookmarkIdentity { + id: b.id as i32, + name: b.name.clone().into(), + identity: b + .identity + .and_then(|id| entries.iter().position(|e| e.id == id)) + .map_or(0, |i| i as i32 + 1), + }) + .collect() +} + +/// An identity another client's files had, for the import list. +pub struct Discovered { + /// The nickname the other client kept with it. + pub nickname: String, + /// Its unique id on TeamSpeak 3 servers (how the store keys it). + pub uid: String, + /// Its level. + pub level: u8, + /// The file it came from. + pub source: String, + /// Picked for import. + pub picked: bool, +} + +/// What an import found, one row each; `known`: the unique ids of the +/// identities we have. +pub fn found_items(found: &[Discovered], known: &HashSet<&str>) -> Vec { + found + .iter() + .map(|f| FoundIdentity { + name: f.nickname.clone().into(), + known: known.contains(f.uid.as_str()), + uid: f.uid.clone().into(), + level: i32::from(f.level), + source: f.source.clone().into(), + picked: f.picked, + }) + .collect() +} + +/// What the search of the other clients' files says. +pub fn found_status(found: usize, first_error: Option<&str>) -> String { + match (found, first_error) { + (0, Some(e)) => format!("Nothing found ({e})."), + (0, None) => "No TeamSpeak client settings found on this device.".to_owned(), + (n, _) => format!("{n} identities found."), + } +} + +/// A file name for an exported identity: letters, digits and `-` stay. +pub fn export_file_stem(name: &str) -> String { + name.chars().map(|c| if c.is_alphanumeric() || c == '-' { c } else { '_' }).collect() +} + +/// My Account: the identity the current server sees us as (`bookmark`: that +/// server's). +pub fn account_form( + bookmark: Option<&Bookmark>, + identity_name: &str, + uid: &str, + uid6: &str, + level: u8, +) -> AccountForm { + AccountForm { + nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into(), + identity: identity_name.into(), + uid: uid.into(), + uid6: uid6.into(), + level: i32::from(level), + server: bookmark.map(|b| b.name.clone()).unwrap_or_default().into(), + } +} + +#[cfg(test)] +mod tests { + use voelin_core::ObserveState; + use voelin_gateway_proto::{Action, ConfigEntry, PermRuleInfo}; + + use super::*; + use crate::settings::UiSettings; + + #[test] + fn layers_round_trip() { + let base = LayerSetting::default(); + let item = LayerItem { + size: "1280x720".into(), + fps: "30".into(), + bitrate: "2500".into(), + min_bitrate: "800".into(), + max_bitrate: "".into(), + }; + let layer = layer_of(&item, &base).unwrap(); + assert_eq!( + (layer.size, layer.max_fps, layer.bitrate), + (Some((1280, 720)), Some(30), 2_500_000) + ); + assert_eq!(layer.min_bitrate, 800_000); + assert_eq!(layer_item(&layer), item); + let scaled = layer_of( + &LayerItem { size: "0.5".into(), bitrate: "900".into(), ..item.clone() }, + &base, + ) + .unwrap(); + assert_eq!((scaled.size, scaled.scale), (None, 0.5)); + assert!(layer_of(&LayerItem { size: "big".into(), ..item.clone() }, &base).is_none()); + assert!(layer_of(&LayerItem { bitrate: "0".into(), ..item }, &base).is_none()); + } + + #[test] + fn quality_presets() { + assert_eq!(quality_of(&[]), 0); + let layer = |size| LayerSetting { size: Some(size), ..LayerSetting::default() }; + assert_eq!(quality_of(&[layer((1920, 1080))]), 2); + assert_eq!(quality_of(&[layer((3840, 2160))]), 4); + assert_eq!(quality_of(&[layer((7680, 4320))]), 5); + assert_eq!(quality_of(&[layer((800, 600))]), -1); + // A preset at the bitrate, or the automatic one of its size and rate. + let one = |l: Option>| l.map(|l| (l[0].size, l[0].bitrate)); + assert_eq!(one(preset_layers(5, 60_000, 30)), Some((Some((7680, 4320)), 60_000_000))); + assert_eq!(one(preset_layers(4, 0, 60)), Some((Some((3840, 2160)), 59_719_680))); + assert_eq!(preset_layers(0, 0, 60), Some(Vec::new())); + assert_eq!(preset_layers(-1, 0, 60), None); + assert_eq!(preset_layers(6, 0, 60), None); + assert_eq!(quality_of(&[layer((1280, 720)), layer((640, 360))]), -1); + for i in 0..5 { + assert_eq!(codec_index(codec_of(i)), i); + } + } + + #[test] + fn typed_values() { + assert_eq!(group_ids("6, 7 x 9"), [6, 7, 9]); + assert_eq!(json_of("30"), serde_json::json!(30)); + assert_eq!(json_of("[1,2]"), serde_json::json!([1, 2])); + assert_eq!(json_of("hello"), serde_json::json!("hello")); + let rule = PermRule { everyone: false, server_groups: vec![6], channel_groups: vec![] }; + assert_eq!(rule_text(&rule), "server groups 6"); + assert_eq!(rule_text(&PermRule::default()), "nobody"); + } + + #[test] + fn privacy_indices() { + for i in 0..3 { + assert_eq!(allowed_index(allowed_of(i)), i); + } + assert_eq!(allowed_of(9), voelin_core::settings::Allowed::Everyone); + } + + #[test] + fn rows_say_where_an_identity_came_from() { + assert_eq!(origin_label(IdentityOrigin::Created), "Made in Voelin"); + assert_eq!(origin_label(IdentityOrigin::Imported), "Imported"); + // Made by the app, then chosen: an import never replaces it. + assert_eq!(origin_label(IdentityOrigin::User), "Chosen by you"); + } + + /// A form read from the settings and applied again changes nothing. + #[test] + fn forms_are_stable_through_the_settings() { + let prefs = Settings::in_memory(); + let cameras = vec!["a".to_owned(), "b".to_owned()]; + let video = video_form(&prefs, &cameras, false); + assert!(apply_video(&prefs, &cameras, &video).is_empty()); + assert_eq!(video_form(&prefs, &cameras, false), video); + let streaming = streaming_form(&prefs); + assert!(apply_streaming(&prefs, &streaming).is_empty()); + assert_eq!(streaming_form(&prefs), streaming); + let (notify, privacy) = (notify_form(&prefs), privacy_form(&prefs)); + assert!(apply_notify(&prefs, ¬ify).is_empty()); + assert!(apply_privacy(&prefs, &privacy).is_empty()); + assert_eq!((notify_form(&prefs), privacy_form(&prefs)), (notify, privacy)); + let advanced = advanced_form(&prefs, "logs", "crashes"); + assert!(apply_advanced(&prefs, &advanced).is_empty()); + assert_eq!(advanced_form(&prefs, "logs", "crashes"), advanced); + assert_eq!((&*advanced.logs, &*advanced.crash_dir), ("logs", "crashes")); + } + + #[test] + fn the_video_form_sets_what_it_says() { + let prefs = Settings::in_memory(); + let cameras = vec!["a".to_owned(), "b".to_owned()]; + let form = VideoForm { + camera: 1, + background: 1, + resolution: "1280x720".into(), + fps: "30".into(), + codec: 2, + mirror: true, + permissions: 3, + quality: 2, + bitrate: 8000.0, + ..video_form(&prefs, &cameras, false) + }; + assert!(apply_video(&prefs, &cameras, &form).is_empty()); + assert_eq!(prefs.get(&VIDEO_CAMERA), "b"); + assert_eq!(prefs.get(&VIDEO_BACKGROUND), "blur"); + assert_eq!(prefs.get(&STREAM_FPS), 30); + assert_eq!(prefs.get(&STREAM_CODEC), CodecChoice::Vp9); + assert_eq!(prefs.get(&STREAM_PERMISSIONS), StreamPermissions::Nobody); + // The 1080p preset at the bitrate. + let layers = prefs.get(&STREAM_LAYERS); + assert_eq!((layers[0].size, layers[0].bitrate), (Some((1920, 1080)), 8_000_000)); + assert_eq!(video_form(&prefs, &cameras, true).camera, 1); + assert!(video_form(&prefs, &cameras, true).preview); + } + + #[test] + fn typed_numbers_that_are_not_numbers_leave_the_setting_alone() { + let prefs = Settings::in_memory(); + let before = advanced_form(&prefs, "", ""); + let form = AdvancedForm { + history_page: "many".into(), + cache_mb: "-1".into(), + progress_ms: "".into(), + encoder: " ".into(), + ..before.clone() + }; + assert!(apply_advanced(&prefs, &form).is_empty()); + assert_eq!(advanced_form(&prefs, "", ""), before); + let form = AdvancedForm { history_page: " 25 ".into(), ..before }; + assert!(apply_advanced(&prefs, &form).is_empty()); + assert_eq!(&*advanced_form(&prefs, "", "").history_page, "25"); + // The Streaming page: auto, a number, or nothing at all. + let form = StreamingForm { bitrate: "Auto".into(), ..streaming_form(&prefs) }; + apply_streaming(&prefs, &form); + assert_eq!(prefs.get(&STREAM_BITRATE_KBPS), 0); + apply_streaming(&prefs, &StreamingForm { bitrate: "4500".into(), ..form.clone() }); + assert_eq!(prefs.get(&STREAM_BITRATE_KBPS), 4500); + apply_streaming(&prefs, &StreamingForm { bitrate: "fast".into(), ..form }); + assert_eq!(prefs.get(&STREAM_BITRATE_KBPS), 4500); + } + + #[test] + fn layers_are_added_edited_and_removed() { + let prefs = Settings::in_memory(); + prefs.set(&STREAM_BITRATE_KBPS, 8000).unwrap(); + assert!(add_layer(&prefs).is_empty()); + assert!(add_layer(&prefs).is_empty()); + let layers = prefs.get(&STREAM_LAYERS); + assert_eq!(layers.len(), 2); + // Each new layer half the size and a quarter of the bitrate. + assert_eq!((layers[0].scale, layers[0].bitrate), (1.0, 8_000_000)); + assert_eq!((layers[1].scale, layers[1].bitrate), (0.5, 2_000_000)); + let mut item = layer_item(&layers[1]); + item.size = "640x360".into(); + assert_eq!(apply_layer(&prefs, 1, &item), Some(Vec::new())); + assert_eq!(prefs.get(&STREAM_LAYERS)[1].size, Some((640, 360))); + // A row that is not a layer is said so; there is no row 5 or -1. + item.bitrate = "0".into(); + assert_eq!(apply_layer(&prefs, 1, &item).map(|s| s.len()), Some(1)); + assert_eq!(prefs.get(&STREAM_LAYERS)[1].size, Some((640, 360))); + assert_eq!(apply_layer(&prefs, 5, &item), None); + assert_eq!(apply_layer(&prefs, -1, &item), None); + assert!(remove_layer(&prefs, 0).is_empty()); + assert!(remove_layer(&prefs, 7).is_empty()); + assert_eq!(prefs.get(&STREAM_LAYERS).len(), 1); + assert_eq!(layer_items(&prefs).len(), 1); + } + + #[test] + fn audio_sources_are_added_changed_and_removed() { + let prefs = Settings::in_memory(); + let before = prefs.get(&STREAM_AUDIO_SOURCES).len(); + assert_eq!(add_audio_source(&prefs, "app", ""), None); + assert_eq!(add_audio_source(&prefs, "radio", "x"), None); + assert_eq!(add_audio_source(&prefs, "app", "firefox"), Some(Vec::new())); + let sources = prefs.get(&STREAM_AUDIO_SOURCES); + assert_eq!(sources.len(), before + 1); + let rows = audio_source_items(&prefs, "Voelin"); + let last = &rows[before]; + assert_eq!((&*last.kind, &*last.name, last.gain), ("app", "firefox", 100.0)); + let item = AudioSourceItem { gain: 50.0, muted: true, ..last.clone() }; + assert!(apply_audio_source(&prefs, before as i32, &item).is_empty()); + let changed = &prefs.get(&STREAM_AUDIO_SOURCES)[before]; + assert_eq!((changed.gain, changed.muted), (0.5, true)); + assert!(remove_audio_source(&prefs, before as i32).is_empty()); + assert_eq!(prefs.get(&STREAM_AUDIO_SOURCES).len(), before); + let desktop = AudioSourceSetting::new(AudioSourceKindSetting::Desktop); + assert_eq!(&*source_item(&desktop, "Voelin").name, "Desktop without Voelin"); + } + + #[test] + fn srtp_profiles_are_moved_and_offered() { + let prefs = Settings::in_memory(); + let offered = prefs.get(&STREAM_SRTP_PROFILES); + assert!(offered.len() > 1); + assert_eq!(srtp_move(&prefs, -1, 1), None); + assert_eq!(srtp_move(&prefs, 0, 1), Some(Vec::new())); + let moved = prefs.get(&STREAM_SRTP_PROFILES); + assert_eq!((&moved[0], &moved[1]), (&offered[1], &offered[0])); + // Off the end: nothing to do, but the page is filled again. + assert_eq!(srtp_move(&prefs, offered.len() as i32 - 1, 1), Some(Vec::new())); + assert_eq!(prefs.get(&STREAM_SRTP_PROFILES), moved); + let name = moved[0].clone(); + assert_eq!(srtp_toggle(&prefs, &name), Some(Vec::new())); + assert!(!prefs.get(&STREAM_SRTP_PROFILES).contains(&name)); + assert!(srtp_unused(&prefs.get(&STREAM_SRTP_PROFILES)).contains(&name.as_str())); + assert_eq!(srtp_toggle(&prefs, &name), Some(Vec::new())); + assert_eq!(prefs.get(&STREAM_SRTP_PROFILES).len(), offered.len()); + // One profile stays. + let one = prefs.get(&STREAM_SRTP_PROFILES)[0].clone(); + prefs.set(&STREAM_SRTP_PROFILES, vec![one.clone()]).unwrap(); + assert_eq!(srtp_toggle(&prefs, &one), None); + assert_eq!(prefs.get(&STREAM_SRTP_PROFILES), [one]); + } + + #[test] + fn the_settings_list_is_filtered_by_name_and_description() { + let prefs = Settings::in_memory(); + let all = setting_items(&prefs, ""); + assert!(all.len() > 10); + let some = setting_items(&prefs, "srtp"); + assert!(!some.is_empty() && some.len() < all.len()); + assert!( + some.iter().all(|s| s.key.contains("srtp") || s.doc.to_lowercase().contains("srtp")) + ); + assert!(setting_items(&prefs, "no such setting xyz").is_empty()); + prefs.set(&STREAM_FPS, 45).unwrap(); + let fps = all.iter().find(|s| &*s.key == "stream.fps").unwrap(); + assert_eq!(&*fps.source, "default"); + let fps = setting_items(&prefs, "stream.fps").into_iter().next().unwrap(); + assert_eq!((&*fps.value, &*fps.source), ("45", "set here")); + } + + fn state() -> AppState<()> { + let bookmark = |id, name: &str, gateway: Option<&str>| Bookmark { + id, + name: name.into(), + gateway_url: gateway.map(str::to_owned), + ..Bookmark::default() + }; + AppState::<()>::new( + vec![bookmark(1, "One", Some("wss://one")), bookmark(2, "Two", None)], + UiSettings::default(), + Default::default(), + Default::default(), + ) + } + + #[test] + fn gateways_are_listed_with_what_they_offer() { + let mut state = state(); + state.bookmarks.push(Bookmark { + id: 3, + name: "Three".into(), + gateway_url: Some("wss://three".into()), + ..Bookmark::default() + }); + let items = gateway_items(&state); + // A server without a gateway is not listed; one not connected is off. + assert_eq!(items.iter().map(|i| &*i.server).collect::>(), ["One", "Three"]); + assert_eq!(&*items[0].status, "off"); + let view = state.sessions.entry(1).or_default(); + view.state.observe = ObserveState::Connecting; + assert_eq!(&*gateway_items(&state)[0].status, "connecting"); + let view = state.sessions.entry(1).or_default(); + view.gateway_caps = vec![feature::ADMIN.to_owned(), "chat".to_owned()]; + let items = gateway_items(&state); + assert_eq!( + (&*items[0].status, items[0].admin, items[0].features.len()), + ("connected", true, 2) + ); + assert_eq!((&*items[1].status, items[1].admin), ("off", false)); + } + + #[test] + fn the_administered_gateway_shows_its_keys_and_rules() { + assert!(config_items(None).is_empty() && perm_items(None).is_empty()); + let extra = SessionExtra { + config: vec![ConfigEntry { + key: "history.retention_days".into(), + value: serde_json::json!(30), + source: ConfigSource::Db, + default: serde_json::json!(0), + value_type: "int".into(), + description: "Days kept".into(), + bootstrap: false, + }], + perms: vec![ + PermRuleInfo { + action: Action::React, + rule: Some(PermRule { + everyone: false, + server_groups: vec![6, 7], + channel_groups: vec![], + }), + source: ConfigSource::File, + default: "everyone".into(), + }, + PermRuleInfo { + action: Action::Pin, + rule: None, + source: ConfigSource::Default, + default: "server admins".into(), + }, + ], + ..SessionExtra::default() + }; + let config = config_items(Some(&extra)); + assert_eq!( + (&*config[0].key, &*config[0].value, &*config[0].source, &*config[0].kind), + ("history.retention_days", "30", "set at runtime", "int") + ); + let perms = perm_items(Some(&extra)); + assert_eq!((&*perms[0].rule, &*perms[0].server_groups), ("server groups 6, 7", "6, 7")); + assert_eq!((&*perms[1].rule, &*perms[1].source), ("Default: server admins", "default")); + } + + #[test] + fn encoders_say_why_they_are_used_or_not() { + use voelin_core::media::voelin_media::Codec; + let info = |status: Result<(), String>, rank| EncoderInfo { + name: "enc".into(), + api: "VA-API".into(), + codec: Codec::H264, + hardware: true, + status, + rank, + }; + let items = encoder_items(&[ + info(Ok(()), Some(0)), + info(Ok(()), Some(1)), + info(Ok(()), None), + info(Err("no device".into()), None), + ]); + let status: Vec<&str> = items.iter().map(|i| &*i.status).collect(); + assert_eq!( + status, + ["VA-API · used first", "VA-API · choice 2", "VA-API · not used", "no device"] + ); + assert_eq!((&*items[0].codec, items[0].ok, items[3].ok), ("H264", true, false)); + assert_eq!(ffmpeg_status(&Ok("7.1".into())), "FFmpeg: 7.1"); + assert_eq!(ffmpeg_status(&Err("missing".into())), "FFmpeg is not used: missing"); + assert!(zero_copy_status(&Ok(())).starts_with("Screen capture goes")); + assert_eq!(zero_copy_status(&Err("x".into())), "No zero-copy capture: x"); + let listed = capture_source_names(Ok(vec![ + ("A".into(), String::new()), + ("B".into(), "1080p".into()), + ])); + assert_eq!(listed, ["A", "B · 1080p"]); + assert_eq!(capture_source_names(Err("none".into())), ["none"]); + } + + #[test] + fn identities_say_who_uses_them_and_what_is_being_raised() { + let entry = |id, name: &str, level, origin| IdentityEntry { + id, + name: name.into(), + uid: format!("uid{id}"), + level, + origin, + is_default: false, + }; + let entries = [ + entry(1, "Main", 8, IdentityOrigin::Created), + entry(2, "Alt", 20, IdentityOrigin::Imported), + ]; + let facts = [ + IdentityFacts { entry: &entries[0], key: Some(("six1".into(), 10)) }, + IdentityFacts { entry: &entries[1], key: None }, + ]; + let used = [("Home", Some(1)), ("Work", Some(2)), ("Club", Some(1)), ("Lost", None)]; + let items = identity_items(&facts, Some(1), &used, |id| (id == 2).then_some((30, 22))); + assert_eq!( + (&*items[0].used_by, items[0].default, &*items[0].uid6, items[0].level), + ("Home, Club", true, "six1", 10) + ); + assert_eq!( + (&*items[1].used_by, items[1].default, &*items[1].uid6, items[1].level), + ("Work", false, "", 20) + ); + assert_eq!((items[0].improving, items[1].improving, items[1].reached), (0, 30, 22)); + assert_eq!(&*items[1].origin, "Imported"); + assert_eq!(identity_names(&entries), ["Default identity", "Main", "Alt"]); + let bookmark = + |id, identity| Bookmark { id, name: format!("b{id}"), identity, ..Bookmark::default() }; + let picks = bookmark_identities( + &[bookmark(1, None), bookmark(2, Some(2)), bookmark(3, Some(9))], + &entries, + ); + assert_eq!(picks.iter().map(|p| p.identity).collect::>(), [0, 2, 0]); + let found = [ + Discovered { + nickname: "Old".into(), + uid: "uid2".into(), + level: 5, + source: "/x".into(), + picked: true, + }, + Discovered { + nickname: "New".into(), + uid: "uid9".into(), + level: 6, + source: "/y".into(), + picked: false, + }, + ]; + let known: HashSet<&str> = entries.iter().map(|e| e.uid.as_str()).collect(); + let rows = found_items(&found, &known); + assert_eq!( + rows.iter().map(|r| (r.known, r.picked)).collect::>(), + [(true, true), (false, false)] + ); + assert_eq!(found_status(0, Some("denied")), "Nothing found (denied)."); + assert_eq!(found_status(0, None), "No TeamSpeak client settings found on this device."); + assert_eq!(found_status(2, Some("ignored")), "2 identities found."); + assert_eq!(export_file_stem("My ID: 1/2-b"), "My_ID__1_2-b"); + let account = account_form(Some(&bookmark(1, None)), "Main", "u3", "u6", 12); + assert_eq!((&*account.server, &*account.identity, account.level), ("b1", "Main", 12)); + } +} diff --git a/crates/voelin-ui-vm/src/settings_pages/mod.rs b/crates/voelin-ui-vm/src/settings_pages/mod.rs new file mode 100644 index 0000000..d25a51f --- /dev/null +++ b/crates/voelin-ui-vm/src/settings_pages/mod.rs @@ -0,0 +1,7 @@ +//! The settings pages added with the new design: My Account, Profiles +//! (identities), Voice & Video, Streaming, Devices, Notifications, Privacy & +//! Safety, Integrations (gateways, gateway administration, encoders) and +//! Advanced. [`logic`] has what the pages show and what their controls +//! change; the front ends put the rows on screen. + +pub mod logic; diff --git a/crates/voelin-ui/src/bind/pages.rs b/crates/voelin-ui/src/bind/pages.rs index 7459314..63d96bb 100644 --- a/crates/voelin-ui/src/bind/pages.rs +++ b/crates/voelin-ui/src/bind/pages.rs @@ -1,4 +1,4 @@ -//! The settings pages of the new design (settings_pages.rs). +//! The settings pages of the new design (`settings_pages/`). use slint::ComponentHandle; diff --git a/crates/voelin-ui/src/identities.rs b/crates/voelin-ui/src/identities.rs index d08eef8..8f08137 100644 --- a/crates/voelin-ui/src/identities.rs +++ b/crates/voelin-ui/src/identities.rs @@ -2,23 +2,13 @@ //! `Store::default_identity`), chosen under Settings → Profiles, and the //! import of the official clients' identities on start //! (`voelin_core::identity::import_new`, app.rs). The rest of the Profiles -//! page is in `settings_pages.rs`. +//! page is in `settings_pages/`. use tracing::warn; use voelin_core::settings::IDENTITY_IMPORT; -use voelin_store::IdentityOrigin; use crate::app::App; -/// Where an identity came from, as Profiles says it. -pub(crate) fn origin_label(origin: IdentityOrigin) -> &'static str { - match origin { - IdentityOrigin::Created => "Made in Voelin", - IdentityOrigin::Imported => "Imported", - IdentityOrigin::User => "Chosen by you", - } -} - impl App { /// The user's choice of the identity servers see us as, from the next /// connection on; no import replaces it. @@ -51,16 +41,3 @@ impl App { self.refresh_identities(); } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rows_say_where_an_identity_came_from() { - assert_eq!(origin_label(IdentityOrigin::Created), "Made in Voelin"); - assert_eq!(origin_label(IdentityOrigin::Imported), "Imported"); - // Made by the app, then chosen: an import never replaces it. - assert_eq!(origin_label(IdentityOrigin::User), "Chosen by you"); - } -} diff --git a/crates/voelin-ui/src/settings_pages.rs b/crates/voelin-ui/src/settings_pages.rs deleted file mode 100644 index 201662f..0000000 --- a/crates/voelin-ui/src/settings_pages.rs +++ /dev/null @@ -1,1460 +0,0 @@ -//! The settings pages added with the new design: My Account, Profiles -//! (identities), the camera and stream quality of Voice & Video, Streaming, -//! Devices, Notifications, Privacy & Safety, Integrations (gateways, -//! gateway administration, encoders) and Advanced. Every control reads and -//! writes a setting (`voelin_core::settings`, `crate::settings`) and -//! applies at once; the forms are filled again when a setting changes -//! anywhere ([`App::page_setting_changed`]). - -use std::collections::HashMap; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; - -use slint::{ComponentHandle, Model, SharedString}; -use tracing::warn; -use voelin_core::media::auto_bitrate; -use voelin_core::settings::{ - AudioSourceKindSetting, AudioSourceSetting, BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, - CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_RETENTION_DAYS, CHAT_STORE_HISTORY, - CaptureChoice, CodecChoice, FILES_PROGRESS_MS, IDENTITY_IMPORT, Key, LayerSetting, - PRIVACY_BLOCK_MODE, PRIVACY_POKES, PRIVACY_PRIVATE_MESSAGES, SRTP_PROFILES, - STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_CAPTURE_BACKEND, STREAM_CODEC, - STREAM_DECODER_BACKEND, STREAM_ENCODER_BACKEND, STREAM_FPS, STREAM_HARDWARE_ACCELERATION, - STREAM_HARDWARE_DECODING, STREAM_LAYERS, STREAM_PERMISSIONS, STREAM_SRTP_PROFILES, - STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB, STUDIO_REPLAY_SECONDS, Source as SettingSource, - StreamPermissions, -}; -use voelin_core::{Command, GatewayRequest}; -use voelin_gateway_proto::{Action, ConfigSource, PermRule, UniqueIds, feature}; - -use crate::app::{App, Bridge, later, model}; -use crate::bind::convert; -use crate::settings::{ - NOTIFY_EVENTS, NOTIFY_FRIENDS, NOTIFY_MENTIONS, NOTIFY_MESSAGES, NOTIFY_POKES, NotifyLevel, - UI_IMAGE_PREVIEW_KB, VIDEO_BACKGROUND, VIDEO_CAMERA, VIDEO_MIRROR, VIDEO_RESOLUTION, page_keys, - parse_size, -}; -use crate::social::{allowed_index, allowed_of}; -use crate::vm::bridge::{ - AccountForm, AdvancedForm, AudioSourceItem, BookmarkIdentity, ConfigItem, EncoderItem, - FoundIdentity, GatewayItem, IdentityItem, LayerItem, NotifyForm, PermItem, PrivacyForm, - SettingItem, StreamingForm, VideoForm, -}; - -/// Sizes of the stream quality presets (Auto: the source's size). -const PRESETS: [(u32, u32); 5] = - [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2160), (7680, 4320)]; - -/// An identity whose level is being raised. -pub(crate) struct Improving { - pub target: u8, - pub reached: u8, - pub cancel: Arc, -} - -/// State of the settings pages. -#[derive(Default)] -pub(crate) struct Pages { - pub improving: HashMap, - /// Identities found in other clients' files, picked for import. - pub found: Vec<(voelin_core::identity::Found, bool)>, - pub settings_filter: String, - /// The gateway being administered. - pub admin: Option, - /// Camera ids by the index of the cameras list. - pub cameras: Vec, - pub camera: Option, - pub encoders_loading: bool, - /// Applications playing audio (the audio sources picker), while the - /// Streaming page is open. - pub audio_apps: Option, -} - -/// "1920x1080" or "0.5" for a layer. -fn layer_size(l: &LayerSetting) -> String { - match l.size { - Some((w, h)) => format!("{w}x{h}"), - None => format!("{}", l.scale), - } -} - -/// kbit/s of bit/s, as typed. -fn kbps(bits: u64) -> String { - (bits / 1000).to_string() -} - -pub(crate) fn layer_item(l: &LayerSetting) -> LayerItem { - LayerItem { - size: layer_size(l).into(), - fps: l.max_fps.map(|f| f.to_string()).unwrap_or_default().into(), - bitrate: kbps(l.bitrate).into(), - min_bitrate: kbps(l.min_bitrate).into(), - max_bitrate: l.max_bitrate.map(kbps).unwrap_or_default().into(), - } -} - -/// A layer from what was typed; `None` when it is not a layer. -pub(crate) fn layer_of(item: &LayerItem, base: &LayerSetting) -> Option { - let mut l = base.clone(); - match parse_size(&item.size) { - Some(size) => l.size = Some(size), - None => { - l.size = None; - l.scale = item.size.trim().parse().ok().filter(|s: &f32| *s > 0.0)?; - } - } - let number = |t: &str| t.trim().parse::().ok(); - l.max_fps = number(&item.fps).map(|f| f as u32).filter(|f| *f > 0); - l.bitrate = number(&item.bitrate).filter(|b| *b > 0)? * 1000; - l.min_bitrate = number(&item.min_bitrate).unwrap_or(0) * 1000; - l.max_bitrate = number(&item.max_bitrate).map(|b| b * 1000).filter(|m| *m >= l.bitrate); - Some(l) -} - -/// The preset of a list of layers: 0 Auto (none), 1..3 a preset size, -1 -/// other layers. -/// The layers of quality preset `quality` (0: none, the source's size; -/// then [`PRESETS`]) at `kbps` (0: automatic, for the preset's size and -/// `fps`); `None` for no preset (layers of one's own). -fn preset_layers(quality: i32, kbps: u32, fps: u32) -> Option> { - match usize::try_from(quality).ok()? { - 0 => Some(Vec::new()), - q => PRESETS.get(q - 1).map(|&(width, height)| { - let bitrate = match kbps { - 0 => auto_bitrate(width, height, fps), - kbps => u64::from(kbps) * 1000, - }; - vec![LayerSetting { size: Some((width, height)), bitrate, ..LayerSetting::default() }] - }), - } -} - -pub(crate) fn quality_of(layers: &[LayerSetting]) -> i32 { - match layers { - [] => 0, - [one] => PRESETS.iter().position(|p| one.size == Some(*p)).map_or(-1, |i| i as i32 + 1), - _ => -1, - } -} - -fn source_item(s: &AudioSourceSetting, app_name: &str) -> AudioSourceItem { - let (kind, name, detail) = match &s.kind { - AudioSourceKindSetting::Desktop => { - ("desktop", format!("Desktop without {app_name}"), "Everything that plays".to_owned()) - } - AudioSourceKindSetting::App { name, pid } => ( - "app", - name.clone().unwrap_or_else(|| format!("Process {}", pid.unwrap_or_default())), - "Application".to_owned(), - ), - AudioSourceKindSetting::Window => { - ("window", "The shared window's app".to_owned(), "Where the system tells".to_owned()) - } - AudioSourceKindSetting::Microphone => { - ("microphone", "Microphone".to_owned(), "After noise suppression".to_owned()) - } - AudioSourceKindSetting::Synthetic { frequency } => { - ("synthetic", "Test tone".to_owned(), format!("{frequency} Hz")) - } - }; - AudioSourceItem { - kind: kind.into(), - name: name.into(), - detail: detail.into(), - gain: s.gain * 100.0, - muted: s.muted, - } -} - -fn config_source(s: ConfigSource) -> &'static str { - match s { - ConfigSource::Db => "set at runtime", - ConfigSource::Cli => "command line", - ConfigSource::Env => "environment", - ConfigSource::File => "file", - ConfigSource::Default => "default", - ConfigSource::Unknown => "?", - } -} - -fn rule_text(rule: &PermRule) -> String { - let mut parts = Vec::new(); - if rule.everyone { - parts.push("everyone".to_owned()); - } - let list = |ids: &[u64]| ids.iter().map(u64::to_string).collect::>().join(", "); - if !rule.server_groups.is_empty() { - parts.push(format!("server groups {}", list(&rule.server_groups))); - } - if !rule.channel_groups.is_empty() { - parts.push(format!("channel groups {}", list(&rule.channel_groups))); - } - if parts.is_empty() { "nobody".into() } else { parts.join("; ") } -} - -/// "6, 7" → [6, 7] (other words are left out). -pub(crate) fn group_ids(text: &str) -> Vec { - text.split([',', ' ']).filter_map(|t| t.trim().parse().ok()).collect() -} - -/// A value typed into a JSON field: JSON when it parses, else a string. -pub(crate) fn json_of(text: &str) -> serde_json::Value { - serde_json::from_str(text).unwrap_or_else(|_| serde_json::Value::String(text.to_owned())) -} - -impl App { - /// Store a setting; a refusal shows in the status line. - fn put(&mut self, key: &'static Key, value: T) - where - T: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static, - { - if let Err(e) = self.prefs.set(key, value) { - warn!(%e, "setting refused"); - self.set_status(e.to_string()); - } - } - - /// A section of the settings was shown: load what it needs. - pub(crate) fn settings_section(&mut self, section: i32) { - for key in page_keys() { - self.prefs.register(key); - } - match section { - 0 | 7 => { - self.load_cameras(); - if section == 7 { - self.load_capture_sources(); - } - } - 2 => self.watch_audio_apps(), - 5 | 6 => self.refresh_identities(), - 9 => { - if self.pages.encoders_loading - || self - .ui - .upgrade() - .is_some_and(|ui| ui.global::().get_encoders().row_count() == 0) - { - self.refresh_encoders(); - } - self.refresh_gateways(); - } - 10 => self.refresh_all_settings(), - _ => {} - } - if section != 0 && section != 7 { - self.stop_camera(); - } - if section != 2 { - self.pages.audio_apps = None; - } - self.refresh_pages(); - } - - /// Every form of the settings pages, from the settings. - pub(crate) fn refresh_pages(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let p = &self.prefs; - let layers = p.get(&STREAM_LAYERS); - let camera = p.get(&VIDEO_CAMERA); - bridge.set_video( - VideoForm { - camera: self.pages.cameras.iter().position(|c| *c == camera).unwrap_or(0) as i32, - background: i32::from(p.get(&VIDEO_BACKGROUND) == "blur"), - resolution: p.get(&VIDEO_RESOLUTION).into(), - fps: p.get(&STREAM_FPS).to_string().into(), - codec: codec_index(p.get(&STREAM_CODEC)), - hardware: p.get(&STREAM_HARDWARE_ACCELERATION), - mirror: p.get(&VIDEO_MIRROR), - permissions: match p.get(&STREAM_PERMISSIONS) { - StreamPermissions::Everyone => 0, - StreamPermissions::Friends => 1, - StreamPermissions::Channel => 2, - StreamPermissions::Nobody => 3, - }, - quality: quality_of(&layers), - bitrate: p.get(&STREAM_BITRATE_KBPS) as f32, - preview: self.pages.camera.is_some(), - } - .into(), - ); - bridge.set_streaming( - StreamingForm { - fps: p.get(&STREAM_FPS).to_string().into(), - bitrate: p.get(&STREAM_BITRATE_KBPS).to_string().into(), - codec: codec_index(p.get(&STREAM_CODEC)), - capture: match p.get(&STREAM_CAPTURE_BACKEND) { - CaptureChoice::Auto => 0, - CaptureChoice::Portal => 1, - CaptureChoice::Wlroots => 2, - CaptureChoice::X11 => 3, - }, - replay_seconds: p.get(&STUDIO_REPLAY_SECONDS).to_string().into(), - replay_memory: p.get(&STUDIO_REPLAY_MEMORY_MB).to_string().into(), - recording_dir: p.get(&STUDIO_RECORDING_DIR).into(), - } - .into(), - ); - self.models.layers.sync(&layers.iter().map(layer_item).collect::>()); - let sources: Vec = p - .get(&STREAM_AUDIO_SOURCES) - .iter() - .map(|s| source_item(s, voelin_platform::APP_NAME)) - .collect(); - self.models.audio_sources.sync(&sources); - bridge.set_has_studio(true); - bridge.set_notify( - NotifyForm { - mentions: p.get(&NOTIFY_MENTIONS).index(), - pokes: p.get(&NOTIFY_POKES).index(), - messages: p.get(&NOTIFY_MESSAGES).index(), - events: p.get(&NOTIFY_EVENTS).index(), - friends: p.get(&NOTIFY_FRIENDS).index(), - } - .into(), - ); - bridge.set_privacy( - PrivacyForm { - block_mode: i32::from(p.get(&PRIVACY_BLOCK_MODE) == BlockMode::Flag), - messages: allowed_index(p.get(&PRIVACY_PRIVATE_MESSAGES)), - pokes: allowed_index(p.get(&PRIVACY_POKES)), - } - .into(), - ); - let srtp = p.get(&STREAM_SRTP_PROFILES); - bridge.set_srtp_profiles(model(srtp.iter().map(SharedString::from).collect())); - bridge.set_srtp_unused(model( - SRTP_PROFILES - .iter() - .filter(|n| !srtp.iter().any(|s| s == *n)) - .map(|n| SharedString::from(*n)) - .collect(), - )); - bridge.set_advanced( - AdvancedForm { - encoder: p.get(&STREAM_ENCODER_BACKEND).into(), - hardware: p.get(&STREAM_HARDWARE_ACCELERATION), - decoder: p.get(&STREAM_DECODER_BACKEND).into(), - hardware_decoding: p.get(&STREAM_HARDWARE_DECODING), - store_history: p.get(&CHAT_STORE_HISTORY), - history_page: p.get(&CHAT_HISTORY_PAGE).to_string().into(), - dedupe_ms: p.get(&CHAT_DEDUPE_TOLERANCE_MS).to_string().into(), - retention_days: p.get(&CHAT_RETENTION_DAYS).to_string().into(), - cache_mb: p.get(&CACHE_MAX_MB).to_string().into(), - fetch_images: p.get(&CACHE_FETCH_IMAGES), - progress_ms: p.get(&FILES_PROGRESS_MS).to_string().into(), - preview_kb: p.get(&UI_IMAGE_PREVIEW_KB).to_string().into(), - logs: log_text().into(), - crash_dir: voelin_platform::crash::dir() - .map(|d| d.display().to_string()) - .unwrap_or_default() - .into(), - } - .into(), - ); - self.refresh_account(); - } - - /// A setting changed anywhere: fill the forms, apply what the engine - /// does not read itself. - pub(crate) fn page_setting_changed(&mut self, key: &str) { - if key == STREAM_SRTP_PROFILES.name() { - self.apply_srtp(); - } - if [STREAM_HARDWARE_ACCELERATION.name(), STREAM_ENCODER_BACKEND.name(), STREAM_CODEC.name()] - .contains(&key) - { - self.video.set_encoder_preference( - voelin_core::media::encoder_preference(&self.prefs), - voelin_core::media::configured_codec(&self.prefs), - ); - } - if key == VIDEO_CAMERA.name() - || key == VIDEO_BACKGROUND.name() - || key == VIDEO_RESOLUTION.name() - { - self.restart_camera(); - } - self.refresh_pages(); - if key.starts_with("stream.") - || key.starts_with("privacy.") - || key.starts_with("chat.") - || key.starts_with("cache.") - { - self.refresh_all_settings(); - } - } - - /// The SRTP profiles of the setting, for the engine (it does not read - /// the setting itself; it takes the names and leaves out the ones its - /// stream transport does not know). - pub(crate) fn apply_srtp(&self) { - let profiles = self.prefs.get(&STREAM_SRTP_PROFILES); - self.engine.send(Command::SetSrtpProfiles(profiles.to_vec())); - } - - pub(crate) fn video_changed(&mut self, form: &crate::vm::bridge::VideoForm) { - if let Some(id) = - usize::try_from(form.camera).ok().and_then(|i| self.pages.cameras.get(i)).cloned() - && self.prefs.get(&VIDEO_CAMERA) != id - { - self.put(&VIDEO_CAMERA, id); - } - let background = if form.background == 1 { "blur" } else { "none" }; - if self.prefs.get(&VIDEO_BACKGROUND) != background { - self.put(&VIDEO_BACKGROUND, background.to_owned()); - } - if self.prefs.get(&VIDEO_RESOLUTION) != form.resolution.as_ref() { - self.put(&VIDEO_RESOLUTION, form.resolution.to_string()); - } - if let Some(fps) = crate::settings::parse_positive(&form.fps) - && self.prefs.get(&STREAM_FPS) != fps - { - self.put(&STREAM_FPS, fps); - } - let codec = codec_of(form.codec); - if self.prefs.get(&STREAM_CODEC) != codec { - self.put(&STREAM_CODEC, codec); - } - if self.prefs.get(&STREAM_HARDWARE_ACCELERATION) != form.hardware { - self.put(&STREAM_HARDWARE_ACCELERATION, form.hardware); - } - if self.prefs.get(&VIDEO_MIRROR) != form.mirror { - self.put(&VIDEO_MIRROR, form.mirror); - } - let permissions = match form.permissions { - 0 => StreamPermissions::Everyone, - 1 => StreamPermissions::Friends, - 3 => StreamPermissions::Nobody, - _ => StreamPermissions::Channel, - }; - if self.prefs.get(&STREAM_PERMISSIONS) != permissions { - self.put(&STREAM_PERMISSIONS, permissions); - } - // 0: automatic. - let bitrate = form.bitrate.round().max(0.0) as u32; - if self.prefs.get(&STREAM_BITRATE_KBPS) != bitrate { - self.put(&STREAM_BITRATE_KBPS, bitrate); - } - // A preset: one layer of that size at the bitrate (an automatic one - // for that size and the frame rate); Auto: none. - let layers = self.prefs.get(&STREAM_LAYERS); - let wanted = preset_layers(form.quality, bitrate, self.prefs.get(&STREAM_FPS)); - if let Some(wanted) = wanted.filter(|w| *w != layers) { - self.put(&STREAM_LAYERS, wanted); - } - self.refresh_pages(); - } - - pub(crate) fn streaming_changed(&mut self, form: &StreamingForm) { - if let Some(fps) = crate::settings::parse_positive(&form.fps) { - self.put(&STREAM_FPS, fps); - } - // Nothing, 0 or "auto": automatic. - let bitrate = form.bitrate.trim(); - let auto = bitrate.is_empty() || bitrate == "0" || bitrate.eq_ignore_ascii_case("auto"); - if let Some(bitrate) = crate::settings::parse_positive(bitrate).or(auto.then_some(0)) { - self.put(&STREAM_BITRATE_KBPS, bitrate); - } - self.put(&STREAM_CODEC, codec_of(form.codec)); - self.put( - &STREAM_CAPTURE_BACKEND, - match form.capture { - 1 => CaptureChoice::Portal, - 2 => CaptureChoice::Wlroots, - 3 => CaptureChoice::X11, - _ => CaptureChoice::Auto, - }, - ); - if let Ok(seconds) = form.replay_seconds.trim().parse() { - self.put(&STUDIO_REPLAY_SECONDS, seconds); - } - if let Ok(mb) = form.replay_memory.trim().parse() { - self.put(&STUDIO_REPLAY_MEMORY_MB, mb); - } - self.put(&STUDIO_RECORDING_DIR, form.recording_dir.trim().to_owned()); - self.refresh_pages(); - } - - pub(crate) fn layer_changed(&mut self, index: i32, item: &LayerItem) { - let mut layers = self.prefs.get(&STREAM_LAYERS); - let Some(slot) = usize::try_from(index).ok().filter(|i| *i < layers.len()) else { return }; - match layer_of(item, &layers[slot]) { - Some(layer) => { - layers[slot] = layer; - self.put(&STREAM_LAYERS, layers); - } - None => { - self.set_status("A layer needs a size (1280x720) or scale (0.5) and a bitrate.") - } - } - self.refresh_pages(); - } - - pub(crate) fn add_layer(&mut self) { - let mut layers = self.prefs.get(&STREAM_LAYERS); - let bitrate = u64::from(self.prefs.get(&STREAM_BITRATE_KBPS)) * 1000; - // Each new layer half the size and a quarter of the bitrate. - let scale = 0.5f32.powi(layers.len() as i32); - layers.push(LayerSetting { - scale, - bitrate: (bitrate / 4u64.pow(layers.len() as u32)).max(100_000), - ..LayerSetting::default() - }); - self.put(&STREAM_LAYERS, layers); - self.refresh_pages(); - } - - pub(crate) fn remove_layer(&mut self, index: i32) { - let mut layers = self.prefs.get(&STREAM_LAYERS); - if let Some(i) = usize::try_from(index).ok().filter(|i| *i < layers.len()) { - layers.remove(i); - self.put(&STREAM_LAYERS, layers); - } - self.refresh_pages(); - } - - pub(crate) fn audio_source_changed(&mut self, index: i32, item: &AudioSourceItem) { - let mut sources = self.prefs.get(&STREAM_AUDIO_SOURCES); - if let Some(s) = usize::try_from(index).ok().and_then(|i| sources.get_mut(i)) { - s.gain = (item.gain / 100.0).max(0.0); - s.muted = item.muted; - self.put(&STREAM_AUDIO_SOURCES, sources); - } - self.refresh_pages(); - } - - pub(crate) fn add_audio_source(&mut self, kind: &str, name: &str) { - let kind = match kind { - "desktop" => AudioSourceKindSetting::Desktop, - "window" => AudioSourceKindSetting::Window, - "microphone" => AudioSourceKindSetting::Microphone, - "app" if !name.is_empty() => { - AudioSourceKindSetting::App { name: Some(name.to_owned()), pid: None } - } - _ => return, - }; - let mut sources = self.prefs.get(&STREAM_AUDIO_SOURCES); - sources.push(AudioSourceSetting::new(kind)); - self.put(&STREAM_AUDIO_SOURCES, sources); - self.refresh_pages(); - } - - pub(crate) fn remove_audio_source(&mut self, index: i32) { - let mut sources = self.prefs.get(&STREAM_AUDIO_SOURCES); - if let Some(i) = usize::try_from(index).ok().filter(|i| *i < sources.len()) { - sources.remove(i); - self.put(&STREAM_AUDIO_SOURCES, sources); - } - self.refresh_pages(); - } - - /// Follow the applications that play audio while the Streaming page is - /// open (`tick` checks for changes). - fn watch_audio_apps(&mut self) { - if self.pages.audio_apps.is_none() && !self.demo_ui { - match voelin_core::media::audio_apps() { - Ok(apps) => self.pages.audio_apps = Some(apps), - Err(e) => warn!("cannot list applications that play audio: {e}"), - } - } - self.refresh_audio_apps(); - } - - pub(crate) fn refresh_audio_apps(&mut self) { - let Some(apps) = self.pages.audio_apps.as_mut() else { return }; - let names: Vec = apps - .current() - .into_iter() - .map(|a| SharedString::from(a.binary.unwrap_or(a.name))) - .collect(); - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_audio_apps(model(names)); - } - } - - /// Called once a second: a changed list of audio applications. - pub(crate) fn tick_pages(&mut self) { - if self.pages.audio_apps.as_ref().is_some_and(|a| a.has_changed()) { - self.refresh_audio_apps(); - } - } - - pub(crate) fn notify_changed(&mut self, form: &NotifyForm) { - self.put(&NOTIFY_MENTIONS, NotifyLevel::from_index(form.mentions)); - self.put(&NOTIFY_POKES, NotifyLevel::from_index(form.pokes)); - self.put(&NOTIFY_MESSAGES, NotifyLevel::from_index(form.messages)); - self.put(&NOTIFY_EVENTS, NotifyLevel::from_index(form.events)); - self.put(&NOTIFY_FRIENDS, NotifyLevel::from_index(form.friends)); - self.refresh_pages(); - } - - pub(crate) fn test_notification(&mut self) { - let n = - voelin_platform::Notification::new(voelin_platform::APP_NAME, "Notifications work."); - self.engine.runtime().spawn(async move { - let result = voelin_platform::notify(&n).await; - later(move |app| { - app.set_status(match result { - Ok(()) => "A desktop notification was sent.".to_owned(), - Err(e) => format!("No desktop notification: {e}"), - }); - }); - }); - } - - pub(crate) fn privacy_changed(&mut self, form: &PrivacyForm) { - self.put( - &PRIVACY_BLOCK_MODE, - if form.block_mode == 1 { BlockMode::Flag } else { BlockMode::Hide }, - ); - self.put(&PRIVACY_PRIVATE_MESSAGES, allowed_of(form.messages)); - self.put(&PRIVACY_POKES, allowed_of(form.pokes)); - self.refresh_pages(); - } - - pub(crate) fn advanced_changed(&mut self, form: &AdvancedForm) { - let number = |t: &Arc| t.trim().parse::().ok(); - if !form.encoder.trim().is_empty() { - self.put(&STREAM_ENCODER_BACKEND, form.encoder.trim().to_owned()); - } - self.put(&STREAM_HARDWARE_ACCELERATION, form.hardware); - if !form.decoder.trim().is_empty() { - self.put(&STREAM_DECODER_BACKEND, form.decoder.trim().to_owned()); - } - self.put(&STREAM_HARDWARE_DECODING, form.hardware_decoding); - self.put(&CHAT_STORE_HISTORY, form.store_history); - if let Some(v) = number(&form.history_page) { - self.put(&CHAT_HISTORY_PAGE, v as u32); - } - if let Some(v) = number(&form.dedupe_ms) { - self.put(&CHAT_DEDUPE_TOLERANCE_MS, v); - } - if let Some(v) = number(&form.retention_days) { - self.put(&CHAT_RETENTION_DAYS, v as u32); - } - if let Some(v) = number(&form.cache_mb) { - self.put(&CACHE_MAX_MB, v); - } - self.put(&CACHE_FETCH_IMAGES, form.fetch_images); - if let Some(v) = number(&form.progress_ms) { - self.put(&FILES_PROGRESS_MS, v as u32); - } - if let Some(v) = number(&form.preview_kb) { - self.put(&UI_IMAGE_PREVIEW_KB, v as u32); - } - self.refresh_pages(); - } - - /// Move an SRTP profile up (`-1`) or down (`1`). - pub(crate) fn srtp_move(&mut self, index: i32, by: i32) { - let mut list = self.prefs.get(&STREAM_SRTP_PROFILES); - let (Ok(from), Ok(to)) = (usize::try_from(index), usize::try_from(index + by)) else { - return; - }; - if from < list.len() && to < list.len() { - list.swap(from, to); - self.put(&STREAM_SRTP_PROFILES, list); - } - self.refresh_pages(); - } - - /// Offer a profile, or stop offering it (one stays). - pub(crate) fn srtp_toggle(&mut self, name: &str) { - let mut list = self.prefs.get(&STREAM_SRTP_PROFILES); - match list.iter().position(|p| p == name) { - Some(i) if list.len() > 1 => { - list.remove(i); - } - Some(_) => return, - None => list.push(name.to_owned()), - } - self.put(&STREAM_SRTP_PROFILES, list); - self.refresh_pages(); - } - - /// Every registered setting (Advanced), filtered. - pub(crate) fn refresh_all_settings(&self) { - let filter = self.pages.settings_filter.trim().to_lowercase(); - let items: Vec = self - .prefs - .keys() - .into_iter() - .filter(|k| { - filter.is_empty() - || k.name().contains(&filter) - || k.doc().to_lowercase().contains(&filter) - }) - .map(|k| SettingItem { - key: k.name().into(), - doc: k.doc().into(), - value: self - .prefs - .get_json(k.name()) - .map(|v| v.to_string()) - .unwrap_or_default() - .into(), - source: match self.prefs.source(k.name()) { - Some(SettingSource::Runtime) => "set here", - Some(SettingSource::Override) => "command line", - Some(SettingSource::Config) => "config file", - _ => "default", - } - .into(), - }) - .collect(); - self.models.all_settings.sync(&items); - } - - pub(crate) fn search_settings(&mut self, text: String) { - self.pages.settings_filter = text; - self.refresh_all_settings(); - } - - /// Set a key from its JSON text; why not, when it is refused. - pub(crate) fn setting_set(&mut self, key: &str, text: &str) -> String { - match self.prefs.set_json(key, json_of(text)) { - Ok(()) => { - self.refresh_all_settings(); - String::new() - } - Err(e) => { - let message = e.to_string(); - self.set_status(message.clone()); - message - } - } - } - - pub(crate) fn setting_reset(&mut self, key: &str) { - if let Err(e) = self.prefs.reset(key) { - self.set_status(e.to_string()); - } - self.refresh_all_settings(); - self.refresh_pages(); - } - - /// The folder with the log files. - pub(crate) fn open_logs(&mut self) { - let dir = voelin_platform::logs::current().and_then(std::path::Path::parent); - let result = dir.ok_or_else(|| "no log file".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 log folder: {e}")); - } - } - - // Integrations. - - /// The gateways of our servers and the one being administered. - pub(crate) fn refresh_gateways(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let items: Vec = self - .state - .bookmarks - .iter() - .filter_map(|b| { - let url = b.gateway_url.clone()?; - let view = self.state.sessions.get(&b.id); - let caps = view.map(|v| v.gateway_caps.clone()).unwrap_or_default(); - let status = match view.map(|v| v.state.observe) { - _ if !caps.is_empty() => "connected", - Some(voelin_core::ObserveState::Connecting) => "connecting", - _ => "off", - }; - Some(GatewayItem { - session: b.id as i32, - server: b.name.clone().into(), - url: url.into(), - status: status.into(), - admin: caps.iter().any(|c| c == feature::ADMIN), - features: caps.into_iter().map(Arc::::from).collect(), - }) - }) - .collect(); - bridge.set_gateways(convert::model(&items)); - bridge.set_admin_session(self.pages.admin.map_or(-1, |s| s as i32)); - let extra = self.pages.admin.and_then(|s| self.state.sessions.get(&s)).map(|v| &v.extra); - let config: Vec = extra - .map(|e| { - e.config - .iter() - .map(|c| ConfigItem { - key: c.key.clone().into(), - value: c.value.to_string().into(), - source: config_source(c.source).into(), - description: c.description.clone().into(), - kind: c.value_type.clone().into(), - bootstrap: c.bootstrap, - }) - .collect() - }) - .unwrap_or_default(); - self.models.gateway_config.sync(&config); - let perms: Vec = extra - .map(|e| { - e.perms - .iter() - .map(|r| { - let rule = r.rule.clone().unwrap_or_default(); - let list = |ids: &[u64]| { - ids.iter().map(u64::to_string).collect::>().join(", ") - }; - PermItem { - action: r.action.as_str().into(), - rule: match &r.rule { - Some(rule) => rule_text(rule), - None => format!("Default: {}", r.default), - } - .into(), - source: config_source(r.source).into(), - everyone: rule.everyone, - server_groups: list(&rule.server_groups).into(), - channel_groups: list(&rule.channel_groups).into(), - } - }) - .collect() - }) - .unwrap_or_default(); - self.models.gateway_perms.sync(&perms); - } - - /// Administer a gateway (`-1`: close). - pub(crate) fn gateway_admin(&mut self, session: i32) { - self.pages.admin = (session >= 0).then_some(i64::from(session)); - if let Some(id) = self.pages.admin { - self.gateway_to(id, GatewayRequest::ConfigList); - self.gateway_to(id, GatewayRequest::PermList); - } - self.refresh_gateways(); - } - - pub(crate) fn config_set(&mut self, key: &str, text: &str) { - if let Some(id) = self.pages.admin { - self.gateway_to( - id, - GatewayRequest::ConfigSet { key: key.to_owned(), value: json_of(text) }, - ); - } - } - - pub(crate) fn config_reset(&mut self, key: &str) { - if let Some(id) = self.pages.admin { - self.gateway_to(id, GatewayRequest::ConfigReset { key: key.to_owned() }); - } - } - - pub(crate) fn config_reload(&mut self) { - if let Some(id) = self.pages.admin { - self.gateway_to(id, GatewayRequest::ConfigReload); - } - } - - pub(crate) fn perm_set(&mut self, action: &str, everyone: bool, server: &str, channel: &str) { - let (Some(id), Some(action)) = (self.pages.admin, Action::parse(action)) else { return }; - let rule = PermRule { - everyone, - server_groups: group_ids(server), - channel_groups: group_ids(channel), - }; - self.gateway_to(id, GatewayRequest::PermSet { action, rule }); - self.gateway_to(id, GatewayRequest::PermList); - } - - pub(crate) fn perm_reset(&mut self, action: &str) { - let (Some(id), Some(action)) = (self.pages.admin, Action::parse(action)) else { return }; - self.gateway_to(id, GatewayRequest::PermReset { action }); - self.gateway_to(id, GatewayRequest::PermList); - } - - /// Probe the encoders off the UI thread (FFmpeg's probe can take a - /// while). - pub(crate) fn refresh_encoders(&mut self) { - self.pages.encoders_loading = true; - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_encoders_loading(true); - } - let codecs = self.video.codecs(); - std::thread::spawn(move || { - let report = codecs.report(); - later(move |app| app.encoders_ready(report)); - }); - } - - fn encoders_ready(&mut self, report: voelin_core::media::voelin_media::EncoderReport) { - self.pages.encoders_loading = false; - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - bridge.set_encoders_loading(false); - bridge.set_ffmpeg_status( - match &report.ffmpeg { - Ok(v) => format!("FFmpeg: {v}"), - Err(e) => format!("FFmpeg is not used: {e}"), - } - .into(), - ); - bridge.set_zero_copy_status( - match &report.zero_copy { - Ok(()) => "Screen capture goes to the GPU encoder without a copy.".to_owned(), - Err(e) => format!("No zero-copy capture: {e}"), - } - .into(), - ); - // A decoder's entry is an encoder's (its rank: the place in its - // codec's ladder). - let items = |list: &[voelin_core::media::voelin_media::EncoderInfo]| { - let items: Vec = list - .iter() - .map(|e| EncoderItem { - name: e.name.clone().into(), - api: e.api.clone().into(), - codec: format!("{:?}", e.codec).to_uppercase().into(), - hardware: e.hardware, - ok: e.status.is_ok(), - status: match (&e.status, e.rank) { - (Err(why), _) => why.clone(), - (Ok(()), Some(0)) => format!("{} · used first", e.api), - (Ok(()), Some(n)) => format!("{} · choice {}", e.api, n + 1), - (Ok(()), None) => format!("{} · not used", e.api), - } - .into(), - }) - .collect(); - convert::model(&items) - }; - bridge.set_encoders(items(&report.encoders)); - bridge.set_decoders(items(&report.decoders)); - } - - /// The screens and windows that can be shared (Devices). - fn load_capture_sources(&mut self) { - let names: Vec = match self.video.sources(false, false) { - Ok(list) => list - .into_iter() - .map(|(n, d)| { - SharedString::from(if d.is_empty() { n } else { format!("{n} · {d}") }) - }) - .collect(), - Err(e) => vec![e.into()], - }; - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_capture_sources(model(names)); - } - } - - // Identities (My Account, Profiles). - - /// Our unique ids (every identity, both server generations), to tell - /// our own messages. - pub(crate) fn load_own_uids(&mut self) { - let mut uids = std::collections::HashSet::new(); - for e in self.store.identities().unwrap_or_default() { - if let Ok(identity) = self.store.identity(e.id) { - let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts()); - uids.insert(ids.ts3); - uids.insert(ids.ts6); - } - } - self.social.own_uids = uids; - } - - /// The identity servers see us as on `bookmark` (the one place that - /// picks it): the bookmark's own if it names one that exists, else the - /// store's default. - fn identity_id_for(&self, bookmark: Option) -> Option { - let entries = self.store.identities().unwrap_or_default(); - bookmark - .and_then(|b| self.bookmark(b)) - .and_then(|b| b.identity) - .filter(|id| entries.iter().any(|e| e.id == *id)) - .or_else(|| self.default_identity_id()) - } - - /// The identity a connection to `bookmark` uses ([`Self::identity_id_for`]). - pub(crate) fn identity_for(&self, bookmark: Option) -> tsclientlib::Identity { - self.identity_id_for(bookmark) - .and_then(|id| self.store.identity(id).ok()) - .unwrap_or_else(|| self.identity.clone()) - } - - /// The store's default identity (`Store::default_identity`). - fn default_identity_id(&self) -> Option { - self.store.default_identity().ok().flatten().map(|e| e.id) - } - - pub(crate) fn refresh_account(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let bookmark = self.state.current.and_then(|id| self.bookmark(id)); - let identity = self.identity_for(self.state.current); - let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts()); - let entry_id = self.identity_id_for(self.state.current); - let name = self - .store - .identities() - .unwrap_or_default() - .into_iter() - .find(|e| Some(e.id) == entry_id) - .map(|e| e.name) - .unwrap_or_default(); - bridge.set_account( - AccountForm { - nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into(), - identity: name.into(), - uid: ids.ts3.into(), - uid6: ids.ts6.into(), - level: i32::from(identity.level()), - server: bookmark.map(|b| b.name.clone()).unwrap_or_default().into(), - } - .into(), - ); - } - - /// The identities, the bookmarks' choices, what an import found. - pub(crate) fn refresh_identities(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let entries = self.store.identities().unwrap_or_default(); - let default = self.default_identity_id(); - let picks: Vec<(&str, Option)> = self - .state - .bookmarks - .iter() - .map(|b| (b.name.as_str(), self.identity_id_for(Some(b.id)))) - .collect(); - let items: Vec = entries - .iter() - .map(|e| { - let identity = self.store.identity(e.id).ok(); - let ids = - identity.as_ref().map(|i| UniqueIds::from_omega(&i.key().to_pub().to_ts())); - let improving = self.pages.improving.get(&e.id); - let used: Vec<&str> = picks - .iter() - .filter(|(_, id)| *id == Some(e.id)) - .map(|(name, _)| *name) - .collect(); - IdentityItem { - id: e.id as i32, - name: e.name.clone().into(), - uid: e.uid.clone().into(), - uid6: ids.map(|i| i.ts6).unwrap_or_default().into(), - level: i32::from(identity.map_or(e.level, |i| i.level())), - default: Some(e.id) == default, - origin: crate::identities::origin_label(e.origin).into(), - improving: improving.map_or(0, |i| i32::from(i.target)), - reached: improving.map_or(0, |i| i32::from(i.reached)), - used_by: used.join(", ").into(), - } - }) - .collect(); - self.models.identities.sync(&items); - let mut names = vec![SharedString::from("Default identity")]; - names.extend(entries.iter().map(|e| SharedString::from(e.name.as_str()))); - bridge.set_identity_names(model(names)); - let choices: Vec = self - .state - .bookmarks - .iter() - .map(|b| BookmarkIdentity { - id: b.id as i32, - name: b.name.clone().into(), - identity: b - .identity - .and_then(|id| entries.iter().position(|e| e.id == id)) - .map_or(0, |i| i as i32 + 1), - }) - .collect(); - bridge.set_bookmark_identities(convert::model(&choices)); - let known: std::collections::HashSet<&str> = - entries.iter().map(|e| e.uid.as_str()).collect(); - let found: Vec = self - .pages - .found - .iter() - .map(|(f, picked)| { - let uid = f.uid(); - FoundIdentity { - name: f.nickname.clone().into(), - known: known.contains(uid.as_str()), - uid: uid.into(), - level: i32::from(f.level()), - source: f.source.display().to_string().into(), - picked: *picked, - } - }) - .collect(); - bridge.set_found_identities(convert::model(&found)); - bridge.set_identity_import(self.prefs.get(&IDENTITY_IMPORT)); - self.refresh_account(); - } - - /// "delete", "export", "stop" (the default: [`Self::use_identity`]). - pub(crate) fn identity_action(&mut self, id: i32, action: &str) { - let id = i64::from(id); - match action { - "delete" => { - if self.default_identity_id() == Some(id) { - self.set_status( - "The default identity cannot be deleted; make another one the default first.", - ); - return; - } - if let Err(e) = self.store.delete_identity(id) { - self.set_status(format!("Could not delete the identity: {e}")); - } - self.load_own_uids(); - } - "export" => self.export_identity(id), - "stop" => { - if let Some(i) = self.pages.improving.remove(&id) { - i.cancel.store(true, Ordering::Relaxed); - } - } - _ => {} - } - self.refresh_identities(); - } - - fn export_identity(&mut self, id: i64) { - let entries = self.store.identities().unwrap_or_default(); - let (Some(entry), Ok(identity)) = - (entries.iter().find(|e| e.id == id), self.store.identity(id)) - else { - return; - }; - let dir = dirs::download_dir().or_else(dirs::home_dir).unwrap_or_else(|| ".".into()); - let file = entry - .name - .chars() - .map(|c| if c.is_alphanumeric() || c == '-' { c } else { '_' }) - .collect::(); - let path = dir.join(format!("{file}.ini")); - match voelin_core::identity::write_export(&path, &entry.name, &identity) { - Ok(()) => self.set_identity_status(format!( - "Exported to {} (it holds the private key: keep it safe).", - path.display() - )), - Err(e) => self.set_identity_status(format!("Could not export: {e}")), - } - } - - fn set_identity_status(&mut self, text: String) { - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_identity_status(text.clone().into()); - } - self.set_status(text); - } - - pub(crate) fn rename_identity(&mut self, id: i32, name: &str) { - let name = name.trim(); - if name.is_empty() { - return; - } - if let Err(e) = self.store.rename_identity(i64::from(id), name) { - self.set_status(format!("Could not rename: {e}")); - } - self.refresh_identities(); - } - - /// Raise an identity's level to `target` on every core, in the - /// background. - pub(crate) fn improve_identity(&mut self, id: i32, target: i32) { - let id = i64::from(id); - let Ok(identity) = self.store.identity(id) else { return }; - let Ok(target) = u8::try_from(target) else { return }; - if target <= identity.level() || self.pages.improving.contains_key(&id) { - self.set_identity_status(format!( - "The identity is at level {} already.", - identity.level() - )); - return; - } - let cancel = Arc::new(AtomicBool::new(false)); - self.pages - .improving - .insert(id, Improving { target, reached: identity.level(), cancel: cancel.clone() }); - std::thread::Builder::new() - .name("identity-level".into()) - .spawn(move || { - let better = - voelin_core::identity::improve_level(&identity, target, &cancel, |level| { - later(move |app| { - if let Some(i) = app.pages.improving.get_mut(&id) { - i.reached = i.reached.max(level); - } - app.refresh_identities(); - }); - }); - later(move |app| app.level_reached(id, better)); - }) - .ok(); - self.refresh_identities(); - } - - fn level_reached(&mut self, id: i64, better: Option) { - self.pages.improving.remove(&id); - if let Some(identity) = better { - match self.store.update_identity(id, &identity) { - Ok(()) => { - self.set_identity_status(format!( - "Security level {} reached.", - identity.level() - )); - if self.default_identity_id() == Some(id) { - self.identity = identity; - } - } - Err(e) => self.set_identity_status(format!("Could not store the identity: {e}")), - } - } - self.refresh_identities(); - } - - /// Look for identities in the official clients' files. - pub(crate) fn find_identities(&mut self) { - let mut found = Vec::new(); - let mut errors = Vec::new(); - for path in voelin_core::identity::discover() { - match voelin_core::identity::read(&path) { - Ok(list) => found.extend(list), - Err(e) => errors.push(e.to_string()), - } - } - let known: std::collections::HashSet = - self.store.identities().unwrap_or_default().into_iter().map(|e| e.uid).collect(); - let status = match (found.len(), errors.first()) { - (0, Some(e)) => format!("Nothing found ({e})."), - (0, None) => "No TeamSpeak client settings found on this device.".to_owned(), - (n, _) => format!("{n} identities found."), - }; - self.pages.found = found - .into_iter() - .map(|f| { - let new = !known.contains(&f.uid()); - (f, new) - }) - .collect(); - self.set_identity_status(status); - self.refresh_identities(); - } - - pub(crate) fn pick_found(&mut self, index: i32, on: bool) { - if let Some(f) = usize::try_from(index).ok().and_then(|i| self.pages.found.get_mut(i)) { - f.1 = on; - } - self.refresh_identities(); - } - - pub(crate) fn import_identities(&mut self) { - let picked: Vec<_> = - self.pages.found.iter().filter(|(_, p)| *p).map(|(f, _)| f.clone()).collect(); - match voelin_core::identity::import(&self.store, &picked) { - Ok(results) => { - let added = results - .iter() - .filter(|r| matches!(r, voelin_core::identity::Imported::Added(_))) - .count(); - self.set_identity_status(format!("{added} identities imported.")); - } - Err(e) => self.set_identity_status(format!("Could not import: {e}")), - } - self.pages.found.clear(); - self.load_own_uids(); - self.refresh_identities(); - } - - /// The identity a bookmark connects with (0: the default). - pub(crate) fn bookmark_identity(&mut self, bookmark: i32, index: i32) { - let entries = self.store.identities().unwrap_or_default(); - let identity = usize::try_from(index - 1).ok().and_then(|i| entries.get(i)).map(|e| e.id); - let Some(mut b) = self.bookmark(i64::from(bookmark)).cloned() else { return }; - b.identity = identity; - if let Err(e) = self.store.update_bookmark(&b) { - self.set_status(format!("Could not save: {e}")); - return; - } - self.state.bookmarks = self.store.bookmarks().unwrap_or_default(); - self.refresh_identities(); - } - - // Camera (Voice & Video, Devices). - - fn load_cameras(&mut self) { - let mut cameras = crate::camera::list(); - // Sample data never opens a real camera. - if self.demo_ui { - cameras.retain(|(id, _)| id == "synthetic"); - } - self.pages.cameras = cameras.iter().map(|(id, _)| id.clone()).collect(); - let names: Vec = - cameras.into_iter().map(|(_, n)| SharedString::from(n)).collect(); - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_cameras(model(names)); - } - } - - pub(crate) fn toggle_camera_preview(&mut self) { - if self.pages.camera.is_some() { - self.stop_camera(); - } else { - self.start_camera(); - } - self.refresh_pages(); - } - - pub(crate) fn start_camera(&mut self) { - let device = - if self.demo_ui { "synthetic".to_owned() } else { self.prefs.get(&VIDEO_CAMERA) }; - let size = parse_size(&self.prefs.get(&VIDEO_RESOLUTION)); - let blur = self.prefs.get(&VIDEO_BACKGROUND) == "blur"; - let mirror = self.prefs.get(&VIDEO_MIRROR); - self.pages.camera = - Some(crate::camera::Preview::start(self.engine.runtime(), &device, size, blur, mirror)); - if let Some(ui) = self.ui.upgrade() { - ui.global::().set_camera_status("Starting the camera…".into()); - } - } - - pub(crate) fn stop_camera(&mut self) { - if self.pages.camera.take().is_some() - && let Some(ui) = self.ui.upgrade() - { - let bridge = ui.global::(); - bridge.set_camera_frame(slint::Image::default()); - bridge.set_camera_status(SharedString::new()); - } - } - - fn restart_camera(&mut self) { - if self.pages.camera.is_some() { - self.stop_camera(); - self.start_camera(); - } - } - - /// The camera preview's newest picture (called by its timer). - pub(crate) fn camera_frame(&mut self) { - let Some(preview) = &self.pages.camera else { return }; - let (frame, status) = (preview.take_picture(), preview.status()); - if let Some(ui) = self.ui.upgrade() { - let bridge = ui.global::(); - if let Some(frame) = frame { - bridge.set_camera_frame(frame); - } - bridge.set_camera_status(status.into()); - } - } - - /// Play a short tone on the speakers (the Test Sound button). - pub(crate) fn test_sound(&mut self) { - let device = self.state.audio.output_device.clone(); - let volume = self.state.audio.output_volume; - std::thread::spawn(move || { - let result = crate::camera::play_tone(device.as_deref(), volume); - if let Err(e) = result { - later(move |app| app.set_status(format!("Cannot play the test sound: {e}"))); - } - }); - } -} - -fn codec_index(c: CodecChoice) -> i32 { - match c { - CodecChoice::Auto => 0, - CodecChoice::Vp8 => 1, - CodecChoice::Vp9 => 2, - CodecChoice::H264 => 3, - CodecChoice::Av1 => 4, - } -} - -fn codec_of(i: i32) -> CodecChoice { - match i { - 1 => CodecChoice::Vp8, - 2 => CodecChoice::Vp9, - 3 => CodecChoice::H264, - 4 => CodecChoice::Av1, - _ => CodecChoice::Auto, - } -} - -/// Where the logs go, for the Advanced page. -fn log_text() -> String { - match voelin_platform::logs::current() { - Some(path) => format!( - "This run logs to {} (the previous runs' next to it, the last as voelin.1.log). \ - VOELIN_LOG=voelin_core=debug,voelin_ui=debug logs more; warnings also go to the terminal.", - path.display() - ), - None => "Logs go to the terminal the app was started from (standard error); \ - RUST_LOG=voelin_core=debug,voelin_ui=debug shows more." - .into(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn layers_round_trip() { - let base = LayerSetting::default(); - let item = LayerItem { - size: "1280x720".into(), - fps: "30".into(), - bitrate: "2500".into(), - min_bitrate: "800".into(), - max_bitrate: "".into(), - }; - let layer = layer_of(&item, &base).unwrap(); - assert_eq!( - (layer.size, layer.max_fps, layer.bitrate), - (Some((1280, 720)), Some(30), 2_500_000) - ); - assert_eq!(layer.min_bitrate, 800_000); - assert_eq!(layer_item(&layer), item); - let scaled = layer_of( - &LayerItem { size: "0.5".into(), bitrate: "900".into(), ..item.clone() }, - &base, - ) - .unwrap(); - assert_eq!((scaled.size, scaled.scale), (None, 0.5)); - assert!(layer_of(&LayerItem { size: "big".into(), ..item.clone() }, &base).is_none()); - assert!(layer_of(&LayerItem { bitrate: "0".into(), ..item }, &base).is_none()); - } - - #[test] - fn quality_presets() { - assert_eq!(quality_of(&[]), 0); - let layer = |size| LayerSetting { size: Some(size), ..LayerSetting::default() }; - assert_eq!(quality_of(&[layer((1920, 1080))]), 2); - assert_eq!(quality_of(&[layer((3840, 2160))]), 4); - assert_eq!(quality_of(&[layer((7680, 4320))]), 5); - assert_eq!(quality_of(&[layer((800, 600))]), -1); - // A preset at the bitrate, or the automatic one of its size and rate. - let one = |l: Option>| l.map(|l| (l[0].size, l[0].bitrate)); - assert_eq!(one(preset_layers(5, 60_000, 30)), Some((Some((7680, 4320)), 60_000_000))); - assert_eq!(one(preset_layers(4, 0, 60)), Some((Some((3840, 2160)), 59_719_680))); - assert_eq!(preset_layers(0, 0, 60), Some(Vec::new())); - assert_eq!(preset_layers(-1, 0, 60), None); - assert_eq!(preset_layers(6, 0, 60), None); - assert_eq!(quality_of(&[layer((1280, 720)), layer((640, 360))]), -1); - for i in 0..5 { - assert_eq!(codec_index(codec_of(i)), i); - } - } - - #[test] - fn typed_values() { - assert_eq!(group_ids("6, 7 x 9"), [6, 7, 9]); - assert_eq!(json_of("30"), serde_json::json!(30)); - assert_eq!(json_of("[1,2]"), serde_json::json!([1, 2])); - assert_eq!(json_of("hello"), serde_json::json!("hello")); - let rule = PermRule { everyone: false, server_groups: vec![6], channel_groups: vec![] }; - assert_eq!(rule_text(&rule), "server groups 6"); - assert_eq!(rule_text(&PermRule::default()), "nobody"); - } -} diff --git a/crates/voelin-ui/src/settings_pages/bind.rs b/crates/voelin-ui/src/settings_pages/bind.rs new file mode 100644 index 0000000..e52c04f --- /dev/null +++ b/crates/voelin-ui/src/settings_pages/bind.rs @@ -0,0 +1,801 @@ +//! The settings pages on the Bridge: the forms and models are filled from +//! the settings (`voelin_ui_vm::settings_pages::logic`), the controls' values +//! go back through it, and what a change sets going (the camera, the engine, +//! the identity store, threads) runs here. + +use std::collections::HashSet; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use slint::{ComponentHandle, Model, SharedString}; +use tracing::warn; +use voelin_core::settings::{ + IDENTITY_IMPORT, STREAM_CODEC, STREAM_ENCODER_BACKEND, STREAM_HARDWARE_ACCELERATION, + STREAM_SRTP_PROFILES, +}; +use voelin_core::{Command, GatewayRequest}; +use voelin_gateway_proto::{Action, PermRule, UniqueIds}; + +use crate::app::{App, Bridge, later, model}; +use crate::bind::convert; +use crate::settings::{ + VIDEO_BACKGROUND, VIDEO_CAMERA, VIDEO_MIRROR, VIDEO_RESOLUTION, page_keys, parse_size, +}; +use crate::vm::bridge::{ + AdvancedForm, AudioSourceItem, LayerItem, NotifyForm, PrivacyForm, StreamingForm, VideoForm, +}; +use crate::vm::settings_pages::logic::{ + self, Discovered, IdentityFacts, Improving, group_ids, json_of, +}; + +impl App { + /// What storing settings had to say (a refusal, something typed wrong): + /// the status line shows it. + fn said(&mut self, messages: Vec) { + for message in messages { + warn!(%message, "setting refused"); + self.set_status(message); + } + } + + /// A section of the settings was shown: load what it needs. + pub(crate) fn settings_section(&mut self, section: i32) { + for key in page_keys() { + self.prefs.register(key); + } + match section { + 0 | 7 => { + self.load_cameras(); + if section == 7 { + self.load_capture_sources(); + } + } + 2 => self.watch_audio_apps(), + 5 | 6 => self.refresh_identities(), + 9 => { + if self.pages.state.encoders_loading + || self + .ui + .upgrade() + .is_some_and(|ui| ui.global::().get_encoders().row_count() == 0) + { + self.refresh_encoders(); + } + self.refresh_gateways(); + } + 10 => self.refresh_all_settings(), + _ => {} + } + if section != 0 && section != 7 { + self.stop_camera(); + } + if section != 2 { + self.pages.audio_apps = None; + } + self.refresh_pages(); + } + + /// Every form of the settings pages, from the settings. + pub(crate) fn refresh_pages(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let p = &self.prefs; + let video = logic::video_form(p, &self.pages.state.cameras, self.pages.camera.is_some()); + bridge.set_video(video.into()); + bridge.set_streaming(logic::streaming_form(p).into()); + self.models.layers.sync(&logic::layer_items(p)); + self.models.audio_sources.sync(&logic::audio_source_items(p, voelin_platform::APP_NAME)); + bridge.set_has_studio(true); + bridge.set_notify(logic::notify_form(p).into()); + bridge.set_privacy(logic::privacy_form(p).into()); + let srtp = p.get(&STREAM_SRTP_PROFILES); + bridge.set_srtp_profiles(model(srtp.iter().map(SharedString::from).collect())); + bridge.set_srtp_unused(model( + logic::srtp_unused(&srtp).into_iter().map(SharedString::from).collect(), + )); + let crash_dir = voelin_platform::crash::dir().map(|d| d.display().to_string()); + bridge.set_advanced( + logic::advanced_form(p, &log_text(), &crash_dir.unwrap_or_default()).into(), + ); + self.refresh_account(); + } + + /// A setting changed anywhere: fill the forms, apply what the engine + /// does not read itself. + pub(crate) fn page_setting_changed(&mut self, key: &str) { + if key == STREAM_SRTP_PROFILES.name() { + self.apply_srtp(); + } + if [STREAM_HARDWARE_ACCELERATION.name(), STREAM_ENCODER_BACKEND.name(), STREAM_CODEC.name()] + .contains(&key) + { + self.video.set_encoder_preference( + voelin_core::media::encoder_preference(&self.prefs), + voelin_core::media::configured_codec(&self.prefs), + ); + } + if key == VIDEO_CAMERA.name() + || key == VIDEO_BACKGROUND.name() + || key == VIDEO_RESOLUTION.name() + { + self.restart_camera(); + } + self.refresh_pages(); + if key.starts_with("stream.") + || key.starts_with("privacy.") + || key.starts_with("chat.") + || key.starts_with("cache.") + { + self.refresh_all_settings(); + } + } + + /// The SRTP profiles of the setting, for the engine (it does not read + /// the setting itself; it takes the names and leaves out the ones its + /// stream transport does not know). + pub(crate) fn apply_srtp(&self) { + let profiles = self.prefs.get(&STREAM_SRTP_PROFILES); + self.engine.send(Command::SetSrtpProfiles(profiles.to_vec())); + } + + pub(crate) fn video_changed(&mut self, form: &VideoForm) { + let messages = logic::apply_video(&self.prefs, &self.pages.state.cameras, form); + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn streaming_changed(&mut self, form: &StreamingForm) { + let messages = logic::apply_streaming(&self.prefs, form); + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn layer_changed(&mut self, index: i32, item: &LayerItem) { + let Some(messages) = logic::apply_layer(&self.prefs, index, item) else { return }; + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn add_layer(&mut self) { + let messages = logic::add_layer(&self.prefs); + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn remove_layer(&mut self, index: i32) { + let messages = logic::remove_layer(&self.prefs, index); + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn audio_source_changed(&mut self, index: i32, item: &AudioSourceItem) { + let messages = logic::apply_audio_source(&self.prefs, index, item); + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn add_audio_source(&mut self, kind: &str, name: &str) { + let Some(messages) = logic::add_audio_source(&self.prefs, kind, name) else { return }; + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn remove_audio_source(&mut self, index: i32) { + let messages = logic::remove_audio_source(&self.prefs, index); + self.said(messages); + self.refresh_pages(); + } + + /// Follow the applications that play audio while the Streaming page is + /// open (`tick` checks for changes). + fn watch_audio_apps(&mut self) { + if self.pages.audio_apps.is_none() && !self.demo_ui { + match voelin_core::media::audio_apps() { + Ok(apps) => self.pages.audio_apps = Some(apps), + Err(e) => warn!("cannot list applications that play audio: {e}"), + } + } + self.refresh_audio_apps(); + } + + pub(crate) fn refresh_audio_apps(&mut self) { + let Some(apps) = self.pages.audio_apps.as_mut() else { return }; + let names: Vec = apps + .current() + .into_iter() + .map(|a| SharedString::from(a.binary.unwrap_or(a.name))) + .collect(); + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_audio_apps(model(names)); + } + } + + /// Called once a second: a changed list of audio applications. + pub(crate) fn tick_pages(&mut self) { + if self.pages.audio_apps.as_ref().is_some_and(|a| a.has_changed()) { + self.refresh_audio_apps(); + } + } + + pub(crate) fn notify_changed(&mut self, form: &NotifyForm) { + let messages = logic::apply_notify(&self.prefs, form); + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn test_notification(&mut self) { + let n = + voelin_platform::Notification::new(voelin_platform::APP_NAME, "Notifications work."); + self.engine.runtime().spawn(async move { + let result = voelin_platform::notify(&n).await; + later(move |app| { + app.set_status(match result { + Ok(()) => "A desktop notification was sent.".to_owned(), + Err(e) => format!("No desktop notification: {e}"), + }); + }); + }); + } + + pub(crate) fn privacy_changed(&mut self, form: &PrivacyForm) { + let messages = logic::apply_privacy(&self.prefs, form); + self.said(messages); + self.refresh_pages(); + } + + pub(crate) fn advanced_changed(&mut self, form: &AdvancedForm) { + let messages = logic::apply_advanced(&self.prefs, form); + self.said(messages); + self.refresh_pages(); + } + + /// Move an SRTP profile up (`-1`) or down (`1`). + pub(crate) fn srtp_move(&mut self, index: i32, by: i32) { + let Some(messages) = logic::srtp_move(&self.prefs, index, by) else { return }; + self.said(messages); + self.refresh_pages(); + } + + /// Offer a profile, or stop offering it (one stays). + pub(crate) fn srtp_toggle(&mut self, name: &str) { + let Some(messages) = logic::srtp_toggle(&self.prefs, name) else { return }; + self.said(messages); + self.refresh_pages(); + } + + /// Every registered setting (Advanced), filtered. + pub(crate) fn refresh_all_settings(&self) { + let filter = self.pages.state.settings_filter.trim().to_lowercase(); + self.models.all_settings.sync(&logic::setting_items(&self.prefs, &filter)); + } + + pub(crate) fn search_settings(&mut self, text: String) { + self.pages.state.settings_filter = text; + self.refresh_all_settings(); + } + + /// Set a key from its JSON text; why not, when it is refused. + pub(crate) fn setting_set(&mut self, key: &str, text: &str) -> String { + match self.prefs.set_json(key, json_of(text)) { + Ok(()) => { + self.refresh_all_settings(); + String::new() + } + Err(e) => { + let message = e.to_string(); + self.set_status(message.clone()); + message + } + } + } + + pub(crate) fn setting_reset(&mut self, key: &str) { + if let Err(e) = self.prefs.reset(key) { + self.set_status(e.to_string()); + } + self.refresh_all_settings(); + self.refresh_pages(); + } + + /// The folder with the log files. + pub(crate) fn open_logs(&mut self) { + let dir = voelin_platform::logs::current().and_then(std::path::Path::parent); + let result = dir.ok_or_else(|| "no log file".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 log folder: {e}")); + } + } + + // Integrations. + + /// The gateways of our servers and the one being administered. + pub(crate) fn refresh_gateways(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + bridge.set_gateways(convert::model(&logic::gateway_items(&self.state))); + bridge.set_admin_session(self.pages.state.admin.map_or(-1, |s| s as i32)); + let extra = + self.pages.state.admin.and_then(|s| self.state.sessions.get(&s)).map(|v| &v.extra); + self.models.gateway_config.sync(&logic::config_items(extra)); + self.models.gateway_perms.sync(&logic::perm_items(extra)); + } + + /// Administer a gateway (`-1`: close). + pub(crate) fn gateway_admin(&mut self, session: i32) { + self.pages.state.admin = (session >= 0).then_some(i64::from(session)); + if let Some(id) = self.pages.state.admin { + self.gateway_to(id, GatewayRequest::ConfigList); + self.gateway_to(id, GatewayRequest::PermList); + } + self.refresh_gateways(); + } + + pub(crate) fn config_set(&mut self, key: &str, text: &str) { + if let Some(id) = self.pages.state.admin { + self.gateway_to( + id, + GatewayRequest::ConfigSet { key: key.to_owned(), value: json_of(text) }, + ); + } + } + + pub(crate) fn config_reset(&mut self, key: &str) { + if let Some(id) = self.pages.state.admin { + self.gateway_to(id, GatewayRequest::ConfigReset { key: key.to_owned() }); + } + } + + pub(crate) fn config_reload(&mut self) { + if let Some(id) = self.pages.state.admin { + self.gateway_to(id, GatewayRequest::ConfigReload); + } + } + + pub(crate) fn perm_set(&mut self, action: &str, everyone: bool, server: &str, channel: &str) { + let (Some(id), Some(action)) = (self.pages.state.admin, Action::parse(action)) else { + return; + }; + let rule = PermRule { + everyone, + server_groups: group_ids(server), + channel_groups: group_ids(channel), + }; + self.gateway_to(id, GatewayRequest::PermSet { action, rule }); + self.gateway_to(id, GatewayRequest::PermList); + } + + pub(crate) fn perm_reset(&mut self, action: &str) { + let (Some(id), Some(action)) = (self.pages.state.admin, Action::parse(action)) else { + return; + }; + self.gateway_to(id, GatewayRequest::PermReset { action }); + self.gateway_to(id, GatewayRequest::PermList); + } + + /// Probe the encoders off the UI thread (FFmpeg's probe can take a + /// while). + pub(crate) fn refresh_encoders(&mut self) { + self.pages.state.encoders_loading = true; + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_encoders_loading(true); + } + let codecs = self.video.codecs(); + std::thread::spawn(move || { + let report = codecs.report(); + later(move |app| app.encoders_ready(report)); + }); + } + + fn encoders_ready(&mut self, report: voelin_core::media::voelin_media::EncoderReport) { + self.pages.state.encoders_loading = false; + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + bridge.set_encoders_loading(false); + bridge.set_ffmpeg_status(logic::ffmpeg_status(&report.ffmpeg).into()); + bridge.set_zero_copy_status(logic::zero_copy_status(&report.zero_copy).into()); + bridge.set_encoders(convert::model(&logic::encoder_items(&report.encoders))); + bridge.set_decoders(convert::model(&logic::encoder_items(&report.decoders))); + } + + /// The screens and windows that can be shared (Devices). + fn load_capture_sources(&mut self) { + let names: Vec = + logic::capture_source_names(self.video.sources(false, false)) + .into_iter() + .map(SharedString::from) + .collect(); + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_capture_sources(model(names)); + } + } + + // Identities (My Account, Profiles). + + /// Our unique ids (every identity, both server generations), to tell + /// our own messages. + pub(crate) fn load_own_uids(&mut self) { + let mut uids = std::collections::HashSet::new(); + for e in self.store.identities().unwrap_or_default() { + if let Ok(identity) = self.store.identity(e.id) { + let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts()); + uids.insert(ids.ts3); + uids.insert(ids.ts6); + } + } + self.social.own_uids = uids; + } + + /// The identity servers see us as on `bookmark` (the one place that + /// picks it): the bookmark's own if it names one that exists, else the + /// store's default. + fn identity_id_for(&self, bookmark: Option) -> Option { + let entries = self.store.identities().unwrap_or_default(); + bookmark + .and_then(|b| self.bookmark(b)) + .and_then(|b| b.identity) + .filter(|id| entries.iter().any(|e| e.id == *id)) + .or_else(|| self.default_identity_id()) + } + + /// The identity a connection to `bookmark` uses ([`Self::identity_id_for`]). + pub(crate) fn identity_for(&self, bookmark: Option) -> tsclientlib::Identity { + self.identity_id_for(bookmark) + .and_then(|id| self.store.identity(id).ok()) + .unwrap_or_else(|| self.identity.clone()) + } + + /// The store's default identity (`Store::default_identity`). + fn default_identity_id(&self) -> Option { + self.store.default_identity().ok().flatten().map(|e| e.id) + } + + pub(crate) fn refresh_account(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let bookmark = self.state.current.and_then(|id| self.bookmark(id)); + let identity = self.identity_for(self.state.current); + let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts()); + let entry_id = self.identity_id_for(self.state.current); + let name = self + .store + .identities() + .unwrap_or_default() + .into_iter() + .find(|e| Some(e.id) == entry_id) + .map(|e| e.name) + .unwrap_or_default(); + bridge.set_account( + logic::account_form(bookmark, &name, &ids.ts3, &ids.ts6, identity.level()).into(), + ); + } + + /// The identities, the bookmarks' choices, what an import found. + pub(crate) fn refresh_identities(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let entries = self.store.identities().unwrap_or_default(); + let default = self.default_identity_id(); + let picks: Vec<(&str, Option)> = self + .state + .bookmarks + .iter() + .map(|b| (b.name.as_str(), self.identity_id_for(Some(b.id)))) + .collect(); + // What each key says: its unique id on TeamSpeak 6 servers and its level. + let keys: Vec> = entries + .iter() + .map(|e| { + let identity = self.store.identity(e.id).ok()?; + let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts()); + Some((ids.ts6, identity.level())) + }) + .collect(); + let facts: Vec = + entries.iter().zip(keys).map(|(entry, key)| IdentityFacts { entry, key }).collect(); + let improving = + |id: i64| self.pages.state.improving.get(&id).map(|i| (i.target, i.reached)); + self.models.identities.sync(&logic::identity_items(&facts, default, &picks, improving)); + let names: Vec = + logic::identity_names(&entries).into_iter().map(SharedString::from).collect(); + bridge.set_identity_names(model(names)); + bridge.set_bookmark_identities(convert::model(&logic::bookmark_identities( + &self.state.bookmarks, + &entries, + ))); + let known: HashSet<&str> = entries.iter().map(|e| e.uid.as_str()).collect(); + let found: Vec = self + .pages + .state + .found + .iter() + .map(|(f, picked)| Discovered { + nickname: f.nickname.clone(), + uid: f.uid(), + level: f.level(), + source: f.source.display().to_string(), + picked: *picked, + }) + .collect(); + bridge.set_found_identities(convert::model(&logic::found_items(&found, &known))); + bridge.set_identity_import(self.prefs.get(&IDENTITY_IMPORT)); + self.refresh_account(); + } + + /// "delete", "export", "stop" (the default: [`Self::use_identity`]). + pub(crate) fn identity_action(&mut self, id: i32, action: &str) { + let id = i64::from(id); + match action { + "delete" => { + if self.default_identity_id() == Some(id) { + self.set_status( + "The default identity cannot be deleted; make another one the default first.", + ); + return; + } + if let Err(e) = self.store.delete_identity(id) { + self.set_status(format!("Could not delete the identity: {e}")); + } + self.load_own_uids(); + } + "export" => self.export_identity(id), + "stop" => { + if let Some(i) = self.pages.state.improving.remove(&id) { + i.cancel.store(true, Ordering::Relaxed); + } + } + _ => {} + } + self.refresh_identities(); + } + + fn export_identity(&mut self, id: i64) { + let entries = self.store.identities().unwrap_or_default(); + let (Some(entry), Ok(identity)) = + (entries.iter().find(|e| e.id == id), self.store.identity(id)) + else { + return; + }; + let dir = dirs::download_dir().or_else(dirs::home_dir).unwrap_or_else(|| ".".into()); + let file = logic::export_file_stem(&entry.name); + let path = dir.join(format!("{file}.ini")); + match voelin_core::identity::write_export(&path, &entry.name, &identity) { + Ok(()) => self.set_identity_status(format!( + "Exported to {} (it holds the private key: keep it safe).", + path.display() + )), + Err(e) => self.set_identity_status(format!("Could not export: {e}")), + } + } + + fn set_identity_status(&mut self, text: String) { + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_identity_status(text.clone().into()); + } + self.set_status(text); + } + + pub(crate) fn rename_identity(&mut self, id: i32, name: &str) { + let name = name.trim(); + if name.is_empty() { + return; + } + if let Err(e) = self.store.rename_identity(i64::from(id), name) { + self.set_status(format!("Could not rename: {e}")); + } + self.refresh_identities(); + } + + /// Raise an identity's level to `target` on every core, in the + /// background. + pub(crate) fn improve_identity(&mut self, id: i32, target: i32) { + let id = i64::from(id); + let Ok(identity) = self.store.identity(id) else { return }; + let Ok(target) = u8::try_from(target) else { return }; + if target <= identity.level() || self.pages.state.improving.contains_key(&id) { + self.set_identity_status(format!( + "The identity is at level {} already.", + identity.level() + )); + return; + } + let cancel = Arc::new(AtomicBool::new(false)); + self.pages + .state + .improving + .insert(id, Improving { target, reached: identity.level(), cancel: cancel.clone() }); + std::thread::Builder::new() + .name("identity-level".into()) + .spawn(move || { + let better = + voelin_core::identity::improve_level(&identity, target, &cancel, |level| { + later(move |app| { + if let Some(i) = app.pages.state.improving.get_mut(&id) { + i.reached = i.reached.max(level); + } + app.refresh_identities(); + }); + }); + later(move |app| app.level_reached(id, better)); + }) + .ok(); + self.refresh_identities(); + } + + fn level_reached(&mut self, id: i64, better: Option) { + self.pages.state.improving.remove(&id); + if let Some(identity) = better { + match self.store.update_identity(id, &identity) { + Ok(()) => { + self.set_identity_status(format!( + "Security level {} reached.", + identity.level() + )); + if self.default_identity_id() == Some(id) { + self.identity = identity; + } + } + Err(e) => self.set_identity_status(format!("Could not store the identity: {e}")), + } + } + self.refresh_identities(); + } + + /// Look for identities in the official clients' files. + pub(crate) fn find_identities(&mut self) { + let mut found = Vec::new(); + let mut errors = Vec::new(); + for path in voelin_core::identity::discover() { + match voelin_core::identity::read(&path) { + Ok(list) => found.extend(list), + Err(e) => errors.push(e.to_string()), + } + } + let known: std::collections::HashSet = + self.store.identities().unwrap_or_default().into_iter().map(|e| e.uid).collect(); + let status = logic::found_status(found.len(), errors.first().map(String::as_str)); + self.pages.state.found = found + .into_iter() + .map(|f| { + let new = !known.contains(&f.uid()); + (f, new) + }) + .collect(); + self.set_identity_status(status); + self.refresh_identities(); + } + + pub(crate) fn pick_found(&mut self, index: i32, on: bool) { + if let Some(f) = usize::try_from(index).ok().and_then(|i| self.pages.state.found.get_mut(i)) + { + f.1 = on; + } + self.refresh_identities(); + } + + pub(crate) fn import_identities(&mut self) { + let picked: Vec<_> = + self.pages.state.found.iter().filter(|(_, p)| *p).map(|(f, _)| f.clone()).collect(); + match voelin_core::identity::import(&self.store, &picked) { + Ok(results) => { + let added = results + .iter() + .filter(|r| matches!(r, voelin_core::identity::Imported::Added(_))) + .count(); + self.set_identity_status(format!("{added} identities imported.")); + } + Err(e) => self.set_identity_status(format!("Could not import: {e}")), + } + self.pages.state.found.clear(); + self.load_own_uids(); + self.refresh_identities(); + } + + /// The identity a bookmark connects with (0: the default). + pub(crate) fn bookmark_identity(&mut self, bookmark: i32, index: i32) { + let entries = self.store.identities().unwrap_or_default(); + let identity = usize::try_from(index - 1).ok().and_then(|i| entries.get(i)).map(|e| e.id); + let Some(mut b) = self.bookmark(i64::from(bookmark)).cloned() else { return }; + b.identity = identity; + if let Err(e) = self.store.update_bookmark(&b) { + self.set_status(format!("Could not save: {e}")); + return; + } + self.state.bookmarks = self.store.bookmarks().unwrap_or_default(); + self.refresh_identities(); + } + + // Camera (Voice & Video, Devices). + + fn load_cameras(&mut self) { + let mut cameras = crate::camera::list(); + // Sample data never opens a real camera. + if self.demo_ui { + cameras.retain(|(id, _)| id == "synthetic"); + } + self.pages.state.cameras = cameras.iter().map(|(id, _)| id.clone()).collect(); + let names: Vec = + cameras.into_iter().map(|(_, n)| SharedString::from(n)).collect(); + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_cameras(model(names)); + } + } + + pub(crate) fn toggle_camera_preview(&mut self) { + if self.pages.camera.is_some() { + self.stop_camera(); + } else { + self.start_camera(); + } + self.refresh_pages(); + } + + pub(crate) fn start_camera(&mut self) { + let device = + if self.demo_ui { "synthetic".to_owned() } else { self.prefs.get(&VIDEO_CAMERA) }; + let size = parse_size(&self.prefs.get(&VIDEO_RESOLUTION)); + let blur = self.prefs.get(&VIDEO_BACKGROUND) == "blur"; + let mirror = self.prefs.get(&VIDEO_MIRROR); + self.pages.camera = + Some(crate::camera::Preview::start(self.engine.runtime(), &device, size, blur, mirror)); + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_camera_status("Starting the camera…".into()); + } + } + + pub(crate) fn stop_camera(&mut self) { + if self.pages.camera.take().is_some() + && let Some(ui) = self.ui.upgrade() + { + let bridge = ui.global::(); + bridge.set_camera_frame(slint::Image::default()); + bridge.set_camera_status(SharedString::new()); + } + } + + fn restart_camera(&mut self) { + if self.pages.camera.is_some() { + self.stop_camera(); + self.start_camera(); + } + } + + /// The camera preview's newest picture (called by its timer). + pub(crate) fn camera_frame(&mut self) { + let Some(preview) = &self.pages.camera else { return }; + let (frame, status) = (preview.take_picture(), preview.status()); + if let Some(ui) = self.ui.upgrade() { + let bridge = ui.global::(); + if let Some(frame) = frame { + bridge.set_camera_frame(frame); + } + bridge.set_camera_status(status.into()); + } + } + + /// Play a short tone on the speakers (the Test Sound button). + pub(crate) fn test_sound(&mut self) { + let device = self.state.audio.output_device.clone(); + let volume = self.state.audio.output_volume; + std::thread::spawn(move || { + let result = crate::camera::play_tone(device.as_deref(), volume); + if let Err(e) = result { + later(move |app| app.set_status(format!("Cannot play the test sound: {e}"))); + } + }); + } +} + +/// Where the logs go, for the Advanced page. +fn log_text() -> String { + match voelin_platform::logs::current() { + Some(path) => format!( + "This run logs to {} (the previous runs' next to it, the last as voelin.1.log). \ + VOELIN_LOG=voelin_core=debug,voelin_ui=debug logs more; warnings also go to the terminal.", + path.display() + ), + None => "Logs go to the terminal the app was started from (standard error); \ + RUST_LOG=voelin_core=debug,voelin_ui=debug shows more." + .into(), + } +} diff --git a/crates/voelin-ui/src/settings_pages/mod.rs b/crates/voelin-ui/src/settings_pages/mod.rs new file mode 100644 index 0000000..d97b6be --- /dev/null +++ b/crates/voelin-ui/src/settings_pages/mod.rs @@ -0,0 +1,27 @@ +//! The settings pages added with the new design: My Account, Profiles +//! (identities), the camera and stream quality of Voice & Video, Streaming, +//! Devices, Notifications, Privacy & Safety, Integrations (gateways, +//! gateway administration, encoders) and Advanced. Every control reads and +//! writes a setting (`voelin_core::settings`, `crate::settings`) and +//! applies at once; the forms are filled again when a setting changes +//! anywhere ([`App::page_setting_changed`](crate::app::App)). +//! +//! What the pages show and what the controls change is +//! `voelin_ui_vm::settings_pages::logic`; `bind.rs` puts it on the Bridge +//! and runs the side effects (the camera, the engine, the identity store). + +mod bind; + +use crate::vm::settings_pages::logic::PagesState; + +/// State of the settings pages. +#[derive(Default)] +pub(crate) struct Pages { + /// What needs no toolkit. + pub state: PagesState, + /// The camera preview of Voice & Video and Devices. + pub camera: Option, + /// Applications playing audio (the audio sources picker), while the + /// Streaming page is open. + pub audio_apps: Option, +} diff --git a/crates/voelin-ui/src/social.rs b/crates/voelin-ui/src/social.rs index 1c0f6f8..dab9893 100644 --- a/crates/voelin-ui/src/social.rs +++ b/crates/voelin-ui/src/social.rs @@ -1078,33 +1078,12 @@ impl App { } } -/// What a privacy or notification choice is as an index, and back. -pub(crate) fn allowed_index(a: voelin_core::settings::Allowed) -> i32 { - match a { - voelin_core::settings::Allowed::Everyone => 0, - voelin_core::settings::Allowed::Friends => 1, - voelin_core::settings::Allowed::Nobody => 2, - } -} - -pub(crate) fn allowed_of(index: i32) -> voelin_core::settings::Allowed { - match index { - 1 => voelin_core::settings::Allowed::Friends, - 2 => voelin_core::settings::Allowed::Nobody, - _ => voelin_core::settings::Allowed::Everyone, - } -} - #[cfg(test)] mod tests { use super::*; #[test] - fn privacy_indices() { - for i in 0..3 { - assert_eq!(allowed_index(allowed_of(i)), i); - } - assert_eq!(allowed_of(9), voelin_core::settings::Allowed::Everyone); + fn notice_names_and_setting_pages() { assert_eq!(NoticeKind::Poke.name(), "poke"); assert!(SETTING_PAGES.iter().any(|(t, _, _)| *t == "Voice & Video")); }