diff --git a/Cargo.lock b/Cargo.lock index 64b60f5..7e48078 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12587,6 +12587,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "tsclientlib", "voelin-core", "voelin-platform", "voelin-store", diff --git a/crates/voelin-gpui/Cargo.toml b/crates/voelin-gpui/Cargo.toml index 091ea3e..f7e8518 100644 --- a/crates/voelin-gpui/Cargo.toml +++ b/crates/voelin-gpui/Cargo.toml @@ -25,14 +25,17 @@ gpui-kit = { workspace = true } tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +# The TeamSpeak identity a connection is made with (the store hands it out). +tsclientlib = { path = "../proto/tsclientlib" } # The engine, with the desktop's capture and codecs: ashpd on async-io (the # commit that moved voelin-media and voelin-platform to it) lets this binary # hold both the portals and gpui-kit. voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] } # The app's name and id, the hotkeys and portals of the slices to come. voelin-platform = { path = "../voelin-platform" } -# The Host trait's types (what the store knows of a chat's read marker). -voelin-store = { path = "../voelin-store" } +# The client's database (bookmarks, identities, settings, chat reads) and the +# secrets: the OS keyring, as the Slint front end keeps them. +voelin-store = { path = "../voelin-store", features = ["keyring"] } # The view models and the state, shared with the Slint front end. voelin-ui-vm = { path = "../voelin-ui-vm" } diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index 571634b..af90360 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -1,42 +1,67 @@ //! The root state of the window, `Entity`: everything the client //! knows (the toolkit-free [`voelin_ui_vm`] state and the friends and pokes -//! beside it) and the three loops that keep it current on GPUI's thread: +//! beside it), the store and the settings it was read from, and the three +//! loops that keep it current on GPUI's thread: //! //! - the **engine's events**: a foreground task awaits the receiver of //! [`crate::engine::HostedEngine`] (a tokio channel needs no reactor, so -//! GPUI's executor can poll it), hands every event to -//! [`events::handle`] and tells the entity to redraw (`cx.notify()`), the -//! pattern of spike 3's hotkey task; +//! GPUI's executor can poll it), takes what is queued (up to [`BATCH`] +//! events) in one go, hands every event to [`events::handle`], tells the +//! entity to redraw once (`cx.notify()`) and then yields to GPUI's +//! executor, so that a burst (a server's first sync) neither starves the +//! window nor draws it once per event; //! - the **tick**, once a second, a loop of `background_executor().timer` -//! (the Slint front end's `slint::Timer` calling `App::tick`); +//! (the Slint front end's `slint::Timer` calling `App::tick`): it keeps +//! what is due (the window's place) and notifies nobody, since nothing the +//! shell shows moves with the clock; //! - **later**: other threads (a hotkey, a camera, a decoder) cannot touch the //! entity, and GPUI's `AsyncApp` is not `Send`, so they hold a [`Later`], a //! channel of jobs a third foreground task runs on GPUI's thread, as //! `later(|app| ...)` does in the Slint front end. //! -//! What a transition asks for besides the state (`Update`: which parts to -//! draw again, what to keep, the streams' capture and decoder) belongs to -//! the slices that have those parts; today only the engine commands go out -//! and the warnings are logged. +//! The root notifies on every batch of events and on every move of the user's; +//! it is the views (`crate::shell`) that decide whether what they show changed +//! and draw again only then. What a transition asks for besides the state +//! (`Update`) is carried out as far as this front end has the parts: the +//! engine's commands go out, the status line is set, what is to be kept goes +//! to the store, a setting the theme follows is applied and the warnings are +//! logged; the redraw flags, the notices, the pictures to decode and the +//! streams' capture and decoder are for the slices that have those parts. +use std::task::Poll; use std::time::{Duration, Instant}; -use gpui_kit::Context; +use gpui_kit::{ClipboardItem, Context}; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; -use voelin_core::{AudioSettings, Command, Engine, Event, VoiceState}; -use voelin_store::{ChatRead, ChatTarget as StoredTarget}; -use voelin_ui_vm::bridge::ChatLine; +use tracing::{debug, info, warn}; +use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings}; +use voelin_core::{Command, Engine, Event, ObserveState, VoiceState}; +use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, QueryTransport, Store}; +use voelin_ui_vm::bridge::{BookmarkForm, ChatLine}; use voelin_ui_vm::events; -use voelin_ui_vm::host::{Host, Update}; -use voelin_ui_vm::settings::UiSettings; +use voelin_ui_vm::host::{Cx, Host, Persist, Update}; +use voelin_ui_vm::image::ImageRef; +use voelin_ui_vm::servers::logic::{self, GatewayFound, ObservePlan}; +use voelin_ui_vm::settings::{ + CLIENT_PLAYBACK, ThemeChoice, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, UI_WINDOW, + WindowState, +}; use voelin_ui_vm::social::logic::Social; +use crate::backend::Backend; +use crate::dev::Switches; use crate::meter::Counters; +use crate::theme::{Choice, VoelinTheme}; /// The toolkit-free state of the client, with the chat lines of a tab as plain /// rows (what a front end that draws again from the list needs). pub type VmState = voelin_ui_vm::state::AppState>; +/// How many engine events one update of the entity takes at most: a burst +/// is handled in steps of this size, with a yield to GPUI's executor between +/// them. +pub const BATCH: usize = 64; + /// A job for GPUI's thread, from any thread. type Job = Box) + Send>; @@ -60,17 +85,21 @@ impl Later { } } -/// What the transitions of the state ask of this front end while they run. -/// There is no store yet (the shell slice opens it): nothing was read, and -/// nothing is kept. -#[derive(Debug, Default)] -struct ShellHost; +/// What the transitions of the state ask of this front end while they run: +/// the store's read marks and the settings they depend on. +struct ShellHost<'a> { + demo_ui: bool, + store: &'a Store, + prefs: &'a Settings, +} -impl Host for ShellHost { +impl Host for ShellHost<'_> { fn demo_ui(&self) -> bool { - false + self.demo_ui } + // No page shows a chat yet, nothing is watched and the Stream Studio does + // not exist: the slices that have them answer from their own state. fn chat_shown(&self) -> bool { false } @@ -88,31 +117,81 @@ impl Host for ShellHost { } fn preview_limit(&self) -> u64 { - 0 + u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024 } fn fetch_images(&self) -> bool { - false + self.prefs.get(&CACHE_FETCH_IMAGES) } fn dm_shown(&self, _session: i64, _uid: &str) -> bool { false } - fn chat_reads(&self, _server_uid: &str) -> Result, String> { - Ok(Vec::new()) + fn chat_reads(&self, server_uid: &str) -> Result, String> { + self.store.chat_reads(server_uid).map_err(|e| e.to_string()) } fn set_chat_read( &self, - _server_uid: &str, - _target: &StoredTarget, - _read: &ChatRead, + server_uid: &str, + target: &StoredTarget, + read: &ChatRead, ) -> Result<(), String> { - Ok(()) + self.store.set_chat_read(server_uid, target, read).map_err(|e| e.to_string()) } } +/// What [`AppState::new`] starts from. +pub struct Setup { + /// The engine commands go to; none in the tests that need none. + pub engine: Option, + /// The engine's events (`tx` stands in for it in tests). + pub events: UnboundedReceiver, + /// What the meter counts. + pub counters: Counters, + /// The store, the settings and the secrets. + pub backend: Backend, + /// The development switches. + pub switches: Switches, +} + +/// The theme mode and the text size factor: a development switch first, else +/// the settings' (`ui.theme`, `ui.font_scale`). +pub fn appearance(prefs: &Settings, switches: &Switches) -> (Choice, f32) { + let choice = switches.theme.unwrap_or(match prefs.get(&UI_THEME) { + ThemeChoice::Dark => Choice::Dark, + ThemeChoice::Light => Choice::Light, + ThemeChoice::System => Choice::System, + }); + (choice, switches.font_scale.unwrap_or_else(|| prefs.get(&UI_FONT_SCALE))) +} + +/// Where the window's place is kept between ticks. +#[derive(Debug, Default)] +struct WindowKeeper { + /// The latest place the window reported and the store has not got. + latest: Option, + /// What the settings hold. + saved: Option, +} + +/// Give up the foreground thread once, so that GPUI's executor runs what is +/// queued before this task goes on. +async fn yield_now() { + let mut yielded = false; + std::future::poll_fn(|task| { + if yielded { + Poll::Ready(()) + } else { + yielded = true; + task.waker().wake_by_ref(); + Poll::Pending + } + }) + .await; +} + /// The root entity. pub struct AppState { /// What the client knows apart from the window. @@ -123,31 +202,49 @@ pub struct AppState { pub events_handled: u64, /// One-second ticks since the window opened. pub ticks: u64, + /// How many times the status line was set: a view that shows it as a + /// toast sees a new text by this number changing, even when the text is + /// the same as the last. + pub status_generation: u64, engine: Option, - host: ShellHost, + backend: Backend, + switches: Switches, + window: WindowKeeper, started: Instant, counters: Counters, later: Later, + /// What went to the engine (tests look at it: an engine of the test's + /// own would have to be asked what it was sent). + #[cfg(test)] + sent: std::cell::RefCell>, } impl AppState { /// The state at start, with its three loops running: the engine's - /// `events` (the engine is `None` in tests that need none), the tick and - /// the jobs of [`Later`]. They end when the entity is released. - pub fn new( - engine: Option, - events: UnboundedReceiver, - counters: Counters, - cx: &mut Context, - ) -> Self { + /// `events`, the tick and the jobs of [`Later`]. They end when the entity + /// is released. The saved servers, the settings and the identity are the + /// `backend`'s; the sample servers replace the saved ones with + /// `VOELIN_DEMO_UI`. + pub fn new(setup: Setup, cx: &mut Context) -> Self { + let Setup { engine, events, counters, backend, switches } = setup; let (later, mut jobs) = mpsc::unbounded_channel::(); cx.spawn(async move |this, cx| { let mut events = events; - while let Some(event) = events.recv().await { - if this.update(cx, |state, cx| state.handle_event(event, cx)).is_err() { + let mut batch = Vec::with_capacity(BATCH); + while let Some(first) = events.recv().await { + batch.push(first); + while batch.len() < BATCH { + let Ok(event) = events.try_recv() else { break }; + batch.push(event); + } + if this.update(cx, |state, cx| state.handle_events(batch.drain(..), cx)).is_err() { break; } + // A tokio receiver that has more is ready at once, outside a + // tokio runtime too: without this the loop would not give GPUI + // a turn until the burst is over. + yield_now().await; } }) .detach(); @@ -155,7 +252,7 @@ impl AppState { cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(Duration::from_secs(1)).await; - if this.update(cx, |state, cx| state.tick(cx)).is_err() { + if this.update(cx, |state, _| state.tick()).is_err() { break; } } @@ -178,22 +275,48 @@ impl AppState { }) .detach(); - Self { - vm: VmState::new( - Vec::new(), - UiSettings::default(), - AudioSettings::default(), - Default::default(), - ), + let loaded = backend.load(); + let saved = backend.prefs.get(&UI_WINDOW); + let mut state = Self { + vm: VmState::new(loaded.bookmarks, loaded.settings, loaded.audio, loaded.playback), social: Social::default(), events_handled: 0, ticks: 0, + status_generation: 0, engine, - host: ShellHost, + backend, + switches, + window: WindowKeeper { latest: None, saved }, started: Instant::now(), counters, later: Later(later), + #[cfg(test)] + sent: Default::default(), + }; + if state.switches.demo_ui { + state.load_demo(); } + state + } + + /// The sample servers of `VOELIN_DEMO_UI`, through the same events a server + /// would send ([`voelin_ui_vm::dev::logic`]): the first is connected, the + /// second observed. + fn load_demo(&mut self) { + use voelin_ui_vm::dev::logic as sample; + self.vm.bookmarks = sample::bookmarks(); + self.vm.settings.last_voice = Some(sample::last_voice()); + self.vm.current = Some(sample::DEMO); + for event in sample::server_events() { + let update = self.handle(event); + self.counters.engine_events.incr(); + self.events_handled += 1; + // Nothing of it goes out: `send` is silent in demo mode, and the + // settings and bookmarks are not kept. + self.log_warnings(update.warnings); + } + self.vm.status.clear(); + self.counters.connections.set(self.connections() as u64); } /// The handle other threads use to run something on GPUI's thread. @@ -201,36 +324,212 @@ impl AppState { self.later.clone() } + /// What the development switches say. + pub fn switches(&self) -> &Switches { + &self.switches + } + + /// The engine, when there is one. + pub fn engine(&self) -> Option<&Engine> { + self.engine.as_ref() + } + + /// The store, the settings and the secrets. + pub fn backend(&self) -> &Backend { + &self.backend + } + /// What an engine event does to the state ([`events::handle`], the one - /// dispatch of both front ends), and what comes of it for the engine. - pub fn handle_event(&mut self, event: Event, cx: &mut Context) { - self.events_handled += 1; - self.counters.engine_events.incr(); - let update = events::handle(&mut self.vm, &mut self.social, &self.host, event); - self.perform(update); + /// dispatch of both front ends), and what asks to be done of it. + fn handle(&mut self, event: Event) -> Update { + let host = ShellHost { + demo_ui: self.switches.demo_ui, + store: &self.backend.store, + prefs: &self.backend.prefs, + }; + events::handle(&mut self.vm, &mut self.social, &host, event) + } + + /// Take engine events in, in order: each changes the state and is carried + /// out, and the entity notifies once for all of them. + pub fn handle_events( + &mut self, + events: impl IntoIterator, + cx: &mut Context, + ) { + for event in events { + self.events_handled += 1; + self.counters.engine_events.incr(); + let update = self.handle(event); + self.perform(update, cx); + } self.counters.connections.set(self.connections() as u64); cx.notify(); } - /// Do what an update asks that this front end has the parts for: the - /// engine's commands go out, the warnings are logged. - fn perform(&mut self, update: Update) { + /// One engine event ([`AppState::handle_events`]). + pub fn handle_event(&mut self, event: Event, cx: &mut Context) { + self.handle_events([event], cx); + } + + /// Run a transition of the view model on the state and carry out what it + /// says. + fn transition( + &mut self, + cx: &mut Context, + f: impl FnOnce(&mut VmState, &mut Cx<'_>) -> R, + ) -> R { + let host = ShellHost { + demo_ui: self.switches.demo_ui, + store: &self.backend.store, + prefs: &self.backend.prefs, + }; + let mut transition = Cx::new(&host); + let result = f(&mut self.vm, &mut transition); + let update = transition.update; + self.perform(update, cx); + result + } + + /// An engine command; none in demo mode (the engine would open the sample + /// sessions for real) and none without an engine. + fn send(&self, command: Command) { + if self.switches.demo_ui { + return; + } + #[cfg(test)] + self.sent.borrow_mut().push(command.clone()); if let Some(engine) = &self.engine { - for command in update.commands { - engine.send(command); + engine.send(command); + } + } + + /// The commands sent since the last call. + #[cfg(test)] + fn take_sent(&self) -> Vec { + std::mem::take(&mut *self.sent.borrow_mut()) + } + + /// A command for the session on screen. + fn command(&self, f: impl FnOnce(u64) -> Command) { + if let Some(id) = self.vm.current { + self.send(f(id as u64)); + } + } + + fn log_warnings(&self, warnings: Vec) { + for text in warnings { + warn!("{text}"); + } + } + + /// Do what an update asks that this front end has the parts for. + fn perform(&mut self, update: Update, cx: &mut Context) { + let Update { status, commands, persist, warnings, rest, password, .. } = update; + self.log_warnings(warnings); + for command in commands { + self.send(command); + } + if let Some(text) = status { + self.set_status(text); + } + for what in persist { + self.keep(what); + } + if let Some(prompt) = password { + debug!(channel = %prompt.name, "the password dialog comes with the channel tree"); + } + // What the front end keeps itself comes before the drawing. + if let Some(Event::SettingChanged { key }) = rest { + self.setting_changed(&key, cx); + } + } + + /// The status line says this from now on. + pub fn set_status(&mut self, text: impl Into) { + self.vm.status = text.into(); + self.status_generation += 1; + } + + /// Keep what a transition changed (nothing in demo mode). + fn keep(&mut self, what: Persist) { + if self.switches.demo_ui { + return; + } + match what { + Persist::Bookmark { id, what } => { + let Some(bookmark) = self.vm.bookmarks.iter().find(|b| b.id == id) else { + return; + }; + match self.backend.store.update_bookmark(bookmark) { + Ok(()) => debug!(server = %bookmark.address, "{what}"), + Err(e) => warn!(%e, "could not keep the bookmark: {what}"), + } + } + Persist::Settings => { + if let Err(e) = self.backend.prefs.set(&UI, self.vm.settings.clone()) { + warn!(%e, "could not store settings"); + } + } + Persist::Audio => { + if let Err(e) = self.backend.prefs.set(&AUDIO, self.vm.audio.clone()) { + warn!(%e, "could not store audio settings"); + } + } + Persist::Playback => { + if let Err(e) = self.backend.prefs.set(&CLIENT_PLAYBACK, self.vm.playback.clone()) { + warn!(%e, "could not store client volumes"); + } } } - for warning in update.warnings { - tracing::warn!("{warning}"); + } + + /// A setting changed, maybe elsewhere (a command, another window): take + /// the values the window keeps copies of. Today that is what the theme + /// follows; the development switches keep what they set. + fn setting_changed(&mut self, key: &str, cx: &mut Context) { + if key == UI_THEME.name() || key == UI_FONT_SCALE.name() { + let (choice, scale) = appearance(&self.backend.prefs, &self.switches); + let appearance = cx.window_appearance(); + VoelinTheme::set_choice(cx, choice, appearance); + VoelinTheme::set_font_scale(cx, scale); } } /// The once-a-second work: what the Slint front end's `App::tick` will be - /// here (stream statistics, stored settings); today it counts. - pub fn tick(&mut self, cx: &mut Context) { + /// here (stream statistics, stored settings). Today it counts and keeps + /// the window's place. It does not notify: nothing the shell shows changes + /// with the clock, so a window that is not touched is not drawn. + pub fn tick(&mut self) { self.ticks += 1; self.counters.ticks.incr(); - cx.notify(); + self.flush_window(); + } + + /// The window moved or changed size: remember it, to keep at the next tick + /// (and at close). Not with a development switch that sets the size, and + /// not with the sample data: neither is the user's window. + pub fn window_moved(&mut self, state: WindowState) { + if self.switches.window.is_none() && !self.switches.demo_ui { + self.window.latest = Some(state); + } + } + + /// The window's place as the last run left it. + pub fn remembered_window(&self) -> Option { + self.window.saved.filter(WindowState::is_sane) + } + + /// Write the window's place to the settings if it changed. + fn flush_window(&mut self) { + let Some(latest) = self.window.latest.take() else { return }; + if self.window.saved == Some(latest) { + return; + } + match self.backend.prefs.set(&UI_WINDOW, Some(latest)) { + Ok(()) => self.window.saved = Some(latest), + Err(e) => warn!(%e, "could not store the window's place"), + } } /// Voice connections that are up. @@ -243,67 +542,453 @@ impl AppState { self.started.elapsed() } - /// The one line of state the window shows: the version, how many voice - /// connections are up, how many engine events came and how long the - /// window has run. Each part moves by a loop above, so a line that - /// changes shows that the loop runs. + /// The window's title: the app's name, and the server shown. + pub fn window_title(&self) -> String { + let shown = self + .vm + .current + .and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id)) + .map(|b| b.name.as_str()); + match shown { + Some(name) => format!("{} - {name}", voelin_platform::APP_NAME), + None => voelin_platform::APP_NAME.to_owned(), + } + } + + /// The server on screen. + pub fn current_bookmark(&self) -> Option<&Bookmark> { + self.vm.current.and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id)) + } + + /// A server's icon: what its session fetched, else what the engine cached. + pub fn server_icon(&self, bookmark: &Bookmark) -> ImageRef { + let current = self + .vm + .sessions + .get(&bookmark.id) + .map(|view| view.server_icon_for(&bookmark.address)) + .unwrap_or_default(); + if current.size().width > 0 { + return current; + } + match &self.engine { + Some(engine) => voelin_ui_vm::servers::cached_icon(bookmark, &engine.cache()), + None => ImageRef::default(), + } + } + + // The callbacks of `bind/servers.rs` that the shell has: what the + // actions of `crate::shell` do. + + /// Show a server, and observe it. + pub fn select_server(&mut self, id: i64, cx: &mut Context) { + self.transition(cx, |state, cx| logic::select_server(state, cx, id)); + self.observe(id, cx); + cx.notify(); + } + + /// Connect the server on screen with voice, into its default channel. + pub fn connect_voice(&mut self, cx: &mut Context) { + let channel = self.current_bookmark().and_then(|b| b.default_channel.clone()); + self.connect_voice_to(channel, None, None, cx); + cx.notify(); + } + + /// Connect the current server with voice, into `channel` (a path, or + /// `/`, with its password) if given, with a privilege key if given; + /// whether it was asked for. + pub fn connect_voice_to( + &mut self, + channel: Option, + channel_password: Option, + token: Option, + cx: &mut Context, + ) -> bool { + let Some(b) = self.current_bookmark().cloned() else { return false }; + if self.switches.demo_ui { + return false; + } + let mut options = match logic::voice_options(&b, channel, channel_password, token) { + Ok(options) => options, + Err(error) => { + self.set_status(error); + return false; + } + }; + options.identity = + Some(voelin_core::ts::identity::to_blob(&self.backend.identity_for(Some(&b)))); + options.server_password = self.backend.secrets.get(&b.server_password_key()).ok().flatten(); + // `options.stream_peer` stays the engine's default: what this front + // end can decode is for the slice with the stream viewer to say. + self.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) }); + self.set_status(format!("Connecting to {}…", b.address)); + // The admin may have published the gateway since it was added. + self.discover_gateway(b.id, cx); + true + } + + /// Leave voice on the server on screen. + pub fn disconnect_voice(&mut self, cx: &mut Context) { + self.command(|session| Command::DisconnectVoice { session }); + cx.notify(); + } + + /// Mute or unmute our microphone on the server on screen. + pub fn set_input_muted(&mut self, muted: bool, cx: &mut Context) { + self.command(|session| Command::SetInputMuted { session, muted }); + cx.notify(); + } + + /// Mute or unmute the sound of the server on screen. + pub fn set_output_muted(&mut self, muted: bool, cx: &mut Context) { + self.command(|session| Command::SetOutputMuted { session, muted }); + cx.notify(); + } + + /// Start or stop transmitting (the window's hold-to-talk button). + pub fn push_to_talk(&mut self, on: bool, cx: &mut Context) { + self.command(|session| Command::SetTransmitting { session, on }); + cx.notify(); + } + + /// A link to the voice channel we are in, copied to the clipboard with a + /// note in the status line; the reason in the status line without one. + pub fn invite(&mut self, cx: &mut Context) -> Option { + let link = match logic::invite_link(&mut self.vm) { + Ok(link) => link, + Err(why) => { + self.set_status(why); + cx.notify(); + return None; + } + }; + cx.write_to_clipboard(ClipboardItem::new_string(link.clone())); + let note = self.vm.copy_note.take().unwrap_or_else(|| "Copied".to_owned()); + self.set_status(note); + cx.notify(); + Some(link) + } + + /// The server dialog's form for a server (id -1: a new one). + pub fn bookmark_form(&self, id: i64) -> BookmarkForm { + let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id) else { + return BookmarkForm { + id: -1, + nickname: self.backend.default_nickname().into(), + ..Default::default() + }; + }; + let password = self.backend.secrets.get(&b.server_password_key()).ok().flatten(); + let state = self.vm.sessions.get(&b.id).map(|view| &view.state); + voelin_ui_vm::servers::form(b, state, password.as_deref().unwrap_or_default()) + } + + /// Save the server the form describes, and show it: its id, none when it + /// could not be saved (the status line says why). + pub fn save_bookmark(&mut self, form: &BookmarkForm, cx: &mut Context) -> Option { + if self.switches.demo_ui { + self.set_status("The sample servers are not kept"); + cx.notify(); + return None; + } + let old = self.vm.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned(); + let mut bookmark = + logic::bookmark_from_form(old.as_ref(), form, || self.backend.default_nickname()); + if bookmark.address.is_empty() { + self.set_status("A server needs an address"); + cx.notify(); + return None; + } + let result = if bookmark.id < 0 { + self.backend.store.add_bookmark(&bookmark).map(|id| bookmark.id = id) + } else { + self.backend.store.update_bookmark(&bookmark) + }; + if let Err(e) = result { + self.set_status(format!("Could not save: {e}")); + cx.notify(); + return None; + } + let key = bookmark.server_password_key(); + let result = if form.server_password.is_empty() { + self.backend.secrets.delete(&key) + } else { + self.backend.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 _ = self.backend.secrets.delete(&old.query_password_key()); + } + self.vm.gateways_looked_up.remove(&bookmark.id); + self.send(Command::StopObserving { session: bookmark.id as u64 }); + if let Some(view) = self.vm.sessions.get_mut(&bookmark.id) { + view.state.observe = ObserveState::Off; + } + } + self.vm.bookmarks = self.backend.store.bookmarks().unwrap_or_default(); + let id = bookmark.id; + self.select_server(id, cx); + Some(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. + /// 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(&mut self, form: &BookmarkForm, cx: &mut Context) -> bool { + let saved = self.save_bookmark(form, cx); + let bookmark = saved.and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id)); + let Some(to) = voelin_ui_vm::servers::connect_to(form, bookmark) else { return false }; + self.connect_voice_to(to.channel, to.channel_password, to.token, cx); + cx.notify(); + true + } + + /// Remove a server: its session is closed, its passwords and the bookmark + /// go, and the first server is shown. + pub fn delete_bookmark(&mut self, id: i64, cx: &mut Context) { + if self.switches.demo_ui { + self.set_status("The sample servers are not kept"); + cx.notify(); + return; + } + self.send(Command::CloseSession { session: id as u64 }); + if let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() { + let _ = self.backend.secrets.delete(&b.server_password_key()); + let _ = self.backend.secrets.delete(&b.query_password_key()); + } + let _ = self.backend.store.delete_bookmark(id); + let bookmarks = self.backend.store.bookmarks().unwrap_or_default(); + self.transition(cx, |state, cx| logic::forget_server(state, cx, id, bookmarks)); + cx.notify(); + } + + /// 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. + fn observe(&mut self, id: i64, cx: &mut Context) { + let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() else { return }; + let session = b.id as u64; + let gateway = |app: &Self, urls| Command::ObserveGateway { + session, + urls, + identity: Box::new(voelin_core::ts::identity::to_blob( + &app.backend.identity_for(Some(&b)), + )), + }; + match self.transition(cx, |state, cx| logic::observe_plan(state, cx, id)) { + ObservePlan::Nothing => return, + ObservePlan::Retry(urls) => { + debug!(server = %b.address, "still connecting to the gateway: try now"); + self.send(gateway(self, urls)); + return; + } + ObservePlan::Gateway(urls) => { + info!(server = %b.address, ?urls, "observing through the gateway"); + self.send(gateway(self, urls)); + // Still the one the server publishes? + self.discover_gateway(b.id, cx); + } + ObservePlan::Query(q) => { + let secret = self.backend.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, + }; + self.send(Command::ObserveQuery { session, connect: Box::new(connect) }); + } + ObservePlan::Discover => { + self.discover_gateway(b.id, cx); + return; + } + } + self.set_status("Observing invisibly…"); + } + + /// Look up the gateway of a server ([`voelin_core::discover`]), once a run + /// ([`logic::discover_wanted`]), on the engine's runtime; what is found + /// comes back through [`Later`]. + fn discover_gateway(&mut self, id: i64, cx: &mut Context) { + let Some(address) = self.transition(cx, |state, cx| logic::discover_wanted(state, cx, id)) + else { + return; + }; + let Some(engine) = &self.engine else { return }; + let later = self.later(); + engine.runtime().spawn(async move { + 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"); + } else { + later.run(move |app, cx| app.gateway_found(id, &address, urls, elapsed_ms, cx)); + } + }); + } + + /// 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). + fn gateway_found( + &mut self, + id: i64, + address: &str, + urls: Vec, + elapsed_ms: u64, + cx: &mut Context, + ) { + let found = + self.transition(cx, |state, cx| logic::gateway_found(state, cx, id, address, urls)); + match found { + GatewayFound::Same => debug!(server = %address, elapsed_ms, "gateway found, as kept"), + GatewayFound::Kept { observe } => { + info!(server = %address, elapsed_ms, kept = true, "gateway found"); + if observe { + self.observe(id, cx); + } + } + GatewayFound::Changed { stop, observe, urls } => { + info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found"); + if stop { + self.send(Command::StopObserving { session: id as u64 }); + } + if observe { + self.observe(id, cx); + } + } + } + } + + /// Leave the servers properly, so no ghost client stays behind until it + /// times out (the window is closing): tell the engine to close every + /// session, keep the window's place and the settings, and the chats' read + /// marks. Returns how many sessions it told, so that the caller can give + /// the engine time to act on them before the runtime goes (none without an + /// engine, none in demo mode). + pub fn shutdown(&mut self, cx: &mut Context) -> usize { + self.flush_window(); + let ids: Vec = self.vm.sessions.keys().copied().collect(); + for id in &ids { + self.transition(cx, |state, cx| voelin_ui_vm::chat::logic::save_reads(state, cx, *id)); + } + self.backend.flush(); + if self.switches.demo_ui || self.engine.is_none() { + return 0; + } + for id in &ids { + self.send(Command::CloseSession { session: *id as u64 }); + } + ids.len() + } + + /// The one line of state: the version, how many voice connections are up + /// and how many engine events came. pub fn state_line(&self) -> String { let connections = self.connections(); format!( - "{} {} · {} connection{} · {} engine event{} · {} s up", + "{} {} · {} connection{} · {} engine event{}", voelin_platform::APP_NAME, env!("CARGO_PKG_VERSION"), connections, if connections == 1 { "" } else { "s" }, self.events_handled, if self.events_handled == 1 { "" } else { "s" }, - self.ticks, ) } - - /// Leave the servers properly, so no ghost client stays behind until it - /// times out (the window is closing): tell the engine to close every - /// session. Returns how many it told, so that the caller can give the - /// engine time to act on them before the runtime goes (none without an - /// engine). - pub fn shutdown(&self) -> usize { - let Some(engine) = &self.engine else { return 0 }; - for id in self.vm.sessions.keys() { - engine.send(Command::CloseSession { session: *id as u64 }); - } - self.vm.sessions.len() - } } #[cfg(test)] mod tests { + use std::cell::Cell; + use std::rc::Rc; use std::time::Duration; use gpui::TestAppContext; - use gpui_kit::AppContext as _; - use voelin_core::{Command, Event, SessionState, VoiceState}; + use gpui_kit::{AppContext as _, Entity, Subscription, WindowAppearance}; + use voelin_core::{Backends, Command, Event, SessionState, VoiceState}; + use voelin_store::MemorySecrets; + use voelin_ui_vm::dev::logic as sample; use super::*; + use crate::backend::testing::TempDir; use crate::engine::HostedEngine; fn voice(voice: VoiceState) -> Event { Event::State { session: 1, state: SessionState { voice, ..Default::default() } } } - /// The entity of a test with no engine behind it: `tx` stands in for the - /// engine's events. - fn entity( + fn bookmark(name: &str, address: &str) -> Bookmark { + Bookmark { + name: name.into(), + address: address.into(), + nickname: "Nova".into(), + ..Default::default() + } + } + + /// The entity of a test over `backend` with no engine behind it: `tx` + /// stands in for the engine's events. + fn entity_over( cx: &mut TestAppContext, - ) -> (gpui_kit::Entity, UnboundedSender, Counters) { + backend: Backend, + switches: Switches, + ) -> (Entity, UnboundedSender, Counters) { let (tx, rx) = mpsc::unbounded_channel(); let counters = Counters::default(); - let app = cx.new({ - let counters = counters.clone(); - move |cx| AppState::new(None, rx, counters, cx) - }); + let setup = + Setup { engine: None, events: rx, counters: counters.clone(), backend, switches }; + let app = cx.new(|cx| AppState::new(setup, cx)); (app, tx, counters) } + /// The entity of a test with nothing stored and no engine. + fn entity(cx: &mut TestAppContext) -> (Entity, UnboundedSender, Counters) { + entity_over(cx, Backend::in_memory().unwrap(), Switches::default()) + } + + /// An in-memory backend whose store has these servers. + fn backend_with(servers: &[(&str, &str)]) -> Backend { + let backend = Backend::in_memory().unwrap(); + for (name, address) in servers { + backend.store.add_bookmark(&bookmark(name, address)).unwrap(); + } + backend + } + + /// How many times `app` notified, and the subscription that counts. + fn notifications( + cx: &mut TestAppContext, + app: &Entity, + ) -> (Rc>, Subscription) { + let seen = Rc::new(Cell::new(0)); + let subscription = cx.update(|cx| { + let seen = seen.clone(); + cx.observe(app, move |_, _| seen.set(seen.get() + 1)) + }); + (seen, subscription) + } + + fn form(address: &str) -> BookmarkForm { + BookmarkForm { id: -1, address: address.into(), ..Default::default() } + } + #[gpui::test] fn an_injected_engine_event_reaches_the_entity(cx: &mut TestAppContext) { let (app, tx, counters) = entity(cx); @@ -337,19 +1022,42 @@ mod tests { #[gpui::test] fn the_entity_redraws_on_an_event(cx: &mut TestAppContext) { let (app, tx, _) = entity(cx); - let notified = std::rc::Rc::new(std::cell::Cell::new(0)); - let _subscription = cx.update(|cx| { - let notified = notified.clone(); - cx.observe(&app, move |_, _| notified.set(notified.get() + 1)) - }); + let (seen, _subscription) = notifications(cx, &app); tx.send(voice(VoiceState::Connecting)).unwrap(); cx.run_until_parked(); - assert_eq!(notified.get(), 1); + assert_eq!(seen.get(), 1); } + /// A burst (a server's first sync) is taken `BATCH` events at a time: one + /// update and one redraw for each, and a turn of GPUI's executor between + /// them, not one pass over the whole burst. #[gpui::test] - fn the_tick_runs_once_a_second(cx: &mut TestAppContext) { + fn a_burst_of_events_is_taken_in_steps_with_one_redraw_each(cx: &mut TestAppContext) { + let (app, tx, counters) = entity(cx); + let (seen, _subscription) = notifications(cx, &app); + let total = BATCH * 3 + 5; + for i in 0..total { + tx.send(Event::Talking { session: 1, client: (i % 50) as u16, talking: true }).unwrap(); + } + let handled = |cx: &mut TestAppContext| app.read_with(cx, |app, _| app.events_handled); + while handled(cx) == 0 { + assert!(cx.executor().tick(), "the events task is runnable"); + } + assert_eq!(handled(cx), BATCH as u64, "one step, then GPUI's turn"); + assert_eq!(seen.get(), 1); + + cx.run_until_parked(); + assert_eq!(handled(cx), total as u64); + assert_eq!(seen.get(), total.div_ceil(BATCH)); + assert_eq!(counters.engine_events.get(), total as u64); + } + + /// The tick counts and keeps what is due, and draws nothing: a window left + /// alone is not redrawn once a second. + #[gpui::test] + fn the_tick_runs_once_a_second_and_notifies_nobody(cx: &mut TestAppContext) { let (app, _tx, counters) = entity(cx); + let (seen, _subscription) = notifications(cx, &app); cx.run_until_parked(); assert_eq!(app.read_with(cx, |app, _| app.ticks), 0); for second in 1..=3 { @@ -358,6 +1066,7 @@ mod tests { assert_eq!(app.read_with(cx, |app, _| app.ticks), second); } assert_eq!(counters.ticks.get(), 3); + assert_eq!(seen.get(), 0, "no redraw"); } #[gpui::test] @@ -401,14 +1110,20 @@ mod tests { .enable_all() .build() .unwrap(); - let hosted = HostedEngine::start(&runtime); + let hosted = HostedEngine::start_with_backends(&runtime, Backends::empty()); let (tx, rx) = mpsc::unbounded_channel(); - let app = - cx.new(|cx| AppState::new(Some(hosted.engine.clone()), rx, Counters::default(), cx)); - assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 0, "no session open yet"); + let setup = Setup { + engine: Some(hosted.engine.clone()), + events: rx, + counters: Counters::default(), + backend: Backend::in_memory().unwrap(), + switches: Switches::default(), + }; + let app = cx.new(|cx| AppState::new(setup, cx)); + assert_eq!(app.update(cx, |app, cx| app.shutdown(cx)), 0, "no session open yet"); tx.send(voice(VoiceState::Connected)).unwrap(); cx.run_until_parked(); - assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 1); + assert_eq!(app.update(cx, |app, cx| app.shutdown(cx)), 1); runtime.shutdown_timeout(Duration::from_secs(2)); } @@ -417,7 +1132,7 @@ mod tests { let (app, tx, _) = entity(cx); tx.send(voice(VoiceState::Connected)).unwrap(); cx.run_until_parked(); - assert_eq!(app.read_with(cx, |app, _| (app.connections(), app.shutdown())), (1, 0)); + assert_eq!(app.update(cx, |app, cx| (app.connections(), app.shutdown(cx))), (1, 0)); } /// The whole path with a real engine: a command makes the engine report a @@ -436,10 +1151,16 @@ mod tests { .enable_all() .build() .unwrap(); - let hosted = HostedEngine::start(&runtime); + let hosted = HostedEngine::start_with_backends(&runtime, Backends::empty()); let engine = hosted.engine.clone(); - let counters = Counters::default(); - let app = cx.new(|cx| AppState::new(Some(engine.clone()), hosted.events, counters, cx)); + let setup = Setup { + engine: Some(engine.clone()), + events: hosted.events, + counters: Counters::default(), + backend: Backend::in_memory().unwrap(), + switches: Switches::default(), + }; + let app = cx.new(|cx| AppState::new(setup, cx)); engine.send(Command::SetSetting { key: "stream.fps".into(), value: 144.into() }); let deadline = Instant::now() + Duration::from_secs(120); while app.read_with(cx, |app, _| app.events_handled) == 0 { @@ -450,4 +1171,446 @@ mod tests { assert!(app.read_with(cx, |app, _| app.events_handled) >= 1); runtime.shutdown_timeout(Duration::from_secs(2)); } + + #[gpui::test] + fn the_servers_of_the_store_are_the_ones_shown_and_the_first_is_on_screen( + cx: &mut TestAppContext, + ) { + let (app, _, _) = entity_over( + cx, + backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]), + Switches::default(), + ); + app.read_with(cx, |app, _| { + let names: Vec<&str> = app.vm.bookmarks.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Nightfall", "Lounge"]); + assert_eq!(app.current_bookmark().map(|b| b.name.as_str()), Some("Nightfall")); + assert_eq!(app.window_title(), "Voelin - Nightfall"); + }); + let (empty, _, _) = entity(cx); + empty.read_with(cx, |app, _| { + assert_eq!((app.vm.current, app.window_title().as_str()), (None, "Voelin")); + }); + } + + #[gpui::test] + fn selecting_a_server_shows_it_and_names_it_in_the_title(cx: &mut TestAppContext) { + let (app, _, _) = entity_over( + cx, + backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]), + Switches::default(), + ); + let (seen, _subscription) = notifications(cx, &app); + let lounge = app.read_with(cx, |app, _| app.vm.bookmarks[1].id); + app.update(cx, |app, cx| app.select_server(lounge, cx)); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.current, Some(lounge)); + assert_eq!(app.window_title(), "Voelin - Lounge"); + }); + assert!(seen.get() >= 1, "the views are told"); + } + + #[gpui::test] + fn a_saved_server_is_stored_shown_and_selected(cx: &mut TestAppContext) { + let (app, _, _) = entity(cx); + let id = app + .update(cx, |app, cx| { + app.save_bookmark( + &BookmarkForm { name: "Nightfall".into(), ..form("ts.example") }, + cx, + ) + }) + .expect("saved"); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.current, Some(id)); + assert_eq!(app.window_title(), "Voelin - Nightfall"); + let kept = app.backend().store.bookmarks().unwrap(); + assert_eq!(kept.iter().map(|b| b.address.as_str()).collect::>(), ["ts.example"]); + assert_eq!(app.vm.bookmarks, kept, "the rail's list is the store's"); + assert!(!kept[0].nickname.is_empty(), "a nickname was given"); + }); + // Another with no name is named by its address. + let second = + app.update(cx, |app, cx| app.save_bookmark(&form("other.example"), cx)).unwrap(); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.bookmarks.len(), 2); + assert_eq!(app.window_title(), "Voelin - other.example"); + assert_eq!(app.vm.current, Some(second)); + }); + } + + #[gpui::test] + fn a_server_without_an_address_is_not_saved(cx: &mut TestAppContext) { + let (app, _, _) = entity(cx); + assert_eq!(app.update(cx, |app, cx| app.save_bookmark(&form(" "), cx)), None); + app.read_with(cx, |app, _| { + assert!( + app.vm.bookmarks.is_empty() && app.backend().store.bookmarks().unwrap().is_empty() + ); + assert_eq!(app.vm.status, "A server needs an address"); + }); + } + + #[gpui::test] + fn editing_a_server_keeps_its_place_and_changes_what_the_form_names(cx: &mut TestAppContext) { + let (app, _, _) = entity_over( + cx, + backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]), + Switches::default(), + ); + let first = app.read_with(cx, |app, _| app.vm.bookmarks[0].id); + let form = app.read_with(cx, |app, _| app.bookmark_form(first)); + assert_eq!((form.id as i64, form.name.as_ref()), (first, "Nightfall")); + let edited = BookmarkForm { name: "Nightfall Guild".into(), ..form }; + assert_eq!(app.update(cx, |app, cx| app.save_bookmark(&edited, cx)), Some(first)); + app.read_with(cx, |app, _| { + let names: Vec<&str> = app.vm.bookmarks.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Nightfall Guild", "Lounge"], "the same place in the rail"); + }); + } + + #[gpui::test] + fn a_removed_server_goes_from_the_rail_and_the_store_and_the_first_is_shown( + cx: &mut TestAppContext, + ) { + let (app, _, _) = entity_over( + cx, + backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]), + Switches::default(), + ); + let (first, second) = + app.read_with(cx, |app, _| (app.vm.bookmarks[0].id, app.vm.bookmarks[1].id)); + app.update(cx, |app, cx| app.select_server(second, cx)); + app.update(cx, |app, cx| app.delete_bookmark(second, cx)); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.bookmarks.len(), 1); + assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1); + assert_eq!(app.vm.current, Some(first), "the first server is shown"); + }); + app.update(cx, |app, cx| app.delete_bookmark(first, cx)); + app.read_with(cx, |app, _| { + assert_eq!((app.vm.current, app.window_title().as_str()), (None, "Voelin")); + }); + } + + /// The real path of a connect: the action's method sends the command, the + /// engine (with no connector, so that nothing leaves the machine and no + /// sound device opens) takes it and answers with its events, which the + /// entity's loop turns into the state the rail shows. + #[gpui::test] + fn a_connect_reaches_the_engine_and_its_answer_reaches_the_rail(cx: &mut TestAppContext) { + cx.executor().allow_parking(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let hosted = HostedEngine::start_with_backends(&runtime, Backends::empty()); + let setup = Setup { + engine: Some(hosted.engine.clone()), + events: hosted.events, + counters: Counters::default(), + backend: backend_with(&[("Nightfall", "ts.example")]), + switches: Switches::default(), + }; + let app = cx.new(|cx| AppState::new(setup, cx)); + let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id); + app.update(cx, |app, cx| app.connect_voice(cx)); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.status, "Connecting to ts.example…"); + }); + // The engine's answer: the session was asked for, and the engine said + // why it did not open (no connector serves the address). + let deadline = Instant::now() + Duration::from_secs(120); + let answered = |cx: &mut TestAppContext| { + app.read_with(cx, |app, _| { + app.vm.status.contains("no connector for ts3server://ts.example") + }) + }; + while !answered(cx) { + assert!( + Instant::now() < deadline, + "the engine never answered: {}", + app.read_with(cx, |app, _| app.vm.status.clone()) + ); + cx.run_until_parked(); + std::thread::sleep(Duration::from_millis(10)); + } + app.read_with(cx, |app, _| { + let session = &app.vm.sessions[&id]; + assert_eq!(session.state.voice, VoiceState::Disconnected); + assert_eq!(app.connections(), 0); + }); + runtime.shutdown_timeout(Duration::from_secs(2)); + } + + /// What a connect asks of the engine: the server on screen, its address and + /// nickname, the identity it connects with, its password from the secrets + /// and its default channel. + #[gpui::test] + fn a_connect_asks_the_engine_for_the_server_on_screen_with_what_it_knows( + cx: &mut TestAppContext, + ) { + let (app, _, _) = entity(cx); + let id = app + .update(cx, |app, cx| { + app.save_bookmark( + &BookmarkForm { + name: "Nightfall".into(), + nickname: "Nova".into(), + server_password: "hunter2".into(), + ..form("ts.example") + }, + cx, + ) + }) + .unwrap(); + app.read_with(cx, |app, _| app.take_sent()); + app.update(cx, |app, cx| app.connect_voice(cx)); + let sent = app.read_with(cx, |app, _| app.take_sent()); + let [Command::ConnectVoice { session, options }] = sent.as_slice() else { + panic!("one connect: {sent:?}") + }; + assert_eq!(*session, id as u64); + assert_eq!((options.address.as_str(), options.nickname.as_str()), ("ts.example", "Nova")); + assert_eq!(options.server_password.as_deref(), Some("hunter2")); + assert!(options.identity.is_some() && options.audio); + assert_eq!(options.channel, None); + } + + #[gpui::test] + fn a_connect_with_no_server_on_screen_asks_nothing(cx: &mut TestAppContext) { + let (app, _, _) = entity(cx); + app.update(cx, |app, cx| app.connect_voice(cx)); + assert!(app.read_with(cx, |app, _| app.take_sent()).is_empty()); + } + + /// The server dialog's Connect: saved first, then connected into the + /// server's default channel; a form that cannot be saved connects nothing. + #[gpui::test] + fn save_and_connect_saves_the_server_and_then_connects_it(cx: &mut TestAppContext) { + let (app, _, _) = entity(cx); + assert!(!app.update(cx, |app, cx| app.save_and_connect(&form(""), cx))); + assert!(app.read_with(cx, |app, _| app.take_sent()).is_empty()); + assert!(app.update(cx, |app, cx| app.save_and_connect(&form("ts.example"), cx))); + let sent = app.read_with(cx, |app, _| app.take_sent()); + let connects: Vec<_> = sent + .iter() + .filter_map(|c| match c { + Command::ConnectVoice { options, .. } => Some(options.address.as_str()), + _ => None, + }) + .collect(); + assert_eq!(connects, ["ts.example"], "{sent:?}"); + app.read_with(cx, |app, _| assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1)); + } + + #[gpui::test] + fn the_voice_controls_and_the_disconnect_go_to_the_session_on_screen(cx: &mut TestAppContext) { + let (app, _, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64; + app.read_with(cx, |app, _| app.take_sent()); + app.update(cx, |app, cx| { + app.set_input_muted(true, cx); + app.set_output_muted(false, cx); + app.push_to_talk(true, cx); + app.disconnect_voice(cx); + }); + let sent = app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!( + sent.as_slice(), + [ + Command::SetInputMuted { session: a, muted: true }, + Command::SetOutputMuted { session: b, muted: false }, + Command::SetTransmitting { session: c, on: true }, + Command::DisconnectVoice { session: d }, + ] if [*a, *b, *c, *d] == [id; 4] + ), + "{sent:?}" + ); + let (empty, _, _) = entity(cx); + empty.update(cx, |app, cx| app.disconnect_voice(cx)); + assert!(empty.read_with(cx, |app, _| app.take_sent()).is_empty(), "no session on screen"); + } + + /// Showing a server also observes it, invisibly, through the gateway it + /// published or its own query login, as the Slint front end does. + #[gpui::test] + fn selecting_a_server_observes_it_through_its_gateway_or_its_query_login( + cx: &mut TestAppContext, + ) { + let backend = Backend::in_memory().unwrap(); + let gateway = Bookmark { + gateway_url: Some("wss://gw.example/v1".into()), + ..bookmark("Gw", "gw.example") + }; + let query = Bookmark { + query: Some(voelin_store::QueryConfig { + host: "q.example".into(), + ..Default::default() + }), + ..bookmark("Q", "q.example") + }; + for b in [&gateway, &query] { + backend.store.add_bookmark(b).unwrap(); + } + let (app, _, _) = entity_over(cx, backend, Switches::default()); + let (gw_id, q_id) = + app.read_with(cx, |app, _| (app.vm.bookmarks[0].id, app.vm.bookmarks[1].id)); + app.update(cx, |app, cx| app.select_server(gw_id, cx)); + let sent = app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::ObserveGateway { session, urls, .. }] + if *session == gw_id as u64 && urls == &["wss://gw.example/v1"]), + "{sent:?}" + ); + assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "Observing invisibly…"); + app.update(cx, |app, cx| app.select_server(q_id, cx)); + let sent = app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::ObserveQuery { session, connect }] + if *session == q_id as u64 && connect.address.starts_with("q.example:")), + "{sent:?}" + ); + } + + /// Removing a server tells the engine to close its session. + #[gpui::test] + fn removing_a_server_closes_its_session(cx: &mut TestAppContext) { + let (app, _, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id); + app.update(cx, |app, cx| app.delete_bookmark(id, cx)); + let sent = app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::CloseSession { session }] if *session == id as u64), + "{sent:?}" + ); + } + + #[gpui::test] + fn the_sample_servers_show_through_the_events_and_nothing_is_stored_or_sent( + cx: &mut TestAppContext, + ) { + let switches = Switches { demo_ui: true, ..Switches::default() }; + let (app, _, counters) = + entity_over(cx, backend_with(&[("Mine", "mine.example")]), switches); + app.read_with(cx, |app, _| { + let names: Vec<&str> = app.vm.bookmarks.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Nightfall Guild", "Pixel Lounge", "Dev TS3"]); + assert_eq!(app.vm.current, Some(sample::DEMO)); + assert_eq!(app.connections(), 1, "the first sample server is connected"); + assert_eq!(app.vm.sessions[&(sample::DEMO + 1)].state.observe, ObserveState::Observing); + assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1, "the store has its own"); + }); + assert_eq!(counters.connections.get(), 1); + assert_eq!(app.update(cx, |app, cx| app.save_bookmark(&form("new.example"), cx)), None); + app.update(cx, |app, cx| app.delete_bookmark(sample::DEMO, cx)); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.bookmarks.len(), 3, "the samples cannot be changed"); + assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1); + }); + assert_eq!( + app.update(cx, |app, cx| app.shutdown(cx)), + 0, + "no session of the samples is closed" + ); + app.update(cx, |app, cx| { + app.select_server(sample::DEMO + 1, cx); + app.connect_voice(cx); + }); + assert!( + app.read_with(cx, |app, _| app.take_sent()).is_empty(), + "nothing goes to the engine" + ); + } + + /// The theme follows the settings (`ui.theme`, `ui.font_scale`) when the + /// engine says one changed, and a development switch keeps what it set. + #[gpui::test] + fn the_theme_follows_the_settings_unless_a_switch_set_it(cx: &mut TestAppContext) { + cx.update(|cx| { + gpui_kit::init(cx); + VoelinTheme::init(cx, Choice::Dark, WindowAppearance::Dark, 1.0); + }); + let (app, tx, _) = entity(cx); + let theme = |cx: &mut TestAppContext| { + cx.update(|cx| { + let theme = VoelinTheme::global(cx); + (theme.choice(), theme.metrics.font_scale) + }) + }; + assert_eq!(theme(cx), (Choice::Dark, 1.0)); + app.read_with(cx, |app, _| { + app.backend().prefs.set(&UI_THEME, ThemeChoice::Light).unwrap(); + app.backend().prefs.set(&UI_FONT_SCALE, 1.25).unwrap(); + }); + tx.send(Event::SettingChanged { key: "ui.theme".into() }).unwrap(); + cx.run_until_parked(); + assert_eq!(theme(cx), (Choice::Light, 1.25)); + + // With a switch for the mode, the settings' value is not applied. + let switches = Switches { theme: Some(Choice::Dark), ..Switches::default() }; + let (switched, tx, _) = entity_over(cx, Backend::in_memory().unwrap(), switches); + switched.read_with(cx, |app, _| { + app.backend().prefs.set(&UI_THEME, ThemeChoice::System).unwrap() + }); + tx.send(Event::SettingChanged { key: "ui.theme".into() }).unwrap(); + cx.run_until_parked(); + assert_eq!(theme(cx).0, Choice::Dark); + } + + fn place() -> WindowState { + WindowState { width: 1100, height: 700, x: Some(30), y: Some(40), maximized: false } + } + + /// The window's place goes to the settings at the next tick, and a later + /// run finds it where the first left it. + #[gpui::test] + fn the_windows_place_is_kept_at_the_tick_and_found_by_the_next_run(cx: &mut TestAppContext) { + let dir = TempDir::new("window-place"); + let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); + let (app, _, _) = entity_over(cx, backend, Switches::default()); + app.read_with(cx, |app, _| assert_eq!(app.remembered_window(), None)); + app.update(cx, |app, _| app.window_moved(place())); + app.read_with(cx, |app, _| { + assert_eq!(app.backend().prefs.get(&UI_WINDOW), None, "not before the tick"); + }); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + app.read_with(cx, |app, _| { + assert_eq!(app.backend().prefs.get(&UI_WINDOW), Some(place())); + assert_eq!(app.remembered_window(), Some(place())); + }); + // The close keeps a place that moved after the last tick. + let moved = WindowState { x: Some(60), ..place() }; + app.update(cx, |app, cx| { + app.window_moved(moved); + app.shutdown(cx) + }); + drop(app); + cx.update(|_| {}); + + let again = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); + let (next, _, _) = entity_over(cx, again, Switches::default()); + next.read_with(cx, |app, _| assert_eq!(app.remembered_window(), Some(moved))); + } + + /// A window sized by a development switch, or showing the sample data, is + /// not the user's: what it reports is not kept. + #[gpui::test] + fn a_window_the_switches_made_does_not_overwrite_the_remembered_place(cx: &mut TestAppContext) { + for switches in [ + Switches { window: Some((1440.0, 960.0)), ..Switches::default() }, + Switches { demo_ui: true, ..Switches::default() }, + ] { + let (app, _, _) = entity_over(cx, Backend::in_memory().unwrap(), switches); + app.update(cx, |app, _| app.window_moved(place())); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + app.read_with(cx, |app, _| assert_eq!(app.backend().prefs.get(&UI_WINDOW), None)); + } + } } diff --git a/crates/voelin-gpui/src/backend.rs b/crates/voelin-gpui/src/backend.rs new file mode 100644 index 0000000..a3d3625 --- /dev/null +++ b/crates/voelin-gpui/src/backend.rs @@ -0,0 +1,317 @@ +//! What the window keeps besides the engine and the state, and opens at start +//! as the Slint front end's `run()` does (`crates/voelin-ui/src/app.rs`): the +//! client's database (the bookmarks, the identities, the chats' read marks), +//! the settings service on the same file, the secrets, and the identity a +//! connection is made with. The directory is the platform's data directory +//! (`voelin_platform::paths::data_dir`, which `VOELIN_DATA_DIR` overrides, so +//! that the two front ends share the store); everything below [`Backend::open`] +//! takes the directory, so that no test reaches the user's own. +//! +//! Left out against the Slint front end: importing the identities of the +//! official TeamSpeak clients at start (it reads the user's own files; the +//! slice with the identities page brings it), the crash reports and the +//! configuration of `--set` on the command line. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context as _, Result}; +use tracing::warn; +use tsclientlib::Identity; +use voelin_core::settings::{AUDIO, Settings}; +use voelin_core::{AudioSettings, Command, Engine, History}; +use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store}; +use voelin_ui_vm::servers::logic::CREATED_IDENTITY; +use voelin_ui_vm::settings::{ + CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_WINDOW, UiSettings, appearance_keys, page_keys, +}; + +/// The client's database, its settings and its secrets. +pub struct Backend { + /// The bookmarks, the identities and the chats' read marks. + pub store: Store, + /// The settings service, on the same file as the store (its own + /// connection); shared with the engine once [`Backend::attach`] ran. + pub prefs: Settings, + /// The servers' passwords. + pub secrets: Box, + /// The identity of a server whose bookmark names none that exists, and + /// the store has no default for. + identity: Identity, + /// The database file, for the engine's chat history. + database: Option, +} + +/// What the store and the settings hold at start, for the state. +#[derive(Debug)] +pub struct Loaded { + /// The saved servers, in the rail's order. + pub bookmarks: Vec, + /// The UI's own settings (the `ui` key). + pub settings: UiSettings, + /// The audio settings. + pub audio: AudioSettings, + /// The clients' local volumes. + pub playback: ClientPlaybackMap, +} + +/// The data directory of this process: `VOELIN_DATA_DIR`, else the platform's. +pub fn data_dir() -> PathBuf { + voelin_platform::paths::data_dir() +} + +/// The settings service on the client database in `dir`: the UI's keys +/// registered, then a config file (`VOELIN_CONFIG`, else `/config.toml` +/// if it exists) and `VOELIN_SETTING_*` variables below the stored values. +/// Without the database the settings live in memory. +fn open_settings(dir: &Path) -> 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); + 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())); + for e in errors { + warn!(%e, "setting ignored"); + } + prefs +} + +/// Make the keys this front end reads known to `prefs`. +fn register_keys(prefs: &Settings) { + prefs.register(&UI); + prefs.register(&CLIENT_PLAYBACK); + prefs.register(&UI_WINDOW); + for key in appearance_keys() { + prefs.register(key); + } + for key in page_keys() { + prefs.register(key); + } +} + +impl Backend { + /// Open the database in `dir` (created if need be), its settings and the + /// default identity (made, and kept, when the store has none). `secrets` + /// are where passwords go. + pub fn open(dir: &Path, secrets: Box) -> Result { + let database = dir.join("client.db"); + let store = Store::open(&database).context("failed to open the client database")?; + let prefs = open_settings(dir); + let identity = match store.default_identity()? { + Some(entry) => store.identity(entry.id)?, + None => { + let identity = Identity::create(); + store.add_identity(CREATED_IDENTITY, &identity, IdentityOrigin::Created)?; + identity + } + }; + Ok(Self { store, prefs, secrets, identity, database: Some(database) }) + } + + /// A backend that stores nothing and keeps its secrets in memory, with a + /// fresh identity: the tests', and the sample data's. + pub fn in_memory() -> Result { + let prefs = Settings::in_memory(); + register_keys(&prefs); + Ok(Self { + store: Store::open_in_memory()?, + prefs, + secrets: Box::new(MemorySecrets::default()), + identity: Identity::create(), + database: None, + }) + } + + /// What the store and the settings hold now. + pub fn load(&self) -> Loaded { + Loaded { + bookmarks: self.store.bookmarks().unwrap_or_else(|e| { + warn!(%e, "the bookmarks cannot be read"); + Vec::new() + }), + settings: (*self.prefs.get_arc(&UI)).clone(), + audio: self.prefs.get(&AUDIO), + playback: self.prefs.get(&CLIENT_PLAYBACK), + } + } + + /// Hand the engine what it keeps for the window: the chat history in the + /// same database (without it the engine keeps chats for this run only), + /// the settings service and the audio settings. + pub fn attach(&self, engine: &Engine) { + if let Some(database) = &self.database { + match History::open(database) { + Ok(history) => engine.send(Command::AttachHistory(history)), + Err(e) => warn!(%e, "chat history is not stored this time"), + } + } + engine.send(Command::AttachSettings(self.prefs.clone())); + engine.send(Command::SetAudioSettings(Box::new(self.prefs.get(&AUDIO)))); + } + + /// The identity a connection to the bookmark `bookmark` uses: its own if + /// it names one the store has, else the store's default, else the one made + /// at start. + pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity { + let entries = self.store.identities().unwrap_or_default(); + let id = bookmark + .and_then(|b| b.identity) + .filter(|id| entries.iter().any(|e| e.id == *id)) + .or_else(|| self.store.default_identity().ok().flatten().map(|e| e.id)); + id.and_then(|id| self.store.identity(id).ok()).unwrap_or_else(|| self.identity.clone()) + } + + /// 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(&self) -> String { + self.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. + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| "Voelin user".to_owned()) + } + + /// Write what the settings service holds to the database. + pub fn flush(&self) { + if let Err(e) = self.prefs.flush() { + warn!(%e, "could not store settings"); + } + } +} + +/// The secrets of this run: the OS keyring, and memory for what the keyring +/// refuses (no Secret Service on a headless Linux); the sample data's never +/// reach the keyring. +pub fn default_secrets(demo: bool) -> Box { + if demo { + Box::new(MemorySecrets::default()) + } else { + Box::new(FallbackSecrets { + keyring: voelin_store::KeyringSecrets::new("voelin"), + memory: MemorySecrets::default(), + }) + } +} + +/// The keyring first, memory when it cannot keep a secret (the Slint front +/// end's `FallbackSecrets`, repeated: both go into `voelin-store` when the +/// Slint front end is retired). +struct FallbackSecrets { + keyring: voelin_store::KeyringSecrets, + memory: MemorySecrets, +} + +impl Secrets for FallbackSecrets { + fn get(&self, key: &str) -> voelin_store::Result> { + match self.memory.get(key)? { + Some(v) => Ok(Some(v)), + None => Ok(self.keyring.get(key).unwrap_or(None)), + } + } + + fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> { + if let Err(error) = self.keyring.set(key, value) { + warn!(%error, "keyring unavailable, keeping the secret for this session only"); + return self.memory.set(key, value); + } + Ok(()) + } + + fn delete(&self, key: &str) -> voelin_store::Result<()> { + let _ = self.keyring.delete(key); + self.memory.delete(key) + } +} + +/// What the tests of this crate need to open a store of their own. +#[cfg(test)] +pub(crate) mod testing { + use std::path::PathBuf; + + /// A directory of its own under the temporary one (`TMPDIR`), removed with + /// the guard: no test reaches the user's data directory. + pub(crate) struct TempDir(pub PathBuf); + + impl TempDir { + /// An empty directory path named `name` and this process. + pub(crate) fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("voelin-gpui-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Self(dir) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } +} + +#[cfg(test)] +mod tests { + use voelin_ui_vm::settings::WindowState; + + use super::testing::TempDir; + use super::*; + + fn bookmark(name: &str, address: &str) -> Bookmark { + Bookmark { name: name.into(), address: address.into(), ..Default::default() } + } + + /// What a run leaves in the directory is what the next one starts from: the + /// bookmarks, the identity (the same one, not a new one) and the settings. + #[test] + fn a_second_start_finds_what_the_first_kept() { + let dir = TempDir::new("backend"); + let first = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); + assert_eq!(first.load().bookmarks, Vec::new(), "a new store has no servers"); + let id = first.store.add_bookmark(&bookmark("Nightfall", "ts.example")).unwrap(); + let uid = first.identity_for(None).key().to_pub().get_uid(); + let window = WindowState { width: 1000, height: 700, x: None, y: None, maximized: false }; + first.prefs.set(&UI_WINDOW, Some(window)).unwrap(); + first.flush(); + drop(first); + + let second = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); + let loaded = second.load(); + assert_eq!( + loaded.bookmarks.iter().map(|b| (b.id, b.name.as_str())).collect::>(), + [(id, "Nightfall")] + ); + assert_eq!(second.identity_for(None).key().to_pub().get_uid(), uid, "the identity is kept"); + assert_eq!(second.prefs.get(&UI_WINDOW), Some(window)); + assert!(dir.0.join("client.db").is_file(), "the database is in the directory given"); + } + + #[test] + fn a_server_names_its_identity_and_the_default_serves_the_rest() { + let backend = Backend::in_memory().unwrap(); + let (default, alt) = (Identity::create(), Identity::create()); + let uid = |identity: &Identity| identity.key().to_pub().get_uid(); + backend.store.add_identity("Default", &default, IdentityOrigin::Created).unwrap(); + let alt_id = backend.store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap(); + assert_eq!(uid(&backend.identity_for(None)), uid(&default), "the first is the default"); + let named = Bookmark { identity: Some(alt_id), ..bookmark("a", "a.test") }; + assert_eq!(uid(&backend.identity_for(Some(&named))), uid(&alt)); + let gone = Bookmark { identity: Some(alt_id + 100), ..bookmark("b", "b.test") }; + assert_eq!(uid(&backend.identity_for(Some(&gone))), uid(&default)); + } +} diff --git a/crates/voelin-gpui/src/dev.rs b/crates/voelin-gpui/src/dev.rs index 527bf0f..9d46f5c 100644 --- a/crates/voelin-gpui/src/dev.rs +++ b/crates/voelin-gpui/src/dev.rs @@ -7,10 +7,14 @@ //! components, the icons) in place of the shell. The Slint front end's //! other pages do not exist here yet; they are named in a warning and //! skipped. +//! - `VOELIN_DEMO_UI=1`: the Slint front end's sample servers, shown through +//! the app's own events; nothing is sent to the engine or kept in the store. //! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the -//! one the settings will give (`ui.theme` in the Slint front end). -//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`). -//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size. +//! one the settings give (`ui.theme`). +//! - `VOELIN_FONT_SCALE=1.25`: the text size factor, in place of the +//! settings' (`ui.font_scale`). +//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size, in place of the +//! remembered one (`ui.window`), which it then leaves alone. //! - `VOELIN_METER=1`: the cost meter, one log line a second //! ([`crate::meter`]). @@ -19,7 +23,7 @@ use crate::theme::Choice; /// A page the window can be opened on. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Page { - /// The shell. Today an empty window with the state line. + /// The desktop shell. Shell, /// Every theme token, a few components and the icons. Swatch, @@ -30,6 +34,8 @@ pub enum Page { pub struct Switches { /// The page to open on. pub open: Page, + /// Show the sample servers instead of the stored ones. + pub demo_ui: bool, /// The theme mode, when the switch names one. pub theme: Option, /// The text size factor, when the switch names one. @@ -42,7 +48,14 @@ pub struct Switches { impl Default for Switches { fn default() -> Self { - Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false } + Self { + open: Page::Shell, + demo_ui: false, + theme: None, + font_scale: None, + window: None, + meter: false, + } } } @@ -84,7 +97,9 @@ impl Switches { None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"), } } - switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0")); + let flag = |name: &str| get(name).is_some_and(|v| !matches!(v.trim(), "" | "0")); + switches.demo_ui = flag("VOELIN_DEMO_UI"); + switches.meter = flag("VOELIN_METER"); switches } } @@ -117,12 +132,14 @@ mod tests { fn every_switch_is_read() { let s = env(&[ ("VOELIN_OPEN", "swatch"), + ("VOELIN_DEMO_UI", "1"), ("VOELIN_DEV_THEME", "light"), ("VOELIN_FONT_SCALE", "1.25"), ("VOELIN_WINDOW_SIZE", "1440x960"), ("VOELIN_METER", "1"), ]); assert_eq!(s.open, Page::Swatch); + assert!(s.demo_ui); assert_eq!(s.theme, Some(Choice::Light)); assert_eq!(s.font_scale, Some(1.25)); assert_eq!(s.window, Some((1440.0, 960.0))); @@ -136,6 +153,7 @@ mod tests { ("VOELIN_DEV_THEME", "blue"), ("VOELIN_FONT_SCALE", "9"), ("VOELIN_WINDOW_SIZE", "10x10"), + ("VOELIN_DEMO_UI", "0"), ("VOELIN_METER", "0"), ]); assert_eq!(s, Switches::default()); diff --git a/crates/voelin-gpui/src/engine.rs b/crates/voelin-gpui/src/engine.rs index 9646555..6878f27 100644 --- a/crates/voelin-gpui/src/engine.rs +++ b/crates/voelin-gpui/src/engine.rs @@ -7,7 +7,8 @@ use tokio::runtime::{Handle, Runtime}; use tokio::sync::{broadcast, mpsc}; -use voelin_core::{Engine, Event}; +use voelin_core::settings::Settings; +use voelin_core::{Backends, Engine, Event, History}; /// An engine owned by the caller of [`crate::run`]. pub struct HostedEngine { @@ -24,7 +25,25 @@ pub struct HostedEngine { impl HostedEngine { /// A new engine on `runtime`, all of whose events go to the window. pub fn start(runtime: &Runtime) -> Self { - let engine = runtime.block_on(async { Engine::start() }); + Self::forward(runtime, runtime.block_on(async { Engine::start() })) + } + + /// A new engine on `runtime` that connects with `backends` only, and keeps + /// nothing (settings and chat history in memory): the tests' (with + /// [`Backends::empty`] a connect ends at once, saying that no connector + /// serves the address, and touches neither the network nor the sound + /// devices). + pub fn start_with_backends(runtime: &Runtime, backends: Backends) -> Self { + Self::forward( + runtime, + runtime.block_on(async { + Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends) + }), + ) + } + + /// Forward the events of `engine` into the channel the window reads. + fn forward(runtime: &Runtime, engine: Engine) -> Self { let (tx, events) = mpsc::unbounded_channel(); let mut rx = engine.subscribe(); runtime.spawn(async move { diff --git a/crates/voelin-gpui/src/lib.rs b/crates/voelin-gpui/src/lib.rs index 48b077b..c40fc38 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -7,6 +7,7 @@ pub mod app; pub mod assets; +pub mod backend; pub mod dev; pub mod engine; pub mod fonts; @@ -20,17 +21,27 @@ use std::rc::Rc; use std::time::Duration; use anyhow::{Context as _, Result}; -use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size}; +use gpui_kit::{ + App, AppContext as _, Bounds, TitlebarOptions, WindowBounds, WindowOptions, point, px, size, +}; use tracing_subscriber::{EnvFilter, fmt, prelude::*}; +use voelin_ui_vm::settings::WindowState; -use crate::app::AppState; +use crate::app::{AppState, Setup, appearance}; use crate::assets::Assets; +use crate::backend::Backend; use crate::dev::Switches; use crate::engine::HostedEngine; use crate::meter::Counters; -use crate::theme::{Choice, VoelinTheme}; +use crate::theme::VoelinTheme; use crate::view::MainView; +/// The smallest size the window can be given. +const MIN_SIZE: (f32, f32) = (640.0, 480.0); + +/// The size of a window that has no remembered one. +const DEFAULT_SIZE: (f32, f32) = (1280.0, 800.0); + /// How long the engine gets, after the window closed, to act on the /// `CloseSession` commands the close sent (the Slint front end waits as long): /// its tasks run on the runtime, and shutting the runtime down drops them. @@ -58,18 +69,48 @@ pub fn init_logging() { .try_init(); } -/// The main window's options: titled with the app's name, grouped by its id, -/// centred, 1280 by 800 unless `VOELIN_WINDOW_SIZE` says otherwise. -fn window_options(switches: &Switches, cx: &App) -> WindowOptions { - let (width, height) = switches.window.unwrap_or((1280.0, 800.0)); +/// Where the window opens: the size a development switch names, else the +/// remembered place if a screen still shows its corner (a monitor can have +/// gone since), else the middle of the screen at the default size. A place +/// that has no position (Wayland does not tell one) is the remembered size +/// in the middle. +fn window_bounds(switches: &Switches, remembered: Option, cx: &App) -> WindowBounds { + let sized = |(width, height): (f32, f32)| size(px(width), px(height)); + if let Some(forced) = switches.window { + return WindowBounds::centered(sized(forced), cx); + } + let Some(state) = remembered else { + return WindowBounds::centered(sized(DEFAULT_SIZE), cx); + }; + let remembered_size = + sized(((state.width as f32).max(MIN_SIZE.0), (state.height as f32).max(MIN_SIZE.1))); + let at = state.x.zip(state.y).map(|(x, y)| point(px(x as f32), px(y as f32))); + let bounds = match at { + Some(origin) + if cx.displays().iter().any(|display| { + display.bounds().intersects(&Bounds::new(origin, size(px(64.0), px(32.0)))) + }) => + { + Bounds::new(origin, remembered_size) + } + _ => Bounds::centered(None, remembered_size, cx), + }; + if state.maximized { WindowBounds::Maximized(bounds) } else { WindowBounds::Windowed(bounds) } +} + +/// The main window's options: titled with the app's name (and the server +/// shown), grouped by its id, opened where [`window_bounds`] says. +fn window_options( + switches: &Switches, + remembered: Option, + title: String, + cx: &App, +) -> WindowOptions { WindowOptions { - titlebar: Some(TitlebarOptions { - title: Some(voelin_platform::APP_NAME.into()), - ..Default::default() - }), + titlebar: Some(TitlebarOptions { title: Some(title.into()), ..Default::default() }), app_id: Some(voelin_platform::APP_ID.to_owned()), - window_min_size: Some(size(px(640.0), px(480.0))), - window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)), + window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))), + window_bounds: Some(window_bounds(switches, remembered, cx)), ..Default::default() } } @@ -81,6 +122,7 @@ fn open_main_window( cx: &mut App, switches: &Switches, engine: HostedEngine, + backend: Backend, counters: Counters, closed_sessions: Rc>, ) -> Result<()> { @@ -94,10 +136,19 @@ fn open_main_window( } let HostedEngine { engine, events, .. } = engine; let app = cx.new({ - let counters = counters.clone(); - move |cx| AppState::new(Some(engine), events, counters, cx) + let setup = Setup { + engine: Some(engine), + events, + counters: counters.clone(), + backend, + switches: switches.clone(), + }; + move |cx| AppState::new(setup, cx) }); - let options = window_options(switches, cx); + let options = { + let app = app.read(cx); + window_options(switches, app.remembered_window(), app.window_title(), cx) + }; let page = switches.open; gpui_kit::open_window(options, cx, { let app = app.clone(); @@ -108,7 +159,7 @@ fn open_main_window( window.on_window_should_close(cx, { let app = app.clone(); move |_, cx| { - closed_sessions.set(app.read(cx).shutdown()); + closed_sessions.set(app.update(cx, |app, cx| app.shutdown(cx))); cx.quit(); true } @@ -139,6 +190,13 @@ pub fn run() -> Result<()> { .build() .context("cannot start the engine's runtime")?; let hosted = HostedEngine::start(&runtime); + // The store and the settings, in the platform's data directory + // (`VOELIN_DATA_DIR` moves it: every run of this binary that is not the + // user's own sets it, and the XDG directories with it). + let backend = Backend::open(&backend::data_dir(), backend::default_secrets(switches.demo_ui)) + .context("cannot open the client's store")?; + backend.attach(&hosted.engine); + let (theme, font_scale) = appearance(&backend.prefs, &switches); let failure: Rc>> = Rc::default(); let closed_sessions: Rc> = Rc::default(); gpui_kit::application().with_assets(Assets).run({ @@ -147,15 +205,12 @@ pub fn run() -> Result<()> { move |cx| { gpui_kit::init(cx); fonts::load(cx); - // Until the settings are read here (the shell slice), the mode and - // the text size are the development switches' or the defaults. - VoelinTheme::init( - cx, - switches.theme.unwrap_or(Choice::System), - cx.window_appearance(), - switches.font_scale.unwrap_or(1.0), - ); - if let Err(e) = open_main_window(cx, &switches, hosted, counters, closed_sessions) { + // The mode and the text size are the settings', or a development + // switch's. + VoelinTheme::init(cx, theme, cx.window_appearance(), font_scale); + if let Err(e) = + open_main_window(cx, &switches, hosted, backend, counters, closed_sessions) + { *failure.borrow_mut() = Some(e); // Not `cx.quit()` here: GPUI's Linux platform runs this callback // before it starts its event loop, and the loop forgets a stop