diff --git a/CHANGELOG.md b/CHANGELOG.md index 4145942..f33b945 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,7 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows ### Added - `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a - window titled Voelin with one line of the app's state in it (the version, - the voice connections that are up, the engine events handled, the seconds - up), fed by the same engine and the same view models as the Slint app + window fed by the same engine and the same view models as the Slint app (`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour, radius, size and type token of the Slint app's `theme.slint`, light and dark (a test reads the Slint file and fails when the two differ), written into @@ -26,6 +24,16 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows stays the app; both run on one engine until the GPUI one reaches parity (docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders in software); no package ships it yet. +- The GPUI front end's desktop shell: the server rail, the top bar, the + sidebar and the main area, on the client's own database (the servers saved in + the Slint app are there, and the other way round). Add, edit, select and + remove a server, connect and disconnect voice, mute the microphone and the + sound, hold to talk and copy an invite link, as in the Slint app; the window's + title names the server on screen, and its size is kept for the next run + (setting `ui.window`). The channel tree, the chat and the other pages are the + next slices; the search and the settings buttons only log that. `VOELIN_DEMO_UI=1` + shows the Slint app's sample servers without sending or keeping anything + (docs/ui.md, "The desktop shell"). - Log files: each run logs to `/voelin/logs/voelin.log`, the previous four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced opens the folder. 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..003eed7 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,48 @@ 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, - started: Instant, + backend: Backend, + switches: Switches, + window: WindowKeeper, 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 +251,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 +274,47 @@ 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, - started: Instant::now(), + backend, + switches, + window: WindowKeeper { latest: None, saved }, 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 +322,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)] + pub(crate) 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. @@ -238,79 +535,442 @@ impl AppState { self.vm.sessions.values().filter(|view| view.state.voice == VoiceState::Connected).count() } - /// Seconds since the window opened. - pub fn uptime(&self) -> Duration { - self.started.elapsed() + /// 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 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. - pub fn state_line(&self) -> String { - let connections = self.connections(); - format!( - "{} {} · {} connection{} · {} engine event{} · {} s up", - 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, - ) + /// 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. 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 }); + /// 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.vm.sessions.len() + 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() } } #[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); - app.read_with(cx, |app, _| { - assert_eq!(app.connections(), 0); - assert!(app.state_line().contains("0 connections · 0 engine events")); - }); + app.read_with(cx, |app, _| assert_eq!((app.connections(), app.events_handled), (0, 0))); tx.send(voice(VoiceState::Connected)).unwrap(); cx.run_until_parked(); @@ -318,11 +978,6 @@ mod tests { assert_eq!(app.events_handled, 1); assert_eq!(app.connections(), 1); assert_eq!(app.vm.status, "Connected", "the transition's status line"); - assert!( - app.state_line().contains("1 connection · 1 engine event"), - "{}", - app.state_line() - ); }); assert_eq!(counters.engine_events.get(), 1); assert_eq!(counters.connections.get(), 1); @@ -337,19 +992,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 +1036,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 +1080,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 +1102,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 +1121,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 +1141,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/assets.rs b/crates/voelin-gpui/src/assets.rs index 9eb69bb..86f5170 100644 --- a/crates/voelin-gpui/src/assets.rs +++ b/crates/voelin-gpui/src/assets.rs @@ -25,11 +25,17 @@ pub fn client_icon_names() -> impl Iterator { ICONS.iter().map(|(name, _)| *name) } +/// The app's mark, the Slint front end's `logo.svg`. +const LOGO: &[u8] = include_bytes!("../../voelin-ui/ui/assets/logo.svg"); + impl AssetSource for Assets { fn load(&self, path: &str) -> Result>> { if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) { return Ok(Some(Cow::Borrowed(bytes))); } + if path == "logo.svg" { + return Ok(Some(Cow::Borrowed(LOGO))); + } gpui_kit::assets::AllAssets.load(path) } 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..f3e45ea 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -7,10 +7,12 @@ pub mod app; pub mod assets; +pub mod backend; pub mod dev; pub mod engine; pub mod fonts; pub mod meter; +pub mod shell; pub mod swatch; pub mod theme; pub mod view; @@ -20,17 +22,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 +70,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 +123,7 @@ fn open_main_window( cx: &mut App, switches: &Switches, engine: HostedEngine, + backend: Backend, counters: Counters, closed_sessions: Rc>, ) -> Result<()> { @@ -94,10 +137,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 +160,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 } @@ -120,6 +172,14 @@ fn open_main_window( Ok(()) } +/// Wait `grace` on `runtime`, so that the engine's tasks run (they send the +/// closes of the sessions) before the runtime drops them. The sleep is made +/// inside the runtime: a `Sleep` made outside it, as an argument of +/// `block_on`, panics ("there is no reactor running"). +fn give_the_engine_time(runtime: &tokio::runtime::Runtime, grace: Duration) { + runtime.block_on(async move { tokio::time::sleep(grace).await }); +} + /// Run the app on the current thread until its window closes. pub fn run() -> Result<()> { init_logging(); @@ -139,6 +199,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 +214,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 @@ -172,7 +236,7 @@ pub fn run() -> Result<()> { // on the servers until they time out. Any other way to end the app that // the slices add must call `AppState::shutdown` too. if closed_sessions.get() > 0 { - runtime.block_on(tokio::time::sleep(CLOSE_GRACE)); + give_the_engine_time(&runtime, CLOSE_GRACE); } runtime.shutdown_timeout(Duration::from_secs(2)); match failure.take() { @@ -180,3 +244,21 @@ pub fn run() -> Result<()> { None => Ok(()), } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The grace after a close with open sessions is a wait on the engine's + /// runtime from the GPUI thread, which is no runtime thread: it must not + /// panic, and it must wait. (The first end-to-end close against a server, + /// the first slice that opens a session, found the panic.) + #[test] + fn the_close_grace_waits_on_the_runtime_from_a_thread_that_is_none() { + let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap(); + let started = std::time::Instant::now(); + give_the_engine_time(&runtime, Duration::from_millis(30)); + assert!(started.elapsed() >= Duration::from_millis(30)); + runtime.shutdown_timeout(Duration::from_secs(2)); + } +} diff --git a/crates/voelin-gpui/src/shell/actions.rs b/crates/voelin-gpui/src/shell/actions.rs new file mode 100644 index 0000000..243e153 --- /dev/null +++ b/crates/voelin-gpui/src/shell/actions.rs @@ -0,0 +1,88 @@ +//! What the user can ask of the shell, as GPUI actions: the callbacks of the +//! Slint front end's `bind/servers.rs` that the desktop shell has (the first +//! eleven below), and the shell's own affordances. A click dispatches the +//! action ([`gpui_kit::Window::dispatch_action`]), the window's root view +//! ([`crate::view::MainView`]) handles it, and the handler asks the root state +//! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings +//! and menus come to the same handlers later. +//! +//! The callbacks of `bind/servers.rs` that are not here belong to the slices +//! after this one: `search_members`, `show_voice_view`, `join_channel`, +//! `join_with_password`, `toggle_collapse`, `open_client` and +//! `client_audio_changed` to the channel tree and the voice page, and `copied` +//! (the toast that follows a copy) to whichever copies: [`Invite`] sets it +//! itself. + +use gpui_kit::{Action, actions}; + +actions!( + voelin, + [ + /// `connect_voice`: connect the server on screen with voice, into its default channel. + ConnectVoice, + /// `disconnect_voice`: leave voice on the server on screen. + DisconnectVoice, + /// `invite`: copy a link to the voice channel we are in. + Invite, + /// `save_bookmark`: save the server form (the form's own Save button). + SaveServer, + /// `save_and_connect`: save the server form, then connect. + SaveAndConnect, + /// Open the empty server form (the rail's plus button). + AddServer, + /// Close the server form without saving. + CancelServerForm, + /// The top bar's search box: the search comes with its slice, today it is logged. + OpenSearch, + /// The settings buttons: the settings come with their slice, today it is logged. + OpenSettings, + ] +); + +/// `select_server`: show a server (and observe it). +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SelectServer { + /// The bookmark's id. + pub id: i64, +} + +/// `edit_bookmark`: open the server form with a saved server. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct EditServer { + /// The bookmark's id. + pub id: i64, +} + +/// `delete_bookmark`: remove a server. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct DeleteServer { + /// The bookmark's id. + pub id: i64, +} + +/// `set_input_muted`: mute or unmute our microphone. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SetInputMuted { + /// Muted from now on. + pub muted: bool, +} + +/// `set_output_muted`: mute or unmute the sound. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SetOutputMuted { + /// Muted from now on. + pub muted: bool, +} + +/// `push_to_talk`: transmit while the hold-to-talk button is held. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct PushToTalk { + /// Transmitting from now on. + pub on: bool, +} diff --git a/crates/voelin-gpui/src/shell/form.rs b/crates/voelin-gpui/src/shell/form.rs new file mode 100644 index 0000000..116fad3 --- /dev/null +++ b/crates/voelin-gpui/src/shell/form.rs @@ -0,0 +1,211 @@ +//! The server form: where a server is added or edited (the server dialog of +//! the Slint front end, `bookmark_form` / `save_bookmark` / +//! `save_and_connect` / `delete_bookmark` of `bind/servers.rs`). The dialogs +//! come with their slice; until then the form takes the place of the main +//! area, with gpui-component's text inputs: the address (the only thing a +//! server needs), a name (empty: the server's own), the nickname and the +//! server's password. + +use gpui_kit::component::button::{Button, ButtonVariants as _}; +use gpui_kit::component::input::{Input, InputEvent, InputState}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + App, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, + ParentElement as _, Render, SharedString, Styled as _, Window, div, px, +}; +use voelin_ui_vm::bridge::BookmarkForm; + +use super::actions::{CancelServerForm, DeleteServer, SaveAndConnect, SaveServer}; +use super::widgets::{panel, tagged}; +use crate::theme::{VoelinTheme, hsla}; + +/// The form. +pub struct ServerForm { + id: i64, + connected: bool, + address: Entity, + name: Entity, + nickname: Entity, + password: Entity, + confirm_remove: bool, +} + +impl ServerForm { + /// A form filled in with `form` (id -1: a new server). The address has the + /// focus; Enter in any field saves. + pub fn new(form: &BookmarkForm, window: &mut Window, cx: &mut Context) -> Self { + let field = |window: &mut Window, + cx: &mut Context, + placeholder: &str, + value: &str, + masked: bool| { + let input = cx.new(|cx| { + InputState::new(window, cx) + .placeholder(SharedString::from(placeholder.to_owned())) + .default_value(SharedString::from(value.to_owned())) + .masked(masked) + }); + cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + window.dispatch_action(Box::new(SaveServer), cx); + } + }) + .detach(); + input + }; + let address = + field(window, cx, "ts.example.com or ts.example.com:9987", &form.address, false); + let name = field(window, cx, "Optional: the server tells its own", &form.name, false); + let nickname = field(window, cx, "The name others see", &form.nickname, false); + let password = field(window, cx, "Optional", &form.server_password, true); + address.update(cx, |input, cx| input.focus(window, cx)); + Self { + id: i64::from(form.id), + connected: form.connected, + address, + name, + nickname, + password, + confirm_remove: false, + } + } + + /// The bookmark this form edits; -1 for a new server. + pub fn id(&self) -> i64 { + self.id + } + + /// The form as the fields hold it now, for `AppState::save_bookmark`. + pub fn to_form(&self, cx: &App) -> BookmarkForm { + let text = |input: &Entity| input.read(cx).value().to_string(); + BookmarkForm { + id: self.id as i32, + name: text(&self.name).into(), + address: text(&self.address).into(), + nickname: text(&self.nickname).into(), + server_password: text(&self.password).into(), + connected: self.connected, + ..Default::default() + } + } + + /// Put `text` in the address field (a link that fills the form comes with + /// its slice; the tests type here). + pub fn set_address(&self, text: &str, window: &mut Window, cx: &mut App) { + self.address.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx)); + } +} + +fn labelled( + theme: &VoelinTheme, + label: &'static str, + input: &Entity, +) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .flex() + .flex_col() + .gap(px(m.space_2)) + .child( + div() + .text_size(px(m.font_sm)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(c.text_secondary)) + .child(label), + ) + .child(Input::new(input)) +} + +impl Render for ServerForm { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + let new = self.id < 0; + let id = self.id; + let confirm = self.confirm_remove; + panel(&theme) + .id("server-form") + .debug_selector(|| "server-form".into()) + .flex_1() + .min_w_0() + .h_full() + .items_center() + .justify_center() + .child( + div() + .w_full() + .max_w(px(440.0)) + .flex() + .flex_col() + .gap(px(m.space_4)) + .p(px(m.space_5)) + .child( + div() + .text_size(px(m.font_xl)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(if new { "Add a server" } else { "Edit the server" }), + ) + .child(labelled(&theme, "Address", &self.address)) + .child(labelled(&theme, "Name", &self.name)) + .child(labelled(&theme, "Nickname", &self.nickname)) + .child(labelled(&theme, "Server password", &self.password)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child(tagged( + "form-save", + Button::new("form-save").primary().label("Save").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(SaveServer), cx) + }, + ), + )) + .when(!self.connected, |row| { + row.child(tagged( + "form-connect", + Button::new("form-connect").label("Save and connect").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(SaveAndConnect), cx) + }, + ), + )) + }) + .child(tagged( + "form-cancel", + Button::new("form-cancel").ghost().label("Cancel").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(CancelServerForm), cx) + }, + ), + )) + .when(!new, |row| { + row.child(div().flex_1()).child(tagged( + "form-remove", + Button::new("form-remove") + .danger() + .label(if confirm { + "Click again to remove" + } else { + "Remove" + }) + .on_click(cx.listener(move |this, _, window, cx| { + if this.confirm_remove { + window.dispatch_action( + Box::new(DeleteServer { id }), + cx, + ); + } else { + this.confirm_remove = true; + cx.notify(); + } + })), + )) + }), + ), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/main_panel.rs b/crates/voelin-gpui/src/shell/main_panel.rs new file mode 100644 index 0000000..0d84c59 --- /dev/null +++ b/crates/voelin-gpui/src/shell/main_panel.rs @@ -0,0 +1,217 @@ +//! The main area. Until the chat, the voice page and the rest come, it is the +//! empty page: the "no server selected" state with the way to add one, and for +//! a server on screen its name, address and state with the buttons that +//! connect, disconnect and edit it. An entity of its own: it observes the root +//! state and draws again only when what it shows changed. + +use gpui_kit::component::button::{Button, ButtonVariants as _}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render, + Styled as _, Subscription, Window, div, px, +}; +use voelin_ui_vm::bridge::ServerItem; +use voelin_ui_vm::servers::logic; + +use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer}; +use super::widgets::{Avatar, Presence, icon, panel, tagged}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// What the main area shows. +#[derive(Clone, Debug, PartialEq)] +pub enum MainState { + /// No server is on screen. + NoServer, + /// A server is. + Server(ServerItem), +} + +impl MainState { + /// The main area for the state. + pub fn of(app: &AppState) -> Self { + let current = app.vm.current; + logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)) + .into_iter() + .find(|item| Some(i64::from(item.id)) == current) + .map_or(Self::NoServer, Self::Server) + } +} + +/// The words for a server's state. +fn state_words(status: &str) -> &'static str { + match status { + "connected" => "Connected with voice", + "connecting" => "Connecting…", + "observing" => "Observed without joining", + _ => "Not connected", + } +} + +/// The main area. +pub struct MainPanel { + state: MainState, + _subscription: Subscription, +} + +impl MainPanel { + /// A main area that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let state = MainState::of(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let state = MainState::of(app.read(cx)); + if state != this.state { + this.state = state; + cx.notify(); + } + }); + Self { state, _subscription: subscription } + } + + /// What it shows now. + pub fn state(&self) -> &MainState { + &self.state + } +} + +impl Render for MainPanel { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + let body = match &self.state { + MainState::NoServer => div() + .id("main-empty") + .debug_selector(|| "main-empty".into()) + .flex() + .flex_col() + .items_center() + .gap(px(m.space_4)) + .child( + div() + .size(px(72.0)) + .rounded(px(m.radius_xl)) + .bg(hsla(c.surface_2)) + .border_1() + .border_color(hsla(c.border)) + .flex() + .items_center() + .justify_center() + .child(icon("server", 32.0, c.text_muted)), + ) + .child( + div() + .text_size(px(m.font_xl)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child("No server selected"), + ) + .child( + div() + .max_w(px(360.0)) + .text_center() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_muted)) + .child("Pick a server in the list, or add one to start talking."), + ) + .child(tagged( + "main-add", + Button::new("main-add") + .primary() + .label("Add a server") + .on_click(|_, window, cx| window.dispatch_action(Box::new(AddServer), cx)), + )), + MainState::Server(item) => { + let id = i64::from(item.id); + let connected = item.status.as_ref() == "connected"; + let connecting = item.status.as_ref() == "connecting"; + div() + .id("main-server") + .debug_selector(|| "main-server".into()) + .flex() + .flex_col() + .items_center() + .gap(px(m.space_4)) + .child( + Avatar::new("main-server-avatar", 72.0, &item.initials, item.tint) + .image(item.icon.clone()) + .square() + .presence(Presence::of_server(&item.status)), + ) + .child( + div() + .max_w(px(480.0)) + .truncate() + .text_size(px(m.font_2xl)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(item.name.to_string()), + ) + .child( + div() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_secondary)) + .child(item.address.to_string()), + ) + .child( + div() + .id("main-server-state") + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_muted)) + .child(state_words(&item.status)), + ) + .child( + div() + .max_w(px(360.0)) + .text_center() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_muted)) + .child("Its channels and its chat come with the next slices."), + ) + .child( + div() + .flex() + .flex_row() + .gap(px(m.space_3)) + .when(connected || connecting, |row| { + row.child(tagged( + "main-disconnect", + Button::new("main-disconnect") + .danger() + .label("Disconnect") + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(DisconnectVoice), cx); + }), + )) + }) + .when(!connected && !connecting, |row| { + row.child(tagged( + "main-connect", + Button::new("main-connect") + .primary() + .label("Connect") + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(ConnectVoice), cx); + }), + )) + }) + .child(tagged( + "main-edit", + Button::new("main-edit").label("Edit").on_click( + move |_, window, cx| { + window.dispatch_action(Box::new(EditServer { id }), cx); + }, + ), + )), + ) + } + }; + panel(&theme) + .id("main") + .flex_1() + .min_w_0() + .h_full() + .items_center() + .justify_center() + .child(body) + } +} diff --git a/crates/voelin-gpui/src/shell/mod.rs b/crates/voelin-gpui/src/shell/mod.rs new file mode 100644 index 0000000..5ebc4bd --- /dev/null +++ b/crates/voelin-gpui/src/shell/mod.rs @@ -0,0 +1,22 @@ +//! The desktop shell of the GPUI front end (`ui/shells/desktop.slint` and +//! the server callbacks of `bind/servers.rs`): the server rail, the top bar, +//! the sidebar, the main area, the server form and the toast, each an entity +//! that observes the root state ([`crate::app::AppState`]) and draws again +//! only when what it shows changed, and the actions the user's moves are +//! ([`actions`]). [`crate::view::MainView`] puts them in the window. + +pub mod actions; +mod form; +mod main_panel; +mod rail; +mod sidebar; +mod toast; +mod topbar; +pub mod widgets; + +pub use form::ServerForm; +pub use main_panel::{MainPanel, MainState}; +pub use rail::{RailView, ServerRail}; +pub use sidebar::{Sidebar, SidebarView}; +pub use toast::{TOAST_TIME, Toast}; +pub use topbar::TopBar; diff --git a/crates/voelin-gpui/src/shell/rail.rs b/crates/voelin-gpui/src/shell/rail.rs new file mode 100644 index 0000000..dea9a2b --- /dev/null +++ b/crates/voelin-gpui/src/shell/rail.rs @@ -0,0 +1,242 @@ +//! The server rail: the saved servers as avatars with their state, the +//! selection, the add-server button and the settings button (`ServerRail` of +//! `ui/shells/desktop.slint`). An entity of its own: it observes the root +//! state and draws again only when the servers it lists changed. + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render, + StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px, +}; +use voelin_ui_vm::bridge::ServerItem; +use voelin_ui_vm::servers::logic; + +use super::actions::{AddServer, EditServer, OpenSettings, SelectServer}; +use super::widgets::{Avatar, IconButton, Presence}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// What the rail shows: the servers in order, and which is on screen. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RailView { + /// The saved servers, as `voelin_ui_vm::servers::logic::rail` has them. + pub servers: Vec, + /// The bookmark on screen. + pub current: Option, +} + +impl RailView { + /// The rail for the state. + pub fn of(app: &AppState) -> Self { + Self { + servers: logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)), + current: app.vm.current, + } + } +} + +/// The rail. +pub struct ServerRail { + view: RailView, + _subscription: Subscription, +} + +impl ServerRail { + /// A rail that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let view = RailView::of(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let view = RailView::of(app.read(cx)); + if view != this.view { + this.view = view; + cx.notify(); + } + }); + Self { view, _subscription: subscription } + } + + /// What it shows now. + pub fn view(&self) -> &RailView { + &self.view + } +} + +/// One server of the rail: the selection pill, the ring of the one on screen, +/// the avatar with its state, the unread count and the live mark. +fn server(theme: &VoelinTheme, item: &ServerItem, selected: bool) -> impl IntoElement + use<> { + let (c, m) = (&theme.colors, &theme.metrics); + let id = i64::from(item.id); + let group = format!("rail-server-{id}"); + let name = item.name.to_string(); + let tooltip = format!("{name}\n{}", item.address); + let pill = div() + .absolute() + .left(px(0.0)) + .w(px(4.0)) + .h(px(if selected { 36.0 } else { 0.0 })) + .rounded(px(2.0)) + .bg(hsla(c.text)) + .when(!selected, |pill| { + let group = group.clone(); + pill.group_hover(group, |style| style.h(px(18.0))) + }); + div() + .id(("rail-server", id as u64)) + .group(group) + .relative() + .w_full() + .h(px(56.0)) + .flex_none() + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .debug_selector(|| format!("rail-server-{id}")) + .tooltip(move |window, cx| { + gpui_kit::component::tooltip::Tooltip::new(tooltip.clone()).build(window, cx) + }) + .on_click(move |event, window, cx| { + // A second click on the server is the Slint rail's double click. + if event.click_count() >= 2 { + window.dispatch_action(Box::new(EditServer { id }), cx); + } else { + window.dispatch_action(Box::new(SelectServer { id }), cx); + } + }) + .child(pill) + .when(selected, |row| { + row.child( + div() + .absolute() + .size(px(52.0)) + .rounded(px(m.radius_lg + 2.0)) + .border_2() + .border_color(hsla(c.accent)) + .bg(hsla(c.glow.with_alpha(0x66))), + ) + }) + .child( + Avatar::new(("rail-avatar", id as u64), 46.0, &item.initials, item.tint) + .image(item.icon.clone()) + .square() + .presence(Presence::of_server(&item.status)), + ) + .when(item.unread > 0, |row| { + row.child( + div() + .absolute() + .top(px(0.0)) + .left(px(50.0)) + .min_w(px(18.0)) + .h(px(18.0)) + .px(px(5.0)) + .rounded(px(9.0)) + .bg(hsla(c.live)) + .border_2() + .border_color(hsla(c.bg_rail)) + .flex() + .items_center() + .justify_center() + .text_size(px(m.font_xs)) + .font_weight(FontWeight::BOLD) + .text_color(hsla(c.on_accent)) + .child(item.unread.to_string()), + ) + }) + .when(item.live && item.unread == 0, |row| { + row.child( + div() + .absolute() + .top(px(4.0)) + .left(px(52.0)) + .size(px(12.0)) + .rounded(px(6.0)) + .bg(hsla(c.live)) + .border_2() + .border_color(hsla(c.bg_rail)), + ) + }) +} + +impl Render for ServerRail { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + let current = self.view.current; + let servers: Vec<_> = self + .view + .servers + .iter() + .map(|item| server(&theme, item, current == Some(i64::from(item.id)))) + .collect(); + div() + .id("rail") + .w(px(m.rail_width)) + .h_full() + .flex_none() + .flex() + .flex_col() + .items_center() + .py(px(m.space_3)) + .gap(px(m.space_2)) + .bg(hsla(c.bg_rail.with_alpha(230))) + .border_r_1() + .border_color(hsla(c.border)) + // The app's mark. (Home, which the Slint rail opens from it, comes + // with its slice.) + .child( + div() + .size(px(48.0)) + .flex_none() + .rounded(px(m.radius_lg)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface_2)) + .flex() + .items_center() + .justify_center() + .child(gpui_kit::img("logo.svg").size(px(30.0))), + ) + .child( + div() + .w(px(32.0)) + .h(px(2.0)) + .my(px(m.space_2)) + .rounded(px(1.0)) + .bg(hsla(c.border_strong)), + ) + .child( + div() + .id("rail-servers") + .flex_1() + .min_h_0() + .w_full() + .overflow_y_scroll() + .flex() + .flex_col() + .items_center() + .gap(px(m.space_2)) + .children(servers) + .child( + div().pt(px(m.space_2)).child( + IconButton::new("rail-add", "plus", "Add a server") + .size(46.0) + .round() + .filled() + .tint(c.success) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(AddServer), cx); + }), + ), + ), + ) + .child( + IconButton::new("rail-settings", "settings", "Settings") + .size(46.0) + .round() + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(OpenSettings), cx); + }), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/sidebar.rs b/crates/voelin-gpui/src/shell/sidebar.rs new file mode 100644 index 0000000..269c32f --- /dev/null +++ b/crates/voelin-gpui/src/shell/sidebar.rs @@ -0,0 +1,422 @@ +//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of +//! `shells/common.slint`): the server on screen, the place of its channel tree +//! (the next slice), the voice card while voice is connecting or connected, and +//! the user's own card with the voice buttons. An entity of its own: it +//! observes the root state and draws again only when what it shows changed. + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent, + ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, Subscription, Window, + div, px, +}; +use voelin_core::TransmitMode; +use voelin_ui_vm::Rgb; +use voelin_ui_vm::bridge::ServerItem; +use voelin_ui_vm::image::ImageRef; +use voelin_ui_vm::servers::logic; + +use super::actions::{ + DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted, +}; +use super::widgets::{Avatar, IconButton, Presence, card, icon, panel}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// What the sidebar shows. +#[derive(Clone, Debug, PartialEq)] +pub struct SidebarView { + /// The server on screen, as the rail has it. + pub server: Option, + /// "9 online · 7 channels" once its presence is known, else empty. + pub stats: String, + /// Our nickname there; empty without a server. + pub nickname: String, + /// The channel we are in; empty while connecting. + pub own_channel: String, + /// Our picture on the server. + pub own_avatar: ImageRef, + /// Voice is connected. + pub voice_connected: bool, + /// Voice is connecting. + pub voice_connecting: bool, + /// The server is observed. + pub observing: bool, + /// Our microphone is muted. + pub input_muted: bool, + /// Our sound is muted. + pub output_muted: bool, + /// Voice goes out. + pub transmitting: bool, + /// The transmit mode is push-to-talk, so the card has a hold-to-talk button. + pub hold_to_talk: bool, +} + +impl SidebarView { + /// The sidebar for the state. + pub fn of(app: &AppState) -> Self { + let card = logic::toolbar(&app.vm, |bookmark| app.server_icon(bookmark)); + let server = app.vm.current.and_then(|id| { + logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)) + .into_iter() + .find(|item| i64::from(item.id) == id) + }); + Self { + server, + stats: card.server_stats, + nickname: card.nickname, + own_channel: card.own_channel, + own_avatar: card.own_avatar, + voice_connected: card.voice_connected, + voice_connecting: card.voice_connecting, + observing: card.observing, + input_muted: card.input_muted, + output_muted: card.output_muted, + transmitting: card.transmitting, + hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk, + } + } +} + +/// The sidebar. +pub struct Sidebar { + view: SidebarView, + /// The hold-to-talk button is held down. + holding: bool, + _subscription: Subscription, +} + +impl Sidebar { + /// A sidebar that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let view = SidebarView::of(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let view = SidebarView::of(app.read(cx)); + if view != this.view { + this.view = view; + cx.notify(); + } + }); + Self { view, holding: false, _subscription: subscription } + } + + /// What it shows now. + pub fn view(&self) -> &SidebarView { + &self.view + } + + /// The hold-to-talk button was released, if it was held. + fn let_go(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context) { + if std::mem::take(&mut self.holding) { + window.dispatch_action(Box::new(PushToTalk { on: false }), cx); + } + } +} + +/// The server's name, its icon and how many are there. +fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let stats = if view.stats.is_empty() { item.address.to_string() } else { view.stats.clone() }; + card(theme, 0xff) + .id("sidebar-server") + .debug_selector(|| "sidebar-server".into()) + .p(px(m.space_3)) + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child( + Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint) + .image(item.icon.clone()) + .square(), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .truncate() + .text_size(px(m.font_lg)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(item.name.to_string()), + ) + .child( + div() + .truncate() + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_muted)) + .child(stats), + ), + ) +} + +/// Where the channel tree goes: the next slice. +fn channels(theme: &VoelinTheme, has_server: bool) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .id("sidebar-channels") + .flex_1() + .min_h_0() + .flex() + .flex_col() + .gap(px(m.space_2)) + .px(px(m.space_2)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .text_size(px(m.font_xs)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text_secondary)) + .child(icon("volume-2", m.icon_sm, c.text_secondary)) + .child("Channels"), + ) + .child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(if has_server { + "The channel tree comes with the next slice." + } else { + "Add a server to see its channels." + })) +} + +/// "Voice Connected" and our channel, disconnect and hold to talk. +fn voice_card( + theme: &VoelinTheme, + view: &SidebarView, + cx: &mut Context, +) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let (dot, words) = if view.voice_connected { + (c.success, "Voice Connected") + } else { + (c.warning, "Connecting…") + }; + let talking = view.transmitting; + card(theme, 0xff) + .id("sidebar-voice") + .debug_selector(|| "sidebar-voice".into()) + .p(px(m.space_3)) + .flex() + .flex_col() + .gap(px(m.space_3)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child(div().size(px(10.0)).flex_none().rounded(px(5.0)).bg(hsla(dot))) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .text_size(px(m.font_sm)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(dot)) + .child(words), + ) + .when(!view.own_channel.is_empty(), |column| { + column.child( + div() + .truncate() + .text_size(px(m.font_xs)) + .text_color(hsla(c.text_muted)) + .child(view.own_channel.clone()), + ) + }), + ) + .when(view.voice_connected && !view.own_channel.is_empty(), |row| { + row.child( + IconButton::new("voice-invite", "link", "Copy an invite to this channel") + .size(32.0) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(Invite), cx); + }), + ) + }) + .child( + IconButton::new("voice-disconnect", "phone-off", "Disconnect") + .size(32.0) + .tint(c.danger) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(DisconnectVoice), cx); + }), + ), + ) + .when(view.voice_connected && view.hold_to_talk, |card| { + card.child( + div() + .id("hold-to-talk") + .debug_selector(|| "hold-to-talk".into()) + .h(px(m.control_height)) + .flex() + .flex_row() + .items_center() + .justify_center() + .gap(px(m.space_2)) + .rounded(px(m.radius_md)) + .border_1() + .border_color(hsla(if talking { c.success } else { c.border })) + .bg(hsla(if talking { c.success.with_alpha(0xcc) } else { c.surface_2 })) + .cursor_pointer() + .hover(move |style| { + style.bg(hsla(if talking { c.success } else { c.surface_3 })) + }) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, window, cx| { + this.holding = true; + window.dispatch_action(Box::new(PushToTalk { on: true }), cx); + }), + ) + // Let go on the button or off it: the end of what was started. + .on_mouse_up(MouseButton::Left, cx.listener(Sidebar::let_go)) + .on_mouse_up_out(MouseButton::Left, cx.listener(Sidebar::let_go)) + .child(icon( + "mic", + m.icon_sm, + if talking { c.on_accent } else { c.text_secondary }, + )) + .child( + div() + .text_size(px(m.font_sm)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(if talking { c.on_accent } else { c.text_secondary })) + .child(if talking { "Talking…" } else { "Hold to talk" }), + ), + ) + }) +} + +/// Who we are, and the buttons for the microphone and the sound. +fn user_card(theme: &VoelinTheme, view: &SidebarView) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let (words, presence) = if view.voice_connected { + ("Online", Presence::Online) + } else if view.observing { + ("Observing", Presence::Info) + } else { + ("Offline", Presence::Offline) + }; + let name = if view.nickname.is_empty() { + voelin_platform::APP_NAME.to_owned() + } else { + view.nickname.clone() + }; + let (input_muted, output_muted) = (view.input_muted, view.output_muted); + card(theme, 0xb3) + .id("sidebar-user") + .debug_selector(|| "sidebar-user".into()) + .min_h(px(60.0)) + .p(px(m.space_2)) + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .child( + div() + .id("sidebar-profile") + .flex_1() + .min_w_0() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .px(px(m.space_2)) + .py(px(m.space_2)) + .rounded(px(m.radius_md)) + .cursor_pointer() + .hover(|style| style.bg(hsla(c.surface_3))) + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)) + .child( + Avatar::new("sidebar-own-avatar", 38.0, &name_initials(&name), Rgb(0x2d6bff)) + .image(view.own_avatar.clone()) + .presence(presence) + .speaking(view.transmitting), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .truncate() + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(name), + ) + .child( + div() + .truncate() + .text_size(px(m.font_xs)) + .text_color(hsla(c.text_muted)) + .child(words), + ), + ), + ) + .child( + IconButton::new( + "user-mic", + if input_muted { "mic-off" } else { "mic" }, + if input_muted { "Microphone off" } else { "Microphone on" }, + ) + .danger() + .checked(input_muted) + .enabled(view.voice_connected) + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx); + }), + ) + .child( + IconButton::new( + "user-sound", + if output_muted { "headphone-off" } else { "headphones" }, + if output_muted { "Sound off" } else { "Sound on" }, + ) + .danger() + .checked(output_muted) + .enabled(view.voice_connected) + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx); + }), + ) +} + +/// The initials of a nickname, for the avatar. +fn name_initials(name: &str) -> String { + voelin_ui_vm::avatar::initials(name) +} + +impl Render for Sidebar { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let m = &theme.metrics; + let view = &self.view; + panel(&theme) + .id("sidebar") + .w(px(m.sidebar_width)) + .h_full() + .flex_none() + .p(px(m.space_3)) + .gap(px(m.space_3)) + .when_some(view.server.as_ref(), |sidebar, item| { + sidebar.child(server_card(&theme, view, item)) + }) + .child(channels(&theme, view.server.is_some())) + .when(view.voice_connected || view.voice_connecting, |sidebar| { + sidebar.child(voice_card(&theme, view, cx)) + }) + .child(user_card(&theme, view)) + } +} diff --git a/crates/voelin-gpui/src/shell/toast.rs b/crates/voelin-gpui/src/shell/toast.rs new file mode 100644 index 0000000..1e30392 --- /dev/null +++ b/crates/voelin-gpui/src/shell/toast.rs @@ -0,0 +1,88 @@ +//! The status line as a toast: what the last move did ("Connecting to +//! ts.example…", why a server was not saved), shown at the bottom of the +//! window for a few seconds. It watches the root state's status line and its +//! generation, so that the same words said twice are two toasts. + +use std::time::Duration; + +use gpui_kit::{ + Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _, + Subscription, Window, div, px, +}; + +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// How long a toast stays. +pub const TOAST_TIME: Duration = Duration::from_secs(5); + +/// The toast. +pub struct Toast { + text: String, + generation: u64, + _subscription: Subscription, +} + +impl Toast { + /// A toast that follows `app`'s status line from now on (what it said + /// before is not shown). + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let generation = app.read(cx).status_generation; + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let (generation, text) = { + let app = app.read(cx); + (app.status_generation, app.vm.status.clone()) + }; + if generation == this.generation { + return; + } + this.generation = generation; + this.text = text; + cx.notify(); + if this.text.is_empty() { + return; + } + cx.spawn(async move |this, cx| { + cx.background_executor().timer(TOAST_TIME).await; + let _ = this.update(cx, |this, cx| { + if this.generation == generation && !this.text.is_empty() { + this.text.clear(); + cx.notify(); + } + }); + }) + .detach(); + }); + Self { text: String::new(), generation, _subscription: subscription } + } + + /// What it shows now; empty when nothing is. + pub fn text(&self) -> &str { + &self.text + } +} + +impl Render for Toast { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + let toast = + div().id("toast").absolute().bottom(px(m.space_7)).w_full().flex().justify_center(); + if self.text.is_empty() { + return toast; + } + toast.child( + div() + .max_w(px(560.0)) + .px(px(m.space_5)) + .py(px(m.space_3)) + .rounded(px(m.radius_md)) + .border_1() + .border_color(hsla(c.border_popup)) + .bg(hsla(c.surface_3)) + .text_size(px(m.font_body)) + .text_color(hsla(c.text)) + .child(self.text.clone()), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/topbar.rs b/crates/voelin-gpui/src/shell/topbar.rs new file mode 100644 index 0000000..6a15ed5 --- /dev/null +++ b/crates/voelin-gpui/src/shell/topbar.rs @@ -0,0 +1,112 @@ +//! The bar at the top of the window: the page's title, the search box and the +//! settings button (`TopBar` of `ui/shells/desktop.slint`; the bell comes +//! with the notifications). The search and the settings are affordances until +//! their slices: a click is logged ([`OpenSearch`], [`OpenSettings`]). + +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render, + StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px, +}; + +use super::actions::{OpenSearch, OpenSettings}; +use super::widgets::{IconButton, icon}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// The page title: the server on screen, else the app's name. +pub fn title(app: &AppState) -> String { + match app.current_bookmark() { + Some(bookmark) => bookmark.name.clone(), + None => voelin_platform::APP_NAME.to_owned(), + } +} + +/// The top bar. +pub struct TopBar { + title: String, + _subscription: Subscription, +} + +impl TopBar { + /// A top bar that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let shown = title(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let shown = title(app.read(cx)); + if shown != this.title { + this.title = shown; + cx.notify(); + } + }); + Self { title: shown, _subscription: subscription } + } + + /// The title it shows now. + pub fn title(&self) -> &str { + &self.title + } +} + +impl Render for TopBar { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + div() + .id("topbar") + .w_full() + .h(px(m.topbar_height)) + .flex_none() + .flex() + .flex_row() + .items_center() + // The main panel starts where the sidebar and the gaps around it end. + .pl(px(m.sidebar_width + 2.0 * m.space_3)) + .pr(px(m.space_4)) + .gap(px(m.space_4)) + .child( + div() + .id("topbar-title") + .max_w(px(280.0 * m.font_scale.max(1.0))) + .flex_none() + .truncate() + .text_size(px(m.font_lg)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(self.title.clone()), + ) + .child( + div().flex_1().min_w_0().flex().justify_center().child( + div() + .id("topbar-search") + .w_full() + .max_w(px(680.0)) + .h(px(m.control_height)) + .px(px(m.space_3)) + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .rounded(px(m.radius_md)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface_2)) + .cursor_text() + .hover(|style| style.border_color(hsla(c.border_strong))) + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSearch), cx)) + .child(icon("search", m.icon_sm, c.text_muted)) + .child( + div() + .flex_1() + .truncate() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_muted)) + .child("Search servers, channels, people or settings…"), + ), + ), + ) + .child( + IconButton::new("topbar-settings", "settings", "Settings") + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/widgets.rs b/crates/voelin-gpui/src/shell/widgets.rs new file mode 100644 index 0000000..ab2e683 --- /dev/null +++ b/crates/voelin-gpui/src/shell/widgets.rs @@ -0,0 +1,358 @@ +//! The few pieces the shell is made of, drawn from the theme's tokens +//! (`VoelinTheme`, not gpui-component's colours): the avatar of a server or a +//! person, the icon button, the panel and the Lucide icon. They are the GPUI +//! counterparts of `ui/components/avatar.slint`, `button.slint` and +//! `shells/common.slint`'s `Panel`. + +use gpui_kit::{ + App, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, + RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, img, px, + svg, +}; +use gpui_kit::{ElementId, ObjectFit, StyledImage as _}; +use voelin_ui_vm::Rgb; +use voelin_ui_vm::image::{ImageRef, ImageSource}; + +use crate::theme::tokens::Rgba; +use crate::theme::{VoelinTheme, hsla}; + +/// A Lucide icon of the client's set, `size` pixels square, in `color`. +pub fn icon(name: &str, size: f32, color: Rgba) -> impl IntoElement { + svg().path(format!("icons/{name}.svg")).size(px(size)).flex_none().text_color(hsla(color)) +} + +/// What the dot on an avatar says (`Status` of `avatar.slint`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Presence { + /// No dot. + None, + /// Connected with voice. + Online, + /// Connecting. + Idle, + /// Observed invisibly. + Info, + /// Not connected. + Offline, +} + +impl Presence { + /// The dot of a server's state as the engine names it + /// (`voelin_ui_vm::servers::status`): connected is online, observing is + /// blue, connecting is idle, offline has none. + pub fn of_server(status: &str) -> Self { + match status { + "connected" => Self::Online, + "observing" => Self::Info, + "connecting" => Self::Idle, + _ => Self::None, + } + } + + /// The dot's colour. + fn color(self, theme: &VoelinTheme) -> Option { + let c = &theme.colors; + match self { + Self::None => None, + Self::Online => Some(c.success), + Self::Idle => Some(c.idle), + Self::Info => Some(c.info), + Self::Offline => Some(c.offline), + } + } +} + +/// The colour a server or person is drawn in. +pub fn tint(color: Rgb) -> Rgba { + Rgba(color.0 << 8 | 0xff) +} + +/// An avatar: the picture when there is one (a file of the engine's cache), +/// else the initials on `tint`, square with rounded corners for a server +/// and round for a person, with a presence dot and a green ring while the +/// person's voice goes out. Pictures other than files of the cache are drawn +/// as initials until the slices that decode them (the chat's, the members'). +#[derive(IntoElement)] +pub struct Avatar { + id: ElementId, + size: f32, + initials: SharedString, + tint: Rgb, + image: ImageRef, + square: bool, + presence: Presence, + speaking: bool, +} + +impl Avatar { + /// An avatar of `size` pixels with these initials on `tint`. + pub fn new(id: impl Into, size: f32, initials: &str, tint: Rgb) -> Self { + Self { + id: id.into(), + size, + initials: initials.to_owned().into(), + tint, + image: ImageRef::default(), + square: false, + presence: Presence::None, + speaking: false, + } + } + + /// Draw this picture when it is a file of the cache. + pub fn image(mut self, image: ImageRef) -> Self { + self.image = image; + self + } + + /// A server's rounded square, not a person's circle. + pub fn square(mut self) -> Self { + self.square = true; + self + } + + /// The dot at the corner. + pub fn presence(mut self, presence: Presence) -> Self { + self.presence = presence; + self + } + + /// The green ring. + pub fn speaking(mut self, speaking: bool) -> Self { + self.speaking = speaking; + self + } +} + +impl RenderOnce for Avatar { + fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = VoelinTheme::global(cx); + let (c, m) = (&theme.colors, &theme.metrics); + let radius = if self.square { m.radius_lg } else { self.size / 2.0 }; + let picture = match &*self.image { + ImageSource::File { path, .. } if self.image.size().width > 0 => Some(path.clone()), + _ => None, + }; + let face = div() + .size(px(self.size)) + .flex_none() + .rounded(px(radius)) + .overflow_hidden() + .flex() + .items_center() + .justify_center() + .bg(hsla(if picture.is_some() { c.surface_3 } else { tint(self.tint) })); + let face = match picture { + Some(path) => face.child(img(path).size_full().object_fit(ObjectFit::Cover)), + None => face.child( + div() + .text_size(px(self.size * 0.38)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(Rgba(0xffff_ffff))) + .child(self.initials), + ), + }; + let mut avatar = div().id(self.id).relative().size(px(self.size)).flex_none(); + if self.speaking { + avatar = avatar.child( + div() + .absolute() + .top(px(-3.0)) + .left(px(-3.0)) + .size(px(self.size + 6.0)) + .rounded(px(radius + 3.0)) + .border_2() + .border_color(hsla(c.success)), + ); + } + avatar = avatar.child(face); + if let Some(color) = self.presence.color(theme) { + let dot = (self.size * 0.3).max(10.0); + avatar = avatar.child( + div() + .absolute() + .top(px(self.size - dot + 1.0)) + .left(px(self.size - dot + 1.0)) + .size(px(dot)) + .rounded(px(dot / 2.0)) + .border_2() + .border_color(hsla(c.surface)) + .bg(hsla(color)), + ); + } + avatar + } +} + +type Handler = Box; + +/// A button that is an icon: 36 pixels (or `size`) square, round or with +/// rounded corners, with a tooltip. Without a handler or disabled it draws +/// dimmed and does nothing. +#[derive(IntoElement)] +pub struct IconButton { + id: ElementId, + icon: &'static str, + label: SharedString, + size: f32, + tint: Option, + danger: bool, + round: bool, + filled: bool, + checked: bool, + enabled: bool, + on_click: Option, +} + +impl IconButton { + /// The Lucide icon `icon` (a file name without `.svg`), named `label` for + /// the tooltip. + pub fn new( + id: impl Into, + icon: &'static str, + label: impl Into, + ) -> Self { + Self { + id: id.into(), + icon, + label: label.into(), + size: 34.0, + tint: None, + danger: false, + round: false, + filled: false, + checked: false, + enabled: true, + on_click: None, + } + } + + /// The button's side in pixels. + pub fn size(mut self, size: f32) -> Self { + self.size = size; + self + } + + /// The icon's colour, instead of the theme's icon colour. + pub fn tint(mut self, tint: Rgba) -> Self { + self.tint = Some(tint); + self + } + + /// A button that turns danger-coloured when checked (mute). + pub fn danger(mut self) -> Self { + self.danger = true; + self + } + + /// A circle. + pub fn round(mut self) -> Self { + self.round = true; + self + } + + /// A button with a border and a face of its own (the rail's plus). + pub fn filled(mut self) -> Self { + self.filled = true; + self + } + + /// Whether it is on. + pub fn checked(mut self, checked: bool) -> Self { + self.checked = checked; + self + } + + /// Whether it can be used. + pub fn enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// What a click does. + pub fn on_click( + mut self, + handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, + ) -> Self { + self.on_click = Some(Box::new(handler)); + self + } +} + +impl RenderOnce for IconButton { + fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = VoelinTheme::global(cx); + let (c, m) = (&theme.colors, &theme.metrics); + let (face, ink, hover) = match (self.checked, self.danger, self.filled) { + (true, true, _) => (c.danger_soft, c.danger, c.danger_soft), + (true, false, _) => (c.accent_soft, c.accent_text, c.accent_soft_hover), + (false, _, true) => { + let ink = self.tint.unwrap_or(c.icon); + (c.surface_2, ink, ink.with_alpha(0x33)) + } + (false, _, false) => (Rgba::TRANSPARENT, self.tint.unwrap_or(c.icon), c.surface_3), + }; + let radius = if self.round { self.size / 2.0 } else { m.radius_md }; + let icon_size = if self.size >= 40.0 { m.icon_md } else { m.icon_sm.max(self.size * 0.5) }; + let label = self.label.clone(); + let selector = self.id.to_string(); + let mut button = div() + .id(self.id) + .debug_selector(move || selector) + .size(px(self.size)) + .flex_none() + .flex() + .items_center() + .justify_center() + .rounded(px(radius)) + .bg(hsla(face)) + .child(icon(self.icon, icon_size, ink)); + if self.filled { + button = button.border_1().border_color(hsla(ink)); + } + if !self.enabled { + return button.opacity(0.4).into_any_element(); + } + button = button.cursor_pointer().hover(move |style| style.bg(hsla(hover))).tooltip( + move |window, cx| { + gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx) + }, + ); + match self.on_click { + Some(handler) => button.on_click(move |event, window, cx| handler(event, window, cx)), + None => button, + } + .into_any_element() + } +} + +/// A rounded panel of the frame (sidebar, main area): `surface` a little +/// see-through over the backdrop, a border, clipped. +pub fn panel(theme: &VoelinTheme) -> gpui_kit::Div { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .flex() + .flex_col() + .rounded(px(m.radius_xl)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface.with_alpha(235))) + .overflow_hidden() +} + +/// What a card of the sidebar is drawn on. +pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .rounded(px(m.radius_lg)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface_2.with_alpha(alpha))) +} + +/// `element` in a box of its own that tests find by `selector` (a debug +/// selector costs nothing in a build without debug assertions): for the +/// components of gpui-component, which have none of their own. +pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement { + div().flex_none().debug_selector(|| selector.into()).child(element) +} diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index 2886a40..2810a61 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -1,28 +1,69 @@ -//! The window's content. The shell is not built yet (slice 1 of the -//! migration): the window is the theme's page with the one line of the root -//! state that proves the loops run in a status bar, or, with -//! `VOELIN_OPEN=swatch`, the swatch page above that bar. +//! The window's content: the desktop shell, or with `VOELIN_OPEN=swatch` the +//! swatch page. [`MainView`] is the window's root view: it puts the shell's +//! entities (`crate::shell`) in place, handles the actions the user's moves +//! dispatch ([`crate::shell::actions`]) by asking the root state for what the +//! Slint callbacks did, owns the server form, titles the window with the +//! server on screen and reports where the window is. use gpui_kit::{ - Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px, + App, AppContext as _, Context, Entity, FocusHandle, InteractiveElement as _, IntoElement, + ParentElement as _, Render, Styled as _, Subscription, Window, WindowBounds, div, px, }; +use voelin_ui_vm::settings::WindowState; use crate::app::AppState; use crate::dev::Page; use crate::meter::Counters; +use crate::shell::actions::{ + AddServer, CancelServerForm, ConnectVoice, DeleteServer, DisconnectVoice, EditServer, Invite, + OpenSearch, OpenSettings, PushToTalk, SaveAndConnect, SaveServer, SelectServer, SetInputMuted, + SetOutputMuted, +}; +use crate::shell::{MainPanel, ServerForm, ServerRail, Sidebar, Toast, TopBar}; use crate::swatch::swatch; use crate::theme::{VoelinTheme, hsla}; +/// Where `window` is, as the setting `ui.window` keeps it: the size, the +/// position where the platform tells one (not Wayland's) and whether it is +/// maximized; none in full screen, and none for what cannot be a window. +pub fn window_state(window: &Window, cx: &App) -> Option { + let (bounds, maximized) = match window.window_bounds() { + WindowBounds::Windowed(bounds) => (bounds, false), + WindowBounds::Maximized(bounds) => (bounds, true), + WindowBounds::Fullscreen(_) => return None, + }; + let whole = |pixels: gpui_kit::Pixels| f32::from(pixels).round() as i32; + let positioned = cx.compositor_name() != "Wayland"; + let state = WindowState { + width: whole(bounds.size.width).max(0) as u32, + height: whole(bounds.size.height).max(0) as u32, + x: positioned.then(|| whole(bounds.origin.x)), + y: positioned.then(|| whole(bounds.origin.y)), + maximized, + }; + state.is_sane().then_some(state) +} + /// What the main window draws, from the root state and the theme. pub struct MainView { app: Entity, page: Page, counters: Counters, + rail: Entity, + topbar: Entity, + sidebar: Entity, + main: Entity, + toast: Entity, + form: Option>, + title: String, + focus: FocusHandle, + _subscriptions: Vec, } impl MainView { - /// A view of `app` that draws again whenever it changes, and that keeps - /// the theme in `system` mode in step with the window's appearance. + /// A view of `app`. It keeps the theme in `system` mode in step with the + /// window's appearance, the window's title with the server on screen, and + /// tells `app` where the window is. pub fn new( app: Entity, page: Page, @@ -30,63 +71,756 @@ impl MainView { window: &mut Window, cx: &mut Context, ) -> Self { - cx.observe(&app, |_, _, cx| cx.notify()).detach(); - cx.observe_window_appearance(window, |_, window, cx| { - VoelinTheme::set_system_appearance(cx, window.appearance()); - }) - .detach(); - Self { app, page, counters } + let title = app.read(cx).window_title(); + window.set_window_title(&title); + // The window's own focus: actions dispatch from the focused element up, + // so the handlers sit on an element that has it, and it comes back to + // it whenever the element that had it is gone (the form closed, a + // button replaced by another). + let focus = cx.focus_handle(); + window.focus(&focus, cx); + let subscriptions = vec![ + cx.on_focus_lost(window, |this, window, cx| window.focus(&this.focus, cx)), + cx.observe_window_appearance(window, |_, window, cx| { + VoelinTheme::set_system_appearance(cx, window.appearance()); + }), + cx.observe_in(&app, window, |this, app, window, cx| { + let title = app.read(cx).window_title(); + if title != this.title { + window.set_window_title(&title); + this.title = title; + } + // A form for a server that is gone (removed from another place) + // has nothing to edit. + let editing = this.form.as_ref().map(|form| form.read(cx).id()); + let known = |id: i64| app.read(cx).vm.bookmarks.iter().any(|b| b.id == id); + if editing.is_some_and(|id| id >= 0 && !known(id)) { + this.form = None; + cx.notify(); + } + }), + cx.observe_window_bounds(window, |this, window, cx| report(&this.app, window, cx)), + ]; + report(&app, window, cx); + Self { + rail: cx.new(|cx| ServerRail::new(&app, cx)), + topbar: cx.new(|cx| TopBar::new(&app, cx)), + sidebar: cx.new(|cx| Sidebar::new(&app, cx)), + main: cx.new(|cx| MainPanel::new(&app, cx)), + toast: cx.new(|cx| Toast::new(&app, cx)), + app, + page, + counters, + form: None, + title, + focus, + _subscriptions: subscriptions, + } + } + + /// The server form on screen, if one is. + pub fn form(&self) -> Option<&Entity> { + self.form.as_ref() + } + + /// Open the form with `form`'s values. + fn open_form( + &mut self, + form: voelin_ui_vm::bridge::BookmarkForm, + window: &mut Window, + cx: &mut Context, + ) { + self.form = Some(cx.new(|cx| ServerForm::new(&form, window, cx))); + cx.notify(); + } + + fn select_server(&mut self, action: &SelectServer, _: &mut Window, cx: &mut Context) { + self.form = None; + self.app.update(cx, |app, cx| app.select_server(action.id, cx)); + cx.notify(); + } + + fn connect_voice(&mut self, _: &ConnectVoice, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.connect_voice(cx)); + } + + fn disconnect_voice(&mut self, _: &DisconnectVoice, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.disconnect_voice(cx)); + } + + fn set_input_muted(&mut self, action: &SetInputMuted, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.set_input_muted(action.muted, cx)); + } + + fn set_output_muted( + &mut self, + action: &SetOutputMuted, + _: &mut Window, + cx: &mut Context, + ) { + self.app.update(cx, |app, cx| app.set_output_muted(action.muted, cx)); + } + + fn push_to_talk(&mut self, action: &PushToTalk, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.push_to_talk(action.on, cx)); + } + + fn invite(&mut self, _: &Invite, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.invite(cx)); + } + + fn add_server(&mut self, _: &AddServer, window: &mut Window, cx: &mut Context) { + let form = self.app.read(cx).bookmark_form(-1); + self.open_form(form, window, cx); + } + + fn edit_server(&mut self, action: &EditServer, window: &mut Window, cx: &mut Context) { + let form = self.app.read(cx).bookmark_form(action.id); + self.open_form(form, window, cx); + } + + /// Save the form's server; the form closes when it was saved, stays + /// (with the toast saying why) when it was not. + fn save(&mut self, connect: bool, cx: &mut Context) { + let Some(form) = &self.form else { return }; + let values = form.read(cx).to_form(cx); + let saved = self.app.update(cx, |app, cx| { + if connect { + app.save_and_connect(&values, cx) + } else { + app.save_bookmark(&values, cx).is_some() + } + }); + if saved { + self.form = None; + cx.notify(); + } + } + + fn save_server(&mut self, _: &SaveServer, _: &mut Window, cx: &mut Context) { + self.save(false, cx); + } + + fn save_and_connect(&mut self, _: &SaveAndConnect, _: &mut Window, cx: &mut Context) { + self.save(true, cx); + } + + fn cancel_form(&mut self, _: &CancelServerForm, _: &mut Window, cx: &mut Context) { + self.form = None; + cx.notify(); + } + + fn delete_server(&mut self, action: &DeleteServer, _: &mut Window, cx: &mut Context) { + self.form = None; + self.app.update(cx, |app, cx| app.delete_bookmark(action.id, cx)); + cx.notify(); + } + + fn open_search(&mut self, _: &OpenSearch, _: &mut Window, _: &mut Context) { + tracing::info!("the search comes with its slice (docs/ui.md, \"What is next\")"); + } + + fn open_settings(&mut self, _: &OpenSettings, _: &mut Window, _: &mut Context) { + tracing::info!("the settings come with their slice (docs/ui.md, \"What is next\")"); + } +} + +/// Tell `app` where `window` is: it keeps the place at the next tick. +fn report(app: &Entity, window: &Window, cx: &mut App) { + if let Some(state) = window_state(window, cx) { + app.update(cx, |app, _| app.window_moved(state)); } } impl Render for MainView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + // One render of the window is one frame: the parts draw when they are + // told, and the window is drawn when one was. self.counters.renders.incr(); - let line = self.app.read(cx).state_line(); let theme = VoelinTheme::global(cx).clone(); let (c, m) = (&theme.colors, &theme.metrics); - let page = match self.page { - Page::Swatch => div().flex_1().overflow_hidden().child(swatch(&theme)), - Page::Shell => div() - .flex_1() - .flex() - .flex_col() - .items_center() - .justify_center() - .gap(px(m.space_3)) - .child( - div() - .text_size(px(m.font_3xl)) - .text_color(hsla(c.text)) - .child(voelin_platform::APP_NAME), - ) - .child( - div() - .text_size(px(m.font_body)) - .text_color(hsla(c.text_muted)) - .child("The desktop shell is the next slice."), - ), - }; - div() + let frame = div() + .id("window") + .relative() .size_full() - .flex() - .flex_col() - .bg(hsla(c.bg_app)) .text_color(hsla(c.text)) - .font_family(crate::theme::FONT_FAMILY) - .child(page) + .font_family(crate::theme::FONT_FAMILY); + if self.page == Page::Swatch { + return frame.bg(hsla(c.bg_app)).child(swatch(&theme)); + } + let main = match &self.form { + Some(form) => form.clone().into_any_element(), + None => self.main.clone().into_any_element(), + }; + frame + .key_context("Shell") + .track_focus(&self.focus) + .bg(theme.backdrop.to_gpui()) + .flex() + .flex_row() + .on_action(cx.listener(Self::select_server)) + .on_action(cx.listener(Self::connect_voice)) + .on_action(cx.listener(Self::disconnect_voice)) + .on_action(cx.listener(Self::set_input_muted)) + .on_action(cx.listener(Self::set_output_muted)) + .on_action(cx.listener(Self::push_to_talk)) + .on_action(cx.listener(Self::invite)) + .on_action(cx.listener(Self::add_server)) + .on_action(cx.listener(Self::edit_server)) + .on_action(cx.listener(Self::save_server)) + .on_action(cx.listener(Self::save_and_connect)) + .on_action(cx.listener(Self::cancel_form)) + .on_action(cx.listener(Self::delete_server)) + .on_action(cx.listener(Self::open_search)) + .on_action(cx.listener(Self::open_settings)) + .child(self.rail.clone()) .child( div() - .h(px(m.control_height_sm)) - .px(px(m.space_5)) + .flex_1() + .min_w_0() + .h_full() .flex() - .items_center() - .bg(hsla(c.surface)) - .border_t_1() - .border_color(hsla(c.border)) - .text_size(px(m.font_sm)) - .text_color(hsla(c.text_secondary)) - .child(line), + .flex_col() + .child(self.topbar.clone()) + .child( + div() + .flex_1() + .min_h_0() + .flex() + .flex_row() + .px(px(m.space_3)) + .pb(px(m.space_3)) + .gap(px(m.space_3)) + .child(self.sidebar.clone()) + .child(main), + ), ) + .child(self.toast.clone()) + } +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + use std::rc::Rc; + use std::time::Duration; + + use gpui::{TestAppContext, VisualTestContext}; + use gpui_kit::{Bounds, WindowAppearance, point, size}; + use tokio::sync::mpsc::{self, UnboundedSender}; + use voelin_core::{Command, Event, SessionState, VoiceState}; + use voelin_store::{Bookmark, MemorySecrets}; + use voelin_ui_vm::bridge::BookmarkForm; + use voelin_ui_vm::dev::logic as sample; + use voelin_ui_vm::settings::UI_WINDOW; + + use super::*; + use crate::app::Setup; + use crate::backend::Backend; + use crate::backend::testing::TempDir; + use crate::dev::Switches; + use crate::shell::RailView; + use crate::theme::Choice; + use crate::window_bounds; + + /// What a test of the shell holds: the root state, the window's view, the + /// engine's events and the meter's counters. + struct Shell { + app: Entity, + view: Entity, + events: UnboundedSender, + counters: Counters, + } + + fn bookmark(name: &str, address: &str) -> Bookmark { + Bookmark { + name: name.into(), + address: address.into(), + nickname: "Nova".into(), + ..Default::default() + } + } + + 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 + } + + /// Open the window of the shell on `backend`, with the theme and the + /// components set up as `run` sets them. + fn open( + cx: &mut TestAppContext, + backend: Backend, + switches: Switches, + ) -> (Shell, &mut VisualTestContext) { + cx.update(|cx| { + gpui_kit::init(cx); + VoelinTheme::init(cx, Choice::Dark, WindowAppearance::Dark, 1.0); + }); + let (events, rx) = mpsc::unbounded_channel(); + let counters = Counters::default(); + let page = switches.open; + let setup = + Setup { engine: None, events: rx, counters: counters.clone(), backend, switches }; + let app = cx.new(|cx| AppState::new(setup, cx)); + let (view, vcx) = cx.add_window_view({ + let (app, counters) = (app.clone(), counters.clone()); + move |window, cx| MainView::new(app, page, counters, window, cx) + }); + let shell = Shell { app, view, events, counters }; + frame(vcx); + (shell, vcx) + } + + /// Run what is queued and draw the window. + fn frame(cx: &mut VisualTestContext) { + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + /// Where the element with this debug selector is on screen. + fn at(cx: &mut VisualTestContext, selector: &str) -> Option> { + cx.debug_bounds(Box::leak(selector.to_owned().into_boxed_str())) + } + + fn click(cx: &mut VisualTestContext, selector: &str) { + let bounds = at(cx, selector).unwrap_or_else(|| panic!("{selector} is not on screen")); + cx.simulate_click(bounds.center(), Default::default()); + frame(cx); + } + + fn ids(shell: &Shell, cx: &mut VisualTestContext) -> Vec { + shell.app.read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.id).collect()) + } + + fn rail(shell: &Shell, cx: &mut VisualTestContext) -> RailView { + shell.view.read_with(cx, |view, cx| view.rail.read(cx).view().clone()) + } + + fn form(address: &str) -> BookmarkForm { + BookmarkForm { id: -1, address: address.into(), ..Default::default() } + } + + fn connected(id: i64) -> Event { + Event::State { + session: id as u64, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + } + } + + /// A saved server shows in the rail, as an icon the user can click. + #[gpui::test] + fn a_server_added_shows_in_the_rail(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + assert_eq!(rail(&shell, cx).servers, []); + let id = shell + .app + .update(cx, |app, cx| { + app.save_bookmark( + &BookmarkForm { name: "Nightfall".into(), ..form("ts.example") }, + cx, + ) + }) + .unwrap(); + frame(cx); + let view = rail(&shell, cx); + assert_eq!(view.servers.len(), 1); + assert_eq!( + (i64::from(view.servers[0].id), view.servers[0].name.as_ref()), + (id, "Nightfall") + ); + assert_eq!(view.servers[0].initials.as_ref(), "NI"); + assert_eq!(view.current, Some(id), "and it is the one on screen"); + assert!(at(cx, &format!("rail-server-{id}")).is_some(), "drawn"); + } + + /// A click on a server of the rail shows it: the window's title, the top + /// bar and the sidebar name it. + #[gpui::test] + fn clicking_a_server_selects_it_and_titles_the_window(cx: &mut TestAppContext) { + let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]); + let (shell, cx) = open(cx, backend, Switches::default()); + let [first, second] = ids(&shell, cx)[..] else { panic!("two servers") }; + assert_eq!( + cx.window_title().as_deref(), + Some("Voelin - Nightfall"), + "the first is shown at start" + ); + click(cx, &format!("rail-server-{second}")); + assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(second)); + assert_eq!(cx.window_title().as_deref(), Some("Voelin - Lounge")); + shell.view.read_with(cx, |view, cx| { + assert_eq!(view.topbar.read(cx).title(), "Lounge"); + let sidebar = view.sidebar.read(cx).view(); + assert_eq!(sidebar.server.as_ref().map(|s| s.name.as_ref()), Some("Lounge")); + }); + assert_eq!(rail(&shell, cx).current, Some(second)); + click(cx, &format!("rail-server-{first}")); + assert_eq!(cx.window_title().as_deref(), Some("Voelin - Nightfall")); + } + + /// Nothing on screen is the "no server selected" state with the way to + /// add one, and the title is the app's. + #[gpui::test] + fn without_a_server_the_main_area_says_so(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + assert_eq!(cx.window_title().as_deref(), Some("Voelin")); + shell.view.read_with(cx, |view, cx| { + assert_eq!(view.main.read(cx).state(), &crate::shell::MainState::NoServer); + assert_eq!(view.topbar.read(cx).title(), "Voelin"); + }); + assert!(at(cx, "main-empty").is_some()); + assert!(at(cx, "sidebar-server").is_none(), "no server card"); + } + + /// The connect button of a server on screen asks the engine to connect it. + #[gpui::test] + fn the_connect_button_connects_the_server_on_screen(cx: &mut TestAppContext) { + let (shell, cx) = + open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = ids(&shell, cx)[0]; + shell.app.read_with(cx, |app, _| app.take_sent()); + click(cx, "main-connect"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::ConnectVoice { session, options, .. }, ..] + if *session == id as u64 && options.address == "ts.example"), + "{sent:?}" + ); + } + + /// What the engine says about a session shows in the rail, the sidebar's + /// voice card and the main area's buttons. + #[gpui::test] + fn an_engine_event_updates_the_rail_and_the_cards(cx: &mut TestAppContext) { + let (shell, cx) = + open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = ids(&shell, cx)[0]; + assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "offline"); + assert!(at(cx, "sidebar-voice").is_none() && at(cx, "main-connect").is_some()); + shell.events.send(connected(id)).unwrap(); + frame(cx); + assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "connected"); + assert!(at(cx, "sidebar-voice").is_some(), "the voice card"); + assert!(at(cx, "main-disconnect").is_some() && at(cx, "main-connect").is_none()); + shell + .events + .send(Event::State { session: id as u64, state: SessionState::default() }) + .unwrap(); + frame(cx); + assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "offline"); + assert!(at(cx, "sidebar-voice").is_none()); + } + + /// The mute buttons of the user card, and the disconnect of the voice card, + /// go to the session as commands once voice is up. + #[gpui::test] + fn the_voice_buttons_send_their_commands_once_voice_is_up(cx: &mut TestAppContext) { + let (shell, cx) = + open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = ids(&shell, cx)[0]; + click(cx, "user-mic"); + assert!( + shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), + "disabled without voice" + ); + shell.events.send(connected(id)).unwrap(); + frame(cx); + click(cx, "user-mic"); + click(cx, "user-sound"); + click(cx, "voice-disconnect"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!( + sent.as_slice(), + [ + Command::SetInputMuted { session: a, muted: true }, + Command::SetOutputMuted { session: b, muted: true }, + Command::DisconnectVoice { session: c }, + ] if [*a, *b, *c] == [id as u64; 3] + ), + "{sent:?}" + ); + } + + /// Hold to talk transmits while the button is held down. + #[gpui::test] + fn hold_to_talk_transmits_while_it_is_held(cx: &mut TestAppContext) { + let (shell, cx) = + open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = ids(&shell, cx)[0]; + shell.events.send(connected(id)).unwrap(); + frame(cx); + let button = at(cx, "hold-to-talk").expect("push-to-talk is the default transmit mode"); + cx.simulate_mouse_down(button.center(), gpui_kit::MouseButton::Left, Default::default()); + cx.simulate_mouse_up(button.center(), gpui_kit::MouseButton::Left, Default::default()); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!( + sent.as_slice(), + [Command::SetTransmitting { session: a, on: true }, Command::SetTransmitting { session: b, on: false }] + if [*a, *b] == [id as u64; 2] + ), + "{sent:?}" + ); + } + + /// What changes nothing the shell shows tells no part, so draws nothing: an + /// engine event about a talker, a setting that is not the theme's, a tick. + /// The root is told every time; the parts compare what they would show. + #[gpui::test] + fn what_changes_nothing_shown_draws_nothing(cx: &mut TestAppContext) { + let (shell, cx) = + open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = ids(&shell, cx)[0]; + let (rail, topbar, sidebar, main, toast) = shell.view.read_with(cx, |v, _| { + (v.rail.clone(), v.topbar.clone(), v.sidebar.clone(), v.main.clone(), v.toast.clone()) + }); + let (root_told, parts_told) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0))); + macro_rules! count { + ($cx:expr, $entity:expr, $told:expr) => {{ + let told = $told.clone(); + $cx.observe(&$entity, move |_, _| told.set(told.get() + 1)) + }}; + } + let _subscriptions = cx.update(|_, cx| { + vec![ + count!(cx, shell.app, root_told), + count!(cx, rail, parts_told), + count!(cx, topbar, parts_told), + count!(cx, sidebar, parts_told), + count!(cx, main, parts_told), + count!(cx, toast, parts_told), + ] + }); + for event in [ + Event::Talking { session: id as u64, client: 3, talking: true }, + Event::SettingChanged { key: "stream.fps".into() }, + ] { + shell.events.send(event).unwrap(); + frame(cx); + } + cx.executor().advance_clock(Duration::from_secs(3)); + frame(cx); + assert_eq!(root_told.get(), 2, "the root hears every batch of events"); + assert_eq!(parts_told.get(), 0, "no part has anything new to show"); + assert_eq!(shell.counters.ticks.get(), 3, "though the clock ran"); + // What does show tells the parts. + shell.events.send(connected(id)).unwrap(); + frame(cx); + assert!(parts_told.get() >= 2, "the rail and the sidebar at least: {}", parts_told.get()); + } + + /// The plus of the rail opens the form; Save with an address adds the + /// server, selects it and closes the form. + #[gpui::test] + fn the_add_button_opens_the_form_and_save_adds_the_server(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + click(cx, "main-add"); + let form = + shell.view.read_with(cx, |view, _| view.form().cloned()).expect("the form is open"); + assert!(at(cx, "server-form").is_some()); + cx.update(|window, cx| { + form.update(cx, |form, cx| form.set_address("ts.example.com", window, cx)) + }); + click(cx, "form-save"); + shell.view.read_with(cx, |view, _| assert!(view.form().is_none(), "closed")); + let names: Vec = shell + .app + .read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.name.clone()).collect()); + assert_eq!(names, ["ts.example.com"]); + assert_eq!(cx.window_title().as_deref(), Some("Voelin - ts.example.com")); + assert!(at(cx, "server-form").is_none() && at(cx, "main-server").is_some()); + } + + /// What is typed after the form opens goes to its address field, and Enter + /// there saves: the form takes the focus from the button that opened it, + /// and the window's own focus does not take it back. + #[gpui::test] + fn typing_in_the_form_fills_the_address_and_enter_saves(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + click(cx, "main-add"); + cx.simulate_input("ts.example.com"); + frame(cx); + let form = + shell.view.read_with(cx, |view, _| view.form().cloned()).expect("the form is open"); + assert_eq!( + form.read_with(cx, |form, cx| form.to_form(cx).address.to_string()), + "ts.example.com" + ); + cx.simulate_keystrokes("enter"); + frame(cx); + shell.view.read_with(cx, |view, _| assert!(view.form().is_none(), "saved and closed")); + assert_eq!(cx.window_title().as_deref(), Some("Voelin - ts.example.com")); + } + + /// Saving a form with no address keeps the form open and says why. + #[gpui::test] + fn a_form_without_an_address_stays_open_and_says_why(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + click(cx, "main-add"); + click(cx, "form-save"); + shell.view.read_with(cx, |view, _| assert!(view.form().is_some())); + assert_eq!( + shell.app.read_with(cx, |app, _| app.vm.status.clone()), + "A server needs an address" + ); + assert_eq!( + shell.view.read_with(cx, |view, cx| view.toast.read(cx).text().to_owned()), + "A server needs an address" + ); + click(cx, "form-cancel"); + shell.view.read_with(cx, |view, _| assert!(view.form().is_none())); + } + + /// Removing asks twice, then the server goes from the rail and the store. + #[gpui::test] + fn removing_a_server_takes_two_clicks(cx: &mut TestAppContext) { + let (shell, cx) = + open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + click(cx, "main-edit"); + shell.view.read_with(cx, |view, _| assert!(view.form().is_some())); + click(cx, "form-remove"); + assert_eq!(ids(&shell, cx).len(), 1, "once is not enough"); + click(cx, "form-remove"); + assert_eq!(ids(&shell, cx), Vec::::new()); + assert!( + shell.app.read_with(cx, |app, _| app.backend().store.bookmarks().unwrap().is_empty()) + ); + assert_eq!(cx.window_title().as_deref(), Some("Voelin")); + assert!(at(cx, "main-empty").is_some()); + } + + /// The status line is a toast that goes after a few seconds. + #[gpui::test] + fn the_status_line_is_a_toast_that_goes(cx: &mut TestAppContext) { + let (shell, cx) = + open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let toast = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| view.toast.read(cx).text().to_owned()) + }; + assert_eq!(toast(&shell, cx), ""); + click(cx, "main-connect"); + assert_eq!(toast(&shell, cx), "Connecting to ts.example…"); + cx.executor().advance_clock(crate::shell::TOAST_TIME + Duration::from_secs(1)); + frame(cx); + assert_eq!(toast(&shell, cx), ""); + } + + /// The window's size and position are kept in `ui.window` when it changes, + /// and the next run opens where they say. + #[gpui::test] + fn the_windows_size_round_trips_through_the_settings(cx: &mut TestAppContext) { + let dir = TempDir::new("shell-window"); + let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); + let (shell, vcx) = open(cx, backend, Switches::default()); + let handle = vcx.update(|window, _| window.window_handle()); + vcx.simulate_window_resize(handle, size(px(900.0), px(600.0))); + frame(vcx); + vcx.executor().advance_clock(Duration::from_secs(1)); + frame(vcx); + let kept = + shell.app.read_with(vcx, |app, _| app.backend().prefs.get(&UI_WINDOW)).expect("kept"); + assert_eq!((kept.width, kept.height), (900, 600)); + assert!(!kept.maximized); + let closed = shell.app.update(vcx, |app, cx| app.shutdown(cx)); + assert_eq!(closed, 0); + let remembered = shell.app.read_with(vcx, |app, _| app.remembered_window()); + assert_eq!(remembered, Some(kept)); + let opens = vcx.update(|_, cx| window_bounds(&Switches::default(), remembered, cx)); + let WindowBounds::Windowed(bounds) = opens else { panic!("{opens:?}") }; + assert_eq!(bounds.size, size(px(900.0), px(600.0))); + } + + /// Where the window opens: a remembered position that no screen shows is + /// the middle of a screen; a maximized window stays maximized; a size the + /// development switch names wins; nothing remembered is the default size. + #[gpui::test] + fn the_window_opens_where_it_was_left_if_a_screen_shows_it(cx: &mut TestAppContext) { + let place = |x: i32, y: i32, maximized: bool| WindowState { + width: 1000, + height: 700, + x: Some(x), + y: Some(y), + maximized, + }; + let opens = |cx: &mut TestAppContext, switches: &Switches, state: Option| { + cx.update(|cx| window_bounds(switches, state, cx)) + }; + let none = Switches::default(); + let WindowBounds::Windowed(on_screen) = opens(cx, &none, Some(place(20, 30, false))) else { + panic!() + }; + assert_eq!( + (on_screen.origin, on_screen.size), + (point(px(20.0), px(30.0)), size(px(1000.0), px(700.0))) + ); + let WindowBounds::Windowed(lost) = opens(cx, &none, Some(place(90_000, 30, false))) else { + panic!() + }; + assert_eq!(lost.size, size(px(1000.0), px(700.0))); + assert_ne!( + lost.origin, + point(px(90_000.0), px(30.0)), + "no screen shows it: the middle of one" + ); + assert!(matches!(opens(cx, &none, Some(place(20, 30, true))), WindowBounds::Maximized(_))); + let default = opens(cx, &none, None); + assert!( + matches!(default, WindowBounds::Windowed(b) if b.size == size(px(1280.0), px(800.0))) + ); + let sized = Switches { window: Some((1440.0, 960.0)), ..Switches::default() }; + let forced = opens(cx, &sized, Some(place(20, 30, true))); + assert!( + matches!(forced, WindowBounds::Windowed(b) if b.size == size(px(1440.0), px(960.0))) + ); + let tiny = WindowState { width: 320, height: 240, ..place(0, 0, false) }; + let WindowBounds::Windowed(small) = opens(cx, &none, Some(tiny)) else { panic!() }; + assert_eq!(small.size, size(px(640.0), px(480.0)), "never under the minimum"); + } + + /// The sample servers fill the rail and the cards, with the first one + /// connected. + #[gpui::test] + fn the_sample_servers_fill_the_shell(cx: &mut TestAppContext) { + let switches = Switches { demo_ui: true, ..Switches::default() }; + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); + let view = rail(&shell, cx); + let names: Vec<&str> = view.servers.iter().map(|s| s.name.as_ref()).collect(); + assert_eq!(names, ["Nightfall Guild", "Pixel Lounge", "Dev TS3"]); + let statuses: Vec<&str> = view.servers.iter().map(|s| s.status.as_ref()).collect(); + assert_eq!(statuses, ["connected", "observing", "offline"]); + assert_eq!(view.current, Some(sample::DEMO)); + assert!(at(cx, "sidebar-voice").is_some()); + assert_eq!(cx.window_title().as_deref(), Some("Voelin - Nightfall Guild")); + } + + /// `VOELIN_OPEN=swatch` shows the swatch in place of the shell. + #[gpui::test] + fn the_swatch_page_replaces_the_shell(cx: &mut TestAppContext) { + let switches = Switches { open: Page::Swatch, ..Switches::default() }; + let (_shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); + assert!(at(cx, "rail").is_none() && at(cx, "sidebar").is_none()); + } + + /// An action dispatched without a click does what the click does: the + /// keys and menus of later slices use the same handlers. + #[gpui::test] + fn an_action_dispatched_is_handled_as_a_click_is(cx: &mut TestAppContext) { + let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]); + let (shell, cx) = open(cx, backend, Switches::default()); + let second = ids(&shell, cx)[1]; + cx.dispatch_action(SelectServer { id: second }); + frame(cx); + assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(second)); + cx.dispatch_action(AddServer); + frame(cx); + shell.view.read_with(cx, |view, _| assert!(view.form().is_some())); + cx.dispatch_action(CancelServerForm); + frame(cx); + shell.view.read_with(cx, |view, _| assert!(view.form().is_none())); } } diff --git a/crates/voelin-ui-vm/src/settings.rs b/crates/voelin-ui-vm/src/settings.rs index 56c66dd..3139cb1 100644 --- a/crates/voelin-ui-vm/src/settings.rs +++ b/crates/voelin-ui-vm/src/settings.rs @@ -113,6 +113,64 @@ pub static UI_VOICE_COMPACT: Key = Key::new( || false, ); +/// Where the main window was and how large, as the last run left it: size and +/// position in logical pixels, and whether it was maximized (then the size is +/// the one it returns to). The position is left out where the platform does +/// not tell it (Wayland). A front end keeps it in [`UI_WINDOW`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WindowState { + /// Width in logical pixels. + pub width: u32, + /// Height in logical pixels. + pub height: u32, + /// Distance of the window's left edge from the screen's, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub x: Option, + /// Distance of the window's top edge from the screen's, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub y: Option, + /// The window was maximized. + #[serde(default)] + pub maximized: bool, +} + +impl WindowState { + /// The smallest size a window can have been left at. + pub const MIN_SIZE: (u32, u32) = (320, 240); + /// The largest size and the farthest position taken as real: a value + /// beyond it is a damaged setting, not a screen. + pub const LIMIT: u32 = 16_384; + + /// Whether the values can be a window: a size within [`Self::MIN_SIZE`] + /// and [`Self::LIMIT`], a position within it either way, and a position + /// that is given whole or not at all. + pub fn is_sane(&self) -> bool { + let limit = i64::from(Self::LIMIT); + (Self::MIN_SIZE.0..=Self::LIMIT).contains(&self.width) + && (Self::MIN_SIZE.1..=Self::LIMIT).contains(&self.height) + && self.x.is_some() == self.y.is_some() + && [self.x, self.y].into_iter().flatten().all(|at| i64::from(at).abs() <= limit) + } +} + +fn valid_window(state: &Option) -> Result<(), String> { + match state { + Some(state) if !state.is_sane() => Err("a window of 320x240 to 16384x16384".into()), + _ => Ok(()), + } +} + +/// `ui.window`: the main window's size and position as the last run left them +/// (none until a run has). The GPUI front end writes it; the Slint one does +/// not read it. +pub static UI_WINDOW: Key> = Key::new( + "ui.window", + Kind::Json, + "The main window's size and position as the last run left them (none: not stored yet).", + || None, +) +.validated(valid_window); + /// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering. pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] { [ @@ -616,6 +674,47 @@ mod tests { assert!(settings.set_json("ui.voice_compact", "small".into()).is_err()); } + /// The window's state is stored as the setting `ui.window`, comes back as it + /// went, and a damaged value is refused in words. + #[test] + fn window_state_roundtrip() { + let state = + WindowState { width: 1440, height: 960, x: Some(-20), y: Some(35), maximized: true }; + let settings = voelin_core::settings::Settings::in_memory(); + assert_eq!(settings.get(&UI_WINDOW), None, "none until a run left one"); + settings.set(&UI_WINDOW, Some(state)).unwrap(); + assert_eq!(settings.get(&UI_WINDOW), Some(state)); + assert_eq!( + settings.get_json("ui.window"), + Some( + serde_json::json!({"width": 1440, "height": 960, "x": -20, "y": 35, "maximized": true}) + ) + ); + // A platform that does not tell the position leaves it out. + let no_position = WindowState { x: None, y: None, maximized: false, ..state }; + let json = serde_json::to_value(no_position).unwrap(); + assert_eq!(json, serde_json::json!({"width": 1440, "height": 960, "maximized": false})); + assert_eq!(serde_json::from_value::(json).unwrap(), no_position); + let older: WindowState = serde_json::from_str(r#"{"width":800,"height":600}"#).unwrap(); + assert_eq!( + older, + WindowState { width: 800, height: 600, x: None, y: None, maximized: false } + ); + for damaged in [ + WindowState { width: 0, ..state }, + WindowState { height: 100_000, ..state }, + WindowState { x: Some(1_000_000), ..state }, + WindowState { y: None, ..state }, + ] { + assert!(!damaged.is_sane(), "{damaged:?}"); + assert!(settings.set(&UI_WINDOW, Some(damaged)).is_err(), "{damaged:?}"); + } + assert!(settings.set_json("ui.window", "big".into()).is_err()); + assert_eq!(settings.get(&UI_WINDOW), Some(state), "a refused value changes nothing"); + settings.set(&UI_WINDOW, None).unwrap(); + assert_eq!(settings.get(&UI_WINDOW), None); + } + #[test] fn ui_settings_defaults() { let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap(); diff --git a/docs/design/gpui-spikes.md b/docs/design/gpui-spikes.md index 7b45fa8..71fa5be 100644 --- a/docs/design/gpui-spikes.md +++ b/docs/design/gpui-spikes.md @@ -23,8 +23,9 @@ cases the foundation's review ran again on a quiet machine. The same day the foundation of step 3 landed on `phase5/gpui-foundation` (items 1 to 4 and 6 of "What step 3's first slice must contain": Rust 1.95, ashpd on `async-io`, the `voelin-gpui` crate with its root entity, the theme with Inter and Lucide, -the cost meter; item 5, the shell, is next): what exists, how to run it and -the slices that follow are in [docs/ui.md](../ui.md), "The GPUI front end". +the cost meter; item 5, the shell, followed the same day, below): what exists, +how to run it and the slices that follow are in [docs/ui.md](../ui.md), "The +GPUI front end". The foundation was reviewed and gated the same day (a Sonnet review, then the Opus gate: no blocker and no major, six minors), and the minors are closed in the commits after it: the meter's `/proc` test waits for a CPU tick instead of @@ -32,7 +33,17 @@ burning 60 ms, zbus runs on `async-io` alone in every binary (with a test for the order of ashpd's callers), the lock figures and the Lucide 1.43 credit are corrected, the slice list points at "Open choices for step 3", and the parity test sees a second brush or string. The risks the review and the gate left to -the slices that meet them are in docs/ui.md, "For the next slices". +the slices that meet them are in docs/ui.md, "For the next slices". Item 5, the +desktop shell, is slice 1 of the step's list and landed on `phase5/gpui-shell` +(2026-10-27): the store at start (the client's database, the settings with the +UI's keys, the secrets, the default identity), the server rail, the sidebar, +the top bar and the main area as entities that draw when what they show +changed, the eleven callbacks of `bind/servers.rs` as actions through +`voelin-ui-vm`'s logic and the engine's commands, the window's size and +position kept in `ui.window`, the engine-event task in steps and a tick that +draws nothing. What it shows, what it costs idle and what it leaves to the +slices after it are in docs/ui.md, "The desktop shell"; the next slice is the +channel tree and the members. | Spike | The plan's no-go | Seen (software rendering, see Setup) | Verdict | |---|---|---|---| @@ -637,8 +648,12 @@ set; the meter as `VOELIN_METER=1`. The crate is named `voelin-gpui` (binary `voelin-gpui`), the choices below stayed as the report leaves them except those named in docs/ui.md ("The GPUI front end"): the theme's second layer is written as a `ThemeColor` mapping (a table there), and the client's Lucide set -is served under gpui-component's `icons/` paths. Item 5, the shell, is the -next task. +is served under gpui-component's `icons/` paths. Item 5, the shell, is done on +`phase5/gpui-shell` (the status paragraph above, docs/ui.md "The desktop +shell"): the screenshots are made the `docs/ui.md` way +(`scripts/gpui-shot.sh` under `headless.sh`), the form that adds a server is the +shell's own until the dialogs slice, and the open choices that remain (video, +emoji, links) are untouched by it. ### The risks of plan section 6, against what was seen diff --git a/docs/ui.md b/docs/ui.md index 4146590..fde833d 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -50,8 +50,9 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit bbcode.rs emoji.rs chat formatting; the Twemoji archive, text → runs of text and emoji crates/voelin-gpui/ the GPUI front end, under construction (binary voelin-gpui; gpui-kit pinned exactly); it uses voelin-ui-vm and the engine, not voelin-ui: - the root state, the theme, Inter and Lucide, the swatch page, the - cost meter ([The GPUI front end](#the-gpui-front-end)) + the root state and the store, the desktop shell, the theme, Inter + and Lucide, the swatch page, the cost meter + ([The GPUI front end](#the-gpui-front-end)) crates/voelin-ui/ the Slint front end ui/ app.slint MainWindow: picks the shell, puts the page's screens in it, dialogs @@ -967,58 +968,91 @@ conditions it settled, are in [design/gpui-spikes.md](design/gpui-spikes.md). crates/voelin-gpui/ build.rs the client's 147 Lucide icons as a table of include_bytes! src/ - main.rs lib.rs `run()`: logging, the engine's runtime, the window; closing it - tells the engine to close the sessions, ends the app and, when - there were sessions, waits 500 ms for the engine to send the + main.rs lib.rs `run()`: logging, the engine's runtime, the store, the window (opened + where it was left); closing it keeps the window's place and the + settings, tells the engine to close the sessions, ends the app and, + when there were sessions, waits 500 ms for the engine to send the closes before the runtime goes (as the Slint front end does) engine.rs HostedEngine: Engine::start on a tokio runtime, its events forwarded into a channel the window reads - app.rs AppState, the root Entity: the voelin-ui-vm state and Social, - the three loops (events, tick, Later), the one line of state - view.rs MainView: the status line, the shell's page (empty), the swatch + backend.rs the store at start: the client's database in the data directory, + the settings service on it with the UI's keys, the secrets, the + default identity; what the engine is handed (history, settings) + app.rs AppState, the root Entity: the voelin-ui-vm state and Social, the + backend, the three loops (events in batches, a quiet tick, Later) + and the callbacks of the Slint `bind/servers.rs` that the shell has + view.rs MainView, the window's root view: the shell or the swatch, the + handlers of the actions, the server form, the title, the window's place + shell/ the desktop shell (below): rail.rs, sidebar.rs, topbar.rs, + main_panel.rs, form.rs, toast.rs, actions.rs, widgets.rs swatch.rs the swatch page (every token, widgets, icons) theme/ VoelinTheme: tokens.rs, components.rs, slint_parity.rs (test) fonts.rs Inter, from crates/voelin-ui/ui/assets/fonts - assets.rs icons/.svg: the client's set before gpui-kit-assets' + assets.rs icons/.svg: the client's set before gpui-kit-assets'; logo.svg dev.rs the development switches meter.rs the cost meter ``` - **The root state.** `AppState` (an `Entity`) holds `voelin_ui_vm::state::AppState>` - and `Social`; `events::handle` is its one dispatch, as in the Slint front end, - and the `Update` it returns is carried out as far as this front end has the - parts: the engine's commands go out, the warnings are logged, the rest - (what to redraw, what to keep, the streams' capture and decoder) is for the - slices that have those parts. Three loops start with it and end when the - entity is released: **the engine's events** (a foreground task awaits the - tokio receiver, `this.update(cx, ...)`, `cx.notify()`; a tokio channel needs - no reactor, so GPUI's executor polls it); **the tick**, once a second, a loop - of `background_executor().timer`; and **`Later`**: GPUI's `AsyncApp` is not - `Send`, so a hotkey, camera or decoder thread holds a `Later` and calls - `later.run(|app, cx| ...)`, a queue a third foreground task drains with the - entity, as `later(|app| ...)` does in Slint. The window shows one line: - the version, the voice connections up, the engine events handled, the seconds - up; each part moves by one of the loops. The window's start shows no store: - the shell slice opens it with the settings and the bookmarks. + and `Social`, and the `Backend` (the store, the settings, the secrets); + `events::handle` is its one dispatch, as in the Slint front end, and the + `Update` it returns is carried out as far as this front end has the parts: + the engine's commands go out, the status line is set (the toast shows it), + what is to be kept goes to the store and the settings (a bookmark, the UI's + settings, the audio settings, the clients' volumes), a changed `ui.theme` or + `ui.font_scale` reaches the theme, the warnings are logged; the rest (what to + redraw, the notices, the pictures to decode, the streams' capture and + decoder) is for the slices that have those parts. Three loops start with it + and end when the entity is released: **the engine's events** (a foreground + task awaits the tokio receiver, takes what is queued, up to 64 events, in one + update with one `cx.notify()`, and yields to GPUI's executor before the next + step: a server's first sync neither starves the window nor draws it once per + event; a tokio channel needs no reactor, so GPUI's executor polls it); **the + tick**, once a second, a loop of `background_executor().timer`, which keeps + what is due (the window's place) and **notifies nobody**: nothing the shell + shows moves with the clock, so a window nobody touches is not drawn; and + **`Later`**: GPUI's `AsyncApp` is not `Send`, so a hotkey, camera or decoder + thread (or the gateway lookup on the engine's runtime) holds a `Later` and + calls `later.run(|app, cx| ...)`, a queue a third foreground task drains with + the entity, as `later(|app| ...)` does in Slint. The root notifies on every + batch and every move of the user's; the views compare what they would show + with what they showed and tell the window only when it differs + ([The desktop shell](#the-desktop-shell)). - **Tests**: the unit tests need no display (GPUI's test platform, `#[gpui::test]`, with `gpui-pre`'s `test-support` as a dev-dependency beside gpui-kit's own pin: its `test-support` feature would make Cargo lock the unused `gpui-fast` backend and - pin taffy 0.15.0): an injected engine event, a real engine's event, the tick - and a job from another thread reach the entity; the theme reaches - gpui-component, follows the window's appearance and the text size; the - Slint file's tokens equal the Rust ones (below); the icons and fonts load. - `tests/launch_failure.rs` starts the built binary where its window cannot - open (below): one of its two cases needs the test display of - `VOELIN_X11_TEST_DISPLAY` and is skipped without it, as the X11 tests of - the other crates are. `cargo test -p voelin-gpui`. + pin taffy 0.15.0): the root state (a burst of events is taken in steps, the tick + is quiet, a job from another thread reaches the entity, the store's servers are + the rail's, a server is saved, edited, removed and selected, a connect and the + other commands reach the engine's wire, the sample servers send nothing, the + window's place is kept and found again, the theme follows the settings and a + switch), the shell on a drawn window that the tests click (a server added is in + the rail, a click selects it and titles the window, an engine event updates the + rail and the cards, the form adds and removes, the toast goes, an idle window is + not told), a connect through a real engine that has no connector (it answers + that none serves the address, which reaches the status line), the store on a + directory of its own, the theme (it reaches gpui-component, follows the window's + appearance and the text size), the Slint file's tokens equal the Rust ones + (below), the icons and fonts load. `tests/launch_failure.rs` starts the built + binary where its window cannot open (below): one of its two cases needs the test + display of `VOELIN_X11_TEST_DISPLAY` and is skipped without it, as the X11 tests + of the other crates are. `cargo test -p voelin-gpui`. ### Running it ```sh -cargo run -p voelin-gpui --release # the window and its one line of state +cargo run -p voelin-gpui --release # the desktop shell, on the client's store +VOELIN_DEMO_UI=1 cargo run -p voelin-gpui --release # the sample servers, nothing kept VOELIN_OPEN=swatch VOELIN_DEV_THEME=light cargo run -p voelin-gpui --release ``` +The shell opens the client's database in the data directory (the platform's, +`~/.local/share/voelin` on Linux; `VOELIN_DATA_DIR` moves it) that the Slint +front end uses too, so the servers saved in one are the other's; **a run that +is not the user's own (a test, a screenshot, a measurement) sets +`VOELIN_DATA_DIR`** and, for the logs, the XDG directories (the headless +scripts below do). + GPUI draws through wgpu: it needs a Vulkan driver (Mesa's RADV, ANV or NVK, NVIDIA's) or OpenGL at run time; in a virtual machine, a remote desktop or CI, Mesa's lavapipe (`mesa-vulkan-drivers`) draws in software. The binary @@ -1055,21 +1089,26 @@ anyway). | Switch | Does | |---|---| | `VOELIN_OPEN=swatch` | the swatch page in place of the shell; the Slint front end's other pages are not here yet and are named in a warning | -| `VOELIN_DEV_THEME=dark\|light\|system` | the theme mode (the settings' `ui.theme` will give it) | -| `VOELIN_FONT_SCALE=1.25` | the text size factor (`ui.font_scale`) | -| `VOELIN_WINDOW_SIZE=1440x960` | the window's size | -| `VOELIN_METER=1` | the cost meter: once a second a log line (`voelin_gpui::meter`) with the process's CPU, the CPU of each group of threads (`llvmpipe` is the software renderer, work a GPU takes over; `voelin-gpui` is GPUI's thread), the resident memory, the app's own counters per second (engine events, ticks, renders, `Later` jobs) and the voice connections up | +| `VOELIN_DEMO_UI=1` | the Slint front end's sample servers (`voelin_ui_vm::dev::logic`) in place of the stored ones, through the app's own events (the first is connected, the second observed); nothing is sent to the engine or kept in the store, the window's place included, and the servers cannot be changed | +| `VOELIN_DEV_THEME=dark\|light\|system` | the theme mode, in place of the settings' `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: the window's place is not kept while it is set | +| `VOELIN_METER=1` | the cost meter: once a second a log line (`voelin_gpui::meter`) with the process's CPU, the CPU of each group of threads (`llvmpipe` is the software renderer, work a GPU takes over; `voelin-gpui` is GPUI's thread), the resident memory, the app's own counters per second (engine events, ticks, renders: one render is one pass of the window's root view, a frame; `Later` jobs) and the voice connections up | Screenshots are made headless, the way `scripts/shots.sh` makes the Slint ones: `scripts/gpui-shot.sh out.png swatch 1440x960` runs the binary under -`xvfb-run`, takes the window with `xwd`, closes it with Alt+F4 when a window -manager is there (else TERM) and says how the app ended. On NixOS, with the -spikes' environment (a headless X display with openbox, lavapipe as the only -Vulkan driver, the XDG directories and the D-Bus bus private): +`xvfb-run`, takes the window with `xwd` (found by its title, "Voelin" and +"Voelin - "), closes it with Alt+F4 when a window manager is there +(else TERM) and says how the app ended; `VOELIN_DEMO_UI=1` in its environment +puts a server on screen. On NixOS, with the spikes' environment (a headless X +display with openbox, lavapipe as the only Vulkan driver, the XDG directories +and the D-Bus bus private): ```sh GPUI_SHOT_HEADLESS=1 DELAY=4 VOELIN_DEV_THEME=dark spikes/gpui/shell.sh \ spikes/gpui/headless.sh -- scripts/gpui-shot.sh docs/ui/gpui-swatch-dark.png swatch 1440x960 +GPUI_SHOT_HEADLESS=1 DELAY=4 VOELIN_DEMO_UI=1 VOELIN_DEV_THEME=dark spikes/gpui/shell.sh \ + spikes/gpui/headless.sh -- scripts/gpui-shot.sh docs/ui/gpui-shell-server-dark.png "" 1440x960 ``` Wayland, the desktop's session bus and its portals are out of the environment, @@ -1081,6 +1120,149 @@ colours would change the tokens' values). ![The swatch page, dark](ui/gpui-swatch-dark.png) ![The swatch page, light](ui/gpui-swatch-light.png) +### The desktop shell + +Slice 1 of plan section 6 step 3: the frame of `ui/shells/desktop.slint` and +the server callbacks of the Slint `bind/servers.rs` (about 13 properties and 11 +callbacks), on the client's store. + +| Empty (no server) | A server on screen | +|---|---| +| ![the shell, no server, dark](ui/gpui-shell-empty-dark.png) | ![the shell with a server, dark](ui/gpui-shell-server-dark.png) | +| ![the shell, no server, light](ui/gpui-shell-empty-light.png) | ![the shell with a server, light](ui/gpui-shell-server-light.png) | + +The pictures are the shell at 1440 by 960 under `scripts/gpui-shot.sh`; the +server on screen is the first of the sample servers (`VOELIN_DEMO_UI=1`), +connected, with its voice card and the user's card. `gpui-shell-form-dark.png` +is the server form. + +![the server form, dark](ui/gpui-shell-form-dark.png) + +What is on screen, each part an entity of `crates/voelin-gpui/src/shell/` that +observes the root state, makes its view of it (`voelin_ui_vm::servers::logic`: +`rail`, `toolbar`) and tells the window only when the view differs from the one +it showed: an engine event about a talker, a setting that is not the theme's or +a tick draws nothing (the `what_changes_nothing_shown_draws_nothing` test counts +the parts told). + +- **The rail** (`rail.rs`): the app's mark, then the saved servers as 46 pixel + rounded squares (the server's icon from the engine's cache, else its initials + on its tint), a dot for the state (green: voice connected, blue: observed + invisibly, amber: connecting), the unread count, a red dot while someone + streams, the pill and the ring of the one on screen; a click selects, a second + click edits; the plus adds a server and the gear is the settings button. +- **The top bar** (`topbar.rs`): the page's title (the server on screen, else + "Voelin"), the search box and the settings button, which log that their + slices are to come (`OpenSearch`, `OpenSettings`). +- **The sidebar** (`sidebar.rs`): the server on screen (name, "9 online · 9 + channels" once its presence is known, else its address), the place of the + channel tree (slice 2), the voice card while voice is connecting or connected + (the channel we are in, copy an invite, disconnect, and Hold to talk when the + transmit mode is push-to-talk) and the user's card (nickname, Online, + Observing or Offline, the microphone and sound buttons, which work with + voice). +- **The main area** (`main_panel.rs`): "No server selected" with an Add a server + button, or the server on screen (name, address, its state) with Connect or + Disconnect and Edit, until the pages of the next slices come. +- **The server form** (`form.rs`), in the place of the main area until the + dialogs slice: address (all a server needs), name (empty: the server's own), + nickname (the default identity's, else the system user's) and the server's + password (kept in the secrets, not in the database); Save, Save and connect, + Cancel, and for a saved server Remove, which asks twice. Enter saves. +- **The toast** (`toast.rs`): the status line ("Connecting to ts.example…", "A + server needs an address") for five seconds. + +The window's title is "Voelin" and "Voelin - " with one on screen. Its +minimum size is 640 by 480. + +The eleven callbacks of `bind/servers.rs` that the shell has are GPUI actions +(`shell/actions.rs`); a click dispatches one with `Window::dispatch_action`, +`MainView` handles it, and the handler asks the root state for what the Slint +callback did, through `voelin-ui-vm`'s `servers::logic` and the engine's +commands: + +| Slint callback | Action | What it does | +|---|---|---| +| `select_server` | `SelectServer { id }` | `logic::select_server`, then observes the server invisibly: through its gateway, else its own query login, else the gateway is looked up on the engine's runtime first (`logic::observe_plan`, `discover_wanted`, `gateway_found`) | +| `connect_voice` | `ConnectVoice` | `Command::ConnectVoice` with the bookmark's address, nickname and default channel, its identity, its password from the secrets | +| `disconnect_voice` | `DisconnectVoice` | `Command::DisconnectVoice` | +| `set_input_muted`, `set_output_muted` | `SetInputMuted { muted }`, `SetOutputMuted { muted }` | the same commands | +| `push_to_talk` | `PushToTalk { on }` | `Command::SetTransmitting`: on at the button's press, off at its release, on or off the button | +| `edit_bookmark` | `EditServer { id }` | opens the form with `servers::form` | +| `save_bookmark` | `SaveServer` | `logic::bookmark_from_form`, the store, the secrets; shows the server | +| `save_and_connect` | `SaveAndConnect` | saves, then connects into the form's channel or the default one (`servers::connect_to`) | +| `delete_bookmark` | `DeleteServer { id }` | `CloseSession`, the secrets and the store, `logic::forget_server` | +| `invite` | `Invite` | `logic::invite_link`, the link on the clipboard, the status line's note | + +The others of that file are the next slices': `search_members`, +`show_voice_view`, `join_channel`, `join_with_password`, `toggle_collapse`, +`open_client` and `client_audio_changed` (the channel tree, the members, the +voice page), and `copied`, which the Slint toast of a copy needs and `Invite` +does for itself. `AddServer`, `CancelServerForm`, `OpenSearch` and +`OpenSettings` are the shell's own. + +**The store at start** (`backend.rs`) is `run()` of the Slint front end through +`voelin-ui-vm`: the client's database at `/client.db` (bookmarks, +identities, chat read marks), the settings service on it with the UI's keys +(and `config.toml` and the `VOELIN_SETTING_*` variables below the stored +values), the secrets (the OS keyring, memory where it refuses, memory alone +with the sample servers), the default identity (made and kept when there is +none), and the engine handed the chat history and the settings. The theme mode +and the text size come from the settings (`ui.theme`, `ui.font_scale`), a +development switch winning, and follow them when the engine reports a change. +Left out against the Slint front end, for later slices: importing the +identities of the official TeamSpeak clients at start (it reads the user's own +files: it comes with the identities page), the crash reports, `--set` on the +command line, `stream_peer` of a connect (what this front end can decode is for +the stream viewer's slice) and the stream effects of an update. + +**The window's place** is the setting `ui.window` (`voelin_ui_vm::settings:: +WindowState`: size, position where the platform tells one, maximized; none until +a run has left one; a value out of any screen's reach is refused in words). The +window reports where it is when it moves or changes size, the root state keeps +it at the next tick and at close, and the next run opens there: the size always, +the position when a screen still shows its corner and the window manager lets a +window choose (GPUI asks X11 for the place, and openbox, like most window +managers, places new windows itself; Wayland tells no position at all, so none +is kept there), maximized if it was. A development switch that sets the size or +the sample data leaves it alone. + +**What the shell costs idle** (`VOELIN_METER=1`, release build of the shell +commit `6b4341a`, the later ones change nothing that runs while idle; 1440 by +960 on Mesa 26.2.5's lavapipe through Vulkan on Xvfb `:97` +with openbox, the machine's other jobs at a load average of 10 to 27; the +first 15 seconds of 75 left out, 60 samples of one second; CPU in percent of +one core, whose resolution is the 1 % of a clock tick): + +| | CPU, mean (max) | Resident memory | Renders per second | Ticks per second | +|---|---|---|---|---| +| The empty shell (no server) | 0.3 % (2 %) | 191.7 MiB | 0.0 | 1.0 | +| The sample servers, the first connected (`VOELIN_DEMO_UI=1`) | 0.5 % (2 %) | 192.7 MiB | 0.0 | 1.0 | + +A window nobody touches is not drawn (a render is one pass of `MainView`, so +one frame of the window): the foundation's tick told the root once a second, +which drew the window once a second by construction (not measured on that +commit). The software renderer's threads (`llvmpipe`) show nowhere in the +lines: they had no work. What the shell costs while it is used (the events of a +connect, a click, the form's typing) is not measured here: a frame takes a +frame's work on the GPU and, on this machine's software device, the CPU +(docs/design/gpui-spikes.md has the per-frame figures of the spikes). + +**Seen against a server** (the TeamSpeak 3 development server of +`dev/docker-compose.yml`, 3.13.8, release build, the same headless display and +no sound card or sound server: `ALSA_CONFIG_PATH` empty, the XDG runtime +directory private): the server added through the form with Save and connect +shows its client (`clientlist -voice` over ServerQuery), the window's title and +the rail take the server's own name ("TeamSpeak ]I[ Server"), the voice card +says "Voice Connected"; the user card's buttons mute the microphone and the +sound, which the server sees (`client_input_muted=1`, `client_output_muted=1`); +the voice card's disconnect leaves the server (no client), the main area's +Connect joins again, and closing the window with Alt+F4 while connected ends +the app with exit status 0 and leaves **no ghost client** on the server after +two seconds. (The close found a panic in the foundation's wait for the engine's +closes, which no run had reached; it is fixed and a test calls the wait from +the GPUI thread.) + ### The theme Two layers (docs/design/gpui-spikes.md, "The theme against Theme tokens"): @@ -1139,10 +1321,15 @@ draws the icons the client draws and the rest of the catalogue still answers. The slices of plan section 6 step 3, in order, with what each takes from the Slint `Bridge` (`ui/bridge.slint:801-1206`; properties / callbacks): -1. the **desktop shell**: the server rail, the sidebar, the top bar, the empty - main area, window state (about 13 / 11, `bind/servers.rs`), the store and the - settings opened as in Slint's `run()`; -2. the channel tree and the members (about 13 / 6); +1. the **desktop shell** (done, [above](#the-desktop-shell)): the server rail, + the sidebar, the top bar, the empty main area, window state (about 13 / 11, + `bind/servers.rs`), the store and the settings opened as in Slint's `run()`; +2. **next: the channel tree and the members** (about 13 / 6): the sidebar's + placeholder becomes `logic::tree_view`'s rows (`TreeItem`, `MemberItem`), the + callbacks `join_channel`, `join_with_password`, `toggle_collapse`, + `search_members`, `show_voice_view`, `open_client` and `client_audio_changed` + become actions beside the shell's, and the password prompt the transitions ask + for (`Update::password`, which the root state only logs today) gets its dialog; 3. the voice page and the call bar (6 / 6); 4. chat, the composer and emoji (about 19 / 18, and the `Emoji` global 3 / 3): first the two open choices of the report that it touches @@ -1171,17 +1358,21 @@ entries); the in-window keys as GPUI key bindings and the global ones through What the foundation's review and the Opus gate (2026-10-27) found and left to the slices that meet it; none of it is a defect of what exists today. -- **The engine-event task drains its channel without yielding** (`app.rs`, - `while let Some(event) = events.recv().await`): a burst of events (a server's - first sync) keeps the receiver ready, so the loop handles them back to back - without returning to GPUI's executor (a tokio receiver is cooperative only - inside a tokio runtime), and the window waits for the whole burst. The shell - slice takes what is queued in one go (`try_recv` after the first event, one - `update`, one `cx.notify()`) or yields between events. -- **The tick notifies the root every second** (`AppState::tick`), which draws - the window once a second whether or not anything changed. Notify only on a - change once the shell shows more than the uptime (the line of state moves - with it today, and it is how the loop is seen to run). +- **Settled by the shell slice: the engine-event task and the tick.** The task + takes what is queued (64 events at most) in one `update` with one + `cx.notify()` and yields between steps, and the tick notifies nobody (the + shell shows nothing that moves with the clock: the line of state with the + seconds is gone, and the meter's `ticks` counter is how the loop is seen to + run). A slice that shows something that moves with time (a clock, a speaking + indicator that fades) makes its own view notify, not the tick. +- **A view that handles actions sits under the window's focus.** GPUI + dispatches an action from the focused element up, and with nothing focused + from the window's root node, which is the root view's wrapper, not its + element. `MainView` keeps a focus handle on its root element, focuses it at + start and takes the focus back when the element that had it is gone + (`on_focus_lost`: the form closed, a button replaced by another). A later + window (the Stream Studio's) does the same, and a new page's buttons dispatch + actions the root handles rather than listeners of their own. - **The hotkey portal calls `tokio::spawn`** (`voelin-platform`, `hotkey/portal.rs`, `PortalBackend::new`): it panics where no tokio runtime is current, and a GPUI foreground task has none. The GPUI front end starts @@ -1204,7 +1395,19 @@ the slices that meet it; none of it is a defect of what exists today. - **System mode's first frame is Light** until the colour-scheme portal answers (`cx.window_appearance()` before the window exists; `set_system_appearance` follows the answer): a dark desktop sees a light frame at start. The shell - slice, which reads the settings, can start from the last resolved mode. + reads `ui.theme`, whose default is dark (as in Slint), so only a user who chose + `system` sees it; starting from the last resolved mode needs a place to keep + it, which nothing has yet. +- **The window's position is the window manager's to give back.** GPUI asks X11 + for the place saved in `ui.window` and sets no position hint, so openbox (and + most window managers) places the window itself; the size is restored, the + position is not, and on Wayland there is none to tell. A window manager that + honours the request, or a hint GPUI does not set, would make the saved + position count; the setting keeps it either way. +- **The identity import and the crash reports are not started** + (`backend.rs` says so): the import reads the official TeamSpeak clients' files + and belongs with the identities page, the crash hook with the settings pages. + A connection uses the store's default identity (made at the first start). - **The gate's deviations from the mapping table** of the report ("The theme against Theme tokens"): `bg-rail` is not mapped (the report has it with `surface` on `sidebar.background`; the sidebar takes `surface` and the shell @@ -1213,13 +1416,11 @@ the slices that meet it; none of it is a defect of what exists today. `overlay` gets `scrim`), and gpui-base's non-colour tokens (radii, spacing, type, shadows, motion) are not written: gpui-base 0.8.1 has no storage to write them to, so those live in `VoelinTheme::metrics` only. -- **The close grace is not seen end to end** until a slice opens sessions: - `run()` waits `CLOSE_GRACE` (500 ms) for the engine to send the closes only - when the window's close found sessions to close, and the binary opens none - yet (the unit test counts the closes `shutdown` sends, and the engine ignores - a close for a session it never opened). The first slice that opens a session - checks against a server that no ghost client stays behind after the window is - closed. +- **The close grace is seen end to end now** (the shell opens sessions): a + connected window closed with Alt+F4 leaves no ghost client on the TeamSpeak 3 + development server and exits with status 0 ([The desktop + shell](#the-desktop-shell)). `run()` waits `CLOSE_GRACE` (500 ms) for the engine + to send the closes only when the window's close found sessions to close. ## Limits diff --git a/docs/ui/gpui-shell-empty-dark.png b/docs/ui/gpui-shell-empty-dark.png new file mode 100644 index 0000000..9238fda Binary files /dev/null and b/docs/ui/gpui-shell-empty-dark.png differ diff --git a/docs/ui/gpui-shell-empty-light.png b/docs/ui/gpui-shell-empty-light.png new file mode 100644 index 0000000..a838e85 Binary files /dev/null and b/docs/ui/gpui-shell-empty-light.png differ diff --git a/docs/ui/gpui-shell-form-dark.png b/docs/ui/gpui-shell-form-dark.png new file mode 100644 index 0000000..c893f2e Binary files /dev/null and b/docs/ui/gpui-shell-form-dark.png differ diff --git a/docs/ui/gpui-shell-server-dark.png b/docs/ui/gpui-shell-server-dark.png new file mode 100644 index 0000000..89313c1 Binary files /dev/null and b/docs/ui/gpui-shell-server-dark.png differ diff --git a/docs/ui/gpui-shell-server-light.png b/docs/ui/gpui-shell-server-light.png new file mode 100644 index 0000000..a298a9f Binary files /dev/null and b/docs/ui/gpui-shell-server-light.png differ diff --git a/docs/ui/gpui-swatch-dark.png b/docs/ui/gpui-swatch-dark.png index aff180e..ce50013 100644 Binary files a/docs/ui/gpui-swatch-dark.png and b/docs/ui/gpui-swatch-dark.png differ diff --git a/docs/ui/gpui-swatch-light.png b/docs/ui/gpui-swatch-light.png index b55539b..edef9ee 100644 Binary files a/docs/ui/gpui-swatch-light.png and b/docs/ui/gpui-swatch-light.png differ diff --git a/scripts/gpui-shot.sh b/scripts/gpui-shot.sh index 89d5505..4ac5a7c 100755 --- a/scripts/gpui-shot.sh +++ b/scripts/gpui-shot.sh @@ -25,7 +25,8 @@ # # VOELIN_BIN: the binary (default target/release/voelin-gpui, else # target/debug); DELAY: seconds the window is shown before the picture -# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE and the other switches of +# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE, VOELIN_DEMO_UI (the sample +# servers: a picture of the shell with one on screen) and the other switches of # `src/dev.rs` are passed on as set. set -eu out=${1:?usage: gpui-shot.sh [ [x]]} @@ -70,7 +71,8 @@ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u XDG_SESSION_TYPE -u DBUS_SESSION_BUS "$bin" >"$work/app.log" 2>&1 & pid=$! i=0 -until win=$(xdotool search --name '^Voelin$' 2>/dev/null | head -1) && [ -n "$win" ]; do +# The title is the app's name, and ` - ` once a server is on screen. +until win=$(xdotool search --name '^Voelin( - |$)' 2>/dev/null | head -1) && [ -n "$win" ]; do i=$((i + 1)) kill -0 "$pid" 2>/dev/null || { echo "gpui-shot.sh: the app ended before its window:" >&2; tail -20 "$work/app.log" >&2; exit 1; } [ $i -lt 300 ] || { echo "gpui-shot.sh: no window after 30 s:" >&2; tail -20 "$work/app.log" >&2; exit 1; }