voelin-ui-vm: the server sequences both front ends ran twice are one
The GPUI shell repeated the Slint crate's connect, observe, gateway lookup, save and remove of a server, its default nickname, its FallbackSecrets and its settings opening and key registration. They now live once and both front ends call them: - voelin_ui_vm::servers::sequence: connect_voice(_to), observe, discover_gateway, gateway_found, select_server, save_bookmark, save_and_connect, delete_bookmark, bookmark_form and default_nickname, as transitions over the state, the Cx and a Backing (the store, the secrets, the identity a connection uses). The commands, the status line and what to keep go out through the Update as for every other transition; a new field, Update::discover, asks the front end to look a gateway up (the thread hop stays with each front end: Later in GPUI, later() in Slint). stream_peer is the one input a front end gives (Slint's codecs; GPUI passes none). - voelin_ui_vm::settings::open_settings and register_keys; a front end adds its own key (ui.window, studio.ui) through a function it passes, so Slint's settings page still lists what it listed. - voelin_store::FallbackSecrets (feature keyring) and Store::identity_for. - voelin-ui: the methods of servers/bind.rs, open_settings and default_secrets call them, so their call sites are unchanged; host.rs gets transition_with and the discover arm of perform. voelin-gpui: AppState's methods and the Backend call them. What cannot move is named in docs/ui.md. voelin-ui-vm now depends on tracing (the sequences log as the copies did): one line of Cargo.lock, THIRD_PARTY_NOTICES.md unchanged (scripts/notices.sh --check clean), cargo deny check clean. The sequences have ten tests over a fake front end (commands, status, store, secrets, gateways), open_settings and Store::identity_for one each; the GPUI and Slint suites pass unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
01bf128c58
commit
a77ccc0415
15 files changed
+1148
-578
No files matched your search
@@ -179,6 +179,12 @@ pub struct Update {
|
||||
/// Pictures the engine wrote again: a front end drops what it decoded
|
||||
/// of them.
|
||||
pub reloaded: Vec<PathBuf>,
|
||||
/// Servers whose gateway is to be looked up in DNS (bookmark id and
|
||||
/// address; [`crate::servers::logic::discover_wanted`] said so): the front
|
||||
/// end runs [`crate::servers::sequence::find_gateways`] on the engine's
|
||||
/// runtime and, when it finds some, calls
|
||||
/// [`crate::servers::sequence::gateway_found`] on its own thread.
|
||||
pub discover: Vec<(i64, String)>,
|
||||
/// The microphone meter: level in dBFS, and whether voice is sent.
|
||||
pub input_level: Option<(f32, bool)>,
|
||||
/// Open the password dialog.
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! and the channel tree as plain data.
|
||||
|
||||
pub mod logic;
|
||||
pub mod sequence;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
|
||||
@@ -0,0 +1,683 @@
|
||||
//! What both front ends do for a server that is more than a state change: the
|
||||
//! sequences over the store, the secrets and the engine.
|
||||
//!
|
||||
//! [`logic`](super::logic) has the transitions that touch the state alone;
|
||||
//! these also read and write the client's store and its secrets (a
|
||||
//! bookmark and its passwords), pick the identity a connection is made with
|
||||
//! and build the engine's commands, and they were written twice, once for
|
||||
//! each front end, before they were one. Each is a transition: it takes the
|
||||
//! state, the transition's [`Cx`] and the [`Backing`], changes the state and
|
||||
//! the store, and says what the front end is to do through the `Cx`
|
||||
//! (commands for the engine, the status line, what to keep, which gateways to
|
||||
//! look up), so that a front end carries it out with its own `perform` and
|
||||
//! tests it as it tests the others: in the GPUI front end the commands of a
|
||||
//! test are the ones its `perform` was handed, and a sample server's are
|
||||
//! dropped there.
|
||||
//!
|
||||
//! What stays with each front end is what needs its toolkit or its runtime:
|
||||
//! the thread hop of a gateway lookup (it runs [`find_gateways`] on the
|
||||
//! engine's runtime and calls [`gateway_found`] when something is found, as
|
||||
//! `Update::discover` asks), the clipboard, the toast, and what it adds to a
|
||||
//! connect (the stream codecs the Slint front end can decode).
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_core::stream::PeerConfig;
|
||||
use voelin_core::{Command, IdentityBlob, ObserveState};
|
||||
use voelin_store::{Bookmark, QueryTransport, Secrets, Store};
|
||||
|
||||
use super::logic::{self, CREATED_IDENTITY, GatewayFound, ObservePlan};
|
||||
use crate::bridge::BookmarkForm;
|
||||
use crate::host::Cx;
|
||||
use crate::state::{AppState, Lines};
|
||||
|
||||
/// What the sequences read and write besides the state: the client's store, its
|
||||
/// secrets and the identity a connection is made with.
|
||||
pub struct Backing<'a> {
|
||||
/// The bookmarks, the identities and the chats' read marks.
|
||||
pub store: &'a Store,
|
||||
/// The servers' passwords.
|
||||
pub secrets: &'a dyn Secrets,
|
||||
/// The identity a connection to a server whose bookmark names `named` is
|
||||
/// made with, as the engine takes it ([`Store::identity_for`]: the named
|
||||
/// one if the store has it, else the default one, else the front end's).
|
||||
pub identity: &'a dyn Fn(Option<i64>) -> IdentityBlob,
|
||||
}
|
||||
|
||||
/// The nickname a new server gets: the default identity's (one imported from
|
||||
/// TeamSpeak keeps the nickname used there), else the system user's.
|
||||
pub fn default_nickname(store: &Store) -> String {
|
||||
store
|
||||
.default_identity()
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|identity| identity.name)
|
||||
.filter(|name| {
|
||||
![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
|
||||
.contains(&name.as_str())
|
||||
})
|
||||
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
|
||||
// Servers refuse an empty nickname (Android has no user name).
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.unwrap_or_else(|| "Voelin user".to_owned())
|
||||
}
|
||||
|
||||
/// The server dialog's form for server `id` (-1: a new one), with its
|
||||
/// password from the secrets and its session's state.
|
||||
pub fn bookmark_form<L>(
|
||||
state: &AppState<L>,
|
||||
store: &Store,
|
||||
secrets: &dyn Secrets,
|
||||
id: i64,
|
||||
) -> BookmarkForm {
|
||||
let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else {
|
||||
return BookmarkForm {
|
||||
id: -1,
|
||||
nickname: default_nickname(store).into(),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
let password = secrets.get(&b.server_password_key()).ok().flatten();
|
||||
let session = state.sessions.get(&b.id).map(|view| &view.state);
|
||||
super::form(b, session, password.as_deref().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Show a server, and observe it.
|
||||
pub fn select_server<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
id: i64,
|
||||
) {
|
||||
logic::select_server(state, cx, id);
|
||||
observe(state, cx, backing, id);
|
||||
}
|
||||
|
||||
/// Connect the server on screen with voice, into its default channel.
|
||||
pub fn connect_voice<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) -> bool {
|
||||
let channel = state
|
||||
.current
|
||||
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
|
||||
.and_then(|b| b.default_channel.clone());
|
||||
connect_voice_to(state, cx, backing, channel, None, None, stream_peer)
|
||||
}
|
||||
|
||||
/// Connect the server on screen with voice, into `channel` (a path, or
|
||||
/// `/<id>`, with its password) if given, with a privilege key if given;
|
||||
/// whether it was asked for. `stream_peer`: what the front end can decode
|
||||
/// of a stream, if it says (the engine's default otherwise).
|
||||
pub fn connect_voice_to<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
channel: Option<String>,
|
||||
channel_password: Option<String>,
|
||||
token: Option<String>,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) -> bool {
|
||||
let Some(b) = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id)).cloned()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if cx.host.demo_ui() {
|
||||
return false;
|
||||
}
|
||||
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
cx.status(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
options.identity = Some((backing.identity)(b.identity));
|
||||
options.server_password = backing.secrets.get(&b.server_password_key()).ok().flatten();
|
||||
if let Some(peer) = stream_peer {
|
||||
options.stream_peer = peer;
|
||||
}
|
||||
cx.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
|
||||
cx.status(format!("Connecting to {}…", b.address));
|
||||
// The admin may have published the gateway since it was added.
|
||||
discover_gateway(state, cx, b.id);
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask for the gateway of a server to be looked up ([`voelin_core::discover`]),
|
||||
/// once a run ([`logic::discover_wanted`]): every one the server publishes is
|
||||
/// kept, best first, and tried in turn; they take the place of a stored one
|
||||
/// that is no longer published (a gateway that moved, or one typed into an
|
||||
/// older version, which showed the field). Nothing found keeps what is
|
||||
/// stored. The front end looks it up (`Update::discover`).
|
||||
pub fn discover_gateway<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64) {
|
||||
if let Some(address) = logic::discover_wanted(state, cx, id) {
|
||||
cx.update.discover.push((id, address));
|
||||
}
|
||||
}
|
||||
|
||||
/// What looking up the gateways of a server found.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Found {
|
||||
/// Every URL the server publishes, best first.
|
||||
pub urls: Vec<String>,
|
||||
/// How long the lookup took.
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
|
||||
/// Look the gateways of the server at `address` up in DNS; none when the
|
||||
/// server publishes none (logged). Runs on the engine's runtime; what it
|
||||
/// finds goes to [`gateway_found`] on the front end's own thread.
|
||||
pub async fn find_gateways(address: &str) -> Option<Found> {
|
||||
let started = Instant::now();
|
||||
let urls = voelin_core::discover::gateways(address).await;
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
if urls.is_empty() {
|
||||
info!(server = %address, elapsed_ms, "no gateway published");
|
||||
None
|
||||
} else {
|
||||
Some(Found { urls, elapsed_ms })
|
||||
}
|
||||
}
|
||||
|
||||
/// Gateways were found for the server at `address` (best first); they are kept
|
||||
/// unless the server changed meanwhile ([`logic::gateway_found`]), and the
|
||||
/// server is observed through them if it is the one shown. Users never hear of
|
||||
/// them (logged only).
|
||||
pub fn gateway_found<L>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
id: i64,
|
||||
address: &str,
|
||||
urls: Vec<String>,
|
||||
elapsed_ms: u64,
|
||||
) {
|
||||
match logic::gateway_found(state, cx, id, address, urls) {
|
||||
GatewayFound::Same => debug!(server = %address, elapsed_ms, "gateway found, as kept"),
|
||||
GatewayFound::Kept { observe: now } => {
|
||||
info!(server = %address, elapsed_ms, kept = true, "gateway found");
|
||||
if now {
|
||||
observe(state, cx, backing, id);
|
||||
}
|
||||
}
|
||||
GatewayFound::Changed { stop, observe: now, urls } => {
|
||||
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
|
||||
if stop {
|
||||
cx.send(Command::StopObserving { session: id as u64 });
|
||||
}
|
||||
if now {
|
||||
observe(state, cx, backing, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe the server invisibly ([`logic::observe_plan`]): through its gateway,
|
||||
/// else its own query login. Without either the gateway is looked up first,
|
||||
/// and observing starts when it is found ([`gateway_found`]).
|
||||
pub fn observe<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, backing: &Backing<'_>, id: i64) {
|
||||
let Some(b) = state.bookmarks.iter().find(|b| b.id == id).cloned() else { return };
|
||||
let session = b.id as u64;
|
||||
let gateway = |urls| Command::ObserveGateway {
|
||||
session,
|
||||
urls,
|
||||
identity: Box::new((backing.identity)(b.identity)),
|
||||
};
|
||||
match logic::observe_plan(state, cx, id) {
|
||||
ObservePlan::Nothing => return,
|
||||
ObservePlan::Retry(urls) => {
|
||||
debug!(server = %b.address, "still connecting to the gateway: try now");
|
||||
cx.send(gateway(urls));
|
||||
return;
|
||||
}
|
||||
ObservePlan::Gateway(urls) => {
|
||||
info!(server = %b.address, ?urls, "observing through the gateway");
|
||||
cx.send(gateway(urls));
|
||||
// Still the one the server publishes?
|
||||
discover_gateway(state, cx, b.id);
|
||||
}
|
||||
ObservePlan::Query(q) => {
|
||||
let secret = backing.secrets.get(&b.query_password_key()).ok().flatten();
|
||||
let transport = match q.transport {
|
||||
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
|
||||
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
|
||||
QueryTransport::Http => voelin_core::QueryTransport::Http,
|
||||
};
|
||||
let connect = voelin_core::QueryLogin {
|
||||
transport,
|
||||
address: format!("{}:{}", q.host, q.port),
|
||||
user: q.user.clone(),
|
||||
secret,
|
||||
server_port: q.server_port,
|
||||
server_id: None,
|
||||
allowlisted: false,
|
||||
};
|
||||
cx.send(Command::ObserveQuery { session, connect: Box::new(connect) });
|
||||
}
|
||||
ObservePlan::Discover => {
|
||||
discover_gateway(state, cx, b.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
cx.status("Observing invisibly…");
|
||||
}
|
||||
|
||||
/// Save the server the form describes in the store and the secrets, and show
|
||||
/// it: its id, none when it could not be saved (the status line says why). A
|
||||
/// new address stops what was observed at the old one.
|
||||
pub fn save_bookmark<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
form: &BookmarkForm,
|
||||
) -> Option<i64> {
|
||||
let old = state.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned();
|
||||
let mut bookmark =
|
||||
logic::bookmark_from_form(old.as_ref(), form, || default_nickname(backing.store));
|
||||
let result = if bookmark.id < 0 {
|
||||
backing.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
|
||||
} else {
|
||||
backing.store.update_bookmark(&bookmark)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
cx.status(format!("Could not save: {e}"));
|
||||
return None;
|
||||
}
|
||||
let key = bookmark.server_password_key();
|
||||
let result = if form.server_password.is_empty() {
|
||||
backing.secrets.delete(&key)
|
||||
} else {
|
||||
backing.secrets.set(&key, &form.server_password)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
warn!(%e, "could not store secret");
|
||||
}
|
||||
// Another server: what was observed is the old one's, and its gateway is
|
||||
// looked up anew.
|
||||
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
|
||||
if old.query.is_some() {
|
||||
let _ = backing.secrets.delete(&old.query_password_key());
|
||||
}
|
||||
state.gateways_looked_up.remove(&bookmark.id);
|
||||
cx.send(Command::StopObserving { session: bookmark.id as u64 });
|
||||
if let Some(view) = state.sessions.get_mut(&bookmark.id) {
|
||||
view.state.observe = ObserveState::Off;
|
||||
}
|
||||
}
|
||||
state.bookmarks = backing.store.bookmarks().unwrap_or_default();
|
||||
select_server(state, cx, backing, bookmark.id);
|
||||
Some(bookmark.id)
|
||||
}
|
||||
|
||||
/// The server dialog's Connect: save the server, then connect it with voice,
|
||||
/// into the channel of the link that filled the form if one did
|
||||
/// ([`super::connect_to`]). Only once saved: connecting what is shown after a
|
||||
/// failed save would connect the server shown before. Whether it was saved.
|
||||
pub fn save_and_connect<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
form: &BookmarkForm,
|
||||
stream_peer: Option<PeerConfig>,
|
||||
) -> bool {
|
||||
let saved = save_bookmark(state, cx, backing, form);
|
||||
let to = super::connect_to(
|
||||
form,
|
||||
saved.and_then(|id| state.bookmarks.iter().find(|b: &&Bookmark| b.id == id)),
|
||||
);
|
||||
let Some(to) = to else { return false };
|
||||
connect_voice_to(state, cx, backing, to.channel, to.channel_password, to.token, stream_peer);
|
||||
true
|
||||
}
|
||||
|
||||
/// Remove a server: its session is closed, its passwords and the bookmark go,
|
||||
/// and the first server is shown.
|
||||
pub fn delete_bookmark<L: Lines>(
|
||||
state: &mut AppState<L>,
|
||||
cx: &mut Cx<'_>,
|
||||
backing: &Backing<'_>,
|
||||
id: i64,
|
||||
) {
|
||||
cx.send(Command::CloseSession { session: id as u64 });
|
||||
if let Some(b) = state.bookmarks.iter().find(|b| b.id == id) {
|
||||
let _ = backing.secrets.delete(&b.server_password_key());
|
||||
let _ = backing.secrets.delete(&b.query_password_key());
|
||||
}
|
||||
let _ = backing.store.delete_bookmark(id);
|
||||
let bookmarks = backing.store.bookmarks().unwrap_or_default();
|
||||
logic::forget_server(state, cx, id, bookmarks);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_store::{MemorySecrets, QueryConfig};
|
||||
|
||||
use super::*;
|
||||
use crate::host::Update;
|
||||
use crate::host::testing::{Fake, State};
|
||||
|
||||
/// A store, secrets and a front end of the tests' own.
|
||||
struct Rig {
|
||||
store: Store,
|
||||
secrets: MemorySecrets,
|
||||
host: Fake,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
store: Store::open_in_memory().unwrap(),
|
||||
secrets: MemorySecrets::default(),
|
||||
host: Fake::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A state with these servers saved, the first on screen.
|
||||
fn state(&self, servers: &[(&str, &str)]) -> State {
|
||||
for (name, address) in servers {
|
||||
let bookmark = Bookmark {
|
||||
name: (*name).into(),
|
||||
address: (*address).into(),
|
||||
nickname: "Nova".into(),
|
||||
..Default::default()
|
||||
};
|
||||
self.store.add_bookmark(&bookmark).unwrap();
|
||||
}
|
||||
let bookmarks = self.store.bookmarks().unwrap();
|
||||
let mut state = State::new(
|
||||
bookmarks.clone(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
);
|
||||
state.current = bookmarks.first().map(|b| b.id);
|
||||
state
|
||||
}
|
||||
|
||||
/// Run a sequence, and what it asks of the front end.
|
||||
fn run<R>(
|
||||
&self,
|
||||
state: &mut State,
|
||||
f: impl FnOnce(&mut State, &mut Cx<'_>, &Backing<'_>) -> R,
|
||||
) -> (R, Update) {
|
||||
let identity = |named: Option<i64>| {
|
||||
IdentityBlob::teamspeak(format!("identity-{}", named.unwrap_or(-1)), 8, "{}")
|
||||
};
|
||||
let backing =
|
||||
Backing { store: &self.store, secrets: &self.secrets, identity: &identity };
|
||||
let mut cx = Cx::new(&self.host);
|
||||
let result = f(state, &mut cx, &backing);
|
||||
(result, cx.update)
|
||||
}
|
||||
}
|
||||
|
||||
fn form(address: &str) -> BookmarkForm {
|
||||
BookmarkForm { id: -1, address: address.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_with_no_identity_to_name_it_gets_the_users_name_or_a_fallback() {
|
||||
let nickname = default_nickname(&Store::open_in_memory().unwrap());
|
||||
assert!(!nickname.trim().is_empty(), "servers refuse an empty nickname");
|
||||
assert!(nickname != CREATED_IDENTITY && nickname != "imported");
|
||||
}
|
||||
|
||||
/// A connect names the server on screen, its nickname and channel, the
|
||||
/// identity it is made with and the password the secrets keep; it says so
|
||||
/// in the status line and asks for the gateway to be looked up, once.
|
||||
#[test]
|
||||
fn a_connect_asks_the_engine_with_what_the_store_and_the_secrets_know() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let id = state.current.unwrap();
|
||||
rig.secrets.set(&state.bookmarks[0].server_password_key(), "hunter2").unwrap();
|
||||
|
||||
let (asked, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
connect_voice_to(state, cx, backing, Some("Lobby".into()), None, None, None)
|
||||
});
|
||||
assert!(asked);
|
||||
let [Command::ConnectVoice { session, options }] = &update.commands[..] else {
|
||||
panic!("{:?}", update.commands.len())
|
||||
};
|
||||
assert_eq!(*session, id as u64);
|
||||
assert_eq!((options.address.as_str(), options.nickname.as_str()), ("ts.example", "Nova"));
|
||||
assert_eq!(options.channel.as_deref(), Some("Lobby"));
|
||||
assert_eq!(options.server_password.as_deref(), Some("hunter2"));
|
||||
assert_eq!(options.identity.as_ref().map(|i| i.uid.as_str()), Some("identity--1"));
|
||||
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
|
||||
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
|
||||
|
||||
// The second connect of a run does not look it up again.
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert_eq!(update.commands.len(), 1);
|
||||
assert!(update.discover.is_empty());
|
||||
}
|
||||
|
||||
/// The sample servers connect nothing, and a client version that is none
|
||||
/// is refused in words.
|
||||
#[test]
|
||||
fn a_connect_that_cannot_be_made_asks_nothing() {
|
||||
let mut rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
rig.host.demo = true;
|
||||
let (asked, update) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert!(!asked && update.commands.is_empty() && update.status.is_none());
|
||||
|
||||
rig.host.demo = false;
|
||||
state.bookmarks[0].client_version = Some("nonsense@0".into());
|
||||
let (asked, update) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert!(!asked && update.commands.is_empty());
|
||||
assert!(update.status.is_some_and(|s| s.starts_with("Invalid client compatibility")));
|
||||
|
||||
state.current = None;
|
||||
let (asked, _) =
|
||||
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
|
||||
assert!(!asked, "no server on screen");
|
||||
}
|
||||
|
||||
/// A new server is in the store with its password in the secrets, is the
|
||||
/// one on screen, and has its gateway looked up (it has none to observe
|
||||
/// through yet).
|
||||
#[test]
|
||||
fn saving_a_new_server_keeps_it_and_its_password_and_shows_it() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[]);
|
||||
let form = BookmarkForm { server_password: "hunter2".into(), ..form(" ts.example ") };
|
||||
let (saved, update) =
|
||||
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &form));
|
||||
let id = saved.expect("saved");
|
||||
let stored = rig.store.bookmarks().unwrap();
|
||||
assert_eq!((stored.len(), stored[0].id), (1, id));
|
||||
assert_eq!(
|
||||
(stored[0].address.as_str(), stored[0].name.as_str()),
|
||||
("ts.example", "ts.example")
|
||||
);
|
||||
assert!(!stored[0].nickname.is_empty(), "the default nickname");
|
||||
assert_eq!(
|
||||
rig.secrets.get(&stored[0].server_password_key()).unwrap().as_deref(),
|
||||
Some("hunter2")
|
||||
);
|
||||
assert_eq!(state.current, Some(id));
|
||||
assert_eq!(state.bookmarks, stored);
|
||||
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
|
||||
assert!(update.commands.is_empty());
|
||||
|
||||
// An empty password in the form removes it.
|
||||
let edit = BookmarkForm { id: id as i32, ..form_of(&stored[0], "") };
|
||||
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &edit));
|
||||
assert_eq!(rig.secrets.get(&stored[0].server_password_key()).unwrap(), None);
|
||||
}
|
||||
|
||||
fn form_of(bookmark: &Bookmark, password: &str) -> BookmarkForm {
|
||||
crate::servers::form(bookmark, None, password)
|
||||
}
|
||||
|
||||
/// Another address is another server: what was observed at the old one
|
||||
/// stops, its query password goes, and the gateway is looked up anew.
|
||||
#[test]
|
||||
fn a_new_address_stops_what_was_observed_at_the_old_one() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let old = state.bookmarks[0].clone();
|
||||
let id = old.id;
|
||||
state.gateways_looked_up.insert(id);
|
||||
rig.secrets.set(&old.query_password_key(), "query-secret").unwrap();
|
||||
state.bookmarks[0].query = Some(QueryConfig::default());
|
||||
rig.store.update_bookmark(&state.bookmarks[0]).unwrap();
|
||||
state.sessions.entry(id).or_default().state.observe = ObserveState::Observing;
|
||||
|
||||
let moved = BookmarkForm { address: "ts.elsewhere".into(), ..form_of(&old, "") };
|
||||
let (saved, update) =
|
||||
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &moved));
|
||||
assert_eq!(saved, Some(id));
|
||||
assert!(
|
||||
matches!(&update.commands[..], [Command::StopObserving { session }] if *session == id as u64)
|
||||
);
|
||||
assert_eq!(rig.secrets.get(&old.query_password_key()).unwrap(), None);
|
||||
assert_eq!(state.sessions[&id].state.observe, ObserveState::Off);
|
||||
assert_eq!(update.discover, [(id, "ts.elsewhere".to_owned())]);
|
||||
assert_eq!(state.bookmarks[0].address, "ts.elsewhere");
|
||||
}
|
||||
|
||||
/// The form's Connect connects only what was saved.
|
||||
#[test]
|
||||
fn save_and_connect_connects_the_server_it_saved() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[]);
|
||||
let linked =
|
||||
BookmarkForm { channel: "Games".into(), token: "key".into(), ..form("ts.example") };
|
||||
let (done, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
save_and_connect(state, cx, backing, &linked, None)
|
||||
});
|
||||
assert!(done);
|
||||
let [Command::ConnectVoice { options, .. }] = &update.commands[..] else {
|
||||
panic!("{}", update.commands.len())
|
||||
};
|
||||
assert_eq!(
|
||||
(options.channel.as_deref(), options.token.as_deref()),
|
||||
(Some("Games"), Some("key"))
|
||||
);
|
||||
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
|
||||
}
|
||||
|
||||
/// A server is removed with its session, its passwords and its row, and
|
||||
/// the first of the others is shown.
|
||||
#[test]
|
||||
fn deleting_a_server_closes_its_session_and_forgets_its_secrets() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]);
|
||||
let [first, second] = [state.bookmarks[0].clone(), state.bookmarks[1].clone()];
|
||||
rig.secrets.set(&first.server_password_key(), "hunter2").unwrap();
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| delete_bookmark(state, cx, backing, first.id));
|
||||
assert!(
|
||||
matches!(&update.commands[..], [Command::CloseSession { session }] if *session == first.id as u64)
|
||||
);
|
||||
assert_eq!(rig.secrets.get(&first.server_password_key()).unwrap(), None);
|
||||
assert_eq!(
|
||||
rig.store.bookmarks().unwrap().iter().map(|b| b.id).collect::<Vec<_>>(),
|
||||
[second.id]
|
||||
);
|
||||
assert_eq!((state.current, state.bookmarks.len()), (Some(second.id), 1));
|
||||
}
|
||||
|
||||
/// Showing a server observes it: through its gateways if it has some (and
|
||||
/// looks the gateway up again, in case it moved), else through its query
|
||||
/// login with the password the secrets keep, else it looks the gateway up
|
||||
/// and observes when it is found.
|
||||
#[test]
|
||||
fn showing_a_server_observes_it_the_way_it_can_be() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let id = state.current.unwrap();
|
||||
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
|
||||
assert!(
|
||||
update.commands.is_empty() && update.status.is_none(),
|
||||
"nothing to observe through yet"
|
||||
);
|
||||
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
|
||||
|
||||
state.bookmarks[0].query = Some(QueryConfig {
|
||||
host: "query.example".into(),
|
||||
port: 10022,
|
||||
user: "serveradmin".into(),
|
||||
..Default::default()
|
||||
});
|
||||
rig.secrets.set(&state.bookmarks[0].query_password_key(), "q").unwrap();
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
|
||||
let [Command::ObserveQuery { session, connect }] = &update.commands[..] else {
|
||||
panic!("{}", update.commands.len())
|
||||
};
|
||||
assert_eq!(*session, id as u64);
|
||||
assert_eq!(connect.address, "query.example:10022");
|
||||
assert_eq!((connect.user.as_str(), connect.secret.as_deref()), ("serveradmin", Some("q")));
|
||||
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
|
||||
|
||||
state.bookmarks[0].set_gateways(vec!["ws://gw.example/".into()]);
|
||||
let (_, update) =
|
||||
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
|
||||
let [Command::ObserveGateway { urls, identity, .. }] = &update.commands[..] else {
|
||||
panic!("{}", update.commands.len())
|
||||
};
|
||||
assert_eq!(urls, &["ws://gw.example/".to_owned()]);
|
||||
assert_eq!(identity.uid, format!("identity-{}", -1));
|
||||
assert!(update.discover.is_empty(), "looked up once");
|
||||
}
|
||||
|
||||
/// What a lookup found is kept for the next start, and the server on
|
||||
/// screen is observed through it.
|
||||
#[test]
|
||||
fn a_found_gateway_is_kept_and_the_server_on_screen_is_observed_through_it() {
|
||||
let rig = Rig::new();
|
||||
let mut state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let id = state.current.unwrap();
|
||||
state.gateways_looked_up.insert(id);
|
||||
let urls = vec!["ws://gw.example/".to_owned()];
|
||||
let (_, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
gateway_found(state, cx, backing, id, "ts.example", urls.clone(), 12)
|
||||
});
|
||||
assert_eq!(state.bookmarks[0].gateways(), urls);
|
||||
assert!(
|
||||
update
|
||||
.persist
|
||||
.iter()
|
||||
.any(|p| matches!(p, crate::host::Persist::Bookmark { id: i, .. } if *i == id))
|
||||
);
|
||||
assert!(matches!(&update.commands[..], [Command::ObserveGateway { .. }]));
|
||||
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
|
||||
|
||||
// For a server that changed meanwhile, nothing.
|
||||
let (_, update) = rig.run(&mut state, |state, cx, backing| {
|
||||
gateway_found(state, cx, backing, id, "another.example", urls.clone(), 12)
|
||||
});
|
||||
assert!(update.commands.is_empty() && update.persist.is_empty());
|
||||
}
|
||||
|
||||
/// The dialog's form: a new server gets the default nickname, a saved one
|
||||
/// its own with the password from the secrets.
|
||||
#[test]
|
||||
fn the_form_of_a_server_has_its_password_and_a_new_one_a_nickname() {
|
||||
let rig = Rig::new();
|
||||
let state = rig.state(&[("Nightfall", "ts.example")]);
|
||||
let saved = &state.bookmarks[0];
|
||||
rig.secrets.set(&saved.server_password_key(), "hunter2").unwrap();
|
||||
let form = bookmark_form(&state, &rig.store, &rig.secrets, saved.id);
|
||||
assert_eq!(
|
||||
(form.address.as_ref(), form.server_password.as_ref()),
|
||||
("ts.example", "hunter2")
|
||||
);
|
||||
assert_eq!(form.nickname.as_ref(), "Nova");
|
||||
let new = bookmark_form(&state, &rig.store, &rig.secrets, -1);
|
||||
assert_eq!((new.id, new.nickname.as_ref()), (-1, default_nickname(&rig.store).as_str()));
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@
|
||||
//! the settings page.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::warn;
|
||||
use voelin_audio::process::NoiseLevel;
|
||||
use voelin_core::settings::{Key, Kind};
|
||||
use voelin_core::settings::{Key, Kind, Settings};
|
||||
use voelin_core::{AudioSettings, TransmitMode};
|
||||
|
||||
use crate::bridge::AudioForm;
|
||||
@@ -320,6 +322,53 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
|
||||
]
|
||||
}
|
||||
|
||||
/// The settings service on the client database in `dir` (`client.db`), the way
|
||||
/// both front ends open it: the keys they read registered ([`UI`],
|
||||
/// [`CLIENT_PLAYBACK`], [`appearance_keys`] and [`page_keys`]; `register` adds
|
||||
/// the keys of one front end only, before anything is read), then a config file
|
||||
/// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists), the
|
||||
/// `VOELIN_SETTING_*` variables and `overrides` (`--set key=value`) below the
|
||||
/// stored values. Without the database the settings live in memory. What
|
||||
/// cannot be applied is logged, not fatal.
|
||||
pub fn open_settings(
|
||||
dir: &Path,
|
||||
overrides: &[String],
|
||||
register: impl FnOnce(&Settings),
|
||||
) -> Settings {
|
||||
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
|
||||
warn!(%e, "settings are not stored this time");
|
||||
Settings::in_memory()
|
||||
});
|
||||
register_keys(&prefs);
|
||||
register(&prefs);
|
||||
let config = std::env::var_os("VOELIN_CONFIG")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
|
||||
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
|
||||
Some(Ok(errors)) => errors,
|
||||
Some(Err(e)) => vec![e],
|
||||
None => Vec::new(),
|
||||
};
|
||||
errors.extend(prefs.apply_env(std::env::vars()));
|
||||
errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str)));
|
||||
for e in errors {
|
||||
warn!(%e, "setting ignored");
|
||||
}
|
||||
prefs
|
||||
}
|
||||
|
||||
/// Make the keys both front ends read known to `prefs`.
|
||||
pub fn register_keys(prefs: &Settings) {
|
||||
prefs.register(&UI);
|
||||
prefs.register(&CLIENT_PLAYBACK);
|
||||
for key in appearance_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
for key in page_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog
|
||||
/// offers, in the order of its lists (`dialogs.slint`); any other value can
|
||||
/// be typed in.
|
||||
@@ -662,6 +711,45 @@ mod tests {
|
||||
assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop);
|
||||
}
|
||||
|
||||
/// The settings both front ends open: the shared keys, the config file's
|
||||
/// values, then `--set` over it, a front end's own key only when it
|
||||
/// registers it, and a database in the directory given.
|
||||
#[test]
|
||||
fn the_settings_open_with_the_shared_keys_a_config_file_and_overrides() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("voelin-ui-vm-settings-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("config.toml"),
|
||||
"\"ui.theme\" = \"light\"\n\"ui.members_width\" = 300\n",
|
||||
)
|
||||
.unwrap();
|
||||
let overrides = ["ui.font_scale=1.5".to_owned(), "ui.members_width=320".to_owned()];
|
||||
let prefs = open_settings(&dir, &overrides, |prefs| prefs.register(&UI_WINDOW));
|
||||
assert_eq!(prefs.get(&UI_THEME), ThemeChoice::Light, "from the config file");
|
||||
assert_eq!(prefs.get(&UI_FONT_SCALE), 1.5, "from --set");
|
||||
assert_eq!(prefs.get(&UI_MEMBERS_WIDTH), 320, "--set over the file");
|
||||
assert_eq!(prefs.get(&UI_WINDOW), None);
|
||||
let names = |prefs: &Settings| prefs.keys().iter().map(|k| k.name()).collect::<Vec<_>>();
|
||||
for shared in
|
||||
["ui", "client_playback", "ui.theme", "notify.mentions", "ui.image_preview_kb"]
|
||||
{
|
||||
assert!(names(&prefs).contains(&shared), "{shared}");
|
||||
}
|
||||
assert!(names(&prefs).contains(&"ui.window"), "the front end's own key");
|
||||
prefs.set(&UI_FONT_SCALE, 1.25).unwrap();
|
||||
prefs.flush().unwrap();
|
||||
drop(prefs);
|
||||
assert!(dir.join("client.db").is_file(), "the database is in the directory given");
|
||||
|
||||
let plain = open_settings(&dir, &[], |_| {});
|
||||
assert!(!names(&plain).contains(&"ui.window"), "not registered by this front end");
|
||||
assert_eq!(plain.get(&UI_FONT_SCALE), 1.25, "what was stored wins over nothing");
|
||||
drop(plain);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_compact_key() {
|
||||
let settings = voelin_core::settings::Settings::in_memory();
|
||||
|
||||
Reference in new issue
Block a user