Files
VoelinClient/crates/voelin-ui-vm/src/settings_pages/logic.rs
T
faumarayandClaude Sonnet 5.5 e13d401b9c Merge main (ad20979) into phase4/session-seam
Main brings the merge of phase5/ui-vm: the toolkit-free crates/voelin-ui-vm
crate and the logic/bind split of crates/voelin-ui. Conflicts, and what each
resolution keeps:

- crates/voelin-ui/src/settings_pages.rs: main deleted it (it is
  settings_pages/{mod,bind}.rs and voelin-ui-vm's settings_pages/logic.rs
  now), this branch had changed its voelin_core::identity paths. Deleted; the
  paths are voelin_core::ts::identity:: in bind.rs and in logic.rs.
- crates/voelin-ui/src/identities.rs: the module comment names
  voelin_core::ts::identity::import_new (this branch) and settings_pages/
  (main).
- docs/architecture.md: the voelin-core row of this branch with the
  voelin-ui-vm and voelin-ui rows of main.

Not conflicts, but needed to compile: voelin-ui-vm named the in-tree
voelin-model by path, which this branch moved to the protocol repository
(workspace dependency), and imported voelin_core::identity::Found, which is
voelin_core::ts::identity::Found. Cargo.lock merged without a conflict and
resolves with --locked; THIRD_PARTY_NOTICES.md is up to date
(scripts/notices.sh --check).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:32:05 +03:00

1368 lines
47 KiB
Rust

//! 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::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_core::ts::identity::Found;
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<AtomicBool>,
}
/// 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<i64, Improving>,
/// 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<i64>,
/// Camera ids by the index of the cameras list.
pub cameras: Vec<String>,
/// 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<LayerSetting> {
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::<u64>().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<Vec<LayerSetting>> {
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::<Vec<_>>().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<u64> {
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<LayerItem> {
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<AudioSourceItem> {
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<SettingItem> {
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<String>,
}
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<T>(&mut self, key: &'static Key<T>, 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<T>(&mut self, key: &'static Key<T>, 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<String>) {
self.said.push(text.into());
}
fn done(self) -> Vec<String> {
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<String> {
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<String> {
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<Vec<String>> {
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<String> {
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<String> {
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<String> {
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<Vec<String>> {
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<String> {
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<String> {
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<String> {
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<String> {
let mut p = Put::new(prefs);
let number = |t: &Arc<str>| t.trim().parse::<u64>().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<Vec<String>> {
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<Vec<String>> {
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<L>(state: &AppState<L>) -> Vec<GatewayItem> {
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::<str>::from).collect(),
})
})
.collect()
}
/// The configuration keys of the gateway being administered.
pub fn config_items(extra: Option<&SessionExtra>) -> Vec<ConfigItem> {
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<PermItem> {
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::<Vec<_>>().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<EncoderItem> {
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, String>) -> 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<Vec<(String, String)>, String>) -> Vec<String> {
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<i64>,
used: &[(&str, Option<i64>)],
improving: impl Fn(i64) -> Option<(u8, u8)>,
) -> Vec<IdentityItem> {
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<String> {
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<BookmarkIdentity> {
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<FoundIdentity> {
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<Vec<LayerSetting>>| 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, &notify).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::<Vec<_>>(), ["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::<Vec<_>>(), [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::<Vec<_>>(),
[(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));
}
}