diff --git a/CHANGELOG.md b/CHANGELOG.md index 3400fe6..320c8e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,26 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows at once. `VOELIN_METER=1` counts the renders of each pane; `VOELIN_DEMO_SERVER` and `VOELIN_DEMO_TALK` pick the sample server and make a sample person talk (docs/ui.md, "The channel tree and the members"). +- The GPUI front end's voice channel page and call bar. A server's Voice channel + button (or `VOELIN_OPEN=voice`) shows the channel we are in with its topic, + its banner and who is there: large avatars ringed green while they talk and + blue while they stream, with the marks of a microphone or sound that is off, + and under them the call bar (mute, deafen, share and the voice settings, which + only log until their pages come, and Leave). The smaller stage, one row of + small avatars centred while it fits and scrolling sideways when crowded, is + remembered and a window under 800 pixels tall always has it (the same setting + as the Slint app's); toggle icon buttons refresh their tooltips as soon as + their state flips. The sidebar's server card shows the server's banner, a + person's card has their volume and a mute for us, and the voice card says the + transmit mode when it is not push-to-talk. Hold to talk and the global + push-to-talk key (`Ctrl+Shift+T` by default, as in the Slint app, working + while another window has focus) track button and hotkey holds independently and + fail closed across voice drops (including drop and reconnect within one event + batch), window focus loss, leaving push-to-talk mode, switching or removing + servers, repeated portal activations across servers, desktop shortcut removal, + hotkey task exit, and window shutdown. A person's picture is round in its + avatar. `voelin-gpui` is still not the app (docs/ui.md, "The voice page and + the call bar"). - 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/crates/voelin-gpui/Cargo.toml b/crates/voelin-gpui/Cargo.toml index f7e8518..59779d3 100644 --- a/crates/voelin-gpui/Cargo.toml +++ b/crates/voelin-gpui/Cargo.toml @@ -21,8 +21,9 @@ anyhow = "1.0.104" # GPUI, gpui-component and gpui-kit-assets behind one pinned dependency. gpui-kit = { workspace = true } # The engine's runtime and the channel of its events (a tokio receiver needs no -# reactor, so GPUI's executor can await it). -tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] } +# reactor, so GPUI's executor can await it); `macros` for the hotkey task's +# `select!`. +tokio = { version = "1.53.1", features = ["macros", "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). diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index 415c690..720a130 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -42,7 +42,7 @@ use gpui_kit::{ClipboardItem, Context}; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; use tracing::{debug, warn}; use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings}; -use voelin_core::{Command, Engine, Event, VoiceState}; +use voelin_core::{Command, Engine, Event, TransmitMode, VoiceState}; use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, Store}; use voelin_ui_vm::bridge::{BookmarkForm, ChatLine}; use voelin_ui_vm::events; @@ -52,13 +52,14 @@ use voelin_ui_vm::servers::logic; use voelin_ui_vm::servers::sequence::{self, Backing}; use voelin_ui_vm::settings::{ CLIENT_PLAYBACK, ThemeChoice, TreeStates, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, - UI_TREE, UI_WINDOW, WindowState, + UI_TREE, UI_VOICE_COMPACT, UI_WINDOW, UiSettings, WindowState, }; use voelin_ui_vm::social::logic::Social; use voelin_ui_vm::tree::ChannelId; use crate::backend::Backend; use crate::dev::Switches; +use crate::hotkey::GlobalPtt; use crate::meter::Counters; use crate::pictures; use crate::signals::{Area, Signals}; @@ -181,6 +182,15 @@ pub fn appearance(prefs: &Settings, switches: &Switches) -> (Choice, f32) { (choice, switches.font_scale.unwrap_or_else(|| prefs.get(&UI_FONT_SCALE))) } +/// The key the global push-to-talk hotkey is registered with at start: the +/// settings' (`global_ptt`, `ptt_key`), with an engine to send the presses to +/// and not with the sample servers, which send nothing (and whose run must not +/// ask the desktop for a shortcut). +fn hotkey_wanted(settings: &UiSettings, demo_ui: bool, has_engine: bool) -> Option { + let key = settings.ptt_key.trim(); + (settings.global_ptt && !demo_ui && has_engine && !key.is_empty()).then(|| key.to_owned()) +} + /// Where the window's place is kept between ticks. #[derive(Debug, Default)] struct WindowKeeper { @@ -251,6 +261,21 @@ pub struct AppState { tree_states: TreeStates, /// The servers whose remembered folds are in their sessions. tree_restored: HashSet, + /// The voice page shows the smaller stage (`ui.voice_compact`, or the + /// development switch that asks for it). + voice_compact: bool, + /// The global push-to-talk hotkey's task, once one was wanted. + ptt: Option, + /// How the hotkey stands, as its task last said. + ptt_status: String, + /// The session the hotkey turned transmit on for and has not turned off. + hotkey_held: Option, + /// The session the window's hold-to-talk button turned transmit on for and + /// has not turned off. + button_held: Option, + /// The window is closing: ignore late push-to-talk presses (such as one + /// already queued from the hotkey task through [`Later`]). + shutting_down: bool, /// Where the sample servers' pictures were written (`VOELIN_DEMO_UI`), /// removed with the state. demo_dir: Option, @@ -364,17 +389,28 @@ impl AppState { password: None, tree_states, tree_restored: HashSet::new(), + voice_compact: false, + ptt: None, + ptt_status: String::new(), + hotkey_held: None, + button_held: None, + shutting_down: false, demo_dir: None, later: Later(later), #[cfg(test)] sent: Default::default(), }; state.window.opening_reports = if state.wants_maximized() { OPENING_REPORTS } else { 0 }; + state.voice_compact = + state.switches.voice_compact || state.backend.prefs.get(&UI_VOICE_COMPACT); if state.switches.demo_ui { state.load_demo(); } else if let Some(id) = state.vm.current { state.restore_tree(id); } + if state.switches.voice { + state.transition(cx, |state, cx| logic::show_voice_view(state, cx, true)); + } state } @@ -487,10 +523,20 @@ impl AppState { ) { let mut refresh = Refresh::default(); for event in events { + let was_connected = match &event { + Event::State { session, .. } => { + let id = *session as i64; + self.is_voice_connected(id).then_some(id) + } + _ => None, + }; self.events_handled += 1; self.counters.engine_events.incr(); let update = self.handle(event); refresh.merge(self.perform(update, cx)); + if let Some(id) = was_connected { + self.release_lost_transmit(id); + } } self.counters.connections.set(self.connections() as u64); // Each area once for the whole batch. @@ -498,6 +544,64 @@ impl AppState { cx.notify(); } + /// Whether `id` currently has voice connected. + fn is_voice_connected(&self, id: i64) -> bool { + self.vm.sessions.get(&id).is_some_and(|view| view.state.voice == VoiceState::Connected) + } + + /// The release guard of Hold to talk and the global hotkey, for voice that + /// dropped: checked per event inside [`Self::handle_events`] so a drop and + /// reconnect in one batch cannot mask it. When `id` leaves `Connected`, any + /// active button or hotkey hold on it ends, and the session is told + /// `SetTransmitting(false)` once if either was held or the engine still + /// reports it transmitting. + fn release_lost_transmit(&mut self, id: i64) { + let Some(view) = self.vm.sessions.get(&id) else { return }; + if view.state.voice != VoiceState::Connected { + let mut was_held = false; + if self.hotkey_held == Some(id) { + self.hotkey_held = None; + was_held = true; + } + if self.button_held == Some(id) { + self.button_held = None; + was_held = true; + } + if was_held || view.state.transmitting { + self.send(Command::SetTransmitting { session: id as u64, on: false }); + } + } + } + + /// Which session the window's hold-to-talk button is holding, if any. + pub(crate) fn button_held(&self) -> Option { + self.button_held + } + + /// Stop transmitting in `id` once neither the window's button nor the global + /// hotkey holds it. + fn stop_transmitting_if_unheld(&self, id: i64) { + if self.hotkey_held != Some(id) && self.button_held != Some(id) { + self.send(Command::SetTransmitting { session: id as u64, on: false }); + } + } + + /// Release the window button's hold, stopping transmit if the global hotkey + /// does not also hold the same session. Returns whether a hold was active. + fn release_button_hold(&mut self) -> bool { + let Some(id) = self.button_held.take() else { return false }; + self.stop_transmitting_if_unheld(id); + true + } + + /// Release the global hotkey's hold, stopping transmit if the window button + /// does not also hold the same session. Returns whether a hold was active. + fn release_hotkey_hold(&mut self) -> bool { + let Some(id) = self.hotkey_held.take() else { return false }; + self.stop_transmitting_if_unheld(id); + true + } + /// One engine event ([`AppState::handle_events`]). pub fn handle_event(&mut self, event: Event, cx: &mut Context) { self.handle_events([event], cx); @@ -591,7 +695,7 @@ impl AppState { /// ([`Signals::raise`]) once for as many updates as it has handled. fn perform(&mut self, update: Update, cx: &mut Context) -> Refresh { let Update { - refresh, + mut refresh, status, commands, persist, @@ -627,7 +731,7 @@ impl AppState { } // What the front end keeps itself comes before the drawing. if let Some(Event::SettingChanged { key }) = rest { - self.setting_changed(&key, cx); + refresh.merge(self.setting_changed(&key, cx)); } refresh } @@ -671,16 +775,36 @@ impl AppState { } } - /// 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) { + /// A setting changed, maybe elsewhere (a command, another window, the + /// config file): take the values the window keeps copies of, and say which + /// areas show them. What the theme follows is applied (the development + /// switches keep what they set); the audio settings (the transmit mode + /// decides whether the voice card has Hold to talk), the clients' volumes + /// (the tree and the card show who is muted) and the smaller stage of the + /// voice page are read again, as the Slint front end's `setting_changed` + /// does. + fn setting_changed(&mut self, key: &str, cx: &mut Context) -> Refresh { + let mut refresh = Refresh::default(); 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); + } else if key == AUDIO.name() && !self.vm.audio_dirty { + self.vm.audio = self.backend.prefs.get(&AUDIO); + if self.vm.audio.transmit != TransmitMode::PushToTalk { + self.release_button_hold(); + } + refresh.toolbar = true; + } else if key == CLIENT_PLAYBACK.name() { + self.vm.playback = self.backend.prefs.get(&CLIENT_PLAYBACK); + refresh.tree = true; + refresh.member_card = true; + } else if key == UI_VOICE_COMPACT.name() && !self.switches.demo_ui { + // The stage's own observer (MainView's) hears the root notify. + self.voice_compact = self.backend.prefs.get(&UI_VOICE_COMPACT); } + refresh } /// The once-a-second work: what the Slint front end's `App::tick` will be @@ -804,6 +928,9 @@ impl AppState { self.transition_with(cx, |state, cx, backing| { sequence::select_server(state, cx, backing, id) }); + if self.button_held.is_some_and(|held| Some(held) != self.vm.current) { + self.release_button_hold(); + } cx.notify(); } @@ -852,10 +979,139 @@ impl AppState { /// 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 }); + if on { + if self.shutting_down { + return; + } + let Some(id) = self.vm.current else { return }; + if let Some(old) = self.button_held.replace(id) { + if old == id { + return; + } + self.stop_transmitting_if_unheld(old); + } + if self.hotkey_held != Some(id) { + self.send(Command::SetTransmitting { session: id as u64, on: true }); + } + cx.notify(); + } else if self.release_button_hold() { + cx.notify(); + } + } + + /// The voice channel page on or off (`show_voice_view` of + /// `bind/servers.rs`, through [`logic::show_voice_view`]): the channel's + /// chat is the one shown, and the people of our channel lead the members + /// panel while the page is. + pub fn show_voice_view(&mut self, on: bool, cx: &mut Context) { + self.transition(cx, |state, cx| logic::show_voice_view(state, cx, on)); cx.notify(); } + /// Whether the main area is the voice page: it was asked for, and voice is + /// connected on the server on screen (the Slint front end's + /// `Nav.voice-view && Bridge.voice-connected`; the page is asked for again + /// by a reconnect, as there). + pub fn voice_page_shown(&self) -> bool { + self.vm.voice_view + && self + .vm + .current + .and_then(|id| self.vm.sessions.get(&id)) + .is_some_and(|view| view.state.voice == VoiceState::Connected) + } + + /// Whether the voice page is on its smaller stage by choice (a window under + /// 800 pixels tall has it whatever this says). + pub fn voice_compact(&self) -> bool { + self.voice_compact + } + + /// The voice page's Smaller stage / Larger stage: kept in `ui.voice_compact` + /// (nothing is kept with the sample servers). + pub fn toggle_voice_compact(&mut self, cx: &mut Context) { + self.voice_compact = !self.voice_compact; + if !self.switches.demo_ui + && let Err(e) = self.backend.prefs.set(&UI_VOICE_COMPACT, self.voice_compact) + { + warn!(%e, "could not store the stage size"); + } + cx.notify(); + } + + /// Start the global push-to-talk hotkey as the settings say (`global_ptt`, + /// `ptt_key`) when there is an engine and no sample servers. [`crate::run`] + /// calls it once the window is open; the state does not start it by itself, + /// so that a test of the state with a real engine never asks the desktop for + /// a shortcut. + pub fn start_global_ptt(&mut self) { + let key = hotkey_wanted(&self.vm.settings, self.switches.demo_ui, self.engine.is_some()); + self.set_global_ptt(key); + } + + /// Register the global push-to-talk hotkey with `key` in place of the one + /// registered, or none: the task starts on the engine's runtime with the + /// first key ([`crate::hotkey`]; the settings page of its slice calls this + /// when the choice changes). Nothing without an engine. + pub fn set_global_ptt(&mut self, key: Option) { + if self.ptt.is_none() && key.is_some() { + let Some(engine) = &self.engine else { return }; + let (status, held) = (self.later(), self.later()); + self.ptt = Some(GlobalPtt::start( + engine.runtime(), + move |line| { + status.run(move |app, _| app.ptt_status_changed(line)); + }, + move |on| { + held.run(move |app, cx| app.hotkey_transmit(on, cx)); + }, + )); + } + if let Some(ptt) = &self.ptt { + ptt.set(key); + } + } + + /// How the hotkey stands, as its task last said ("Active: Ctrl+Shift+T + /// (X11)", why it could not be registered); empty until it said. + pub fn ptt_status(&self) -> &str { + &self.ptt_status + } + + /// The hotkey task's word on how the key stands. + fn ptt_status_changed(&mut self, line: String) { + tracing::info!(target: "voelin_gpui::hotkey", "{line}"); + self.ptt_status = line; + } + + /// The global push-to-talk key went down or up. It transmits into the + /// session on screen while that has voice, and the release ends that same + /// session's transmit, whichever is on screen by then (a server chosen + /// while the key is down). A repeated press on another connected server + /// ends the first session's transmit before starting the new one. A press + /// without voice, or during shutdown, does nothing. + pub fn hotkey_transmit(&mut self, on: bool, cx: &mut Context) { + if on { + if self.shutting_down { + return; + } + let connected = self.vm.current.filter(|&id| self.is_voice_connected(id)); + let Some(id) = connected else { return }; + if let Some(old) = self.hotkey_held.replace(id) { + if old == id { + return; + } + self.stop_transmitting_if_unheld(old); + } + if self.button_held != Some(id) { + self.send(Command::SetTransmitting { session: id as u64, on: true }); + } + cx.notify(); + } else if self.release_hotkey_hold() { + 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 { @@ -911,6 +1167,41 @@ impl AppState { self.password.as_ref() } + /// The volume of a client of the server on screen, in percent (the member + /// card's slider): the engine plays them so, and the choice is kept by their + /// unique id. + pub fn set_member_volume(&mut self, client: u16, percent: f32, cx: &mut Context) { + self.set_client_audio(client, |form| form.volume = percent, cx); + } + + /// Play a client of the server on screen or not (the member card's Mute for + /// me), kept by their unique id. + pub fn set_member_muted(&mut self, client: u16, muted: bool, cx: &mut Context) { + self.set_client_audio(client, |form| form.muted = muted, cx); + } + + /// What the volume dialog of the Slint front end does, without the dialog: + /// the client's volume and mute as the vm has them, changed by `change`, and + /// handed back to `client_playback_changed` (the engine's commands, what is + /// kept, the tree's marks). + fn set_client_audio( + &mut self, + client: u16, + change: impl FnOnce(&mut voelin_ui_vm::bridge::ClientAudio), + cx: &mut Context, + ) { + self.transition(cx, |state, cx| { + let Some(mut form) = voelin_ui_vm::settings_page::logic::open_client(state, client) + else { + return; + }; + change(&mut form); + voelin_ui_vm::settings_page::logic::client_playback_changed(state, cx, &form); + state.playback_dialog = None; + }); + cx.notify(); + } + /// Fold or unfold a channel of the tree (`toggle_collapse`), and remember /// it for the server ([`UI_TREE`]). pub fn toggle_collapse(&mut self, channel: ChannelId, cx: &mut Context) { @@ -1053,6 +1344,12 @@ impl AppState { cx.notify(); return; } + if self.hotkey_held == Some(id) { + self.hotkey_held = None; + } + if self.button_held == Some(id) { + self.button_held = None; + } self.transition_with(cx, |state, cx, backing| { sequence::delete_bookmark(state, cx, backing, id) }); @@ -1100,6 +1397,10 @@ impl AppState { /// 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.shutting_down = true; + self.ptt = None; + self.release_button_hold(); + self.release_hotkey_hold(); self.flush_window(); // The sample pictures are not needed once the window is closing. if let Some(folder) = self.demo_dir.take() { @@ -1354,6 +1655,10 @@ mod tests { switches: Switches::default(), }; let app = cx.new(|cx| AppState::new(setup, cx)); + assert!( + app.read_with(cx, |app, _| app.ptt.is_none()), + "the state starts no hotkey by itself: run does, with the window" + ); 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(); @@ -1737,6 +2042,276 @@ mod tests { assert!(empty.read_with(cx, |app, _| app.take_sent()).is_empty(), "no session on screen"); } + /// The global push-to-talk key is registered at start with the settings' + /// key when there is an engine to send to, not with the sample servers. + #[test] + fn the_hotkey_is_wanted_with_an_engine_outside_the_sample_servers() { + let settings = |global_ptt, key: &str| UiSettings { + global_ptt, + ptt_key: key.into(), + ..Default::default() + }; + let on = settings(true, " Ctrl+Shift+T "); + assert_eq!(hotkey_wanted(&on, false, true).as_deref(), Some("Ctrl+Shift+T")); + assert_eq!(hotkey_wanted(&on, true, true), None, "the sample servers ask for nothing"); + assert_eq!(hotkey_wanted(&on, false, false), None, "no engine: nowhere to send"); + assert_eq!(hotkey_wanted(&settings(false, "F9"), false, true), None, "switched off"); + assert_eq!(hotkey_wanted(&settings(true, " "), false, true), None, "no key"); + assert_eq!( + hotkey_wanted(&UiSettings::default(), false, true).as_deref(), + Some("Ctrl+Shift+T"), + "the default is on, as in the Slint front end" + ); + } + + /// What the commands sent since the last call say about transmitting: the + /// session and whether it was turned on. + fn transmits(app: &Entity, cx: &mut TestAppContext) -> Vec<(u64, bool)> { + app.read_with(cx, |app, _| app.take_sent()) + .into_iter() + .filter_map(|command| match command { + Command::SetTransmitting { session, on } => Some((session, on)), + _ => None, + }) + .collect() + } + + /// The global key transmits into the session on screen while it has voice, + /// and its release ends that session's transmit, whichever is on screen by + /// then; a press without voice, or a second press, does nothing. + #[gpui::test] + fn the_hotkey_transmits_into_the_session_that_has_voice_and_its_release_ends_it( + cx: &mut TestAppContext, + ) { + let (app, tx, _) = 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]); + let hotkey = |app: &Entity, cx: &mut TestAppContext, on| { + app.update(cx, |app, cx| app.hotkey_transmit(on, cx)) + }; + hotkey(&app, cx, true); + assert_eq!(transmits(&app, cx), [], "no voice, no transmit"); + hotkey(&app, cx, false); + assert_eq!(transmits(&app, cx), [], "and nothing to release"); + + tx.send(Event::State { + session: first as u64, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + cx.run_until_parked(); + hotkey(&app, cx, true); + hotkey(&app, cx, true); + assert_eq!(transmits(&app, cx), [(first as u64, true)], "once"); + + // Another server is shown while the key is down: the release still ends + // the transmit of the one it began in. + app.update(cx, |app, cx| app.select_server(second, cx)); + app.read_with(cx, |app, _| assert_eq!(app.vm.current, Some(second))); + hotkey(&app, cx, false); + assert_eq!(transmits(&app, cx), [(first as u64, false)]); + hotkey(&app, cx, false); + assert_eq!(transmits(&app, cx), [], "released once"); + } + + /// The hotkey task runs on the engine's runtime and hands each press and + /// release to GPUI's thread through `Later`. + #[gpui::test] + fn the_hotkey_tasks_thread_reaches_the_entity_through_later(cx: &mut TestAppContext) { + let (app, _, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.update(cx, |app, _| { + let id = app.vm.bookmarks[0].id; + app.vm.sessions.entry(id).or_default().state.voice = VoiceState::Connected; + id as u64 + }); + let later = app.read_with(cx, |app, _| app.later()); + let queued = std::thread::spawn(move || later.run(|app, cx| app.hotkey_transmit(true, cx))) + .join() + .unwrap(); + assert!(queued); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [(id, true)]); + } + + /// The voice that drops under a held key ends the hold: the session is told + /// once (the release guard), and the key's own release has nothing left to + /// end. + #[gpui::test] + fn voice_that_drops_under_the_hotkey_ends_its_hold(cx: &mut TestAppContext) { + let (app, tx, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64; + let state = |voice, transmitting| Event::State { + session: id, + state: SessionState { voice, transmitting, ..Default::default() }, + }; + tx.send(state(VoiceState::Connected, false)).unwrap(); + cx.run_until_parked(); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + tx.send(state(VoiceState::Connected, true)).unwrap(); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [(id, true)]); + tx.send(state(VoiceState::Disconnected, true)).unwrap(); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [(id, false)], "told once"); + app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&app, cx), [], "the release has nothing to end"); + } + + /// A second hotkey press without a release between them, after switching to + /// another connected server (a portal that repeats `Activated`), ends the + /// first session's transmit before starting the new one. + #[gpui::test] + fn a_second_hotkey_press_on_another_server_releases_the_first(cx: &mut TestAppContext) { + let (app, tx, _) = entity_over( + cx, + backend_with(&[ + ("Nightfall", "ts.example"), + ("Lounge", "lounge.example"), + ("Offline", "off.example"), + ]), + Switches::default(), + ); + let [first, second, third] = app.read_with(cx, |app, _| { + [app.vm.bookmarks[0].id, app.vm.bookmarks[1].id, app.vm.bookmarks[2].id] + }); + for id in [first, second] { + tx.send(Event::State { + session: id as u64, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + } + cx.run_until_parked(); + transmits(&app, cx); + + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.select_server(second, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!( + transmits(&app, cx), + [ + (first as u64, true), + (first as u64, false), + (second as u64, true), + (second as u64, false) + ], + "switching connected servers under repeated Activated stops the old session first" + ); + + // Switching to an offline server and getting a repeated press leaves the + // active hold intact so the real release still ends it. + app.update(cx, |app, cx| app.select_server(first, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.select_server(third, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&app, cx), [(first as u64, true), (first as u64, false)]); + } + + /// Deleting a bookmarked server clears any button or hotkey hold on it so a + /// subsequent release does not send a stale command to the closed session. + #[gpui::test] + fn removing_a_server_clears_active_transmit_holds(cx: &mut TestAppContext) { + let (app, tx, _) = 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]); + for id in [first, second] { + tx.send(Event::State { + session: id as u64, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + } + cx.run_until_parked(); + transmits(&app, cx); + + app.update(cx, |app, cx| { + app.hotkey_transmit(true, cx); + app.push_to_talk(true, cx); + }); + assert_eq!(transmits(&app, cx), [(first as u64, true)]); + + app.update(cx, |app, cx| app.delete_bookmark(first, cx)); + let sent = app.read_with(cx, |app, _| app.take_sent()); + assert!( + sent.iter().any( + |c| matches!(c, Command::CloseSession { session } if *session == first as u64) + ), + "{sent:?}" + ); + + app.update(cx, |app, cx| { + app.hotkey_transmit(false, cx); + app.push_to_talk(false, cx); + }); + assert_eq!(transmits(&app, cx), [], "no stale release to the deleted session"); + + app.update(cx, |app, cx| { + app.hotkey_transmit(true, cx); + app.hotkey_transmit(false, cx); + }); + assert_eq!(transmits(&app, cx), [(second as u64, true), (second as u64, false)]); + } + + /// Closing the window releases any active hotkey or button hold and ignores + /// late presses queued through `Later` after shutdown. + #[gpui::test] + fn closing_releases_a_held_transmit_and_ignores_late_presses(cx: &mut TestAppContext) { + // Hotkey held during shutdown + late release/press queued on `Later`. + let (app, tx, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64; + tx.send(Event::State { + session: id, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + cx.run_until_parked(); + transmits(&app, cx); + + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&app, cx), [(id, true)]); + app.update(cx, |app, cx| app.shutdown(cx)); + assert_eq!(transmits(&app, cx), [(id, false)], "shutdown releases the held key"); + + let later = app.read_with(cx, |app, _| app.later()); + assert!(later.run(|app, cx| { + app.hotkey_transmit(false, cx); + app.hotkey_transmit(true, cx); + app.push_to_talk(true, cx); + })); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [], "late presses after shutdown are ignored"); + + // Window button held during shutdown is released too. + let (app2, tx2, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id2 = app2.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64; + tx2.send(Event::State { + session: id2, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + cx.run_until_parked(); + transmits(&app2, cx); + + app2.update(cx, |app, cx| app.push_to_talk(true, cx)); + assert_eq!(transmits(&app2, cx), [(id2, true)]); + app2.update(cx, |app, cx| app.shutdown(cx)); + assert_eq!(transmits(&app2, cx), [(id2, false)], "shutdown releases the held button"); + } + /// 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] diff --git a/crates/voelin-gpui/src/dev.rs b/crates/voelin-gpui/src/dev.rs index 00c3cca..8df11a1 100644 --- a/crates/voelin-gpui/src/dev.rs +++ b/crates/voelin-gpui/src/dev.rs @@ -7,6 +7,9 @@ //! 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_OPEN=voice` (`voice:compact`): the voice channel page on screen +//! once voice is connected, in place of the server page; `voice:compact` +//! with the smaller stage, which is not stored. //! - `VOELIN_DEMO_UI=1`: the Slint front end's sample servers, shown through //! the app's own events, with their pictures as files of a folder in the //! temporary directory (removed when the window closes); nothing is sent to @@ -42,6 +45,12 @@ pub enum Page { pub struct Switches { /// The page to open on. pub open: Page, + /// The voice channel page is asked for (`VOELIN_OPEN=voice`): it shows + /// once voice is connected. + pub voice: bool, + /// With the voice page, the smaller stage, as the switch says (it is not + /// stored, as the Slint front end's `voice:compact`). + pub voice_compact: bool, /// Show the sample servers instead of the stored ones. pub demo_ui: bool, /// Write the sample servers' pictures to a folder of the temporary @@ -69,6 +78,8 @@ impl Default for Switches { fn default() -> Self { Self { open: Page::Shell, + voice: false, + voice_compact: false, demo_ui: false, demo_pictures: false, demo_server: None, @@ -95,8 +106,10 @@ impl Switches { for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) { match what { "swatch" => switches.open = Page::Swatch, + "voice" => switches.voice = true, + "voice:compact" => (switches.voice, switches.voice_compact) = (true, true), other => tracing::warn!( - "VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch is)" + "VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch and voice are)" ), } } @@ -166,7 +179,7 @@ mod tests { #[test] fn every_switch_is_read() { let s = env(&[ - ("VOELIN_OPEN", "swatch"), + ("VOELIN_OPEN", "swatch,voice:compact"), ("VOELIN_DEMO_UI", "1"), ("VOELIN_DEMO_SERVER", "2"), ("VOELIN_DEMO_TALK", "10"), @@ -176,6 +189,7 @@ mod tests { ("VOELIN_METER", "1"), ]); assert_eq!(s.open, Page::Swatch); + assert!(s.voice && s.voice_compact, "the voice page, with the smaller stage"); assert!(s.demo_ui && s.demo_pictures, "the sample servers come with their pictures"); assert_eq!(s.demo_server, Some(2)); assert_eq!(s.demo_talk, Some(10.0)); @@ -185,6 +199,12 @@ mod tests { assert!(s.meter); } + #[test] + fn the_voice_page_alone_has_the_larger_stage() { + let s = env(&[("VOELIN_OPEN", "voice")]); + assert_eq!((s.open, s.voice, s.voice_compact), (Page::Shell, true, false)); + } + #[test] fn what_makes_no_sense_is_left_out() { let s = env(&[ diff --git a/crates/voelin-gpui/src/hotkey.rs b/crates/voelin-gpui/src/hotkey.rs new file mode 100644 index 0000000..32652f9 --- /dev/null +++ b/crates/voelin-gpui/src/hotkey.rs @@ -0,0 +1,361 @@ +//! Global push-to-talk: a task owns the [`voelin_platform::HotkeyManager`] (the +//! desktop's portal on Wayland, XInput2 on X11, a hook on Windows) and reports +//! the key's presses and releases, whichever window has the focus. +//! +//! It is the Slint front end's `GlobalPtt` (`crates/voelin-ui/src/hotkey.rs`), +//! repeated here as `engine.rs` repeats `HostedEngine`: the loop needs the +//! engine's runtime and the front end's own way back to its state, and the +//! Slint crate cannot be a dependency (it brings Slint in); both go into one +//! place when the Slint front end is retired. +//! +//! **The task runs on the engine's runtime** ([`GlobalPtt::start`] spawns on +//! it), not from a foreground task of GPUI: the portal's backend calls +//! `tokio::spawn` when it is made (`voelin-platform`, `hotkey/portal.rs`), which +//! panics where no tokio runtime is current, and GPUI's executor has none. + +use std::future::Future; + +use tokio::runtime::Handle; +use tokio::sync::mpsc; +use voelin_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager}; + +/// The id of the push-to-talk registration (the portal remembers the user's +/// choice by it). +const PTT_ID: &str = "push-to-talk"; + +/// The handle to the hotkey task. +pub struct GlobalPtt { + tx: mpsc::UnboundedSender>, +} + +impl GlobalPtt { + /// Start the task on `runtime`. `status` gets a line that says how the key + /// stands ("Active: Ctrl+Shift+T (X11)", why it could not be registered), + /// `transmit` the key's state; both are called on the runtime, so they hand + /// over to GPUI's thread ([`crate::app::Later`]). + pub fn start( + runtime: &Handle, + status: impl Fn(String) + Send + 'static, + transmit: impl Fn(bool) + Send + 'static, + ) -> Self { + let (tx, rx) = mpsc::unbounded_channel(); + runtime.spawn(run(rx, status, transmit)); + Self { tx } + } + + /// Register `key` (such as `Ctrl+Shift+T`) in place of the one registered, + /// or nothing. + pub fn set(&self, key: Option) { + let _ = self.tx.send(key); + } +} + +/// A stream of press and release events for one registered hotkey (`None` once +/// the desktop removes it). +trait EventStream: Send { + fn recv(&mut self) -> impl Future> + Send; +} + +impl EventStream for HotkeyEvents { + fn recv(&mut self) -> impl Future> + Send { + HotkeyEvents::recv(self) + } +} + +/// Registers and unregisters the global push-to-talk hotkey with the platform +/// (or a test double). +trait Registrar: Send { + type Events: EventStream; + + fn register( + &mut self, + key: String, + hotkey: Hotkey, + ) -> impl Future> + Send; + + fn unregister(&mut self) -> impl Future + Send; +} + +/// The real platform hotkey manager, opened lazily on the first registration. +struct PlatformRegistrar { + manager: Option, +} + +impl Registrar for PlatformRegistrar { + type Events = HotkeyEvents; + + async fn register( + &mut self, + key: String, + hotkey: Hotkey, + ) -> Result<(Self::Events, String), String> { + if self.manager.is_none() { + match HotkeyManager::new().await { + Ok(m) => self.manager = Some(m), + Err(e) => return Err(format!("Global hotkeys are not available: {e}")), + } + } + let Some(m) = &mut self.manager else { + return Err("Global hotkeys are not available.".into()); + }; + match m.register(PTT_ID, "Push to talk", hotkey).await { + Ok(registered) => { + let line = match m.backend() { + BackendKind::Portal => format!( + "Registered with the desktop: {}", + m.trigger_description(PTT_ID).unwrap_or(key) + ), + BackendKind::X11 => format!("Active: {hotkey} (X11)"), + BackendKind::WindowsHook => format!("Active: {hotkey}"), + }; + Ok((registered, line)) + } + Err(e) => Err(format!("Could not register {key}: {e}")), + } + } + + async fn unregister(&mut self) { + if let Some(m) = &mut self.manager { + let _ = m.unregister(PTT_ID).await; + } + } +} + +/// The next event of the registration, or never while there is none. +async fn next_event(events: &mut Option) -> Option { + match events { + Some(events) => events.recv().await, + None => std::future::pending().await, + } +} + +/// The task: a key to register (or none) arrives on `rx`, the registered key's +/// events are reported through `transmit`, and `status` says what happened. +async fn run( + rx: mpsc::UnboundedReceiver>, + status: impl Fn(String), + transmit: impl Fn(bool), +) { + run_loop(rx, PlatformRegistrar { manager: None }, status, transmit).await; +} + +/// The event loop of [`run`], parameterised over `registrar` so the +/// fail-closed release paths are tested without a portal or display. +async fn run_loop( + mut rx: mpsc::UnboundedReceiver>, + mut registrar: R, + status: impl Fn(String), + transmit: impl Fn(bool), +) { + let mut events: Option = None; + loop { + tokio::select! { + key = rx.recv() => { + let Some(key) = key else { + // Fail closed on task exit: drop any hold that was still down. + transmit(false); + break; + }; + events = None; + // Whatever was held no longer counts. + transmit(false); + registrar.unregister().await; + let Some(key) = key else { + status("Off.".into()); + continue; + }; + let hotkey: Hotkey = match key.parse() { + Ok(h) => h, + Err(e) => { + status(format!("{e}")); + continue; + } + }; + match registrar.register(key, hotkey).await { + Ok((registered, line)) => { + events = Some(registered); + status(line); + } + Err(line) => status(line), + } + } + event = next_event(&mut events) => match event { + Some(HotkeyEvent::Pressed) => transmit(true), + Some(HotkeyEvent::Released) => transmit(false), + None => { + events = None; + // Fail closed if the desktop removes the shortcut mid-hold. + transmit(false); + status("The hotkey was removed by the desktop.".into()); + } + }, + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use super::*; + + /// A channel-backed event stream for testing [`run_loop`] without a display. + struct FakeEvents(mpsc::UnboundedReceiver); + + impl EventStream for FakeEvents { + async fn recv(&mut self) -> Option { + self.0.recv().await + } + } + + /// A registrar that hands out a prepared [`FakeEvents`] stream once. + struct FakeRegistrar { + stream: Option, + } + + impl Registrar for FakeRegistrar { + type Events = FakeEvents; + + async fn register( + &mut self, + _key: String, + hotkey: Hotkey, + ) -> Result<(Self::Events, String), String> { + let events = self.stream.take().ok_or_else(|| "no fake stream left".to_owned())?; + Ok((events, format!("Active: {hotkey} (test)"))) + } + + async fn unregister(&mut self) {} + } + + /// Next recorded message from the task, bounded only against a hang. + async fn recv_log(rx: &mut mpsc::UnboundedReceiver) -> String { + tokio::time::timeout(Duration::from_secs(30), rx.recv()) + .await + .expect("hotkey loop timed out") + .expect("log channel closed unexpectedly") + } + + /// A key that is not one is said so and registers nothing, and the held + /// state is let go first; no display or desktop is needed to say it. + #[test] + fn a_key_that_cannot_be_parsed_is_reported_and_lets_go_of_the_hold() { + let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap(); + let log = Arc::new(Mutex::new(Vec::::new())); + let (said, held) = (log.clone(), log.clone()); + let ptt = GlobalPtt::start( + runtime.handle(), + move |line| said.lock().unwrap().push(format!("status: {line}")), + move |on| held.lock().unwrap().push(format!("transmit: {on}")), + ); + ptt.set(Some("Ctrl+Hyper+Banana".into())); + ptt.set(None); + // The task answers in order: the last answer says the end of the list. + let deadline = std::time::Instant::now() + Duration::from_secs(30); + while log.lock().unwrap().len() < 4 { + assert!(std::time::Instant::now() < deadline, "{:?}", log.lock().unwrap()); + std::thread::sleep(Duration::from_millis(5)); + } + let log = log.lock().unwrap().clone(); + assert_eq!(log[0], "transmit: false", "{log:?}"); + assert!(log[1].starts_with("status: "), "the parse error: {log:?}"); + assert_eq!(log[2], "transmit: false", "{log:?}"); + assert_eq!(log[3], "status: Off.", "{log:?}"); + drop(ptt); + runtime.shutdown_timeout(Duration::from_secs(2)); + } + + /// When the desktop removes the registered hotkey while it is pressed, the + /// loop releases transmit before reporting the removal. + #[test] + fn desktop_removal_mid_hold_releases_transmit_before_reporting_status() { + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + runtime.block_on(async { + let (tx_key, rx_key) = mpsc::unbounded_channel(); + let (tx_evt, rx_evt) = mpsc::unbounded_channel(); + let (tx_log, mut rx_log) = mpsc::unbounded_channel(); + let (said, held) = (tx_log.clone(), tx_log); + let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) }; + let task = tokio::spawn(run_loop( + rx_key, + registrar, + move |line| { + let _ = said.send(format!("status: {line}")); + }, + move |on| { + let _ = held.send(format!("transmit: {on}")); + }, + )); + + tx_key.send(Some("Ctrl+Shift+T".into())).unwrap(); + assert_eq!(recv_log(&mut rx_log).await, "transmit: false"); + assert!(recv_log(&mut rx_log).await.starts_with("status: Active: ")); + + tx_evt.send(HotkeyEvent::Pressed).unwrap(); + assert_eq!(recv_log(&mut rx_log).await, "transmit: true"); + + // Desktop removes the shortcut while held. + drop(tx_evt); + assert_eq!( + recv_log(&mut rx_log).await, + "transmit: false", + "transmit must fail closed before reporting removal" + ); + assert_eq!( + recv_log(&mut rx_log).await, + "status: The hotkey was removed by the desktop." + ); + + drop(tx_key); + tokio::time::timeout(Duration::from_secs(30), task) + .await + .expect("task exit timed out") + .unwrap(); + }); + } + + /// When the command channel closes (task exit) while the hotkey is pressed, + /// the loop releases transmit before exiting. + #[test] + fn closing_command_channel_mid_hold_releases_transmit_before_exiting() { + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + runtime.block_on(async { + let (tx_key, rx_key) = mpsc::unbounded_channel(); + let (tx_evt, rx_evt) = mpsc::unbounded_channel(); + let (tx_log, mut rx_log) = mpsc::unbounded_channel(); + let (said, held) = (tx_log.clone(), tx_log); + let registrar = FakeRegistrar { stream: Some(FakeEvents(rx_evt)) }; + let task = tokio::spawn(run_loop( + rx_key, + registrar, + move |line| { + let _ = said.send(format!("status: {line}")); + }, + move |on| { + let _ = held.send(format!("transmit: {on}")); + }, + )); + + tx_key.send(Some("Ctrl+Shift+T".into())).unwrap(); + assert_eq!(recv_log(&mut rx_log).await, "transmit: false"); + assert!(recv_log(&mut rx_log).await.starts_with("status: Active: ")); + + tx_evt.send(HotkeyEvent::Pressed).unwrap(); + assert_eq!(recv_log(&mut rx_log).await, "transmit: true"); + + // Keep the event stream open while the handle drops (task exit). + drop(tx_key); + tokio::time::timeout(Duration::from_secs(30), task) + .await + .expect("task exit timed out") + .unwrap(); + assert_eq!( + rx_log.try_recv().ok().as_deref(), + Some("transmit: false"), + "closing rx mid-hold must release transmit before breaking" + ); + drop(tx_evt); + }); + } +} diff --git a/crates/voelin-gpui/src/lib.rs b/crates/voelin-gpui/src/lib.rs index 438db8d..8591575 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -11,6 +11,7 @@ pub mod backend; pub mod dev; pub mod engine; pub mod fonts; +pub mod hotkey; pub mod meter; pub mod pictures; pub mod shell; @@ -150,6 +151,9 @@ fn open_main_window( }; move |cx| AppState::new(setup, cx) }); + // The global push-to-talk key, on the engine's runtime (docs/ui.md): once the + // state exists, and never from a test of the state. + app.update(cx, |app, _| app.start_global_ptt()); let options = { let app = app.read(cx); window_options(switches, app.remembered_window(), app.window_title(), cx) diff --git a/crates/voelin-gpui/src/meter.rs b/crates/voelin-gpui/src/meter.rs index 7b79432..8c76186 100644 --- a/crates/voelin-gpui/src/meter.rs +++ b/crates/voelin-gpui/src/meter.rs @@ -60,11 +60,13 @@ pub struct Panes { pub main: Counter, /// The members panel. pub members: Counter, + /// The voice channel page. + pub voice: Counter, } impl Panes { /// The counters with the names the meter reports them under. - pub fn named(&self) -> [(&'static str, Counter); 6] { + pub fn named(&self) -> [(&'static str, Counter); 7] { [ ("rail", self.rail.clone()), ("topbar", self.topbar.clone()), @@ -72,6 +74,7 @@ impl Panes { ("tree", self.tree.clone()), ("main", self.main.clone()), ("members", self.members.clone()), + ("voice", self.voice.clone()), ] } } @@ -278,9 +281,9 @@ mod tests { panes.members.incr(); let named = panes.named(); let names: Vec<&str> = named.iter().map(|(name, _)| *name).collect(); - assert_eq!(names, ["rail", "topbar", "sidebar", "tree", "main", "members"]); + assert_eq!(names, ["rail", "topbar", "sidebar", "tree", "main", "members", "voice"]); let seen: Vec = named.iter().map(|(_, counter)| counter.get()).collect(); - assert_eq!(seen, [0, 0, 0, 0, 0, 1], "the counters are the panes' own"); + assert_eq!(seen, [0, 0, 0, 0, 0, 1, 0], "the counters are the panes' own"); } #[test] diff --git a/crates/voelin-gpui/src/shell/actions.rs b/crates/voelin-gpui/src/shell/actions.rs index 89ee31c..fb48eae 100644 --- a/crates/voelin-gpui/src/shell/actions.rs +++ b/crates/voelin-gpui/src/shell/actions.rs @@ -6,12 +6,18 @@ //! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings //! and menus come to the same handlers later. //! +//! The voice page and the call bar add `show_voice_view`, the page's own +//! buttons (the smaller stage, Leave) and the two affordances of the call bar +//! whose pages come with later slices (Share, the voice settings), which are +//! logged. +//! //! The channel tree and the members panel add `join_channel`, //! `join_with_password`, `toggle_collapse`, `search_members`, `open_member` and //! `open_client` (the last one only logs: the client's volume dialog is a //! dialog of its own slice). The callbacks of `bind/servers.rs` that are -//! still not here belong to the slices after: `show_voice_view` to the voice -//! page, `client_audio_changed` to the dialogs, and `copied` (the toast that +//! still not here belong to the slices after: `client_audio_changed` to the +//! dialogs (the member card has the volume and the mute of a person, +//! [`SetMemberVolume`] and [`SetMemberMuted`]), and `copied` (the toast that //! follows a copy) to whichever copies: [`Invite`] sets it itself. use gpui_kit::{Action, actions}; @@ -41,9 +47,47 @@ actions!( SubmitChannelPassword, /// Close the password prompt without joining. CancelChannelPassword, + /// The voice page's Leave (`Nav.show-voice(false)` then `disconnect_voice`). + LeaveVoice, + /// The voice page's Smaller stage / Larger stage (`ui.voice_compact`). + ToggleVoiceCompact, + /// The call bar's Share: the share menu comes with the stream slices, today it is logged. + OpenShare, + /// The call bar's voice settings: the settings come with their slice, today it is logged. + OpenVoiceSettings, ] ); +/// `show_voice_view`: the voice channel page on (the main area) or off (back to +/// the server page, where the chat will be). +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct ShowVoiceView { + /// Shown from now on. + pub on: bool, +} + +/// The member card's volume slider: the person's playback volume, in percent +/// (`member_volume` of the Slint card). +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SetMemberVolume { + /// The client's id on the server. + pub client: u16, + /// 0 to 200. + pub percent: f32, +} + +/// The member card's Mute for me: stop playing the person (local only). +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SetMemberMuted { + /// The client's id on the server. + pub client: u16, + /// Muted from now on. + pub muted: bool, +} + /// `select_server`: show a server (and observe it). #[derive(Clone, Debug, PartialEq, Action)] #[action(namespace = voelin, no_json)] diff --git a/crates/voelin-gpui/src/shell/channels.rs b/crates/voelin-gpui/src/shell/channels.rs index d2a0811..047a156 100644 --- a/crates/voelin-gpui/src/shell/channels.rs +++ b/crates/voelin-gpui/src/shell/channels.rs @@ -76,7 +76,7 @@ impl ChannelTree { } this.emptiness = emptiness; } - TreeEvent::People(..) | TreeEvent::Card => return, + TreeEvent::People(..) | TreeEvent::Voice(_) | TreeEvent::Card => return, } cx.notify(); }); diff --git a/crates/voelin-gpui/src/shell/main_panel.rs b/crates/voelin-gpui/src/shell/main_panel.rs index 596844b..3cfb5eb 100644 --- a/crates/voelin-gpui/src/shell/main_panel.rs +++ b/crates/voelin-gpui/src/shell/main_panel.rs @@ -14,7 +14,7 @@ use gpui_kit::{ use voelin_ui_vm::bridge::ServerItem; use voelin_ui_vm::servers::logic; -use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer}; +use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer, ShowVoiceView}; use super::widgets::{Avatar, Presence, icon, panel, tagged}; use crate::app::AppState; use crate::meter::Counters; @@ -173,7 +173,7 @@ impl Render for MainPanel { .text_center() .text_size(px(m.font_body)) .text_color(hsla(c.text_muted)) - .child("Its chat and its voice page come with the next slices."), + .child("Its chat comes with a later slice."), ) .child( div() @@ -202,6 +202,20 @@ impl Render for MainPanel { }), )) }) + .when(connected, |row| { + row.child(tagged( + "main-voice", + Button::new("main-voice") + .primary() + .label("Voice channel") + .on_click(|_, window, cx| { + window.dispatch_action( + Box::new(ShowVoiceView { on: true }), + cx, + ); + }), + )) + }) .child(tagged( "main-edit", Button::new("main-edit").label("Edit").on_click( diff --git a/crates/voelin-gpui/src/shell/members.rs b/crates/voelin-gpui/src/shell/members.rs index 1a07b0f..d559a49 100644 --- a/crates/voelin-gpui/src/shell/members.rs +++ b/crates/voelin-gpui/src/shell/members.rs @@ -8,12 +8,14 @@ //! the list applies). A talker redraws it, with the tree: a person's row has //! the speaking ring, "Speaking" and the bars, and no other pane of the window //! is told. [`MemberCardView`] is the card, a card over the window with a scrim -//! that a click outside closes; its buttons (the volume, a message, a poke, -//! friends, blocking) come with the slices that have those dialogs. +//! that a click outside closes; it has the volume and the mute of the person for +//! us (`SetMemberVolume`, `SetMemberMuted`), and its other buttons (a message, a +//! poke, friends, blocking) come with the slices that have those dialogs. use std::sync::Arc; use gpui_kit::component::input::{Input, InputEvent, InputState}; +use gpui_kit::component::slider::{Slider, SliderEvent, SliderState}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ AnyElement, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, @@ -23,7 +25,7 @@ use gpui_kit::{ use voelin_ui_vm::bridge::{MemberCard, MemberItem}; use voelin_ui_vm::list::Changes; -use super::actions::{OpenMember, SearchMembers}; +use super::actions::{OpenMember, SearchMembers, SetMemberMuted, SetMemberVolume}; use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check}; use super::widgets::{ Avatar, IconButton, Presence, chip, icon, live_badge, small_picture, speaking_bars, @@ -84,7 +86,7 @@ impl MembersPane { (this.total, this.emptiness) = now; } TreeEvent::Card => this.open = model.read(cx).card().map(|card| card.id), - TreeEvent::Rows(..) | TreeEvent::Selection => return, + TreeEvent::Rows(..) | TreeEvent::Voice(_) | TreeEvent::Selection => return, } cx.notify(); }), @@ -448,25 +450,67 @@ impl Render for MembersPane { } /// The card over a member row, over the window: a scrim that a click outside -/// the card closes, and the card with what is known of the person. +/// the card closes, and the card with what is known of the person, and the +/// volume and the mute of their voice for us (the Slint card's Volume rows). pub struct MemberCardView { card: Option, /// How wide the members panel is: the card stands beside it. panel_width: f32, - _subscription: Subscription, + /// The volume slider, in percent (0 to 200, as the Slint card's). + slider: Entity, + _subscriptions: Vec, } +/// The loudest the card's slider plays a person, in percent. +const LOUDEST: f32 = 200.0; + impl MemberCardView { /// A card that follows `model`, beside a panel `panel_width` pixels wide. - pub fn new(model: &Entity, panel_width: f32, cx: &mut Context) -> Self { + pub fn new( + model: &Entity, + panel_width: f32, + window: &mut Window, + cx: &mut Context, + ) -> Self { let card = model.read(cx).card().cloned(); - let subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| { - if matches!(event, TreeEvent::Card) { - this.card = model.read(cx).card().cloned(); - cx.notify(); - } + let slider = cx.new(|_| { + SliderState::new() + .min(0.0) + .max(LOUDEST) + .step(5.0) + .default_value(card.as_ref().map_or(100.0, |card| card.volume)) }); - Self { card, panel_width, _subscription: subscription } + let subscriptions = vec![ + cx.subscribe_in( + model, + window, + |this: &mut Self, model, event: &TreeEvent, window, cx| { + if matches!(event, TreeEvent::Card) { + this.card = model.read(cx).card().cloned(); + // The slider shows the person's volume as it is now (a change + // the slider itself made comes back the same). + if let Some(card) = &this.card { + let volume = card.volume.clamp(0.0, LOUDEST); + this.slider + .update(cx, |slider, cx| slider.set_value(volume, window, cx)); + } + cx.notify(); + } + }, + ), + cx.subscribe_in( + &slider, + window, + |this: &mut Self, _, event: &SliderEvent, window, cx| { + if let (SliderEvent::Change(value), Some(card)) = (event, &this.card) { + let client = u16::try_from(card.id).unwrap_or_default(); + let percent = value.end(); + window.dispatch_action(Box::new(SetMemberVolume { client, percent }), cx); + } + }, + ), + ]; + Self { card, panel_width, slider, _subscriptions: subscriptions } } /// The card that is open. @@ -485,6 +529,79 @@ fn caption(theme: &VoelinTheme, text: &'static str) -> impl IntoElement { .child(text) } +/// The card's Volume rows: what the person is played at, a mute for us and +/// the slider. Both need a person the server gave a unique id (the choice is +/// kept by it), as the Slint card's do. +fn volume( + theme: &VoelinTheme, + person: &MemberCard, + slider: &Entity, +) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let client = u16::try_from(person.id).unwrap_or_default(); + let (muted, known) = (person.muted, person.known); + div() + .id("member-volume") + .debug_selector(|| "member-volume".into()) + .flex() + .flex_col() + .gap(px(m.space_2)) + .pt(px(m.space_3)) + .border_t_1() + .border_color(hsla(c.border_popup)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .child( + div() + .flex_1() + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_secondary)) + .child("Volume"), + ) + .child( + div() + .id("member-volume-percent") + .debug_selector(|| "member-volume-percent".into()) + .text_size(px(m.font_xs)) + .text_color(hsla(c.text_muted)) + .child(format!("{}%", person.volume.round() as i32)), + ), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child( + IconButton::new( + "member-mute", + if muted { "volume-x" } else { "volume-2" }, + if muted { "Unmute for me" } else { "Mute for me" }, + ) + .size(30.0) + .danger() + .checked(muted) + .enabled(known) + .on_click(move |_, window, cx| { + window + .dispatch_action(Box::new(SetMemberMuted { client, muted: !muted }), cx) + }), + ) + .child( + div() + .id("member-slider") + .debug_selector(|| "member-slider".into()) + .flex_1() + .child(Slider::new(slider).disabled(!known || muted)), + ), + ) +} + impl Render for MemberCardView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let Some(person) = self.card.clone() else { return div().into_any_element() }; @@ -611,7 +728,8 @@ impl Render for MemberCardView { )), ) }) - .child(facts); + .child(facts) + .child(volume(&theme, &person, &self.slider)); // The card stands beside the panel, near the top. div() .id("member-card-scrim") diff --git a/crates/voelin-gpui/src/shell/mod.rs b/crates/voelin-gpui/src/shell/mod.rs index 56778ef..417ec23 100644 --- a/crates/voelin-gpui/src/shell/mod.rs +++ b/crates/voelin-gpui/src/shell/mod.rs @@ -1,12 +1,13 @@ //! 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 +//! the sidebar, the main area, the voice channel page that takes its place +//! while voice is on screen, the server form and the toast, each an entity //! that listens to the per-area signals of the root state //! ([`crate::signals`]) and tells the window only when what it shows changed, -//! and the actions the user's moves are ([`actions`]). The rail, the top bar -//! and the main area are embedded cached (they have a size of their own), so -//! gpui-pre 0.3.10 renders them again only when they were told something -//! changed; [`crate::view::MainView`] puts them in the window. +//! and the actions the user's moves are ([`actions`]). The rail, the top bar, +//! the main area and the voice page are embedded cached (they have a size of +//! their own), so gpui-pre 0.3.10 renders them again only when they were told +//! something changed; [`crate::view::MainView`] puts them in the window. pub mod actions; mod channels; @@ -19,6 +20,7 @@ mod sidebar; mod toast; mod topbar; mod tree_model; +mod voice; pub mod widgets; pub use channels::ChannelTree; @@ -37,3 +39,4 @@ pub use sidebar::{Sidebar, SidebarView}; pub use toast::{TOAST_TIME, Toast}; pub use topbar::TopBar; pub use tree_model::{Emptiness, TreeEvent, TreeModel}; +pub use voice::{SHORT_WINDOW, VoiceHead, VoicePage}; diff --git a/crates/voelin-gpui/src/shell/sidebar.rs b/crates/voelin-gpui/src/shell/sidebar.rs index e9edad2..60733b6 100644 --- a/crates/voelin-gpui/src/shell/sidebar.rs +++ b/crates/voelin-gpui/src/shell/sidebar.rs @@ -1,5 +1,6 @@ //! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of -//! `shells/common.slint`): the server on screen, its channel tree +//! `shells/common.slint`): the server on screen (its card has the server's +//! banner behind it, under the same veil as the tree's rows), its channel tree //! ([`super::ChannelTree`], a cached pane of its own), 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 listens to the servers' and the toolbar's @@ -8,8 +9,8 @@ use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent, - ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement, Styled as _, - Subscription, Window, div, px, + ObjectFit, ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement, + Styled as _, StyledImage as _, Subscription, Window, div, px, }; use voelin_core::TransmitMode; use voelin_ui_vm::Rgb; @@ -21,9 +22,10 @@ use super::actions::{ DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted, }; use super::channels::ChannelTree; -use super::widgets::{Avatar, IconButton, Presence, card, icon, panel}; +use super::widgets::{Avatar, IconButton, Presence, banner_scrim, card, icon, panel}; use crate::app::AppState; use crate::meter::Counters; +use crate::pictures::{PictureKey, picture}; use crate::signals::Area; use crate::theme::{VoelinTheme, hsla}; @@ -34,6 +36,8 @@ pub struct SidebarView { pub server: Option, /// "9 online · 7 channels" once its presence is known, else empty. pub stats: String, + /// The server's banner, behind its card; empty without one. + pub server_banner: ImageRef, /// Our nickname there; empty without a server. pub nickname: String, /// The channel we are in; empty while connecting. @@ -54,6 +58,9 @@ pub struct SidebarView { pub transmitting: bool, /// The transmit mode is push-to-talk, so the card has a hold-to-talk button. pub hold_to_talk: bool, + /// How our voice is sent, as the audio settings say: the card has the + /// button for push-to-talk and says the mode otherwise. + pub transmit: TransmitMode, } impl SidebarView { @@ -68,6 +75,7 @@ impl SidebarView { Self { server, stats: card.server_stats, + server_banner: card.server_banner, nickname: card.nickname, own_channel: card.own_channel, own_avatar: card.own_avatar, @@ -78,6 +86,7 @@ impl SidebarView { output_muted: card.output_muted, transmitting: card.transmitting, hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk, + transmit: app.vm.audio.transmit, } } } @@ -104,7 +113,23 @@ impl Sidebar { }; let subscriptions = signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| { - let view = SidebarView::of(app.read(cx)); + let state = app.read(cx); + let view = SidebarView::of(state); + // The button goes away when voice leaves `Connected`, transmit + // leaves push-to-talk, or another server is shown; and a drop + // and reconnect inside one batch ends the hold in `AppState` + // while `view.voice_connected` stays true. Keep `holding` in + // sync with the root state's own button hold (this observer + // only sets its own fields). + let same_server = + view.server.as_ref().map(|s| s.id) == this.view.server.as_ref().map(|s| s.id); + let held_here = view + .server + .as_ref() + .is_some_and(|s| state.button_held() == Some(i64::from(s.id))); + if !view.voice_connected || !view.hold_to_talk || !same_server || !held_here { + this.holding = false; + } if view != this.view { this.view = view; cx.notify(); @@ -118,6 +143,19 @@ impl Sidebar { &self.view } + /// Whether the hold-to-talk button is currently held down. + #[cfg(test)] + pub(crate) fn is_holding(&self) -> bool { + self.holding + } + + /// Let go of the hold-to-talk button if it is held (the window lost the + /// focus: the release will not come to it): whether it was held. The caller + /// tells the session. + pub fn release(&mut self) -> bool { + std::mem::take(&mut self.holding) + } + /// 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) { @@ -126,18 +164,41 @@ impl Sidebar { } } -/// The server's name, its icon and how many are there. +/// The server's name, its icon and how many are there, over its banner when it +/// has one (`ServerHeader` of `channels.slint`: the picture covers the card, +/// the surface veil of `banner-picture.slint` lies over it, and the stats read +/// in the text colour instead of the secondary one). 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() }; + let banner = PictureKey::of(&view.server_banner); + let ink = if banner.is_some() { c.text } else { c.text_muted }; card(theme, 0xff) .id("sidebar-server") .debug_selector(|| "sidebar-server".into()) + .relative() + .overflow_hidden() .p(px(m.space_3)) .flex() .flex_row() .items_center() .gap(px(m.space_3)) + .when_some(banner, |card, key| { + card.child( + div() + .id("sidebar-server-banner") + .debug_selector(|| "sidebar-server-banner".into()) + .absolute() + .top(px(0.0)) + .left(px(0.0)) + .size_full() + // The picture covers the card and is cropped to it, not past + // its border. + .overflow_hidden() + .child(picture(key).size_full().object_fit(ObjectFit::Cover)), + ) + .child(div().absolute().top(px(0.0)).left(px(0.0)).size_full().bg(banner_scrim(theme))) + }) .child( Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint) .image(item.icon.clone()) @@ -158,16 +219,22 @@ fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> im .child(item.name.to_string()), ) .child( - div() - .truncate() - .text_size(px(m.font_sm)) - .text_color(hsla(c.text_muted)) - .child(stats), + div().truncate().text_size(px(m.font_sm)).text_color(hsla(ink)).child(stats), ), ) } -/// "Voice Connected" and our channel, disconnect and hold to talk. +/// How our voice is sent, in words, for the modes that have no button. +fn transmit_words(mode: TransmitMode) -> &'static str { + match mode { + TransmitMode::PushToTalk => "Push to talk", + TransmitMode::VoiceActivation => "Voice activity", + TransmitMode::Continuous => "Open microphone", + } +} + +/// "Voice Connected" and our channel, disconnect, and Hold to talk in the +/// push-to-talk mode (the other modes say themselves). fn voice_card( theme: &VoelinTheme, view: &SidebarView, @@ -235,6 +302,26 @@ fn voice_card( }), ), ) + .when(view.voice_connected && !view.hold_to_talk, |card| { + card.child( + div() + .id("transmit-mode") + .debug_selector(|| "transmit-mode".into()) + .h(px(m.control_height_sm)) + .flex() + .flex_row() + .items_center() + .justify_center() + .gap(px(m.space_2)) + .child(icon("mic", m.icon_sm, c.text_muted)) + .child( + div() + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_muted)) + .child(transmit_words(view.transmit)), + ), + ) + }) .when(view.voice_connected && view.hold_to_talk, |card| { card.child( div() diff --git a/crates/voelin-gpui/src/shell/tree_model.rs b/crates/voelin-gpui/src/shell/tree_model.rs index 8fff4fc..4369d05 100644 --- a/crates/voelin-gpui/src/shell/tree_model.rs +++ b/crates/voelin-gpui/src/shell/tree_model.rs @@ -11,6 +11,11 @@ //! inserted, not a list that starts again at the top. A change that moves none //! of what a pane shows emits nothing. //! +//! The people of our voice channel (`TreeView::members`, the voice page's +//! rows) come out of the same build as the other two lists: the model keeps +//! them and emits them when they differ ([`TreeEvent::Voice`]), so the voice +//! page needs no build of its own. +//! //! **The tree marks who is talking**, as the Slint tree does (the ring on the //! avatar and the speaking bars on the row): someone who starts or stops //! talking changes one row of the tree and one of the members panel, so each @@ -93,6 +98,10 @@ pub enum TreeEvent { /// The members panel's rows: the operations from the rows the pane has to /// the rows carried (the model's [`TreeModel::people`] when it made them). People(Changes, Arc>), + /// The people of our voice channel, the voice page's rows, as they are + /// now (the whole list: the page lays its people out in a wrapping row, not + /// a virtual list, and takes them as they come). + Voice(Arc>), /// The card over a member row opened, changed or closed /// ([`TreeModel::card`]). Card, @@ -125,6 +134,7 @@ pub struct TreeModel { refreshes: u64, rows: Arc>, people: Arc>, + voice: Arc>, total: i32, card: Option, selected: Option, @@ -153,6 +163,7 @@ pub(super) fn debug_check(old: usize, changes: &Changes, new: usize) { struct Snapshot { rows: Vec, people: Vec, + voice: Vec, total: i32, card: Option, selected: Option, @@ -164,14 +175,15 @@ impl Snapshot { fn of(app: &AppState) -> Self { let vm = &app.vm; let view = vm.current.and_then(|id| vm.sessions.get(&id)); - let (rows, people, total) = match logic::tree_view(vm, false) { - Some(tree) => (tree.rows, tree.server_members, tree.member_total), - None => (Vec::new(), Vec::new(), 0), + let (rows, people, voice, total) = match logic::tree_view(vm, false) { + Some(tree) => (tree.rows, tree.server_members, tree.members, tree.member_total), + None => (Vec::new(), Vec::new(), Vec::new(), 0), }; Self { people_emptiness: Emptiness::of_people(vm, people.len(), total), rows, people, + voice, total, card: view .and_then(|view| view.member_card.map(|id| (view, id))) @@ -197,6 +209,7 @@ impl TreeModel { refreshes: 0, rows: Arc::new(snapshot.rows), people: Arc::new(snapshot.people), + voice: Arc::new(snapshot.voice), total: snapshot.total, card: snapshot.card, selected: snapshot.selected, @@ -216,6 +229,12 @@ impl TreeModel { &self.people } + /// The people of our voice channel, in the voice page's order (empty while + /// voice is not connected). + pub fn voice(&self) -> &Arc> { + &self.voice + } + /// How many are on the server (the query clients not counted). pub fn total(&self) -> i32 { self.total @@ -266,6 +285,10 @@ impl TreeModel { if !people.is_empty() { self.people = Arc::new(new.people); } + let voice = *self.voice != new.voice; + if voice { + self.voice = Arc::new(new.voice); + } let lists = (self.emptiness, self.people_emptiness, self.total) != (new.emptiness, new.people_emptiness, new.total); (self.emptiness, self.people_emptiness, self.total) = @@ -280,6 +303,9 @@ impl TreeModel { if !people.is_empty() { cx.emit(TreeEvent::People(people, self.people.clone())); } + if voice { + cx.emit(TreeEvent::Voice(self.voice.clone())); + } if lists { cx.emit(TreeEvent::Lists); } diff --git a/crates/voelin-gpui/src/shell/voice.rs b/crates/voelin-gpui/src/shell/voice.rs new file mode 100644 index 0000000..327c86f --- /dev/null +++ b/crates/voelin-gpui/src/shell/voice.rs @@ -0,0 +1,657 @@ +//! The voice channel page (`VoiceView` of `screens/voice.slint`, with its +//! `Participant` of `voice-parts.slint` and the `CallBar`): the channel we are +//! in, who is there and who talks, and the call's controls under them. +//! +//! [`VoicePage`] is a cached pane of its own, a sibling of the server page +//! ([`super::MainPanel`]) that [`crate::view::MainView`] puts in the main +//! area in its place while the page is asked for and voice is connected +//! ([`crate::app::AppState::voice_page_shown`]). It takes its people from the +//! tree model ([`TreeEvent::Voice`]: the rows `TreeView::members` gave the one +//! build the tree and the members panel come from, so the page builds nothing +//! of its own) and the header and the call bar from the servers' and the +//! toolbar's signals, compares what it would show with what it showed, and +//! tells the window only when they differ. A person who starts or stops +//! talking, or mutes, is one row of the page and one render of this pane. +//! +//! The larger stage lays the people out as large avatars in a wrapping row; +//! the smaller stage (`ui.voice_compact`, and always in a window under 800 +//! pixels tall) is one row of small avatars that scrolls sideways. The streams +//! of the Slint page come with the stream slices and its chat with the chat's. + +use std::sync::Arc; + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ObjectFit, + ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, StyledImage as _, + Subscription, Window, div, px, +}; +use voelin_ui_vm::bridge::MemberItem; +use voelin_ui_vm::image::ImageRef; +use voelin_ui_vm::servers::logic; + +use super::actions::{ + Invite, LeaveVoice, OpenMember, OpenShare, OpenVoiceSettings, SetInputMuted, SetOutputMuted, + ShowVoiceView, ToggleVoiceCompact, +}; +use super::tree_model::{TreeEvent, TreeModel}; +use super::widgets::{Avatar, IconButton, banner_scrim, icon, live_badge, panel, speaking_bars_in}; +use crate::app::AppState; +use crate::meter::Counters; +use crate::pictures::{PictureKey, picture}; +use crate::signals::Area; +use crate::theme::tokens::Rgba; +use crate::theme::{VoelinTheme, hsla}; + +/// A window under this tall (pixels) has the smaller stage whatever the +/// setting says (`Nav.short` of the Slint front end). +pub const SHORT_WINDOW: f32 = 800.0; + +/// What the page's header and call bar show, from the state. +#[derive(Clone, Debug, PartialEq)] +pub struct VoiceHead { + /// The channel we are in, as the tree shows it. + pub channel: String, + /// Its topic. + pub topic: String, + /// Its banner, empty without one. + pub banner: ImageRef, + /// Its client limit, -1 without one. + pub limit: i32, + /// Voice is connected. + pub connected: bool, + /// Our microphone is muted. + pub input_muted: bool, + /// Our sound is muted. + pub output_muted: bool, + /// The server can stream (TeamSpeak 6 with voice): the call bar has Share. + pub can_share: bool, +} + +impl VoiceHead { + /// The header and the call bar for the state. + pub fn of(app: &AppState) -> Self { + let card = logic::toolbar(&app.vm, |_| ImageRef::default()); + let can_share = app + .vm + .current + .and_then(|id| app.vm.sessions.get(&id)) + .is_some_and(|view| view.streams_available()); + Self { + channel: card.own_channel, + topic: card.own_channel_topic, + banner: card.own_channel_banner, + limit: card.own_channel_limit, + connected: card.voice_connected, + input_muted: card.input_muted, + output_muted: card.output_muted, + can_share, + } + } +} + +/// The voice channel page. +pub struct VoicePage { + head: VoiceHead, + people: Arc>, + /// The smaller stage by choice. + compact: bool, + /// The window is too short for the larger stage. + short: bool, + counters: Counters, + _subscriptions: Vec, +} + +impl VoicePage { + /// A page that follows `app` for the header and the call bar and `model` for + /// the people, on the stage the setting says (`compact`) in a window that is + /// `short` or not. + pub fn new( + app: &Entity, + model: &Entity, + compact: bool, + short: bool, + cx: &mut Context, + ) -> Self { + let (head, counters, signals) = { + let state = app.read(cx); + (VoiceHead::of(state), state.counters().clone(), state.signals().clone()) + }; + let mut subscriptions = + signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| { + let head = VoiceHead::of(app.read(cx)); + if head != this.head { + this.head = head; + cx.notify(); + } + }); + subscriptions.push(cx.subscribe(model, |this: &mut Self, _, event: &TreeEvent, cx| { + if let TreeEvent::Voice(people) = event { + this.people = people.clone(); + cx.notify(); + } + })); + let people = model.read(cx).voice().clone(); + Self { head, people, compact, short, counters, _subscriptions: subscriptions } + } + + /// What the header and the call bar show. + pub fn head(&self) -> &VoiceHead { + &self.head + } + + /// The people it shows. + pub fn people(&self) -> &[MemberItem] { + &self.people + } + + /// Whether the page is on the smaller stage now: chosen, or the window is too + /// short for the larger. + pub fn compact_shown(&self) -> bool { + self.compact || self.short + } + + /// Whether the window is too short for the larger stage (the stage button is + /// off then). + pub fn short(&self) -> bool { + self.short + } + + /// The setting `ui.voice_compact` is `compact`: tells the window if the stage + /// changes. + pub fn set_compact(&mut self, compact: bool, cx: &mut Context) { + if self.compact != compact { + self.compact = compact; + cx.notify(); + } + } + + /// The window is `short` (under [`SHORT_WINDOW`] tall) or not. + pub fn set_short(&mut self, short: bool, cx: &mut Context) { + if self.short != short { + self.short = short; + cx.notify(); + } + } +} + +/// The ring around a person's avatar: green while they talk, blue while they +/// stream (3 pixels, 2 on the smaller stage), else the quiet border of the +/// larger stage (2 pixels; the smaller has none). +fn ring(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> (u8, Rgba) { + let c = &theme.colors; + let loud = if compact { 2 } else { 3 }; + if person.talking { + (loud, c.success) + } else if person.streaming { + (loud, c.accent) + } else { + (if compact { 0 } else { 2 }, c.border_strong) + } +} + +/// What the corner of a person's avatar says: the bars while they talk, else +/// that their sound or their microphone is off. +fn corner(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> Option { + let (c, bars) = (&theme.colors, if compact { 12.0 } else { 14.0 }); + let size = if compact { 22.0 } else { 26.0 }; + if !(person.talking || person.muted || person.sound_off) { + return None; + } + let (face, inside) = if person.talking { + if compact { + (c.accent, speaking_bars_in(theme, bars, c.on_accent).into_any_element()) + } else { + (c.surface, speaking_bars_in(theme, bars, c.success).into_any_element()) + } + } else { + let name = if person.sound_off { "headphone-off" } else { "mic-off" }; + (c.surface, icon(name, if compact { 12.0 } else { 15.0 }, c.danger).into_any_element()) + }; + let (id, talking) = (person.id, person.talking); + let inset = if compact { 0.0 } else { 2.0 }; + Some( + div() + .absolute() + .right(px(inset)) + .bottom(px(inset)) + .debug_selector(move || { + format!("voice-{}-{id}", if talking { "speaking" } else { "off" }) + }) + .size(px(size)) + .rounded(px(size / 2.0)) + .border_2() + .border_color(hsla(c.surface)) + .bg(hsla(face)) + .flex() + .items_center() + .justify_center() + .child(inside) + .into_any_element(), + ) +} + +/// One person: an avatar with its ring, the mark in its corner, the name with +/// the crown of an admin, and what they do. A click opens their card. +fn participant(theme: &VoelinTheme, person: &MemberItem, compact: bool) -> AnyElement { + let (c, m) = (&theme.colors, &theme.metrics); + let size = if compact { 54.0 } else { 80.0 }; + let width = if compact { 68.0 } else { 120.0 }; + let outer = size + 8.0; + let id = person.id; + let (ring_width, ring_color) = ring(theme, person, compact); + let client = u16::try_from(id).unwrap_or_default(); + let name_width = width - if person.admin { 16.0 } else { 0.0 }; + let words = if person.talking { + "Speaking" + } else if person.streaming { + "Streaming" + } else if person.away { + "Away" + } else { + "" + }; + let mut face = div() + .relative() + .size(px(outer)) + .flex_none() + .rounded(px(outer / 2.0)) + .border_color(hsla(ring_color)) + .flex() + .items_center() + .justify_center(); + face = match ring_width { + 3 => face.border_3(), + 2 => face.border_2(), + _ => face, + }; + let mut face = face.child( + Avatar::new(("voice-avatar", id as u64), size, &person.initials, person.tint) + .image(person.avatar.clone()), + ); + if let Some(mark) = corner(theme, person, compact) { + face = face.child(mark); + } + div() + .id(("voice-member", id as u64)) + .debug_selector(move || format!("voice-member-{id}")) + .w(px(width)) + .flex_none() + .flex() + .flex_col() + .items_center() + .gap(px(if compact { m.space_1 } else { m.space_2 })) + .cursor_pointer() + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(OpenMember { client: i32::from(client) }), cx) + }) + .child(face) + .child( + div() + .flex() + .flex_row() + .items_center() + .justify_center() + .gap(px(if compact { m.space_1 } else { m.space_2 })) + .child( + div() + .max_w(px(name_width)) + .truncate() + .text_size(px(if compact { m.font_sm } else { m.font_md })) + .font_weight(if compact { FontWeight::NORMAL } else { FontWeight::MEDIUM }) + .text_color(hsla(if person.myself { c.accent_text } else { c.text })) + .child(person.name.to_string()), + ) + .when(person.admin, |row| { + row.child(icon("crown", if compact { 13.0 } else { 15.0 }, c.gold)) + }), + ) + .when(!compact, |column| { + column.child( + div() + .h(px(m.font_sm + 4.0)) + .flex() + .flex_row() + .items_center() + .justify_center() + .gap(px(m.space_2)) + .when(person.talking, |row| row.child(speaking_bars_in(theme, 12.0, c.success))) + .child( + div() + .truncate() + .text_size(px(m.font_sm)) + .text_color(hsla(if person.talking { + c.success + } else { + c.text_secondary + })) + .child(words), + ) + .when(person.streaming && !person.talking, |row| { + row.child(icon("monitor", 14.0, c.text_secondary)) + }), + ) + }) + .when(compact && person.streaming, |column| column.child(live_badge(theme))) + .into_any_element() +} + +/// The channel's name, its topic and how many are in voice, over its banner. +fn header( + theme: &VoelinTheme, + head: &VoiceHead, + people: usize, + page: &VoicePage, +) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let banner = PictureKey::of(&head.banner); + let ink = if banner.is_some() { c.text } else { c.text_secondary }; + let compact = page.compact_shown(); + let count = if head.limit >= 0 { + format!("{people} in voice / {} total", head.limit) + } else { + format!("{people} in voice") + }; + let stage = if page.short() { + "The window is too short for the larger stage" + } else if compact { + "Larger stage" + } else { + "Smaller stage" + }; + div() + .id("voice-header") + .debug_selector(|| "voice-header".into()) + .relative() + .w_full() + .flex_none() + .overflow_hidden() + .when_some(banner, |header, key| { + header + .child( + div() + .absolute() + .top(px(0.0)) + .left(px(0.0)) + .size_full() + .child(picture(key).size_full().object_fit(ObjectFit::Cover)), + ) + .child( + div() + .id("voice-banner") + .debug_selector(|| "voice-banner".into()) + .absolute() + .top(px(0.0)) + .left(px(0.0)) + .size_full() + .bg(banner_scrim(theme)), + ) + }) + .child( + div() + .relative() + .flex() + .flex_row() + .gap(px(m.space_5)) + .pl(px(m.space_7)) + .pr(px(m.space_5)) + .pt(px(m.space_5)) + .pb(px(m.space_3)) + .child(div().pt(px(m.space_1)).child(icon("volume-2", 40.0, c.text_secondary))) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(m.space_1)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child( + div() + .id("voice-channel") + .debug_selector(|| "voice-channel".into()) + .flex_1() + .min_w_0() + .truncate() + .text_size(px(m.font_3xl)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(head.channel.clone()), + ) + .child( + IconButton::new( + "voice-invite", + "user-plus", + "Copy invite link", + ) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(Invite), cx) + }), + ) + .child( + IconButton::new( + "voice-stage", + if compact { "chevron-down" } else { "chevron-up" }, + stage, + ) + .enabled(!page.short()) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(ToggleVoiceCompact), cx) + }), + ) + .child( + IconButton::new( + "voice-chat-only", + "message-square", + "Chat only", + ) + .on_click(|_, window, cx| { + window.dispatch_action( + Box::new(ShowVoiceView { on: false }), + cx, + ) + }), + ), + ) + .when(!head.topic.is_empty(), |column| { + column.child( + div() + .truncate() + .text_size(px(m.font_md)) + .text_color(hsla(ink)) + .child(head.topic.clone()), + ) + }) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .child(icon("users", 16.0, c.text_secondary)) + .child( + div() + .id("voice-count") + .debug_selector(|| "voice-count".into()) + .text_size(px(m.font_body)) + .text_color(hsla(ink)) + .child(count), + ), + ), + ), + ) +} + +/// Mute, deafen, share, the voice settings and Leave, under the people. +fn call_bar(theme: &VoelinTheme, head: &VoiceHead) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let (input_muted, output_muted) = (head.input_muted, head.output_muted); + let leave = c.danger; + div() + .id("voice-callbar") + .debug_selector(|| "voice-callbar".into()) + .w_full() + .flex_none() + .flex() + .flex_row() + .justify_center() + .items_center() + .gap(px(m.space_3)) + .px(px(m.space_6)) + .pb(px(m.space_3)) + .child( + IconButton::new( + "call-mic", + if input_muted { "mic-off" } else { "mic" }, + if input_muted { "Microphone off" } else { "Microphone on" }, + ) + .size(44.0) + .round() + .filled() + .danger() + .checked(input_muted) + .enabled(head.connected) + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx) + }), + ) + .child( + IconButton::new( + "call-sound", + if output_muted { "headphone-off" } else { "headphones" }, + if output_muted { "Sound off" } else { "Sound on" }, + ) + .size(44.0) + .round() + .filled() + .danger() + .checked(output_muted) + .enabled(head.connected) + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx) + }), + ) + .when(head.can_share, |bar| { + bar.child( + IconButton::new("call-share", "monitor-up", "Share or go live") + .size(44.0) + .round() + .filled() + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenShare), cx)), + ) + }) + .child( + IconButton::new("call-settings", "settings", "Voice Settings") + .size(44.0) + .round() + .filled() + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenVoiceSettings), cx)), + ) + .child( + div() + .id("call-leave") + .debug_selector(|| "call-leave".into()) + .h(px(m.control_height)) + .px(px(m.space_5)) + .flex_none() + .flex() + .flex_row() + .items_center() + .justify_center() + .gap(px(m.space_3)) + .rounded(px(m.radius_md)) + .border_1() + .border_color(hsla(leave.with_alpha(0x73))) + .bg(hsla(c.danger_soft)) + .cursor_pointer() + .hover(move |style| style.bg(hsla(c.danger_soft.mix(leave, 0.25)))) + .on_click(|_, window, cx| window.dispatch_action(Box::new(LeaveVoice), cx)) + .child(icon("phone-off", m.icon_md, leave)) + .child( + div() + .text_size(px(m.font_body)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(leave)) + .child("Leave"), + ), + ) +} + +impl Render for VoicePage { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.counters.panes.voice.incr(); + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + let compact = self.compact_shown(); + let stage = if compact { + // One row, scrolling sideways when there are many; centred while it fits. + div() + .id("voice-people") + .debug_selector(|| "voice-people".into()) + .w_full() + .h(px(112.0)) + .flex_none() + .overflow_x_scroll() + .flex() + .flex_row() + .child( + div() + .h_full() + .flex_none() + .mx_auto() + .flex() + .flex_row() + .gap(px(m.space_3)) + .px(px(m.space_6)) + .pt(px(m.space_2)) + .children( + self.people.iter().map(|person| participant(&theme, person, true)), + ), + ) + } else { + // Centred, wrapping into more rows when there are many. + div() + .id("voice-people") + .debug_selector(|| "voice-people".into()) + .w_full() + // Rows taller than the page scroll; the header and the call bar keep + // their places. + .flex_shrink(1.0) + .min_h_0() + .overflow_y_scroll() + .flex() + .flex_row() + .flex_wrap() + .justify_center() + .gap_x(px(m.space_6)) + .gap_y(px(m.space_4)) + .px(px(m.space_6)) + .pt(px(m.space_3)) + .pb(px(m.space_4)) + .children(self.people.iter().map(|person| participant(&theme, person, false))) + }; + // A cached pane's root takes the size its place gives it. + panel(&theme) + .id("voice-page") + .debug_selector(|| "voice-page".into()) + .size_full() + .child(header(&theme, &self.head, self.people.len(), self)) + .child(stage) + .child(call_bar(&theme, &self.head)) + .child( + div() + .flex_1() + .flex() + .items_center() + .justify_center() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_muted)) + .child("The channel's chat comes with a later slice."), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/widgets.rs b/crates/voelin-gpui/src/shell/widgets.rs index 18829d4..cf2b4aa 100644 --- a/crates/voelin-gpui/src/shell/widgets.rs +++ b/crates/voelin-gpui/src/shell/widgets.rs @@ -4,6 +4,8 @@ //! counterparts of `ui/components/avatar.slint`, `button.slint` and //! `shells/common.slint`'s `Panel`. +use std::sync::Arc; + use gpui_kit::{ AnyElement, App, Background, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, @@ -181,7 +183,10 @@ impl RenderOnce for Avatar { .justify_center() .bg(hsla(if key.is_some() { c.surface_3 } else { tint(self.tint) })); let face = match key { - Some(key) => face.child(picture(key).size_full().object_fit(ObjectFit::Cover)), + // The picture rounds its own corners: a parent's `overflow_hidden` + // clips to a rectangle. + Some(key) => face + .child(picture(key).size_full().rounded(px(radius)).object_fit(ObjectFit::Cover)), None => { let (letters, size) = initials_for(&self.initials, self.size); face.child( @@ -229,7 +234,7 @@ 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. +/// dimmed and does nothing, and keeps its tooltip. #[derive(IntoElement)] pub struct IconButton { id: ElementId, @@ -337,8 +342,14 @@ impl RenderOnce for IconButton { 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(); + #[cfg(test)] + let tooltip_selector = selector.clone(); + // Key the element by both its id and its label so GPUI drops stale + // hover/tooltip state when a toggle button's label changes, while + // keeping the debug selector stable for tests. + let id = ElementId::NamedChild(Arc::new(self.id), self.label); let mut button = div() - .id(self.id) + .id(id) .debug_selector(move || selector) .size(px(self.size)) .flex_none() @@ -351,14 +362,17 @@ impl RenderOnce for IconButton { if self.filled { button = button.border_1().border_color(hsla(ink)); } + // The tooltip is there while the button is off too: it says why (the voice + // page's stage button in a window too short for the larger stage). + button = button.tooltip(move |window, cx| { + #[cfg(test)] + tests::record_tooltip(&tooltip_selector, &label); + gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx) + }); 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) - }, - ); + button = button.cursor_pointer().hover(move |style| style.bg(hsla(hover))); match self.on_click { Some(handler) => button.on_click(move |event, window, cx| handler(event, window, cx)), None => button, @@ -432,13 +446,14 @@ pub fn live_badge(theme: &VoelinTheme) -> impl IntoElement { /// Three bars: someone speaks. (The Slint bars move; these stand still, as /// nothing here may draw the window anew with the clock.) pub fn speaking_bars(theme: &VoelinTheme, size: f32) -> impl IntoElement { - let c = &theme.colors; + speaking_bars_in(theme, size, theme.colors.success) +} + +/// The speaking bars in `color`, for a ground the green does not stand out on +/// (the accent of the voice page's corner badge). +pub fn speaking_bars_in(_theme: &VoelinTheme, size: f32, color: Rgba) -> impl IntoElement { let bar = move |height: f32| { - div() - .w(px(size * 3.0 / 14.0)) - .h(px(size * height)) - .rounded(px(size / 9.0)) - .bg(hsla(c.success)) + div().w(px(size * 3.0 / 14.0)).h(px(size * height)).rounded(px(size / 9.0)).bg(hsla(color)) }; div() .w(px(size)) @@ -483,11 +498,27 @@ pub fn chip( .child(text.into()) } +/// Tooltips built by [`IconButton`] since the last call, as `(selector, label)`. +#[cfg(test)] +pub(crate) fn take_tooltips() -> Vec<(String, String)> { + tests::TOOLTIPS.with(|log| std::mem::take(&mut *log.borrow_mut())) +} + #[cfg(test)] mod tests { + use std::cell::RefCell; + use super::*; use crate::theme::Choice; + thread_local! { + pub(super) static TOOLTIPS: RefCell> = const { RefCell::new(Vec::new()) }; + } + + pub(super) fn record_tooltip(selector: &str, label: &str) { + TOOLTIPS.with(|log| log.borrow_mut().push((selector.to_owned(), label.to_owned()))); + } + #[test] fn two_letters_are_written_large_enough_and_one_letter_under_28_pixels() { // The tree's 22 pixel avatars: one letter, half the size. diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index 0835767..d88b77a 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -18,14 +18,15 @@ use crate::dev::Page; use crate::meter::Counters; use crate::shell::actions::{ AddServer, CancelChannelPassword, CancelServerForm, ConnectVoice, DeleteServer, - DisconnectVoice, EditChannel, EditServer, Invite, JoinChannel, MoveClient, OpenClient, - OpenMember, OpenSearch, OpenSettings, PushToTalk, SaveAndConnect, SaveServer, SearchMembers, - SelectChannel, SelectServer, SetInputMuted, SetOutputMuted, SubmitChannelPassword, - ToggleChannel, + DisconnectVoice, EditChannel, EditServer, Invite, JoinChannel, LeaveVoice, MoveClient, + OpenClient, OpenMember, OpenSearch, OpenSettings, OpenShare, OpenVoiceSettings, PushToTalk, + SaveAndConnect, SaveServer, SearchMembers, SelectChannel, SelectServer, SetInputMuted, + SetMemberMuted, SetMemberVolume, SetOutputMuted, ShowVoiceView, SubmitChannelPassword, + ToggleChannel, ToggleVoiceCompact, }; use crate::shell::{ - ChannelPassword, ChannelTree, Emptiness, MainPanel, MemberCardView, MembersPane, ServerForm, - ServerRail, Sidebar, Toast, TopBar, TreeEvent, TreeModel, + ChannelPassword, ChannelTree, Emptiness, MainPanel, MemberCardView, MembersPane, SHORT_WINDOW, + ServerForm, ServerRail, Sidebar, Toast, TopBar, TreeEvent, TreeModel, VoicePage, }; use crate::swatch::swatch; use crate::theme::{VoelinTheme, hsla}; @@ -66,6 +67,10 @@ pub struct MainView { /// How wide the members panel is (`ui.members_width`, read at start). members_width: f32, main: Entity, + /// The voice channel page, which the main area is while voice is on screen. + voice: Entity, + /// The main area is the voice page. + voice_shown: bool, toast: Entity, form: Option>, /// The prompt for a locked channel's password, when one is open, and how @@ -115,6 +120,18 @@ impl MainView { this.form = None; cx.notify(); } + // The voice page takes the main area while it is asked for and voice + // is connected, and keeps the stage the setting says: an observer of + // the root state reads it and sets its own fields. + let (shown, compact) = { + let app = app.read(cx); + (app.voice_page_shown(), app.voice_compact()) + }; + if shown != this.voice_shown { + this.voice_shown = shown; + cx.notify(); + } + this.voice.update(cx, |page, cx| page.set_compact(compact, cx)); // A channel's password was asked for. let (generation, ask) = { let app = app.read(cx); @@ -127,7 +144,27 @@ impl MainView { cx.notify(); } }), - cx.observe_window_bounds(window, |this, window, cx| report(&this.app, window, cx)), + // The release guard of Hold to talk for a window that loses the focus + // while the button is held: the mouse button comes up somewhere else, + // and the release never reaches the button. Only the window's own + // button: the global hotkey is for use while another window has the + // focus. + cx.observe_window_activation(window, |this, window, cx| { + if window.is_window_active() { + return; + } + this.sidebar.update(cx, |sidebar, _| { + let _ = sidebar.release(); + }); + this.app.update(cx, |app, cx| app.push_to_talk(false, cx)); + }), + cx.observe_window_bounds(window, |this, window, cx| { + report(&this.app, window, cx); + // A cached pane renders only when told: it is told when the window + // becomes short or tall. + let short = is_short(window); + this.voice.update(cx, |page, cx| page.set_short(short, cx)); + }), ]; report(&app, window, cx); // The window is mapped by now: a window the last run left maximized @@ -140,7 +177,13 @@ impl MainView { let model = cx.new(|cx| TreeModel::new(&app, cx)); let tree = cx.new(|cx| ChannelTree::new(&model, counters.clone(), cx)); let members = cx.new(|cx| MembersPane::new(&model, counters.clone(), window, cx)); - let card = cx.new(|cx| MemberCardView::new(&model, members_width, cx)); + let card = cx.new(|cx| MemberCardView::new(&model, members_width, window, cx)); + let (voice_shown, compact) = { + let app = app.read(cx); + (app.voice_page_shown(), app.voice_compact()) + }; + let short = is_short(window); + let voice = cx.new(|cx| VoicePage::new(&app, &model, compact, short, cx)); // The members panel comes with the first server on screen. subscriptions.push(cx.subscribe(&model, |_, _, event: &TreeEvent, cx| { if matches!(event, TreeEvent::Lists) { @@ -157,6 +200,8 @@ impl MainView { card, members_width, main: cx.new(|cx| MainPanel::new(&app, cx)), + voice, + voice_shown, toast: cx.new(|cx| Toast::new(&app, cx)), app, page, @@ -195,6 +240,28 @@ impl MainView { &self.card } + /// What the sidebar shows now. + #[cfg(test)] + pub(crate) fn sidebar_view(&self, cx: &gpui_kit::App) -> crate::shell::SidebarView { + self.sidebar.read(cx).view().clone() + } + + /// Whether the sidebar's hold-to-talk button is held down. + #[cfg(test)] + pub(crate) fn sidebar_holding(&self, cx: &gpui_kit::App) -> bool { + self.sidebar.read(cx).is_holding() + } + + /// The voice channel page. + pub fn voice_page(&self) -> &Entity { + &self.voice + } + + /// Whether the main area is the voice page now. + pub fn voice_page_shown(&self) -> bool { + self.voice_shown + } + /// Open the form with `form`'s values. fn open_form( &mut self, @@ -241,6 +308,63 @@ impl MainView { self.app.update(cx, |app, cx| app.invite(cx)); } + fn set_member_volume( + &mut self, + action: &SetMemberVolume, + _: &mut Window, + cx: &mut Context, + ) { + self.app.update(cx, |app, cx| app.set_member_volume(action.client, action.percent, cx)); + } + + fn set_member_muted( + &mut self, + action: &SetMemberMuted, + _: &mut Window, + cx: &mut Context, + ) { + self.app.update(cx, |app, cx| app.set_member_muted(action.client, action.muted, cx)); + } + + fn show_voice_view(&mut self, action: &ShowVoiceView, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.show_voice_view(action.on, cx)); + } + + /// The voice page's Leave: the page goes (the chat it stands for is what + /// the main area shows next time), then voice is left. + fn leave_voice(&mut self, _: &LeaveVoice, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| { + app.show_voice_view(false, cx); + app.disconnect_voice(cx); + }); + } + + fn toggle_voice_compact( + &mut self, + _: &ToggleVoiceCompact, + _: &mut Window, + cx: &mut Context, + ) { + self.app.update(cx, |app, cx| app.toggle_voice_compact(cx)); + } + + fn open_share(&mut self, _: &OpenShare, _: &mut Window, _: &mut Context) { + tracing::info!( + "sharing a screen comes with the stream slices (docs/ui.md, \"What is next\")" + ); + } + + fn open_voice_settings( + &mut self, + _: &OpenVoiceSettings, + _: &mut Window, + _: &mut Context, + ) { + tracing::info!( + "the voice settings come with the settings slice (docs/ui.md, \"What is next\")" + ); + } + 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); @@ -397,6 +521,11 @@ fn zoom(_: &Window) { tests::ZOOMS.with(|zooms| zooms.set(zooms.get() + 1)); } +/// Whether `window` is too short for the voice page's larger stage. +fn is_short(window: &Window) -> bool { + f32::from(window.viewport_size().height) < SHORT_WINDOW +} + /// 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) { @@ -428,13 +557,14 @@ impl Render for MainView { // says and not narrower than the least a panel can be. let people = self.model.read(cx).emptiness() != Emptiness::NoServer; let members_width = self.members_width.max(m.right_panel_min); + // The main area is the server form, else the voice page while voice is + // asked for and connected, else the server page. A cached pane renders + // only when it was told, and the one not chosen is not in the tree. + let place = StyleRefinement::default().flex_1().min_w_0().h_full(); let main = match &self.form { Some(form) => form.clone().into_any_element(), - None => self - .main - .clone() - .cached(StyleRefinement::default().flex_1().min_w_0().h_full()) - .into_any_element(), + None if self.voice_shown => self.voice.clone().cached(place).into_any_element(), + None => self.main.clone().cached(place).into_any_element(), }; frame .key_context("Shell") @@ -449,6 +579,13 @@ impl Render for MainView { .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::set_member_volume)) + .on_action(cx.listener(Self::set_member_muted)) + .on_action(cx.listener(Self::show_voice_view)) + .on_action(cx.listener(Self::leave_voice)) + .on_action(cx.listener(Self::toggle_voice_compact)) + .on_action(cx.listener(Self::open_share)) + .on_action(cx.listener(Self::open_voice_settings)) .on_action(cx.listener(Self::add_server)) .on_action(cx.listener(Self::edit_server)) .on_action(cx.listener(Self::save_server)) @@ -525,7 +662,7 @@ mod tests { use tokio::sync::mpsc::{self, UnboundedSender}; use voelin_core::{Command, Event, SessionState, VoiceState}; use voelin_store::{Bookmark, MemorySecrets}; - use voelin_ui_vm::bridge::{BookmarkForm, TreeItem}; + use voelin_ui_vm::bridge::{BookmarkForm, MemberItem, TreeItem}; use voelin_ui_vm::dev::logic as sample; use voelin_ui_vm::list::{Change, Changes}; use voelin_ui_vm::settings::{TreeState, TreeStates, UI_TREE, UI_WINDOW}; @@ -553,11 +690,11 @@ mod tests { /// 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, + pub(super) struct Shell { + pub(super) app: Entity, + pub(super) view: Entity, + pub(super) events: UnboundedSender, + pub(super) counters: Counters, } fn bookmark(name: &str, address: &str) -> Bookmark { @@ -569,7 +706,7 @@ mod tests { } } - fn backend_with(servers: &[(&str, &str)]) -> Backend { + pub(super) 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(); @@ -579,7 +716,7 @@ mod tests { /// Open the window of the shell on `backend`, with the theme and the /// components set up as `run` sets them. - fn open( + pub(super) fn open( cx: &mut TestAppContext, backend: Backend, switches: Switches, @@ -605,23 +742,26 @@ mod tests { } /// Run what is queued and draw the window. - fn frame(cx: &mut VisualTestContext) { + pub(super) 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> { + pub(super) 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) { + pub(super) 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 { + pub(super) fn ids(shell: &Shell, cx: &mut VisualTestContext) -> Vec { shell.app.read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.id).collect()) } @@ -633,7 +773,7 @@ mod tests { BookmarkForm { id: -1, address: address.into(), ..Default::default() } } - fn connected(id: i64) -> Event { + pub(super) fn connected(id: i64) -> Event { Event::State { session: id as u64, state: SessionState { voice: VoiceState::Connected, ..Default::default() }, @@ -881,7 +1021,7 @@ mod tests { /// A server as an engine reports one: the sample server's events (nested /// channels, spacers, a locked channel, people with groups) played into the /// window, its bookmark the one shown. Voice is up and we are in Chill Zone. - fn sample_server(shell: &Shell, cx: &mut VisualTestContext) { + pub(super) fn sample_server(shell: &Shell, cx: &mut VisualTestContext) { shell.app.update(cx, |app, _| { app.vm.bookmarks = sample::bookmarks(); app.vm.current = Some(sample::DEMO); @@ -1440,6 +1580,76 @@ mod tests { ); } + /// The people of our voice channel are the model's too, out of the same + /// build as the tree's rows and the members panel's: they come with the + /// connected voice, a talker or a mute changes just that person's row, a + /// change elsewhere on the server tells nobody of them, and the model + /// builds once for each change, not once more for the voice page. + #[gpui::test] + fn the_model_keeps_the_people_of_our_channel_out_of_the_same_build(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + let model = shell.view.read_with(cx, |view, _| view.tree_model().clone()); + assert!(model.read_with(cx, |model, _| model.voice().is_empty()), "no server"); + sample_server(&shell, cx); + let people = |cx: &mut VisualTestContext| model.read_with(cx, |m, _| m.voice().clone()); + let names = |rows: &[MemberItem]| { + rows.iter().map(|m| (m.name.to_string(), m.talking, m.muted)).collect::>() + }; + assert_eq!( + names(&people(cx)), + [ + ("Lumen".to_owned(), false, false), + ("Kairo".to_owned(), true, false), + ("Nova".to_owned(), false, false), + ("dex".to_owned(), false, true), + ("Mira".to_owned(), false, false), + ], + "our channel's people, by group and name; Kairo talks, dex's microphone is off" + ); + + let (log, _subscription) = tree_events(&shell, cx); + let voice_told = |log: &Rc>>| -> Vec>> { + log.borrow() + .iter() + .filter_map(|e| match e { + TreeEvent::Voice(rows) => Some(rows.clone()), + _ => None, + }) + .collect() + }; + let refreshes = |cx: &mut VisualTestContext| model.read_with(cx, |m, _| m.refreshes()); + let before = refreshes(cx); + shell + .events + .send(Event::Talking { session: sample::DEMO as u64, client: 3, talking: false }) + .unwrap(); + frame(cx); + let told = voice_told(&log); + let [rows] = &told[..] else { panic!("{:?}", log.borrow()) }; + assert!(!rows.iter().find(|m| m.id == 3).unwrap().talking, "Kairo stopped"); + assert_eq!(*rows, people(cx), "the rows the event carries are the model's"); + assert_eq!(refreshes(cx), before + 1, "one build for the tree, the panel and the page"); + + // Someone in another channel talks: the tree and the panel change, the + // page has nothing new. + log.borrow_mut().clear(); + shell + .events + .send(Event::Talking { session: sample::DEMO as u64, client: 6, talking: true }) + .unwrap(); + frame(cx); + assert!(voice_told(&log).is_empty(), "{:?}", log.borrow()); + assert!(!rows_told(&log).is_empty(), "though the tree has a row to change"); + + // Voice gone: nobody is in our channel. + log.borrow_mut().clear(); + let gone = SessionState { voice: VoiceState::Disconnected, ..Default::default() }; + shell.events.send(Event::State { session: sample::DEMO as u64, state: gone }).unwrap(); + frame(cx); + let told = voice_told(&log); + assert!(matches!(&told[..], [rows] if rows.is_empty()), "{told:?}"); + } + /// The members panel as the pane has it: the rows' names, `H` before the /// first of a section with its heading. fn members_shape(shell: &Shell, cx: &mut VisualTestContext) -> Vec { @@ -2087,3 +2297,6 @@ mod tests { shell.view.read_with(cx, |view, _| assert!(view.form().is_none())); } } + +#[cfg(test)] +mod voice_tests; diff --git a/crates/voelin-gpui/src/view/voice_tests.rs b/crates/voelin-gpui/src/view/voice_tests.rs new file mode 100644 index 0000000..b52147b --- /dev/null +++ b/crates/voelin-gpui/src/view/voice_tests.rs @@ -0,0 +1,1134 @@ +//! The voice page and the call bar on a drawn window (`crate::shell::VoicePage`), +//! and the sidebar's server card with its banner: +//! the page takes the main area while voice is connected and asked for, its +//! people carry their marks, a talker or a mute redraws it and no pane that has +//! nothing to show for it, the call bar's buttons reach the engine, and the +//! smaller stage is kept. + +use std::sync::Arc; + +use gpui::{TestAppContext, VisualTestContext}; +use gpui_kit::{MouseButton, px, size}; +use voelin_core::settings::AUDIO; +use voelin_core::{AudioSettings, Command, Event, SessionState, TransmitMode, VoiceState}; +use voelin_ui_vm::bridge::MemberItem; +use voelin_ui_vm::dev::logic as sample; +use voelin_ui_vm::settings::{ + CLIENT_PLAYBACK, ClientPlayback, ClientPlaybackMap, UI_VOICE_COMPACT, +}; + +use super::tests::{Shell, at, click, connected, frame, open, sample_server}; +use crate::backend::Backend; +use crate::dev::Switches; + +/// The sample server's presence with `$body` applied to it, named `$p`, as an +/// event (a macro: `voelin_core` does not name its presence type). +macro_rules! sample_presence { + ($p:ident => $body:expr) => {{ + let Some(Event::Presence { session, mut presence }) = + sample::server_events().into_iter().find(|e| matches!(e, Event::Presence { .. })) + else { + panic!("the sample server has a presence") + }; + { + let $p = Arc::make_mut(&mut presence); + $body; + } + Event::Presence { session, presence } + }}; +} + +/// The window on the sample server, tall enough for the larger stage (the test +/// platform's window is 1024 by 768). +fn tall(cx: &mut TestAppContext, switches: Switches) -> (Shell, &mut VisualTestContext) { + let (shell, vcx) = open(cx, Backend::in_memory().unwrap(), switches); + vcx.simulate_resize(size(px(1440.0), px(960.0))); + sample_server(&shell, vcx); + (shell, vcx) +} + +/// The sample server's window with the voice page asked for. +fn on_the_voice_page( + cx: &mut TestAppContext, + switches: Switches, +) -> (Shell, &mut VisualTestContext) { + let (shell, vcx) = tall(cx, switches); + click(vcx, "main-voice"); + (shell, vcx) +} + +/// The people the page shows. +fn people(shell: &Shell, cx: &mut VisualTestContext) -> Vec { + shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).people().to_vec()) +} + +/// How many times each pane was rendered: the rail, the top bar, the main +/// area, the tree, the members panel and the voice page. +fn drawn(shell: &Shell) -> [u64; 6] { + let panes = &shell.counters.panes; + [&panes.rail, &panes.topbar, &panes.main, &panes.tree, &panes.members, &panes.voice] + .map(|pane| pane.get()) +} + +fn session(voice: VoiceState) -> Event { + Event::State { + session: sample::DEMO as u64, + state: SessionState { voice, ..Default::default() }, + } +} + +/// The page takes the main area when asked for with voice connected, in the +/// server page's place, and gives it back on Chat only, on a lost connection +/// and on Leave; a reconnect asks for it again, as the Slint page does. +#[gpui::test] +fn the_voice_page_takes_the_main_area_while_voice_is_connected_and_asked_for( + cx: &mut TestAppContext, +) { + let (shell, cx) = tall(cx, Switches::default()); + assert!(at(cx, "main-server").is_some() && at(cx, "voice-page").is_none()); + assert!(at(cx, "main-voice").is_some(), "the server page offers the voice channel"); + + click(cx, "main-voice"); + assert!(at(cx, "voice-page").is_some(), "the page"); + assert!(at(cx, "main-server").is_none(), "in the server page's place"); + assert!(shell.view.read_with(cx, |view, _| view.voice_page_shown())); + assert!(shell.app.read_with(cx, |app, _| app.vm.voice_view), "the view model knows"); + // Asking for the page opens the channel's chat tab in the state, which a + // front end that shows no chat does not mark as read: nothing is stored. + let reads = shell.app.read_with(cx, |app, _| app.backend().store.chat_reads("demo-server")); + assert!(reads.unwrap().is_empty(), "no read mark for a chat nobody sees"); + + click(cx, "voice-chat-only"); + assert!(at(cx, "voice-page").is_none() && at(cx, "main-server").is_some()); + assert!(!shell.app.read_with(cx, |app, _| app.vm.voice_view)); + + click(cx, "main-voice"); + shell.events.send(session(VoiceState::Disconnected)).unwrap(); + frame(cx); + assert!(at(cx, "voice-page").is_none(), "no page without voice"); + assert!(at(cx, "main-server").is_some()); + shell + .events + .send(Event::State { + session: sample::DEMO as u64, + state: SessionState { + voice: VoiceState::Connected, + own_channel: Some(2), + own_client: Some(1), + ..Default::default() + }, + }) + .unwrap(); + frame(cx); + assert!(at(cx, "voice-page").is_some(), "asked for still: back with the connection"); +} + +/// The people of our channel are on the page, each with the marks the Slint +/// page gives them, the channel's name, its topic and the count. +#[gpui::test] +fn the_page_shows_the_people_of_our_channel_with_their_marks(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + let names: Vec = people(&shell, cx).iter().map(|m| m.name.to_string()).collect(); + assert_eq!(names, ["Lumen", "Kairo", "Nova", "dex", "Mira"]); + for id in [1, 2, 3, 4, 5] { + assert!(at(cx, &format!("voice-member-{id}")).is_some(), "client {id} is on the stage"); + } + assert!(at(cx, "voice-member-6").is_none(), "Talon is in another channel"); + assert!(at(cx, "voice-speaking-3").is_some(), "Kairo talks: the bars in the corner"); + assert!(at(cx, "voice-off-5").is_some(), "dex's microphone is off: its mark"); + assert!(at(cx, "voice-off-3").is_none() && at(cx, "voice-speaking-5").is_none()); + let head = shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).head().clone()); + assert_eq!( + (head.channel.as_str(), head.topic.as_str(), head.limit), + ("Chill Zone", "Hang out, chat, and explore the worlds beyond.", 50) + ); + assert!(head.can_share && head.connected && !head.input_muted && !head.output_muted); + assert!(at(cx, "voice-banner").is_none(), "no picture has arrived: no banner"); + assert!(at(cx, "voice-count").is_some() && at(cx, "voice-channel").is_some()); +} + +/// The channel's banner is behind the header, under the surface veil, once its +/// picture is in the cache (the sample server's, as files of a folder of the +/// state's own). +#[gpui::test] +fn the_channels_banner_is_behind_the_header_under_a_veil(cx: &mut TestAppContext) { + let switches = + Switches { demo_ui: true, demo_pictures: true, voice: true, ..Default::default() }; + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); + cx.simulate_resize(size(px(1440.0), px(960.0))); + frame(cx); + assert!(at(cx, "voice-banner").is_some(), "the veil over Chill Zone's picture"); + let head = shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).head().clone()); + assert!(head.banner.size().width > 0, "the picture is decoded"); + // The sample pictures' folder goes with the close. + let folder = shell.app.read_with(cx, |app, _| app.demo_dir().cloned()); + shell.app.update(cx, |app, cx| app.shutdown(cx)); + assert!(!folder.is_some_and(|folder| folder.exists()), "the close removes it"); +} + +/// Someone who starts or stops talking, or mutes, is one row of the page and +/// one render of it: the model builds the rows once for the tree, the panel and +/// the page, and the rail, the top bar and the main area are not drawn. A change +/// that is not in our channel does not draw the page at all. +#[gpui::test] +fn talking_and_mute_events_update_the_voice_page_rows_and_nothing_else(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + let model = shell.view.read_with(cx, |view, _| view.tree_model().clone()); + let row = |shell: &Shell, cx: &mut VisualTestContext, id: i32| { + people(shell, cx).into_iter().find(|m| m.id == id).unwrap() + }; + assert!(row(&shell, cx, 3).talking && row(&shell, cx, 5).muted); + + let (before, builds) = (drawn(&shell), model.read_with(cx, |m, _| m.refreshes())); + shell + .events + .send(Event::Talking { session: sample::DEMO as u64, client: 3, talking: false }) + .unwrap(); + frame(cx); + let after = drawn(&shell); + assert!(!row(&shell, cx, 3).talking, "Kairo stopped"); + assert!(at(cx, "voice-speaking-3").is_none(), "and the bars are gone"); + assert_eq!(after[5], before[5] + 1, "the page was drawn once"); + assert_eq!(model.read_with(cx, |m, _| m.refreshes()), builds + 1, "one build for all three"); + assert_eq!( + [after[0], after[1], after[2]], + [before[0], before[1], before[2]], + "the rail, the top bar and the main area were not drawn" + ); + + // dex unmutes: the presence says so. + let before = drawn(&shell); + shell + .events + .send(sample_presence!(p => p.clients.get_mut(&5).unwrap().input_muted = false)) + .unwrap(); + frame(cx); + let after = drawn(&shell); + assert!(!row(&shell, cx, 5).muted && at(cx, "voice-off-5").is_none(), "dex's mark is gone"); + assert_eq!(after[5], before[5] + 1, "the page was drawn once"); + assert_eq!([after[0], after[1], after[2]], [before[0], before[1], before[2]]); + + // Someone in another channel talks: the tree has a row to change, the page + // has nothing new. + let before = drawn(&shell); + shell + .events + .send(Event::Talking { session: sample::DEMO as u64, client: 6, talking: true }) + .unwrap(); + frame(cx); + let after = drawn(&shell); + assert_eq!(after[5], before[5], "the page was not drawn"); + assert!(after[3] > before[3], "though the tree was"); +} + +/// Leave reaches the engine: the voice session is left, and the page goes. +#[gpui::test] +fn leave_reaches_the_engine(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + shell.app.read_with(cx, |app, _| app.take_sent()); + click(cx, "call-leave"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::DisconnectVoice { session }] if *session == sample::DEMO as u64), + "{sent:?}" + ); + assert!(!shell.app.read_with(cx, |app, _| app.vm.voice_view), "and the page is not asked for"); +} + +/// The call bar's mute and deafen buttons send their commands; Share and the +/// voice settings are logged and send nothing; the muted state shows on the +/// buttons once the engine says it. +#[gpui::test] +fn the_call_bars_buttons_send_their_commands_and_the_placeholders_nothing(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + shell.app.read_with(cx, |app, _| app.take_sent()); + for button in ["call-mic", "call-sound", "call-share", "call-settings"] { + click(cx, button); + } + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + let id = sample::DEMO as u64; + assert!( + matches!( + sent.as_slice(), + [ + Command::SetInputMuted { session: a, muted: true }, + Command::SetOutputMuted { session: b, muted: true }, + ] if *a == id && *b == id + ), + "{sent:?}" + ); + let state = SessionState { + voice: VoiceState::Connected, + own_channel: Some(2), + own_client: Some(1), + input_muted: true, + ..Default::default() + }; + shell.events.send(Event::State { session: id, state }).unwrap(); + frame(cx); + let head = shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).head().clone()); + assert!(head.input_muted && !head.output_muted); + click(cx, "call-mic"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::SetInputMuted { muted: false, .. }]), + "muted: the next click unmutes {sent:?}" + ); +} + +/// The smaller stage is a row of small avatars, chosen with the button and kept +/// in `ui.voice_compact`; a window under 800 pixels tall has it whatever the +/// setting says, and the button is off there. +#[gpui::test] +fn the_smaller_stage_is_remembered_and_a_short_window_has_it_anyway(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + let compact = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).compact_shown()) + }; + let stored = |shell: &Shell, cx: &mut VisualTestContext| { + shell.app.read_with(cx, |app, _| app.backend().prefs.get(&UI_VOICE_COMPACT)) + }; + assert!(!compact(&shell, cx) && !stored(&shell, cx)); + let tall_stage = at(cx, "voice-people").expect("the people").size.height; + click(cx, "voice-stage"); + assert!(compact(&shell, cx) && stored(&shell, cx), "chosen and kept"); + let row = at(cx, "voice-people").expect("the people").size.height; + assert_eq!(row, px(112.0), "one row of small avatars"); + assert!(row < tall_stage, "{row:?} against {tall_stage:?}"); + click(cx, "voice-stage"); + assert!(!compact(&shell, cx) && !stored(&shell, cx), "and back"); + + // A short window: the smaller stage, and its button does nothing. + cx.simulate_resize(size(px(1440.0), px(700.0))); + frame(cx); + assert!(compact(&shell, cx), "under 800 pixels tall"); + click(cx, "voice-stage"); + assert!(compact(&shell, cx) && !stored(&shell, cx), "the button is off"); + cx.simulate_resize(size(px(1440.0), px(960.0))); + frame(cx); + assert!(!compact(&shell, cx), "tall again"); +} + +/// The setting is read at start: a run that left the smaller stage opens on it. +#[gpui::test] +fn the_stage_comes_back_as_the_last_run_left_it(cx: &mut TestAppContext) { + let backend = Backend::in_memory().unwrap(); + backend.prefs.set(&UI_VOICE_COMPACT, true).unwrap(); + let (shell, vcx) = open(cx, backend, Switches::default()); + vcx.simulate_resize(size(px(1440.0), px(960.0))); + frame(vcx); + assert!(shell.app.read_with(vcx, |app, _| app.voice_compact())); + assert!(shell.view.read_with(vcx, |view, cx| view.voice_page().read(cx).compact_shown())); +} + +/// `VOELIN_OPEN=voice:compact` on the sample servers: the page, on the smaller +/// stage; the sample servers keep nothing, so the stage the button then picks +/// is not stored either. +#[gpui::test] +fn a_development_switch_asks_for_the_voice_page_and_its_stage(cx: &mut TestAppContext) { + let switches = Switches { + demo_ui: true, + demo_pictures: false, + voice: true, + voice_compact: true, + ..Default::default() + }; + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); + cx.simulate_resize(size(px(1440.0), px(960.0))); + frame(cx); + assert!(at(cx, "voice-page").is_some(), "the sample server is connected: its voice page"); + assert!(shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).compact_shown())); + // The sample servers keep nothing: the stage is the switch's only. + click(cx, "voice-stage"); + assert!(!shell.app.read_with(cx, |app, _| app.backend().prefs.get(&UI_VOICE_COMPACT))); + assert!(!shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).compact_shown())); +} + +/// The sidebar's server card has the server's banner behind it, under the +/// surface veil, once the picture is in the cache; a server without one has the +/// plain card. +#[gpui::test] +fn the_server_card_shows_the_banner(cx: &mut TestAppContext) { + let switches = Switches { demo_ui: true, demo_pictures: true, ..Default::default() }; + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); + assert!(at(cx, "sidebar-server").is_some(), "the card"); + assert!(at(cx, "sidebar-server-banner").is_some(), "the host banner is behind it"); + let card = shell.view.read_with(cx, |view, cx| view.sidebar_view(cx)); + assert!(card.server_banner.size().width > 0, "the picture is decoded"); + + // Another server of the sample, which has no banner: the plain card. + let other = shell.app.read_with(cx, |app, _| app.vm.bookmarks[2].id); + click(cx, &format!("rail-server-{other}")); + assert!(at(cx, "sidebar-server").is_some()); + assert!(at(cx, "sidebar-server-banner").is_none(), "no banner, no picture behind the card"); + + let folder = shell.app.read_with(cx, |app, _| app.demo_dir().cloned()); + shell.app.update(cx, |app, cx| app.shutdown(cx)); + assert!(!folder.is_some_and(|folder| folder.exists()), "the close removes the sample pictures"); +} + +/// What the engine reports for the sample session, in our channel. +fn reported(voice: VoiceState, transmitting: bool) -> Event { + Event::State { + session: sample::DEMO as u64, + state: SessionState { + voice, + own_channel: Some(2), + own_client: Some(1), + transmitting, + ..Default::default() + }, + } +} + +/// What a test that sent no command compares with. +const NOTHING: [bool; 0] = []; + +/// What the commands sent since the last call say about our own session's +/// transmitting, in order (the connection's own commands, such as the channel +/// chat it opens, are not what these tests are about). +fn transmits(shell: &Shell, cx: &mut VisualTestContext) -> Vec { + let id = sample::DEMO as u64; + shell + .app + .read_with(cx, |app, _| app.take_sent()) + .into_iter() + .filter_map(|command| match command { + Command::SetTransmitting { session, on } if session == id => Some(on), + _ => None, + }) + .collect() +} + +/// Hold to talk is released when voice drops under it: the button goes with +/// the voice card, nothing is left to release it, and the session would go on +/// transmitting into the next connection. The guard tells the session once, +/// when the batch that took the voice away says it still transmits, and not +/// again for the engine's answer or for a reconnect. +#[gpui::test] +fn hold_to_talk_is_released_when_voice_drops(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + let button = at(cx, "hold-to-talk").expect("push-to-talk is the default transmit mode"); + transmits(&shell, cx); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true], "the button was pressed"); + + // The engine confirms it; still connected: nothing to guard. + shell.events.send(reported(VoiceState::Connected, true)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "a connected session transmitting is a hold"); + + // The voice drops with the button still down: the session says it transmits. + shell.events.send(reported(VoiceState::Disconnected, true)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), [false], "told once"); + assert!(at(cx, "hold-to-talk").is_none(), "the button went with the voice card"); + + // The engine's answer and the reconnect are not answered. + shell.events.send(reported(VoiceState::Disconnected, false)).unwrap(); + shell.events.send(reported(VoiceState::Connecting, false)).unwrap(); + shell.events.send(reported(VoiceState::Connected, false)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "nothing more"); + + // The mouse button comes up where the button was: nothing was held any more. + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), NOTHING); +} + +/// A session that drops while it does not transmit is left alone. +#[gpui::test] +fn a_voice_that_drops_without_a_hold_is_not_told_anything(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + transmits(&shell, cx); + shell.events.send(reported(VoiceState::Disconnected, false)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING); +} + +/// Hold to talk is released when the window loses the focus while the button is +/// held: the mouse button comes up elsewhere, and the release never reaches the +/// button. +#[gpui::test] +fn hold_to_talk_is_released_when_the_window_loses_the_focus(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + cx.update(|window, _| assert!(window.is_window_active(), "the window has the focus")); + transmits(&shell, cx); + let button = at(cx, "hold-to-talk").expect("the button"); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true]); + cx.deactivate_window(); + frame(cx); + cx.update(|window, _| assert!(!window.is_window_active(), "the window lost the focus")); + assert_eq!(transmits(&shell, cx), [false], "released with the focus"); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + assert_eq!( + transmits(&shell, cx), + NOTHING, + "and the release that comes later has nothing to do" + ); +} + +/// A window that held nothing sends nothing when it loses the focus: what +/// transmits then is not the window's button (the global hotkey is for use +/// while another window has the focus). +#[gpui::test] +fn a_window_that_holds_nothing_tells_the_session_nothing_when_it_loses_the_focus( + cx: &mut TestAppContext, +) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + transmits(&shell, cx); + cx.deactivate_window(); + frame(cx); + cx.update(|window, _| assert!(!window.is_window_active(), "the window lost the focus")); + assert_eq!(transmits(&shell, cx), NOTHING); +} + +/// The global hotkey is for use while another window has the focus: the window +/// losing it does not cut a hold the key began, and the key's release ends it. +#[gpui::test] +fn the_global_hotkey_is_not_cut_by_the_window_losing_the_focus(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + transmits(&shell, cx); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "the window's focus is not the key's"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), [false], "the key's release ends it"); +} + +/// Every `SetTransmitting` command sent since the last call, across all +/// sessions. +fn all_transmits(shell: &Shell, cx: &mut VisualTestContext) -> Vec<(u64, bool)> { + shell + .app + .read_with(cx, |app, _| app.take_sent()) + .into_iter() + .filter_map(|command| match command { + Command::SetTransmitting { session, on } => Some((session, on)), + _ => None, + }) + .collect() +} + +/// Leaving push-to-talk mode while the hold-to-talk button is pressed releases +/// transmit immediately and clears the sidebar's hold so neither a later click +/// nor focus loss emits a stray release (Opus gate P1 / P1b). +#[gpui::test] +fn leaving_push_to_talk_releases_a_held_button(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + let set_mode = |shell: &Shell, cx: &mut VisualTestContext, mode: TransmitMode| { + let audio = AudioSettings { transmit: mode, ..Default::default() }; + shell.app.read_with(cx, |app, _| app.backend().prefs.set(&AUDIO, audio).unwrap()); + setting_changed(shell, cx, AUDIO.name()); + }; + + let button = at(cx, "hold-to-talk").expect("the button"); + transmits(&shell, cx); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true]); + shell.events.send(reported(VoiceState::Connected, true)).unwrap(); + frame(cx); + + set_mode(&shell, cx, TransmitMode::VoiceActivation); + assert!(at(cx, "hold-to-talk").is_none()); + assert!( + !shell.view.read_with(cx, |view, cx| view.sidebar_holding(cx)), + "sidebar cleared holding when leaving push-to-talk" + ); + assert_eq!(transmits(&shell, cx), [false], "mode change releases the button hold"); + + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING); + + // Returning to push-to-talk and clicking elsewhere sends nothing stale. + set_mode(&shell, cx, TransmitMode::PushToTalk); + assert!(at(cx, "hold-to-talk").is_some()); + let elsewhere = at(cx, "sidebar-server").expect("server card"); + cx.simulate_mouse_down(elsewhere.center(), MouseButton::Left, Default::default()); + cx.simulate_mouse_up(elsewhere.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "no stale hold left in sidebar"); + + // P1b: mode leaves push-to-talk and then window loses focus before returning. + let button = at(cx, "hold-to-talk").expect("the button"); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true]); + set_mode(&shell, cx, TransmitMode::VoiceActivation); + assert_eq!(transmits(&shell, cx), [false]); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "focus loss has nothing left to release"); +} + +/// A voice drop and reconnect inside one event batch still releases a held +/// button and a held hotkey, and clears the sidebar's hold (Opus gate P3). +#[gpui::test] +fn a_drop_and_reconnect_in_one_batch_releases_a_held_button_and_hotkey(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + let button = at(cx, "hold-to-talk").expect("the button"); + transmits(&shell, cx); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + shell.events.send(reported(VoiceState::Connected, true)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), [true]); + + shell.app.update(cx, |app, cx| { + app.handle_events( + [ + reported(VoiceState::Disconnected, true), + reported(VoiceState::Connecting, true), + reported(VoiceState::Connected, true), + ], + cx, + ); + }); + frame(cx); + assert_eq!(transmits(&shell, cx), [false], "drop inside the batch ends transmit once"); + assert!(at(cx, "hold-to-talk").is_some(), "reconnected within the batch"); + assert!( + !shell.view.read_with(cx, |view, cx| view.sidebar_holding(cx)), + "sidebar hold cleared even when voice reconnected inside the same batch" + ); + + // Releasing the mouse button now does nothing because the hold ended. + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "sidebar hold was cleared too"); + + // Same single-batch drop+reconnect while the global hotkey is held. + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + shell.events.send(reported(VoiceState::Connected, true)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), [true]); + shell.app.update(cx, |app, cx| { + app.handle_events( + [ + reported(VoiceState::Disconnected, true), + reported(VoiceState::Connecting, true), + reported(VoiceState::Connected, true), + ], + cx, + ); + }); + frame(cx); + assert_eq!(transmits(&shell, cx), [false]); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), NOTHING); +} + +/// Holding the window button and the global hotkey at the same time keeps +/// transmitting until both have let go, in either order, without duplicate +/// commands (Opus gate P6). +#[gpui::test] +fn holding_the_button_and_the_hotkey_together_stops_only_when_both_let_go(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + let button = at(cx, "hold-to-talk").expect("the button"); + transmits(&shell, cx); + + // Button down, hotkey down, hotkey up (still held by button), button up. + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true]); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), NOTHING, "already transmitting"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), NOTHING, "button still holds transmit"); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), [false], "both released"); + + // Hotkey down, button down, button up (still held by hotkey), hotkey up. + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), NOTHING); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "hotkey still holds transmit"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), [false]); + + // Both held, window loses focus: button releases, hotkey keeps holding. + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "hotkey stays active across focus loss"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), [false]); +} + +/// Switching the server on screen releases a held hold-to-talk button (its +/// voice card leaves the screen) while leaving a global hotkey hold intact for +/// its own release (Opus gate P8 and P2b). +#[gpui::test] +fn switching_servers_releases_a_held_button_but_keeps_the_global_hotkey(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + let (a, b, offline) = (sample::DEMO, sample::DEMO + 1, sample::DEMO + 2); + shell.events.send(connected(b)).unwrap(); + frame(cx); + all_transmits(&shell, cx); + + // P8: button held on A, then current moves to an offline server. + let button = at(cx, "hold-to-talk").expect("the button"); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(all_transmits(&shell, cx), [(a as u64, true)]); + shell.app.update(cx, |app, cx| app.select_server(offline, cx)); + frame(cx); + assert_eq!(all_transmits(&shell, cx), [(a as u64, false)], "leaving A releases button hold"); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + cx.deactivate_window(); + frame(cx); + assert_eq!(all_transmits(&shell, cx), []); + + // P2b: global hotkey held on A, current switches to B, hotkey releases A. + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + shell.app.update(cx, |app, cx| app.select_server(a, cx)); + frame(cx); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + shell.app.update(cx, |app, cx| app.select_server(b, cx)); + frame(cx); + assert_eq!(all_transmits(&shell, cx), [(a as u64, true)], "hotkey stays held across switch"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(all_transmits(&shell, cx), [(a as u64, false)]); +} + +/// Window focus loss releases an active `AppState::push_to_talk` button hold +/// even if the sidebar's own flag was not set (guard in `MainView`). +#[gpui::test] +fn focus_loss_releases_app_button_hold_unconditionally(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + transmits(&shell, cx); + shell.app.update(cx, |app, cx| app.push_to_talk(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), [false]); +} + +/// A setting changed elsewhere (a command, the config file) reaches the window. +fn setting_changed(shell: &Shell, cx: &mut VisualTestContext, key: &str) { + shell.events.send(Event::SettingChanged { key: key.into() }).unwrap(); + frame(cx); +} + +/// The voice card follows the transmit mode the audio settings give: the button +/// for push-to-talk, the mode in words for the others, live when the setting +/// changes elsewhere. +#[gpui::test] +fn the_voice_card_follows_the_transmit_mode_the_settings_give(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + assert!(at(cx, "hold-to-talk").is_some() && at(cx, "transmit-mode").is_none(), "push-to-talk"); + for (mode, words) in [ + (TransmitMode::VoiceActivation, "Voice activity"), + (TransmitMode::Continuous, "Open microphone"), + ] { + let audio = AudioSettings { transmit: mode, ..Default::default() }; + shell.app.read_with(cx, |app, _| app.backend().prefs.set(&AUDIO, audio).unwrap()); + setting_changed(&shell, cx, AUDIO.name()); + assert!(at(cx, "hold-to-talk").is_none(), "{mode:?}: no button"); + assert!(at(cx, "transmit-mode").is_some(), "{mode:?}: it says {words}"); + let seen = shell.view.read_with(cx, |view, cx| view.sidebar_view(cx).transmit); + assert_eq!(seen, mode); + } + shell + .app + .read_with(cx, |app, _| app.backend().prefs.set(&AUDIO, AudioSettings::default()).unwrap()); + setting_changed(&shell, cx, AUDIO.name()); + assert!(at(cx, "hold-to-talk").is_some() && at(cx, "transmit-mode").is_none(), "back"); +} + +/// A person's volume changed elsewhere shows in the tree and on the card, and +/// the smaller stage chosen elsewhere reaches the page. +#[gpui::test] +fn a_volume_and_a_stage_changed_elsewhere_reach_the_window(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + let row = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| { + view.tree_model() + .read(cx) + .rows() + .iter() + .find(|r| !r.is_channel && r.id == 3) + .cloned() + .unwrap() + }) + }; + assert!(!row(&shell, cx).local_muted); + let playback = ClientPlaybackMap::from([( + "demo-3".to_owned(), + ClientPlayback { volume: 1.5, muted: true }, + )]); + shell.app.read_with(cx, |app, _| app.backend().prefs.set(&CLIENT_PLAYBACK, playback).unwrap()); + setting_changed(&shell, cx, CLIENT_PLAYBACK.name()); + let kairo = row(&shell, cx); + assert!(kairo.local_muted, "Kairo is muted for us now"); + assert_eq!(kairo.local_volume, 150); + + let compact = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).compact_shown()) + }; + assert!(!compact(&shell, cx)); + shell.app.read_with(cx, |app, _| app.backend().prefs.set(&UI_VOICE_COMPACT, true).unwrap()); + setting_changed(&shell, cx, UI_VOICE_COMPACT.name()); + assert!(compact(&shell, cx), "the page is on the smaller stage"); +} + +/// The volume and the mute of a person, on the card a click on them opens +/// (from the voice page as from the members panel): the engine plays them so, +/// the choice is kept by their unique id, and the tree marks who is muted. +#[gpui::test] +fn a_persons_card_has_their_volume_and_mute(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + click(cx, "voice-member-3"); + assert!(at(cx, "member-card").is_some(), "Kairo's card"); + assert!(at(cx, "member-volume").is_some()); + let card = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| view.member_card().read(cx).card().cloned().unwrap()) + }; + assert_eq!((card(&shell, cx).volume, card(&shell, cx).muted), (100.0, false)); + shell.app.read_with(cx, |app, _| app.take_sent()); + + click(cx, "member-mute"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!( + sent.as_slice(), + [ + Command::SetClientVolume { client: 3, volume, .. }, + Command::SetClientMuted { client: 3, muted: true, .. }, + ] if *volume == 1.0 + ), + "{sent:?}" + ); + assert!(card(&shell, cx).muted, "the card has it"); + let kept = shell.app.read_with(cx, |app, _| app.backend().prefs.get(&CLIENT_PLAYBACK)); + assert_eq!(kept["demo-3"], ClientPlayback { volume: 1.0, muted: true }, "kept by their id"); + let marked = shell.view.read_with(cx, |view, cx| { + view.tree_model() + .read(cx) + .rows() + .iter() + .find(|r| !r.is_channel && r.id == 3) + .unwrap() + .local_muted + }); + assert!(marked, "and the tree marks them"); + + click(cx, "member-mute"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [_, Command::SetClientMuted { client: 3, muted: false, .. }]), + "{sent:?}" + ); + let kept = shell.app.read_with(cx, |app, _| app.backend().prefs.get(&CLIENT_PLAYBACK)); + assert!(!kept.contains_key("demo-3"), "the default is no choice"); +} + +/// The slider sets the volume as the person is heard: a click on the track is +/// a value, which the engine and the card follow. +#[gpui::test] +fn the_volume_slider_sets_the_volume_of_the_person(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + click(cx, "voice-member-3"); + shell.app.read_with(cx, |app, _| app.take_sent()); + let track = at(cx, "member-slider").expect("the slider"); + let quarter = gpui_kit::point(track.left() + track.size.width * 0.25, track.center().y); + cx.simulate_mouse_down(quarter, MouseButton::Left, Default::default()); + cx.simulate_mouse_up(quarter, MouseButton::Left, Default::default()); + frame(cx); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + let volume = sent.iter().find_map(|command| match command { + Command::SetClientVolume { client: 3, volume, .. } => Some(*volume), + _ => None, + }); + let volume = volume.unwrap_or_else(|| panic!("no volume was sent: {sent:?}")); + assert!( + (0.3..=0.7).contains(&volume), + "a click a quarter along 0 to 200 % is about half: {volume}" + ); + let shown = + shell.view.read_with(cx, |view, cx| view.member_card().read(cx).card().unwrap().volume); + assert!((shown - volume * 100.0).abs() < 0.5, "the card shows {shown} for {volume}"); +} + +/// A person the server gave no unique id has the controls off: nothing could be +/// kept for them, as the Slint card says. +#[gpui::test] +fn a_person_without_a_unique_id_has_the_controls_off(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + shell.events.send(sample_presence!(p => p.clients.get_mut(&5).unwrap().uid = None)).unwrap(); + frame(cx); + click(cx, "voice-member-5"); + assert!(at(cx, "member-card").is_some()); + shell.app.read_with(cx, |app, _| app.take_sent()); + click(cx, "member-mute"); + assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), "nothing is sent"); +} + +/// A person whose sound is off, who does not hear, has the headphone mark in +/// the corner of their avatar, and a talker's bars win over both marks, as in +/// the Slint page. +#[gpui::test] +fn a_person_whose_sound_is_off_has_the_deafen_mark(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + assert!(at(cx, "voice-off-2").is_none(), "Lumen hears"); + shell + .events + .send(sample_presence!(p => p.clients.get_mut(&2).unwrap().output_muted = true)) + .unwrap(); + frame(cx); + assert!(at(cx, "voice-off-2").is_some(), "Lumen's sound is off: the mark"); + assert!(people(&shell, cx).iter().any(|m| m.id == 2 && m.sound_off)); + // Kairo talks and is muted too: the bars, not the mark. + shell + .events + .send(sample_presence!(p => p.clients.get_mut(&3).unwrap().input_muted = true)) + .unwrap(); + frame(cx); + assert!(at(cx, "voice-speaking-3").is_some() && at(cx, "voice-off-3").is_none()); +} + +/// A channel with many people: the larger stage wraps them into rows and, when +/// the rows are taller than the page, scrolls them (the page's other parts stay +/// where they are: the header on top, the call bar under the people). +#[gpui::test] +fn many_people_scroll_and_the_call_bar_stays_on_the_page(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + shell + .events + .send(sample_presence!(p => { + for id in 100..140u16 { + let mut person = p.clients[&1].clone(); + person.id = id; + person.nickname = format!("Guest {id}"); + person.uid = Some(format!("guest-{id}")); + p.clients.insert(id, person); + } + })) + .unwrap(); + frame(cx); + assert_eq!(people(&shell, cx).len(), 45); + let page = at(cx, "voice-page").expect("the page"); + let bar = at(cx, "voice-callbar").expect("the call bar is still on the page"); + let stage = at(cx, "voice-people").expect("the people"); + assert!(bar.bottom() <= page.bottom(), "{bar:?} is inside {page:?}"); + assert!(stage.bottom() <= bar.top(), "the people end where the call bar begins"); + let header = at(cx, "voice-header").expect("the header"); + assert!(header.bottom() <= stage.top(), "the header stays on top"); +} + +/// On the smaller stage, a small channel (2–5 people) is centred horizontally +/// inside `"voice-people"`, while a crowded channel (20+ people) overflows +/// sideways starting cleanly at the left edge without clipping the first person. +#[gpui::test] +fn the_smaller_stage_centres_few_people_and_does_not_clip_many(cx: &mut TestAppContext) { + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + click(cx, "voice-stage"); + assert!(shell.view.read_with(cx, |view, cx| view.voice_page().read(cx).compact_shown())); + + let check_centred = |shell: &Shell, cx: &mut VisualTestContext, expected_len: usize| { + let list = people(shell, cx); + assert_eq!(list.len(), expected_len); + let stage = at(cx, "voice-people").expect("compact stage"); + let first = at(cx, &format!("voice-member-{}", list.first().unwrap().id)).unwrap(); + let last = at(cx, &format!("voice-member-{}", list.last().unwrap().id)).unwrap(); + let left_gap = f32::from(first.left() - stage.left()); + let right_gap = f32::from(stage.right() - last.right()); + assert!( + (left_gap - right_gap).abs() < 2.0, + "{expected_len} people should be centred: left_gap={left_gap}, right_gap={right_gap}, stage={stage:?}, first={first:?}, last={last:?}" + ); + assert!(left_gap > 50.0, "{expected_len} people should not sit flush left: {left_gap}"); + assert!(first.left() >= stage.left() && last.right() <= stage.right()); + }; + + // Five people (the sample channel). + check_centred(&shell, cx, 5); + + // Two people: still centred with wider margins. + shell + .events + .send(sample_presence!(p => { + for id in [3u16, 4, 5] { + p.clients.remove(&id); + } + })) + .unwrap(); + frame(cx); + check_centred(&shell, cx, 2); + + // Twenty-five people: overflows sideways without clipping the first person off the left edge. + shell + .events + .send(sample_presence!(p => { + for id in 100..120u16 { + let mut person = p.clients[&1].clone(); + person.id = id; + person.nickname = format!("Guest {id}"); + person.uid = Some(format!("guest-{id}")); + p.clients.insert(id, person); + } + })) + .unwrap(); + frame(cx); + let list = people(&shell, cx); + assert_eq!(list.len(), 25); + let stage = at(cx, "voice-people").expect("compact stage"); + let first = at(cx, &format!("voice-member-{}", list.first().unwrap().id)).unwrap(); + let last = at(cx, &format!("voice-member-{}", list.last().unwrap().id)).unwrap(); + assert_eq!(stage.size.height, px(112.0)); + assert_eq!(first.top(), last.top(), "stays one horizontal row"); + assert!( + first.left() >= stage.left(), + "first participant must not be clipped left: first={first:?}, stage={stage:?}" + ); + assert!( + f32::from(first.left() - stage.left()) <= 32.0, + "overflowing row starts at left padding: first={first:?}, stage={stage:?}" + ); + assert!( + last.right() > stage.right(), + "25 people overflow horizontally to scroll: last={last:?}, stage={stage:?}" + ); +} + +/// Hovering a toggle icon button and flipping its state drops GPUI's stale +/// active tooltip and builds the updated tooltip label while keeping the +/// button's `debug_selector` intact (`"call-mic"`, `"call-sound"`, +/// `"member-mute"`, `"voice-stage"`). +#[gpui::test] +fn toggle_button_tooltips_refresh_after_click(cx: &mut TestAppContext) { + use std::time::Duration; + + use crate::shell::actions::SetMemberMuted; + use crate::shell::widgets::take_tooltips; + + let (shell, cx) = on_the_voice_page(cx, Switches::default()); + let hover_tooltip = + |cx: &mut VisualTestContext, selector: &str, dx: f32| -> Vec<(String, String)> { + let bounds = at(cx, selector).unwrap_or_else(|| panic!("{selector} is not on screen")); + let pos = gpui_kit::point(bounds.center().x + px(dx), bounds.center().y); + take_tooltips(); + cx.simulate_mouse_move(pos, None, Default::default()); + frame(cx); + cx.executor().advance_clock(Duration::from_secs(2)); + frame(cx); + take_tooltips() + }; + + // 1. Call bar microphone: click sends the command while the button is still + // unmuted, hover shows "Microphone on", then the engine confirms mute while + // the pointer stays on the button -> stale tooltip is dropped and + // "Microphone off" is built. + click(cx, "call-mic"); + assert_eq!( + hover_tooltip(cx, "call-mic", 0.0), + vec![("call-mic".into(), "Microphone on".into())] + ); + shell + .events + .send(Event::State { + session: sample::DEMO as u64, + state: SessionState { + voice: VoiceState::Connected, + own_channel: Some(2), + own_client: Some(1), + input_muted: true, + ..Default::default() + }, + }) + .unwrap(); + frame(cx); + assert!(at(cx, "call-mic").is_some(), "debug_selector stays intact"); + assert_eq!( + hover_tooltip(cx, "call-mic", 1.0), + vec![("call-mic".into(), "Microphone off".into())] + ); + + // 2. Call bar sound: click + hover "Sound on", engine confirms deafen -> + // stale tooltip dropped and "Sound off" built. + click(cx, "call-sound"); + assert_eq!( + hover_tooltip(cx, "call-sound", 0.0), + vec![("call-sound".into(), "Sound on".into())] + ); + shell + .events + .send(Event::State { + session: sample::DEMO as u64, + state: SessionState { + voice: VoiceState::Connected, + own_channel: Some(2), + own_client: Some(1), + input_muted: true, + output_muted: true, + ..Default::default() + }, + }) + .unwrap(); + frame(cx); + assert!(at(cx, "call-sound").is_some(), "debug_selector stays intact"); + assert_eq!( + hover_tooltip(cx, "call-sound", 1.0), + vec![("call-sound".into(), "Sound off".into())] + ); + + // 3. Member card mute: hover "Mute for me", state flips while pointer stays + // on the button (and clicking again also keeps selector working) -> + // "Unmute for me" built. + click(cx, "voice-member-3"); + assert_eq!( + hover_tooltip(cx, "member-mute", 0.0), + vec![("member-mute".into(), "Mute for me".into())] + ); + cx.dispatch_action(SetMemberMuted { client: 3, muted: true }); + frame(cx); + assert!(at(cx, "member-mute").is_some(), "debug_selector stays intact"); + assert_eq!( + hover_tooltip(cx, "member-mute", 1.0), + vec![("member-mute".into(), "Unmute for me".into())] + ); + click(cx, "member-mute"); + assert_eq!( + hover_tooltip(cx, "member-mute", 0.0), + vec![("member-mute".into(), "Mute for me".into())] + ); + + // 4. Voice stage button: close member card, hover "Smaller stage", window + // shrinks below 800 px -> disabled button builds its new tooltip. + click(cx, "member-card-close"); + assert_eq!( + hover_tooltip(cx, "voice-stage", 0.0), + vec![("voice-stage".into(), "Smaller stage".into())] + ); + cx.simulate_resize(size(px(1440.0), px(700.0))); + frame(cx); + assert!(at(cx, "voice-stage").is_some(), "debug_selector stays intact"); + assert_eq!( + hover_tooltip(cx, "voice-stage", 1.0), + vec![("voice-stage".into(), "The window is too short for the larger stage".into())] + ); +} diff --git a/docs/design/gpui-spikes.md b/docs/design/gpui-spikes.md index 8d67391..cb1499e 100644 --- a/docs/design/gpui-spikes.md +++ b/docs/design/gpui-spikes.md @@ -66,8 +66,17 @@ banner is drawn under the surface veil of the Slint tree's `BannerPicture`, an avatar under 28 pixels shows one letter, the password prompt ignores an empty field and closes on Escape, and the `ui.tree` row of the settings table, the list of the Bridge's properties and callbacks that the two panes use and some -long lines are corrected in docs/ui.md. The next slice is the voice page and the -call bar. +long lines are corrected in docs/ui.md. Slice 3, the voice page and the call bar, +landed on `phase5/gpui-voice` (2026-10-28): the page as a cached pane of its own +that takes the main area (its people from the tree model's one build, so a talker +is still one build for three lists), the call bar and the smaller stage kept in +`ui.voice_compact`, the sidebar's server card with its banner, the voice card's +transmit modes and the volume of a person following the settings, the release +guard of Hold to talk (voice that drops, a window that loses the focus) and the +global push-to-talk key started on the engine's runtime; it was seen against both +development servers with a second client that talks. What it costs and what it +leaves is in docs/ui.md, "The voice page and the call bar". The next slice is the +chat, the composer and emoji. | Spike | The plan's no-go | Seen (software rendering, see Setup) | Verdict | |---|---|---|---| diff --git a/docs/ui.md b/docs/ui.md index dfd68cf..9b397e7 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -663,7 +663,7 @@ live when they change (settings page, `--set`, another window): | `ui.members_width` | pixels | 280 | width of the members panel (dragging its edge sets it) | | `ui.window` | JSON `{width, height, x?, y?, maximized}` | none | where the main window was when the last run ended: its size (the one it returns to when `maximized`), its position where the platform tells one (Wayland does not: no `x` and `y`), and whether it was maximized; the next run opens there. Read at start, not applied live; written by the GPUI front end only (the Slint app neither registers nor reads it) | | `ui.tree` | JSON by server id: `{"": {collapsed, selected}}` | none | what each server's channel tree remembers: the channels folded shut (`collapsed`, channel ids) and the channel last selected (`selected`), under the id of the server's bookmark; a server with nothing folded or selected has no entry. Read at start, written at every fold, unfold and selection (not with the sample servers); written by the GPUI front end only (the Slint app neither registers nor reads it: its tree forgets both when it ends) | -| `ui.voice_compact` | bool | false | the voice channel view's smaller stage (its Smaller stage / Larger stage button sets it; windows under 800 px tall always have it) | +| `ui.voice_compact` | bool | false | the voice channel view's smaller stage (its Smaller stage / Larger stage button sets it, in both front ends; windows under 800 px tall always have it) | | `ui.image_preview_kb` | kilobytes | 8192 | pictures linked in chat (files and `[img]`) up to this size show as pictures (0: never) | | `notify.mentions`, `notify.private_messages`, `notify.pokes`, `notify.event_reminders`, `notify.friends_online` | off / app / desktop | desktop (friends: app) | what the bell and the desktop say about each kind | | `video.camera`, `video.background`, `video.resolution`, `video.mirror` | device id; none / blur; auto or WxH; bool | first camera, none, auto, true | the camera of the preview and the default of camera sources | @@ -990,6 +990,8 @@ crates/voelin-gpui/ and the callbacks of the Slint `bind/servers.rs` that the shell, the channel tree and the members have (over `voelin_ui_vm::servers:: {logic, sequence}`, which Slint calls too) + hotkey.rs GlobalPtt: the global push-to-talk key's task, spawned on the engine's + runtime, its presses and releases handed to GPUI's thread through Later signals.rs `Update.refresh` as per-area signals: entities with a generation that the panes observe pictures.rs the engine's pictures on screen: decoded per file and stamp, the @@ -999,8 +1001,9 @@ crates/voelin-gpui/ title, the window's place shell/ the desktop shell and its panes (below): rail.rs, sidebar.rs, topbar.rs, main_panel.rs, channels.rs (the tree), members.rs (the - panel and its card), tree_model.rs, password.rs, form.rs, toast.rs, - actions.rs, widgets.rs + panel and its card, with the volume of a person), voice.rs (the + voice channel page and its call bar), tree_model.rs, password.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 @@ -1056,7 +1059,7 @@ crates/voelin-gpui/ exact row operations, a talker that redraws the tree and the members panel and no other pane, the member card, an avatar written again), 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 + reaches the status line), the voice page and the call bar (below), 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 @@ -1115,13 +1118,14 @@ 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_OPEN=voice` (`voice:compact`) | the voice channel page in the main area once voice is connected (with the sample servers the first one is, so at start); `voice:compact` on the smaller stage, which is not stored | | `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, with its channels, people and their pictures, the second observed); nothing is sent to the engine or kept in the store, the window's place and what the trees remember included, and the servers cannot be changed. The pictures are files of a folder of the state's own in the temporary directory, removed when the window closes (a killed run leaves it) | | `VOELIN_DEMO_SERVER=2` | with the sample servers, the one on screen, counting from 0: the first (the default) is connected and populated, the second observed (its tree says it is loading), the third not connected (its tree says to connect) | | `VOELIN_DEMO_TALK=10` | with the sample servers, one sample person starts or stops talking this many times a second (a rate from 0.1 to 100), through the app's own events: what the meter measures while someone talks | | `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; the renders of each pane, `rail`, `topbar`, `sidebar`, `tree`, `main` and `members`; `Later` jobs) and the voice connections up | +| `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; the renders of each pane, `rail`, `topbar`, `sidebar`, `tree`, `main`, `members` and `voice`; `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 @@ -1199,15 +1203,16 @@ rendered with every frame ([what a change costs](#what-a-change-costs)). "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 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). + channels" once its presence is known, else its address, over the server's + banner when it has one: slice 3), 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, else the + mode in words) 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 voice page and the chat come. + Disconnect, Voice channel (while voice is connected: it opens the voice page, + [below](#the-voice-page-and-the-call-bar)) and Edit, until the chat comes. - **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 @@ -1243,8 +1248,9 @@ front end](#shared-with-the-slint-front-end)): The others of that file: `join_channel`, `join_with_password`, `toggle_collapse`, `search_members` and `open_client` are slice 2's ([the channel tree and the members](#the-channel-tree-and-the-members)); `show_voice_view` is the voice -page's (slice 3), `client_audio_changed` the dialogs', and `copied`, which the -Slint toast of a copy needs, `Invite` does for itself. `AddServer`, +page's (slice 3, [below](#the-voice-page-and-the-call-bar)), `client_audio_changed` +the dialogs' (the member card has the volume of a person, `SetMemberVolume`), and +`copied`, which the Slint toast of a copy needs, `Invite` does for itself. `AddServer`, `CancelServerForm`, `OpenSearch` and `OpenSettings` are the shell's own. #### Shared with the Slint front end @@ -1289,7 +1295,8 @@ state: the thread hop of the gateway lookup (`look_up_gateway`: each front end runs `sequence::find_gateways` on the engine's runtime and comes back through its own `Later`/`later`), `perform` (what an `Update` does to a window), the status line's toast, the invite's clipboard write, `HostedEngine` (`engine.rs`), -the guards of the GPUI shell's save (`save_refused`: the sample servers are not +`GlobalPtt` (`hotkey.rs`: the global key's task needs the engine's runtime and the +front end's own way back to its state), the guards of the GPUI shell's save (`save_refused`: the sample servers are not kept, and a server needs an address, which the Slint dialog checks in `dialogs.slint` before it calls), the store at start (`Backend::open` against `run()`: the identity import, the crash reports and `--set` of the Slint one) @@ -1475,8 +1482,9 @@ What is on screen: power. The search narrows the sections to the names it matches. - **The member card**: a click on a person opens their card over the panel with a scrim a click outside closes: name, status, description, groups, badges (what - each is for on hover), talk power and country. It follows the person while it - is open and goes when they leave. + each is for on hover), talk power and country, and since the voice page the + Volume rows: what they are played at, a mute for us and a slider. It follows + the person while it is open and goes when they leave. - **The password prompt**: joining a channel that has a password and whose password was not given this connection asks for it (a card over the window, Enter joins); a password the server refuses asks again, in words. As in the @@ -1689,7 +1697,7 @@ seventh standing in for the chat. The callbacks are GPUI actions | `connect_voice` (`channels.slint`, the server card's Connect) | `ConnectVoice` | slice 1 (the shell) | | `Nav.add_server`, `Nav.edit_server` (`channels.slint`, the server card's menu) | `AddServer`, `EditServer { id }` | slice 1 (the shell) | | `watch_client` (`channels.slint`, the LIVE tag of a person who streams) | none | the tag is drawn and not clickable: the stream viewer, slice 6 | -| `member_action("mute")` and `member_volume` (`members.slint`, the card's mute button and volume slider) | none | the card has no buttons yet: the person's volume, with `open_client` and `client_audio_changed`, the dialogs slice (9) | +| `member_action("mute")` and `member_volume` (`members.slint`, the card's mute button and volume slider) | `SetMemberMuted`, `SetMemberVolume` | slice 3: the card's Volume rows ([below](#the-voice-page-and-the-call-bar)); the volume dialog of `open_client` and `client_audio_changed` stays the dialogs slice's (9) | | `member_action("watch")` | none | the stream viewer, slice 6 | | `member_action("message")` | none | the chat, slice 4 | | `member_action("poke")` | none | the poke dialog, the dialogs slice (9) | @@ -1702,24 +1710,300 @@ seventh standing in for the chat. The callbacks are GPUI actions | `server_members` (`members.slint`) | `TreeModel::people` | | `member_total` (`members.slint`) | `TreeModel::total` ("Members — N") | | `member_card` (`members.slint`) | `TreeModel::card` (`voelin_ui_vm::tree::member_card`), shown by `MemberCardView` | -| `members` (the people in our channel: the voice page, not the two files) | built by `tree_view` and not shown: the voice page (slice 3) draws it | +| `members` (the people in our channel: the voice page, not the two files) | `TreeModel::voice` (`TreeEvent::Voice`), built with the other two lists and shown by the voice page (slice 3) | | `current_server` (`channels.slint`) | `AppState::vm.current` (slice 1) | | `observing` (`channels.slint`, `members.slint`) | `SidebarView::observing` (slice 1: the user's card says Observing); here also `Emptiness`, the words of a list with nothing in it: the tree's ("No server yet.", "Loading the channels…", "Connect to see the channels.") and the panel's ("Loading who is here…", "Connect to see who is here.", and "Nobody matches." for a search that leaves nobody of a server that has people); a server whose voice is connecting is loading | | `server_title`, `server_icon`, `server_stats` (`channels.slint`, the server card) | slice 1: the sidebar's server card (`ServerItem`'s name and icon, `SidebarView::stats`, "9 online · 9 channels") | | `voice_connected`, `voice_connecting` (`channels.slint`, the server card and its Connect) | slice 1: `SidebarView::voice_connected` and `voice_connecting`, the voice card ("Voice Connected", "Connecting…") | -| `server_banner` (`channels.slint`, the server card's picture) | not drawn: the sidebar's server card has no banner behind it. The same `BannerPicture` and veil (`widgets::banner_scrim`, which the tree's rows use) would do; it comes with the slice that lays the sidebar's cards again, the voice page and call bar (3) | +| `server_banner` (`channels.slint`, the server card's picture) | `SidebarView::server_banner`, behind the sidebar's server card under the same veil as the tree's rows (slice 3) | | `Nav.right_panel_width`, `Nav.right_panel_open` (the frame, `desktop.slint`, not the two files) | `ui.members_width`, read at start (no resize handle yet), and the panel is there while a server is on screen (the pins and topics drawers that share it come with the chat) | -`show_voice_view` (the voice page) and `client_audio_changed` (the volume -dialog) are the other server callbacks of the Bridge that these panes will meet -later; neither file uses them. +`show_voice_view` (the voice page, slice 3) and `client_audio_changed` (the volume +dialog) are the other server callbacks of the Bridge that these panes meet; +neither file uses them. What differs from the Slint tree and panel: the speaking bars stand still (nothing here may draw the window with the clock); the lists scroll with the wheel and have no scrollbar; a click on a channel -selects it where Slint opens its chat; the card has no buttons; the members +selects it where Slint opens its chat; the card has the volume and the mute of a +person and none of the buttons of the dialogs' slices; the members panel has no resize handle; the fill spacer's line is drawn with the channel's -own characters, as the rows give it; the sidebar's server card has no banner. +own characters, as the rows give it. + +### The voice page and the call bar + +Slice 3 of plan section 6 step 3: the voice channel page of the Slint front end +(`screens/voice.slint`, with the `Participant` of `voice-parts.slint`) and its +call bar, the sidebar's server card with its banner behind it, the release guard +of Hold to talk, the global push-to-talk key and the volume of a person, on the +same `voelin-ui-vm` rows (`TreeView::members`) and logic as the Slint front end. + +| The larger stage | The smaller stage | +|---|---| +| ![the voice page, dark](ui/gpui-voice-dark.png) | ![the voice page on the smaller stage, dark](ui/gpui-voice-compact-dark.png) | +| ![the voice page, light](ui/gpui-voice-light.png) | ![the voice page on the smaller stage, light](ui/gpui-voice-compact-light.png) | + +The pictures are the shell at 1440 by 960 under `scripts/gpui-shot.sh` (the +recipe above: `VOELIN_DEMO_UI=1` with `VOELIN_OPEN=voice` and `voice:compact`, a +display of its own, the state under the checkout's `.scratch/`): the larger +stage on the release build of `7140718` (Xvfb `:511` and `:512` of 3840 by 2160 +with openbox, Mesa 26.2.5's lavapipe) and the smaller stage re-shot on the +release build of `15a1b60` after centring its row (Xvfb `:621` and `:622` of +3840 by 2160 with openbox, Mesa 26.3.0's lavapipe, both `llvmpipe (LLVM 21.1.8, +256 bits)` through Vulkan). The first sample +server's Chill Zone: Kairo talks (the green ring and the bars in the corner of +the avatar, "Speaking"), Lumen streams (the blue ring, "Streaming" or LIVE), dex's +microphone is off (the mark in the corner), the channel's banner is behind the +header, and the server's own banner behind the server card of the sidebar. Two +more pictures are from the live run against the TeamSpeak 3 development server +([below](#seen-against-the-servers)): the voice page with a second client +that talks (a real `Event::Talking`), and the card of that person with the +volume rows. + +| A real talker (TeamSpeak 3 server) | The volume of a person | +|---|---| +| ![the voice page on a TeamSpeak 3 server, dark](ui/gpui-voice-live-dark.png) | ![a person's card with the volume, dark](ui/gpui-voice-card-dark.png) | + +What is on screen: + +- **The page** (`voice.rs`, `VoicePage`, a cached pane of its own). It is the main + area while the page is asked for and voice is connected (the Slint front end's + `Nav.voice-view && Bridge.voice-connected`): the server page's Voice channel + button asks for it (`ShowVoiceView { on: true }`, through `logic::show_voice_view`, + which also puts the people of our channel first in the members panel) and + the page's Chat only button gives the area back to the server page, where the + chat will be. A connection that drops takes the page away and a reconnect brings + it back, as in Slint (the flag is kept); Leave asks for the page off and leaves + voice (`LeaveVoice`: `show_voice_view(false)`, then the engine's + `DisconnectVoice`). `MainView` puts the page *instead of* the server page (they + are siblings, never nested: a cached view inside a view that renders again is + rendered again), so `panes.main` is not rendered while the page is up. +- **The header**: the channel's name, its topic, "5 in voice / 50 total" (the + limit when the channel has one) and, behind them, the channel's banner under + the same surface veil as the tree's rows (`widgets::banner_scrim`; the text + reads in the text colour instead of the secondary one over a picture). Copy + invite link (`Invite`), Smaller stage / Larger stage (`ToggleVoiceCompact`, + kept in `ui.voice_compact`, which both front ends read) and Chat only. +- **The people**, from `TreeView::members` as the model's `TreeEvent::Voice` (the + tree model builds the three lists once and tells the page its rows when they + differ, so the page builds nothing of its own): large avatars (80 pixels) in a + wrapping row, centred; a ring that is green while they talk and blue while they + stream (3 pixels, else 2 in the border colour), the mark in the corner of the + avatar (the speaking bars, else the headphones off, else the microphone off), the + name (ours in the accent colour) with the crown of an admin, and "Speaking", + "Streaming" or "Away" with the bars or the monitor mark. A click opens the + person's card (`OpenMember`). The smaller stage is one row of 54 pixel avatars + (a flex-row scroll container whose inner row carries `.flex_none().mx_auto()`), + centred horizontally while the people fit and scrolling sideways from the left + edge without clipping when they outgrow the page, ringed only while they talk + or stream, with the name and the crown, and LIVE under a streamer. A window + under 800 pixels tall has the smaller stage whatever the setting says and the + button is off, with the reason as its tooltip (`Nav.short`): `MainView` tells + the page when the window crosses 800 pixels, since a cached pane does not see + a resize. +- **The call bar**: Mute and Deafen (44 pixel round buttons, red while on: + `SetInputMuted`, `SetOutputMuted`), Share when the server can stream and the + voice settings (`OpenShare`, `OpenVoiceSettings`: logged, their pages are + the stream slices' and the settings slice's), and Leave. `IconButton` keys its + GPUI element ID by both its base ID and its label (`ElementId::NamedChild`, + keeping `.debug_selector` on the base ID), so toggle buttons (`call-mic`, + `call-sound`, `member-mute`, `user-mic`, `user-sound`, `voice-stage`) drop + stale hover/tooltip state and render the updated tooltip as soon as their + label changes. The streams of the Slint page and its channel chat come with + their slices; the page says so where the chat will be. +- **The voice card and the modes.** Hold to talk is for the push-to-talk mode of + the audio settings; for voice activity and for an open microphone the card says + the mode in words instead of showing a button. `SettingChanged` for `audio`, + `client_playback` and `ui.voice_compact` is read again, as the Slint front end's + `setting_changed` does, so the modes, the volumes and the stage follow the + config file and the commands. +- **The volume of a person**: the member card (a click on a person on the voice + page or in the members panel) has the Slint card's Volume rows, the percentage, a + mute for us and a slider (0 to 200 percent in steps of 5), off for a person the + server gave no unique id. They are `SetMemberVolume` and `SetMemberMuted`, which + go through `voelin_ui_vm::settings_page::logic::{open_client, + client_playback_changed}` (the logic the Slint volume dialog calls: the engine's + `SetClientVolume` and `SetClientMuted`, the `client_playback` key by the person's + unique id, the tree's mark of who is muted). The dialog of `open_client` itself, + which the tree's click on a person asks for, stays the dialogs slice's. +- **The server card's banner**: `server_banner` behind the card of the sidebar, as + `ServerHeader` of `channels.slint` has it (the picture covers the card and is + cropped to its inside, the veil lies over it, the stats read in the text + colour). GPUI clips to rectangles, so the picture's corners are square, as the + tree's banner rows'. + +**The release guard of Hold to talk and the global hotkey** (the risk slice 2 +recorded, hardened in the voice fix round). `AppState` tracks the window button +(`button_held`), the global hotkey (`hotkey_held`), and window teardown +(`shutting_down`) independently, with `stop_transmitting_if_unheld`, +`release_button_hold`, and `release_hotkey_hold`: holding both at once keeps +transmit active until both release without duplicate start or stop commands. +Every path that can orphan a hold is guarded: + +- *Voice that drops:* checked per event inside `AppState::handle_events` (not + only across a whole 64-event batch, so a drop and reconnect inside one batch + cannot mask it). Whenever a session leaves `Connected`, any button or hotkey + hold on it ends, and `SetTransmitting(false)` is emitted once if either was + held or the engine still reports `transmitting` (the engine's answer and a + reconnect are not answered). `Sidebar`'s signal observer clears its own + `holding` flag whenever voice disconnects, transmit leaves push-to-talk, the + shown server changes, or `AppState::button_held` no longer matches (it only + sets its own field and never mutates root state). +- *Leaving push-to-talk, switching servers, or removing a server:* + `setting_changed` releases `button_held` when `audio.transmit` leaves + `PushToTalk` (while `!audio_dirty`); `select_server` releases `button_held` + when the held server leaves the screen (without touching `hotkey_held`, so the + global key still releases the server it started on); `delete_bookmark` clears + any hold on the removed session before closing it. +- *Window focus loss and shutdown:* `MainView`'s `observe_window_activation` + unconditionally releases `Sidebar` and calls `AppState::push_to_talk(false)` + when the window becomes inactive (a no-op when `button_held` is `None`; + `hotkey_held` is untouched so the global key keeps working while another + window has focus). `AppState::shutdown` sets `shutting_down`, drops `ptt`, and + releases both holds before sending `CloseSession`, ignoring any late press + that arrives through `Later` after close begins. + +Each guard has deterministic tests (`hold_to_talk_is_released_when_voice_drops`, +`hold_to_talk_is_released_when_the_window_loses_the_focus`, +`leaving_push_to_talk_releases_a_held_button`, +`a_drop_and_reconnect_in_one_batch_releases_a_held_button_and_hotkey`, +`holding_the_button_and_the_hotkey_together_stops_only_when_both_let_go`, +`switching_servers_releases_a_held_button_but_keeps_the_global_hotkey`, +`focus_loss_releases_app_button_hold_unconditionally`, +`a_second_hotkey_press_on_another_server_releases_the_first`, +`removing_a_server_clears_active_transmit_holds`, +`closing_releases_a_held_transmit_and_ignores_late_presses`), and each guard was +mutated to confirm its test goes red. + +**The global push-to-talk key** (`hotkey.rs`). `voelin_platform::HotkeyManager` +(the desktop's portal on Wayland, XInput2 on X11) runs in a task spawned on the +engine's runtime: the portal backend calls `tokio::spawn` when it is made, which +panics where no tokio runtime is current, and a GPUI foreground task has none +("For the next slices" said so). `run()` starts it once the window is open when +there is an engine, no sample servers and the settings (`ui`: `global_ptt`, on by +default, and `ptt_key`, `Ctrl+Shift+T`) ask for it; the state does not start it by +itself, so that a test of the state with a real engine never asks the desktop for +a shortcut (the first version of the commit did, and the test scheduler found it: +the status line came back from a tokio thread). Its presses and releases come to +GPUI's thread through `Later`: a press transmits into the session on screen while +it has voice, a repeated press on a different connected server ends the previous +session's transmit before starting the new one, and the release ends the session +the press began in, whichever is on screen then. The event loop (`run_loop`, +tested over private `EventStream` / `Registrar` traits without a portal or +display) fails closed on both termination paths, calling `transmit(false)` before +exiting when the command channel closes and before reporting status when the +desktop removes the shortcut mid-hold. How the key stands ("Active: Ctrl+Shift+T +(X11)", why it could not be registered) is in the log and `AppState::ptt_status`; +changing the key at run time (`AppState::set_global_ptt`) is the settings slice's. +The loop is the Slint front end's `GlobalPtt` repeated, as `HostedEngine` is. + +#### The properties and callbacks of the voice page + +The plan counts 6 properties and 6 callbacks. The properties the page reads, and +the callbacks of `bind/servers.rs` (and of `Nav`, whose functions call it) that its +controls have, each with what takes it here; the first six rows of each table are +the plan's six. + +| Slint property (used by) | Here | +|---|---| +| `members` (`voice.slint`) | `TreeModel::voice`, `VoicePage::people` | +| `own_channel` (`voice.slint`, the voice card) | `VoiceHead::channel` | +| `own_channel_topic` (`voice.slint`) | `VoiceHead::topic` | +| `own_channel_banner` (`voice.slint`) | `VoiceHead::banner`, the veil of `banner_scrim` | +| `own_channel_limit` (`voice.slint`) | `VoiceHead::limit` ("5 in voice / 50 total") | +| `server_banner` (`channels.slint`) | `SidebarView::server_banner`, behind the server card | +| `input_muted`, `output_muted`, `voice_connected` (`VoiceButtons`) | `VoiceHead`, the call bar's buttons | +| `audio.transmit` (`VoiceCard`) | `SidebarView::transmit`: Hold to talk, or the mode in words | +| `transmitting` (`VoiceCard`, `UserCard`) | `SidebarView::transmitting` (the button, the ring of our avatar) | +| `Nav.voice_view`, `Nav.voice_compact`, `Nav.short` | `vm.voice_view` (`logic::show_voice_view`), `AppState::voice_compact` (`ui.voice_compact`), `VoicePage::short` | +| `streams`, `messages`, `streams_available`, `can_share` | the stream slices' and the chat's; the call bar shows Share when `streams_available` | + +| Slint callback (used by) | Action | What it does | +|---|---|---| +| `show_voice_view` (`Nav.show-voice`) | `ShowVoiceView { on }` | `logic::show_voice_view`: the page asked for or not | +| `disconnect_voice` (the call bar's Leave, with `Nav.show-voice(false)`) | `LeaveVoice` | the page off, then `Command::DisconnectVoice` | +| `set_input_muted`, `set_output_muted` (`VoiceButtons`) | `SetInputMuted`, `SetOutputMuted` | the shell's, from the call bar too | +| `invite` (the header's Copy invite link) | `Invite` | the shell's | +| `open_member` (`Participant`) | `OpenMember` | slice 2's: the card | +| `voice_compact_changed` (`Nav.toggle-voice-compact`) | `ToggleVoiceCompact` | `ui.voice_compact` kept (not with the sample servers) | +| `push_to_talk` (`HoldToTalk`) | `PushToTalk` | the shell's, with the two guards above | +| `Nav.open-settings(voice)`, the share menu | `OpenVoiceSettings`, `OpenShare` | logged: the settings slice and the stream slices | +| `member_volume`, `member_action("mute")` (the card) | `SetMemberVolume`, `SetMemberMuted` | `client_playback_changed` | + +What differs from the Slint page: no members button (the panel is there while a +server is on screen), no streams and no chat under the call bar (their slices), no +Share menu (logged), the speaking bars stand still, the page does not open by +itself when voice connects (Slint's chat is its default; here the server page has +the Voice channel button, and `VOELIN_OPEN=voice` asks for it at start), and the +smaller stage is the desktop's row of small avatars (the phone's compact layout is +dropped with the phone layouts). + +#### What the voice page costs + +`VOELIN_METER=1`, release build of `7140718`, 1440 by 960 on Mesa 26.2.5's lavapipe +through Vulkan on Xvfb `:531` and `:532` with openbox, the first sample server on +screen with the voice page open (`VOELIN_OPEN=voice`: the larger stage, nine +people on the server, five in Chill Zone), the machine's other jobs at a load +average of 10.1 before the first run, 3.7 between the two and 2.4 after (the one-minute figure); the first 15 seconds of 75 left out; CPU in percent of one +core, whose resolution is the 1 % of a clock tick; renders per second as the meter +counts them: + +| | CPU, mean (max) | Of it `llvmpipe` | GPUI's thread | Resident memory | Window frames a second | Rendered a second: rail, top bar, sidebar, tree, main, members, voice page | +|---|---|---|---|---|---|---| +| Idle, the voice page of the first sample server on screen | 0.3 % (2 %) | none | 0.1 % (1 %) | 223.2 MiB | 0.0 | 0, 0, 0, 0, 0, 0, 0 | +| A sample person starts or stops talking 10 times a second (`VOELIN_DEMO_TALK=10`) | 123.9 % (127 %) | 117.4 % | 3.6 % (6 %) | 227.9 MiB | 10.0 | 0, 0, 10.0, 10.0, 0, 10.0, 10.0 | + +60 samples each. The same two runs on the release build before the last three +small commits (`65b60f2`; Xvfb `:431` and `:432`, load average 25.3 before and 21.0 +after): idle 0.5 % (2 %), 220.2 MiB, no pane rendered; talking 109.9 % (122 %) in +all, `llvmpipe` 102.1 %, GPUI's thread 6.4 % (11 %), 226.3 MiB, 9.95 events and +frames a second, the sidebar, the tree, the members panel and the voice page +rendered 9.97 times a second each (59 samples: the loaded machine left a second +out). The software device's share moves with the machine's load (102 to 117 % +here); the thread's, which is the app's, did not. + +A window nobody touches is not drawn, with the voice page on screen as before. +Someone who starts or stops talking is one engine event, one frame and one render +of the sidebar (every frame renders it), the tree, the members panel and the voice +page, and none of the rail, the top bar and the main area; the model builds the +rows once for the three lists. The page's own cost is within the spread the load +of the machine makes (the tree slice's figures at the same rate were 102 to 106 % +in all and 3.1 to 5.0 % for GPUI's thread, 4.2 % on the minors round's); `llvmpipe` +draws the whole window again for every frame whichever pane asked for it, which is +the 90 ms of CPU a frame of this software device and what a GPU takes over. + +#### Seen against the servers + +Release build of `7140718`, the two development servers of +`dev/docker-compose.yml` used read-only (nothing created, deleted or reset; for +each, one connect of the app and one of a second client), a display of its own for +each run (Xvfb `:533` and `:534` of 3840 by 2160 with openbox, Mesa 26.2.5's +lavapipe, `llvmpipe (LLVM 21.1.8, 256 bits)` through Vulkan as the log's "Selected +GPU adapter" says, 1440 by 960), the state under the checkout's `.scratch/`, no +Wayland, no session bus, no XDG directory of the desktop, `ALSA_CONFIG_PATH` empty +(no sound card), driven with `xdotool` and read back with `xwd`. *TeamSpeak 3* +(3.13.8, `127.0.0.1:9987`): the form's Save and connect (the nickname `gpui-voice`) +shows the server page "Connected with voice", and ServerQuery's `clientlist -voice` +has the client in Default Channel; the Voice channel button opens the page with +one person; a second client, `voelinctl connect 127.0.0.1:9987 --nick +voelinctl-talker voice send --tone 440 --seconds 25`, joins and talks: the page +shows two people and the talker's ring, the bars in the corner of their avatar +and "Speaking" (the server's `client_flag_talking=1`, the page's marks from the +engine's `Talking` events), the same in the tree and the panel, which lead with +"In Voice — 2". The call bar's mute: the server says `client_input_muted=1`; +deafen: `client_output_muted=1` too; both clicked back: 0 and 0. Hold to talk held +with the pointer says "Talking…" and rings our avatar, as does `Ctrl+Shift+T` held +with `xdotool` (the log's line from the hotkey task: "Active: Ctrl+Shift+T +(X11)"); there is no microphone, so no audio goes out and the server's +`client_flag_talking` stays 0 for our client: the held key and button are seen in +the window, and the engine got `SetTransmitting`. The smaller stage, and the card +of the talker with the volume at 100 %. Leave: the page goes, and `clientlist` +does not have the client; Alt+F4 ended the app with exit status 0 and `clientlist` +after the close had no ghost of the app's client either. *TeamSpeak 6* +(6.0.0-beta13.1, `127.0.0.1:9988`), the same steps up to Leave (the smaller stage +and the card were not repeated) with Share in the call bar (the server can +stream: the click is logged) and no ServerQuery (it is SSH): the same page, marks, +hold, key and close, exit status 0; the pictures here are the TeamSpeak 3 run's. ### The theme @@ -1789,13 +2073,15 @@ Slint `Bridge` (`ui/bridge.slint:801-1206`; properties / callbacks): `toggle_collapse`, `search_members` and `open_member` as actions beside the shell's (`open_client` logged), and the password prompt the transitions ask for; -3. **next: the voice page and the call bar** (6 / 6): the people of our - channel (`TreeView::members`, built and not shown yet), `show_voice_view`, - the voice card's controls, the sidebar's server card with the banner behind - it (`server_banner`, which the tree slice left out: - [the table](#the-callbacks-and-the-properties)), and the release guard of - Hold to talk (below); -4. chat, the composer and emoji (about 19 / 18, and the `Emoji` global 3 / 3): +3. the **voice page and the call bar** (done, + [above](#the-voice-page-and-the-call-bar); 6 / 6): the people of our channel + (`TreeView::members`, through the tree model) with their marks, + `show_voice_view`, the call bar (mute, deafen, Share and the voice settings + logged, Leave) with the remembered smaller stage, the voice card's modes, the + volume of a person on the member card, the sidebar's server card with the banner + behind it (`server_banner`), the release guard of Hold to talk and the global + push-to-talk key on the engine's runtime; +4. **next:** 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 (design/gpui-spikes.md, "Open choices for step 3"): emoji (the one-line `gpui-pre-wgpu` patch for colour emoji, or Noto Color Emoji bundled with a @@ -1832,7 +2118,10 @@ the slices that meet it; none of it is a defect of what exists today. its own and a signal of its own, embeds it cached as a sibling of the other panes (a cached view inside a view that renders again is rendered again), and raises its flag from `Signals::areas`. A new area is one more variant of - `signals::Area`. + `signals::Area`. The voice page (slice 3) is such a pane and needed no new area: + it watches the servers' and the toolbar's signals for its header and call bar, + takes its people from the model's `TreeEvent::Voice`, and `MainView` pushes + what no signal says (the stage chosen, the window too short) into it. - **No state change from a signal's observer, inside a flush.** The model listens to three signals (tree, toolbar, member card) and a batch raises several of them, so it may refresh twice in one flush of GPUI's effects, and @@ -1861,9 +2150,12 @@ the slices that meet it; none of it is a defect of what exists today. build: `a_picture_that_arrives_builds_the_rows_once`), but what a build costs is what a server of hundreds of people will pay for each event. A refresh that only flips `talking` of the rows it has (the talker's row, from the event's - client) or a reuse of the `ImageRef`s of the rows that did not change is the - voice page's (slice 3) or a later slice's, when a measurement on a large - server says it matters; the 9-person sample server does not. + client) or a reuse of the `ImageRef`s of the rows that did not change is still + a later slice's, when a measurement on a large server says it matters; the + 9-person sample server does not. The voice page (slice 3) did not need it: its + people are the third list of the same build (`TreeView::members`), not a + second build, and a talker is still one build for the tree, the panel and the + page ([what the voice page costs](#what-the-voice-page-costs)). - **The rail, the top bar and the main area refresh on the servers flag only.** Before the tree slice they compared what they would show with what they showed on every notify of the root; they listen to `Refresh::servers` now @@ -1898,9 +2190,11 @@ the slices that meet it; none of it is a defect of what exists today. What the caches save is the stream of engine events (a talker, a join), not the user's own clicks. - **The tree's and the panel's lists have no scrollbar and the panel no resize - handle**; the wheel scrolls (`gpui::ListState`), as the voice page's and the - chat's lists will have to as well, with gpui-component's scrollbar if it fits - a `ListState`, and `ui.members_width` is read at start. + handle**; the wheel scrolls (`gpui::ListState`), as the chat's list will have to + as well, with gpui-component's scrollbar if it fits a `ListState`, and + `ui.members_width` is read at start. The voice page's people scroll with the + wheel too (a plain scrolling container: down on the larger stage when the rows + outgrow the page, sideways on the smaller one) and have no scrollbar. - **Three copies stay in the Slint crate**, because `voelin-ui` is not edited beyond the identity helper in this round: `connect_into` and the two joins of `bind/servers.rs` (the shared ones are `sequence::join_channel`, @@ -1914,13 +2208,14 @@ the slices that meet it; none of it is a defect of what exists today. the GPUI front end alone, and Slint's copies can drift from them: a change to the rules of a join or of the card is made in both, or the Slint copy becomes the call first. -- **`SettingChanged` for the audio and the playback keys is not reloaded.** - `AppState::setting_changed` follows `ui.theme` and `ui.font_scale` only; the - Slint front end also reloads `audio` (unless the page has unsaved edits) and - `client_playback`, the crash-reports flag and the decoder keys. The values the - window keeps copies of (`vm.audio`, `vm.playback`) go stale when a command, - the config file or another window changes them; the settings slice (5) adds - the reload with the page that shows them. +- **`SettingChanged` is reloaded for the keys the voice page shows, not yet for + all of the Slint front end's.** `AppState::setting_changed` follows `ui.theme` + and `ui.font_scale`, and since the voice slice `audio` (unless the page has + unsaved edits: `audio_dirty`), `client_playback` and `ui.voice_compact`. The + Slint front end also reloads the crash-reports flag, the stream audio sources + and the decoder keys; and the `ui` value (the hotkey's `global_ptt` and + `ptt_key` are read at start only here); the settings slice (5) and the stream + slices add those with the pages and the parts that use them. - **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 @@ -1948,11 +2243,15 @@ the slices that meet it; none of it is a defect of what exists today. field's `Escape`: with the field focused its Escape passes the key on and the binding closes the prompt, with anything else in the prompt focused the binding is the only one there. -- **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 - the hotkey task on the engine's runtime (`runtime.spawn(...)`), as the Slint - front end's `GlobalPtt::start(runtime, ...)` does, not from a foreground task. +- **Settled by the voice slice: the hotkey runs on the engine's runtime.** 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, so `hotkey.rs` spawns the task on the engine's + runtime, as the Slint front end's `GlobalPtt::start(runtime, ...)` does, and + `run()` starts it (`AppState::start_global_ptt`), never the state itself: a + test of the state with a real engine would ask the desktop for a shortcut. A + new part that talks to the desktop (a portal, a hotkey) is started by `run()` + and not by `AppState::new` for the same reason. - **`PortalCapture::stop` closes the portal session only inside a tokio runtime** (`voelin-media`, `capture/portal.rs`: `Handle::try_current()`; elsewhere the session closes only with the connection). Stop a capture inside @@ -2017,9 +2316,40 @@ the slices that meet it; none of it is a defect of what exists today. 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. -- **Four risks of the shell the gate found by reading, left to the slices that +- **What the voice slice leaves to the slices that meet it.** + - *The chat's slice puts the way to the voice page where the chat is.* Today the + server page has the Voice channel button and the voice page's Chat only goes + back to it; with the chat, the button goes to the chat's header as in Slint + and the page's lower part is the channel's chat (the page says so where it + will be). `show_voice_view(true)` already opens the channel's chat tab in the + state (`open_chat`, with `focus`), whose reading marks wait for the front + end's answer to `Host::chat_shown` (`ShellHost` says `false` until a page + shows a chat), so the chat slice answers that from its own state. + - *The streams of the Slint page and the Share menu* are the stream slices': + the call bar's Share is logged (`OpenShare`) and shows when the server can + stream (`streams_available`), and the stream cards go between the people and + the call bar. + - *The person's volume writes `client_playback` at every step of a drag* (the + Slint card does too: `member_volume` stores each change). A settings page + that shows the volumes, or a profile that shows the writes, may want the + write on release (`SliderEvent::Release`) and the engine's command at every + step. The volume dialog the tree's click on a person asks for (`OpenClient`) + is still logged: the dialogs slice's. + - *The hotkey's key is read at start.* `AppState::set_global_ptt` is the entry + for the settings page that changes it, and the `ui` value is not reloaded on + `SettingChanged` (above). + - *A test of a pane that follows the window's height resizes the window first*: + GPUI's test platform has a window of 1024 by 768, which is under the 800 + pixels of the voice page's smaller stage (`voice_tests.rs`, `tall`). + - *Two X11 test binaries need an Xvfb with no window manager* (`voelin-media`'s + `x11_capture` and `voelin-platform`'s `x11`: CI has "xvfb only"): on + `spikes/gpui/headless.sh`'s display, with openbox, they fail (the first reads + the wrong pixels of its test window, the second hears no release of the key), + and they pass on the same display with `headless.sh -n`. +- **Three risks of the shell the gate found by reading, left to the slices that meet them** (none reproduced here, none is a defect of a path the shell's - tests exercise): + tests exercise; the fourth, Hold to talk staying on if voice drops while the + button is held, was settled by the voice slice, [above](#the-voice-page-and-the-call-bar)): - *The server on screen is not remembered across restarts.* `AppState::new` takes the first saved server (`bookmarks.first()`), whichever the user had on screen; the Slint app does the same and keeps only the last voice channel @@ -2029,12 +2359,6 @@ the slices that meet it; none of it is a defect of what exists today. without asking*, and what was typed in it is gone (`MainView::select_server` and `delete_server` drop `form`). The dialogs slice (9) turns the form into a dialog; it keeps the draft or asks. - - *Hold to talk stays on if voice drops while the button is held.* The voice - card, with the button, goes when voice leaves `Connected`, so the release - (`on_mouse_up`, `on_mouse_up_out`) has no element to land on: `Sidebar` - keeps `holding` and the session keeps `transmitting` until the next press. - Releasing on the window, or clearing the flag when voice drops, belongs - with the voice page (slice 3). - *A tiling compositor's tile is stored as the window size* (and, on X11 under a tiling window manager, as its position): `ui.window` takes what the window reports without asking whether it is tiled or floating, so the next diff --git a/docs/ui/gpui-voice-card-dark.png b/docs/ui/gpui-voice-card-dark.png new file mode 100644 index 0000000..23c869c Binary files /dev/null and b/docs/ui/gpui-voice-card-dark.png differ diff --git a/docs/ui/gpui-voice-compact-dark.png b/docs/ui/gpui-voice-compact-dark.png new file mode 100644 index 0000000..a532b89 Binary files /dev/null and b/docs/ui/gpui-voice-compact-dark.png differ diff --git a/docs/ui/gpui-voice-compact-light.png b/docs/ui/gpui-voice-compact-light.png new file mode 100644 index 0000000..dc98a3e Binary files /dev/null and b/docs/ui/gpui-voice-compact-light.png differ diff --git a/docs/ui/gpui-voice-dark.png b/docs/ui/gpui-voice-dark.png new file mode 100644 index 0000000..171ed9d Binary files /dev/null and b/docs/ui/gpui-voice-dark.png differ diff --git a/docs/ui/gpui-voice-light.png b/docs/ui/gpui-voice-light.png new file mode 100644 index 0000000..8cb289b Binary files /dev/null and b/docs/ui/gpui-voice-light.png differ diff --git a/docs/ui/gpui-voice-live-dark.png b/docs/ui/gpui-voice-live-dark.png new file mode 100644 index 0000000..bbb48d9 Binary files /dev/null and b/docs/ui/gpui-voice-live-dark.png differ