diff --git a/CHANGELOG.md b/CHANGELOG.md index b7139bc..3400fe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,8 +45,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows same, and what is folded and selected is kept for each server (setting `ui.tree`). The panel on the right lists everyone on the server in sections, with a search; a click on a person opens their card. A person who starts or - stops talking redraws the members panel and nothing else of the window (the - tree does not mark who talks), and the pictures the engine writes again show + stops talking is marked in the tree (the ring on their avatar and the bars on + their row, as in the Slint app) and the members panel, which are redrawn for + it and nothing else of the window, and the pictures the engine writes again show 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"). diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index ef741b6..415c690 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -535,6 +535,13 @@ impl AppState { let mut transition = Cx::new(&host); let result = f(&mut self.vm, &mut transition, &backing); let update = transition.update; + // Whichever server the transition left on screen (a removal shows the + // first, a save the saved one, a connect the one it connects) has its + // remembered folds before the tree is built from it, and before the + // next fold writes them over. + if let Some(id) = self.vm.current { + self.restore_tree(id); + } let refresh = self.perform(update, cx); self.signals.raise(&refresh, cx); result @@ -559,6 +566,12 @@ impl AppState { std::mem::take(&mut *self.sent.borrow_mut()) } + /// The folder the sample pictures were written to, while there is one. + #[cfg(test)] + pub(crate) fn demo_dir(&self) -> Option<&PathBuf> { + self.demo_dir.as_ref() + } + /// A command for the session on screen. fn command(&self, f: impl FnOnce(u64) -> Command) { if let Some(id) = self.vm.current { @@ -788,7 +801,6 @@ impl AppState { /// Show a server, and observe it. pub fn select_server(&mut self, id: i64, cx: &mut Context) { - self.restore_tree(id); self.transition_with(cx, |state, cx, backing| { sequence::select_server(state, cx, backing, id) }); @@ -936,7 +948,10 @@ impl AppState { self.transition(cx, |state, cx| logic::open_member(state, cx, client)); } - /// Put the folds a server's tree remembered into its session, once. + /// Put the folds a server's tree remembered into its session, once: every + /// transition that can change the server on screen + /// ([`AppState::transition_with`]) and the start do it for the one that is + /// shown. fn restore_tree(&mut self, id: i64) { if self.switches.demo_ui || !self.tree_restored.insert(id) { return; @@ -1124,6 +1139,7 @@ mod tests { use voelin_core::{Backends, Command, Event, ObserveState, SessionState, VoiceState}; use voelin_store::MemorySecrets; use voelin_ui_vm::dev::logic as sample; + use voelin_ui_vm::settings::TreeState; use super::*; use crate::backend::testing::TempDir; @@ -1487,6 +1503,68 @@ mod tests { }); } + /// Two saved servers, the second with a fold remembered in `ui.tree`. + fn two_servers_the_second_with_a_fold() -> (Backend, [i64; 2]) { + let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]); + let ids: Vec = backend.store.bookmarks().unwrap().iter().map(|b| b.id).collect(); + let fold = TreeState { collapsed: vec![7], selected: None }; + backend.prefs.set(&UI_TREE, TreeStates::from([(ids[1].to_string(), fold)])).unwrap(); + (backend, [ids[0], ids[1]]) + } + + /// What `ui.tree` holds of a server. + fn remembered(app: &Entity, id: i64, cx: &mut TestAppContext) -> Option { + app.read_with(cx, |app, _| app.backend().prefs.get(&UI_TREE).remove(&id.to_string())) + } + + /// The server that comes on screen when the one shown is removed has the + /// folds `ui.tree` remembers for it, and the next fold adds to them where + /// it used to write over them (the session had none, so the stored ones + /// were replaced by the one just made). + #[gpui::test] + fn the_server_shown_after_a_removal_has_its_remembered_folds(cx: &mut TestAppContext) { + let (backend, [first, second]) = two_servers_the_second_with_a_fold(); + let (app, _, _) = entity_over(cx, backend, Switches::default()); + app.read_with(cx, |app, _| assert_eq!(app.vm.current, Some(first))); + + app.update(cx, |app, cx| app.delete_bookmark(first, cx)); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.current, Some(second)); + assert_eq!(app.vm.sessions[&second].collapsed, HashSet::from([7])); + }); + + app.update(cx, |app, cx| app.toggle_collapse(3, cx)); + assert_eq!( + remembered(&app, second, cx), + Some(TreeState { collapsed: vec![3, 7], selected: None }), + "the fold made now is added to the one remembered" + ); + } + + /// The same for a server a save brings on screen: editing another server + /// shows it. + #[gpui::test] + fn a_server_a_save_shows_has_its_remembered_folds(cx: &mut TestAppContext) { + let (backend, [first, second]) = two_servers_the_second_with_a_fold(); + let (app, _, _) = entity_over(cx, backend, Switches::default()); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.current, Some(first)); + assert!(!app.vm.sessions.contains_key(&second), "not shown yet, not put back yet"); + }); + + let form = app.read_with(cx, |app, _| app.bookmark_form(second)); + app.update(cx, |app, cx| app.save_bookmark(&form, cx)); + app.read_with(cx, |app, _| { + assert_eq!(app.vm.current, Some(second)); + assert_eq!(app.vm.sessions[&second].collapsed, HashSet::from([7])); + }); + app.update(cx, |app, cx| app.toggle_collapse(3, cx)); + assert_eq!( + remembered(&app, second, cx), + Some(TreeState { collapsed: vec![3, 7], selected: None }) + ); + } + #[gpui::test] fn a_removed_server_goes_from_the_rail_and_the_store_and_the_first_is_shown( cx: &mut TestAppContext, diff --git a/crates/voelin-gpui/src/lib.rs b/crates/voelin-gpui/src/lib.rs index 3fe8a43..438db8d 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -217,6 +217,7 @@ pub fn run() -> Result<()> { let closed_sessions = closed_sessions.clone(); move |cx| { gpui_kit::init(cx); + shell::bind_keys(cx); fonts::load(cx); // The mode and the text size are the settings', or a development // switch's. diff --git a/crates/voelin-gpui/src/shell/channels.rs b/crates/voelin-gpui/src/shell/channels.rs index 417d4c3..d2a0811 100644 --- a/crates/voelin-gpui/src/shell/channels.rs +++ b/crates/voelin-gpui/src/shell/channels.rs @@ -19,8 +19,9 @@ use gpui_kit::component::menu::ContextMenuExt as _; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ AnyElement, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ListAlignment, - ListState, ObjectFit, ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, - StyledImage as _, Subscription, Window, div, list, px, + ListState, ObjectFit, ParentElement as _, Render, SharedString, + StatefulInteractiveElement as _, Styled as _, StyledImage as _, Subscription, Window, div, + list, px, }; use voelin_ui_vm::bridge::TreeItem; use voelin_ui_vm::tree::ChannelId; @@ -28,8 +29,8 @@ use voelin_ui_vm::tree::ChannelId; use super::actions::{ EditChannel, JoinChannel, MoveClient, OpenClient, OpenMember, SelectChannel, ToggleChannel, }; -use super::tree_model::{Emptiness, TreeEvent, TreeModel}; -use super::widgets::{Avatar, banner_scrim, icon, live_badge, small_picture}; +use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check}; +use super::widgets::{Avatar, banner_scrim, icon, live_badge, small_picture, speaking_bars}; use crate::meter::Counters; use crate::pictures::{PictureKey, picture}; use crate::theme::{VoelinTheme, hsla}; @@ -37,6 +38,13 @@ use crate::theme::{VoelinTheme, hsla}; /// How far each level of the tree is indented. const INDENT: f32 = 14.0; +/// How opaque the hover and selection tints of a row with a banner are over +/// the banner and its veil: the hover is `channels.slint`'s (`Theme.surface-3. +/// transparentize(0.5)`), the selection, which Slint has no state for, is a +/// stronger one of the same colour. +const BANNER_HOVER: f32 = 0.5; +const BANNER_SELECTED: f32 = 0.75; + /// The channel tree. pub struct ChannelTree { rows: Arc>, @@ -58,10 +66,7 @@ impl ChannelTree { }; let subscription = cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| { match event { - TreeEvent::Rows(changes) => { - let new = model.read(cx).rows().clone(); - this.apply(changes, new); - } + TreeEvent::Rows(changes, rows) => this.apply(changes, rows.clone()), TreeEvent::Selection => this.selected = model.read(cx).selected(), // The count of people is the members panel's. TreeEvent::Lists => { @@ -71,7 +76,7 @@ impl ChannelTree { } this.emptiness = emptiness; } - TreeEvent::People(_) | TreeEvent::Card => return, + TreeEvent::People(..) | TreeEvent::Card => return, } cx.notify(); }); @@ -96,11 +101,18 @@ impl ChannelTree { self.selected } - /// Take the new rows in, telling the list which rows came, went or - /// changed their height (a channel row and a person's differ). + /// Why it shows no rows, were it empty. + pub fn emptiness(&self) -> Emptiness { + self.emptiness + } + + /// Take the new rows in (the rows `changes` lead to, carried by the event), + /// telling the list which rows came, went or changed their height (a + /// channel row and a person's differ). fn apply(&mut self, changes: &voelin_ui_vm::list::Changes, new: Arc>) { use voelin_ui_vm::list::Change; + debug_check(self.rows.len(), changes, new.len()); let mut channels: Vec = self.rows.iter().map(|row| row.is_channel).collect(); for change in &changes.0 { match *change { @@ -141,7 +153,10 @@ fn empty_words(emptiness: Emptiness) -> &'static str { match emptiness { Emptiness::NoServer => "No server yet.", Emptiness::Loading => "Loading the channels…", - Emptiness::Connect => "Connect to see the channels.", + // The tree is not searched, so it is never `NoMatch` (the members + // panel's, `TreeModel::people_emptiness`): the model gives it + // `Emptiness::of`, which does not say it. + Emptiness::Connect | Emptiness::NoMatch => "Connect to see the channels.", } } @@ -202,9 +217,11 @@ fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyEleme } else { item.members.to_string() }; + let group = SharedString::from(format!("tree-row-{id}")); let row = div() .id(("tree-channel", id)) .debug_selector(move || format!("tree-channel-{id}")) + .group(group.clone()) .relative() .w_full() .h(px(34.0 * m.font_scale)) @@ -217,8 +234,21 @@ fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyEleme .when(!own && !selected, |row| row.hover(move |style| style.bg(hover))) // Artwork behind the same compact row as its title, from the indent on, // under a veil of the surface colour that keeps the text readable over - // any picture, and under the tint of our own channel. + // any picture, and under the tints of the row: our own channel's, the + // selected one and the one the pointer is over. The artwork covers the + // row's own background (which only the indent shows), so the tints + // are translucent children above the veil, as `channels.slint` does + // for the hover. .when_some(banner, |row, key| { + let tint = || { + div() + .absolute() + .top(px(0.0)) + .bottom(px(0.0)) + .left(px(indent)) + .right(px(0.0)) + .rounded(px(m.radius_md)) + }; row.child( div() .absolute() @@ -251,6 +281,18 @@ fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyEleme .bg(accent_soft.opacity(0.65)), ) }) + .when(!own && selected, |row| { + row.child( + tint() + .debug_selector(move || format!("tree-selected-{id}")) + .bg(selected_fill.opacity(BANNER_SELECTED)), + ) + }) + .when(!own && !selected, |row| { + row.child( + tint().group_hover(group, move |style| style.bg(hover.opacity(BANNER_HOVER))), + ) + }) }) .flex() .flex_row() @@ -337,7 +379,8 @@ fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement { .gap(px(m.space_3)) .child( Avatar::new(("tree-avatar", id), 22.0, &item.initials, item.tint) - .image(item.avatar.clone()), + .image(item.avatar.clone()) + .speaking(item.talking), ) .child( div() @@ -356,6 +399,16 @@ fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement { .filter_map(|badge| small_picture(badge, 14.0)), ), ) + // The Slint bars move; these stand still (nothing here draws the window + // anew with the clock). + .when(item.talking, |row| { + row.child( + div() + .debug_selector(move || format!("tree-speaking-{id}")) + .flex_none() + .child(speaking_bars(theme, 14.0)), + ) + }) .when(item.streaming, |row| row.child(live_badge(theme))) .when(item.local_muted, |row| row.child(mark("volume-x", c.warning))) .when(!item.local_muted && item.local_volume != 100, |row| { diff --git a/crates/voelin-gpui/src/shell/members.rs b/crates/voelin-gpui/src/shell/members.rs index 423e13f..1a07b0f 100644 --- a/crates/voelin-gpui/src/shell/members.rs +++ b/crates/voelin-gpui/src/shell/members.rs @@ -5,9 +5,9 @@ //! //! [`MembersPane`] is a cached pane over a virtual list that follows //! [`TreeModel`] as the tree does ([`TreeEvent::People`]: the row operations -//! the list applies). It is the pane a talker redraws: a person's row has the -//! speaking ring, "Speaking" and the bars, and nothing else of the window is -//! told. [`MemberCardView`] is the card, a card over the window with a scrim +//! 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. @@ -24,7 +24,7 @@ use voelin_ui_vm::bridge::{MemberCard, MemberItem}; use voelin_ui_vm::list::Changes; use super::actions::{OpenMember, SearchMembers}; -use super::tree_model::{Emptiness, TreeEvent, TreeModel}; +use super::tree_model::{Emptiness, TreeEvent, TreeModel, debug_check}; use super::widgets::{ Avatar, IconButton, Presence, chip, icon, live_badge, small_picture, speaking_bars, }; @@ -61,7 +61,12 @@ impl MembersPane { ) -> Self { let (rows, total, emptiness, open) = { let model = model.read(cx); - (model.people().clone(), model.total(), model.emptiness(), model.card().map(|c| c.id)) + ( + model.people().clone(), + model.total(), + model.people_emptiness(), + model.card().map(|c| c.id), + ) }; let search = cx.new(|cx| { InputState::new(window, cx).placeholder(SharedString::from("Search members…")) @@ -69,20 +74,17 @@ impl MembersPane { let subscriptions = vec![ cx.subscribe(model, |this: &mut Self, model, event: &TreeEvent, cx| { match event { - TreeEvent::People(changes) => { - let new = model.read(cx).people().clone(); - this.apply(changes, new); - } + TreeEvent::People(changes, rows) => this.apply(changes, rows.clone()), TreeEvent::Lists => { let model = model.read(cx); - let now = (model.total(), model.emptiness()); + let now = (model.total(), model.people_emptiness()); if now == (this.total, this.emptiness) { return; } (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::Selection => return, } cx.notify(); }), @@ -117,16 +119,23 @@ impl MembersPane { self.open } + /// Why it shows no one, were it empty. + pub fn emptiness(&self) -> Emptiness { + self.emptiness + } + /// Whether the search box is shown. pub fn searching(&self) -> bool { self.searching } - /// Take the new rows in, telling the list which rows came, went or changed - /// their height (the first row of a section has the heading above it). + /// Take the new rows in (the rows `changes` lead to, carried by the event), + /// telling the list which rows came, went or changed their height (the + /// first row of a section has the heading above it). fn apply(&mut self, changes: &Changes, new: Arc>) { use voelin_ui_vm::list::Change; + debug_check(self.rows.len(), changes, new.len()); let mut headed: Vec = self.rows.iter().map(|row| row.first_in_group).collect(); for change in &changes.0 { match *change { @@ -182,6 +191,7 @@ impl MembersPane { fn empty_words(emptiness: Emptiness) -> &'static str { match emptiness { Emptiness::Loading => "Loading who is here…", + Emptiness::NoMatch => "Nobody matches.", Emptiness::NoServer | Emptiness::Connect => "Connect to see who is here.", } } @@ -624,3 +634,17 @@ impl Render for MemberCardView { .into_any_element() } } + +#[cfg(test)] +mod tests { + use super::*; + + /// What an empty panel says for each reason it can be empty. + #[test] + fn an_empty_panel_says_why() { + assert_eq!(empty_words(Emptiness::NoServer), "Connect to see who is here."); + assert_eq!(empty_words(Emptiness::Connect), "Connect to see who is here."); + assert_eq!(empty_words(Emptiness::Loading), "Loading who is here…"); + assert_eq!(empty_words(Emptiness::NoMatch), "Nobody matches."); + } +} diff --git a/crates/voelin-gpui/src/shell/mod.rs b/crates/voelin-gpui/src/shell/mod.rs index 1fb78c7..56778ef 100644 --- a/crates/voelin-gpui/src/shell/mod.rs +++ b/crates/voelin-gpui/src/shell/mod.rs @@ -26,6 +26,12 @@ pub use form::ServerForm; pub use main_panel::{MainPanel, MainState}; pub use members::{MemberCardView, MembersPane}; pub use password::ChannelPassword; + +/// Bind the shell's keys (Escape in the password prompt): once, after the +/// widget library's own are (`gpui_kit::init`). +pub fn bind_keys(cx: &mut gpui_kit::App) { + password::bind_keys(cx); +} pub use rail::{RailView, ServerRail}; pub use sidebar::{Sidebar, SidebarView}; pub use toast::{TOAST_TIME, Toast}; diff --git a/crates/voelin-gpui/src/shell/password.rs b/crates/voelin-gpui/src/shell/password.rs index 7d44081..9642b13 100644 --- a/crates/voelin-gpui/src/shell/password.rs +++ b/crates/voelin-gpui/src/shell/password.rs @@ -5,15 +5,24 @@ //! card over the window with a scrim; until the dialogs slice makes every //! dialog one, it is this view's own. As in the Slint dialog, Join (and Enter) //! do nothing while the field is empty, and Escape closes the prompt. +//! +//! Escape is a key binding of the prompt's key context ([`bind_keys`]) that +//! dispatches [`CancelChannelPassword`], and the prompt is a focus target of +//! its own (its scrim, which the card is on): a click on the card, off the +//! field, takes the focus from the field, and a click outside any focus target +//! would hand it to the window's root, which the prompt is not under, so +//! without a target the context would not be on the dispatch path and Escape +//! would do nothing. With the field focused its own Escape (which has nothing +//! to undo in a password) passes the key on, and the binding closes the prompt. use gpui_kit::component::Disableable as _; use gpui_kit::component::button::{Button, ButtonVariants as _}; -use gpui_kit::component::input::{Escape, Input, InputEvent, InputState}; +use gpui_kit::component::input::{Input, InputEvent, InputState}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ - App, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, - ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Window, - div, px, + App, AppContext as _, Context, Entity, FocusHandle, FontWeight, InteractiveElement as _, + IntoElement, KeyBinding, ParentElement as _, Render, SharedString, + StatefulInteractiveElement as _, Styled as _, Window, div, px, }; use voelin_ui_vm::host::PasswordPrompt; @@ -21,11 +30,23 @@ use super::actions::{CancelChannelPassword, SubmitChannelPassword}; use super::widgets::tagged; use crate::theme::{VoelinTheme, hsla}; +/// The key context of the prompt. +const CONTEXT: &str = "ChannelPassword"; + +/// The keys of the prompt: Escape closes it. Bound once, at start, with the +/// widget library's own. +pub fn bind_keys(cx: &mut App) { + cx.bind_keys([KeyBinding::new("escape", CancelChannelPassword, Some(CONTEXT))]); +} + /// The prompt for the password of one channel. pub struct ChannelPassword { channel: String, wrong: bool, input: Entity, + /// What the prompt's scrim holds the focus with, so that Escape reaches the + /// prompt wherever in it the last click was. + focus: FocusHandle, } impl ChannelPassword { @@ -44,7 +65,7 @@ impl ChannelPassword { }) .detach(); input.update(cx, |input, cx| input.focus(window, cx)); - Self { channel: ask.name.clone(), wrong: ask.wrong, input } + Self { channel: ask.name.clone(), wrong: ask.wrong, input, focus: cx.focus_handle() } } /// The channel it asks for. @@ -76,12 +97,8 @@ impl Render for ChannelPassword { div() .id("password-prompt") .debug_selector(|| "password-prompt".into()) - .key_context("ChannelPassword") - // The field has the keys, and its Escape has nothing to undo and - // passes the key on: it closes the prompt. - .on_action(cx.listener(|_, _: &Escape, window, cx| { - window.dispatch_action(Box::new(CancelChannelPassword), cx) - })) + .key_context(CONTEXT) + .track_focus(&self.focus) .absolute() .top(px(0.0)) .left(px(0.0)) @@ -95,6 +112,7 @@ impl Render for ChannelPassword { .child( div() .id("password-card") + .debug_selector(|| "password-card".into()) .w(px(380.0)) .flex() .flex_col() diff --git a/crates/voelin-gpui/src/shell/tree_model.rs b/crates/voelin-gpui/src/shell/tree_model.rs index dd881cb..8fff4fc 100644 --- a/crates/voelin-gpui/src/shell/tree_model.rs +++ b/crates/voelin-gpui/src/shell/tree_model.rs @@ -6,20 +6,21 @@ //! ([`crate::signals`]), builds the rows once for both panes, compares them //! with the rows it had ([`voelin_ui_vm::list::diff`], the row operations the //! Slint front end applies to its `VecModel`) and emits what differs -//! ([`TreeEvent`]): a pane applies the operations to its list state, so a -//! person who joins is a row that is inserted, not a list that starts again -//! at the top. A change that moves none of what a pane shows emits nothing. +//! ([`TreeEvent`], with the rows the operations lead to): a pane applies the +//! operations to its list state, so a person who joins is a row that is +//! inserted, not a list that starts again at the top. A change that moves none +//! of what a pane shows emits nothing. //! -//! **The tree does not mark who is talking.** Its rows are built with -//! `talking` cleared: a talker changes the rows of the members panel (and the -//! sidebar's own card), not the tree's, which therefore is not drawn again -//! with every start and stop of someone's voice. The Slint tree draws speaking -//! bars on the row; docs/ui.md records the difference. +//! **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 +//! of the two panes is drawn again once for it, and no other pane is +//! (docs/ui.md, "What a change costs"). use std::sync::Arc; -use gpui_kit::{Context, Entity, EventEmitter, Subscription}; -use voelin_core::ObserveState; +use gpui_kit::{App, Context, Entity, EventEmitter, Subscription}; +use voelin_core::{ObserveState, VoiceState}; use voelin_ui_vm::bridge::{MemberCard, MemberItem, TreeItem}; use voelin_ui_vm::list::{Changes, diff}; use voelin_ui_vm::servers::logic; @@ -33,59 +34,121 @@ use crate::signals::Area; pub enum Emptiness { /// No server is on screen. NoServer, - /// The server is observed and its presence is on the way. + /// The server is observed or being connected to, and its presence is on + /// the way. Loading, /// Nothing is known of the server until it is connected. Connect, + /// The server has people and the members' search matches none of them (the + /// members panel's only: the tree is not searched). + NoMatch, } impl Emptiness { - /// Why the lists of the server on screen are empty. + /// Why the lists of the server on screen are empty: never + /// [`Emptiness::NoMatch`], which is [`Emptiness::of_people`]'s. pub fn of(vm: &VmState) -> Self { match vm.current { None => Self::NoServer, Some(id) => match vm.sessions.get(&id) { - Some(view) if view.state.observe != ObserveState::Off => Self::Loading, + Some(view) + if view.state.observe != ObserveState::Off + || view.state.voice == VoiceState::Connecting => + { + Self::Loading + } _ => Self::Connect, }, } } + + /// Why the members panel is empty: as [`Emptiness::of`], except that a + /// search that leaves nobody of the `total` on the server (`shown` rows + /// are left) is [`Emptiness::NoMatch`], where "Connect to see who is here" + /// would be false. + pub fn of_people(vm: &VmState, shown: usize, total: i32) -> Self { + if shown == 0 && total > 0 && !vm.member_filter.trim().is_empty() { + Self::NoMatch + } else { + Self::of(vm) + } + } } /// What changed in the model, as the panes need it. +/// +/// The list events carry the rows their operations lead to. A model that +/// refreshed twice before the first event is delivered (an observer that +/// changes the state inside a flush makes it) holds the second rows by the +/// time a pane hears of the first operations, and operations applied to rows +/// they were not made for index past their end. A pane applies them to the +/// rows it has and keeps the rows the event carries, so the events, in the +/// order they are delivered, lead from the rows the pane started with to the +/// model's last. #[derive(Clone, Debug, PartialEq)] pub enum TreeEvent { - /// The tree's rows: the operations from the old rows to - /// [`TreeModel::rows`]. - Rows(Changes), - /// The members panel's rows: the operations from the old rows to - /// [`TreeModel::people`]. - People(Changes), + /// The tree's rows: the operations from the rows the pane has to the rows + /// carried (the model's [`TreeModel::rows`] when it made them). + Rows(Changes, Arc>), + /// 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 card over a member row opened, changed or closed /// ([`TreeModel::card`]). Card, /// The selected channel ([`TreeModel::selected`]). Selection, /// Why the lists are empty, or how many people there are - /// ([`TreeModel::emptiness`], [`TreeModel::total`]). + /// ([`TreeModel::emptiness`], [`TreeModel::people_emptiness`], + /// [`TreeModel::total`]). Lists, } +/// The areas the model listens to. +const AREAS: [Area; 3] = [Area::Tree, Area::Toolbar, Area::MemberCard]; + +/// How many times each of [`AREAS`] was raised. +fn generations(app: &Entity, cx: &App) -> [u64; 3] { + let signals = app.read(cx).signals(); + AREAS.map(|area| signals.of(area).read(cx).generation()) +} + /// The rows of the tree and of the members panel, the member card and the /// selection of the server on screen. pub struct TreeModel { app: Entity, + /// The generations of its signals it last built the rows at: a batch that + /// raises several of them (a picture that arrives raises three) has them + /// all raised before the first is heard, so the first refresh builds the + /// rows and the others find nothing new. + seen: [u64; 3], + refreshes: u64, rows: Arc>, people: Arc>, total: i32, card: Option, selected: Option, emptiness: Emptiness, + people_emptiness: Emptiness, _subscriptions: Vec, } impl EventEmitter for TreeModel {} +/// Check that `changes` lead from a list of `old` rows to one of `new` rows +/// (debug builds): a pane that applies operations to rows they were not made +/// for finds the counts out of step, where a release build would index past +/// the end or leave its list state out of step with its rows. +pub(super) fn debug_check(old: usize, changes: &Changes, new: usize) { + debug_assert_eq!( + old + changes.inserted(), + new + changes.removed(), + "{changes:?} do not lead from {old} rows to {new}: applied to rows they were not made \ + for? (docs/ui.md, \"For the next slices\": no state change from a signal's observer \ + inside a flush)" + ); +} + /// Everything the model keeps, as the state gives it now. struct Snapshot { rows: Vec, @@ -94,20 +157,19 @@ struct Snapshot { card: Option, selected: Option, emptiness: Emptiness, + people_emptiness: Emptiness, } impl Snapshot { fn of(app: &AppState) -> Self { let vm = &app.vm; let view = vm.current.and_then(|id| vm.sessions.get(&id)); - let (mut rows, people, total) = match logic::tree_view(vm, false) { + 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), }; - for row in &mut rows { - row.talking = false; - } Self { + people_emptiness: Emptiness::of_people(vm, people.len(), total), rows, people, total, @@ -127,20 +189,19 @@ impl TreeModel { let state = app.read(cx); (Snapshot::of(state), state.signals().clone()) }; - let subscriptions = signals.watch( - app, - &[Area::Tree, Area::Toolbar, Area::MemberCard], - cx, - |this: &mut Self, _, cx| this.refresh(cx), - ); + let subscriptions = + signals.watch(app, &AREAS, cx, |this: &mut Self, _, cx| this.refresh(cx)); Self { app: app.clone(), + seen: generations(app, cx), + refreshes: 0, rows: Arc::new(snapshot.rows), people: Arc::new(snapshot.people), total: snapshot.total, card: snapshot.card, selected: snapshot.selected, emptiness: snapshot.emptiness, + people_emptiness: snapshot.people_emptiness, _subscriptions: subscriptions, } } @@ -170,13 +231,32 @@ impl TreeModel { self.selected } - /// Why the lists are empty, were they. + /// Why the tree is empty, were it. pub fn emptiness(&self) -> Emptiness { self.emptiness } - /// Build the rows again, and tell the panes what differs. + /// Why the members panel is empty, were it: the same as + /// [`TreeModel::emptiness`], or that the search matches nobody. + pub fn people_emptiness(&self) -> Emptiness { + self.people_emptiness + } + + /// How many times the rows were built again since the model was made: one + /// for each batch of changes, not one for each signal it raised. + pub fn refreshes(&self) -> u64 { + self.refreshes + } + + /// Build the rows again, and tell the panes what differs. Nothing, when + /// none of the signals was raised since the last time. fn refresh(&mut self, cx: &mut Context) { + let now = generations(&self.app, cx); + if now == self.seen { + return; + } + self.seen = now; + self.refreshes += 1; let new = Snapshot::of(self.app.read(cx)); let rows = diff(&self.rows, &new.rows); let people = diff(&self.people, &new.people); @@ -186,17 +266,19 @@ impl TreeModel { if !people.is_empty() { self.people = Arc::new(new.people); } - let lists = (self.emptiness, self.total) != (new.emptiness, new.total); - (self.emptiness, self.total) = (new.emptiness, new.total); + let lists = (self.emptiness, self.people_emptiness, self.total) + != (new.emptiness, new.people_emptiness, new.total); + (self.emptiness, self.people_emptiness, self.total) = + (new.emptiness, new.people_emptiness, new.total); let card = self.card != new.card; self.card = new.card; let selection = self.selected != new.selected; self.selected = new.selected; if !rows.is_empty() { - cx.emit(TreeEvent::Rows(rows)); + cx.emit(TreeEvent::Rows(rows, self.rows.clone())); } if !people.is_empty() { - cx.emit(TreeEvent::People(people)); + cx.emit(TreeEvent::People(people, self.people.clone())); } if lists { cx.emit(TreeEvent::Lists); diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index fe2b4b3..0835767 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -538,6 +538,7 @@ mod tests { use crate::pictures::PictureKey; use crate::shell::actions::{EditChannel, MoveClient, OpenClient}; use crate::shell::{RailView, TreeEvent}; + use crate::signals::Area; use crate::theme::Choice; use crate::window_bounds; @@ -585,6 +586,7 @@ mod tests { ) -> (Shell, &mut VisualTestContext) { cx.update(|cx| { gpui_kit::init(cx); + crate::shell::bind_keys(cx); VoelinTheme::init(cx, Choice::Dark, WindowAppearance::Dark, 1.0); }); let (events, rx) = mpsc::unbounded_channel(); @@ -939,12 +941,12 @@ mod tests { (log, subscription) } - /// The row operations the model told the tree. - fn rows_told(log: &Rc>>) -> Vec { + /// The row operations the model told the tree, with the rows they lead to. + fn rows_told(log: &Rc>>) -> Vec<(Changes, Arc>)> { log.borrow() .iter() .filter_map(|event| match event { - TreeEvent::Rows(changes) => Some(changes.clone()), + TreeEvent::Rows(changes, rows) => Some((changes.clone(), rows.clone())), _ => None, }) .collect() @@ -974,7 +976,8 @@ mod tests { /// The sample server's channels and people are the rows of the tree, in /// the Slint tree's order and nesting, with its spacers, the locked - /// channel and the counts, each on screen; none of them marks a talker. + /// channel and the counts, each on screen; Kairo, who talks as the sample + /// starts, is marked. #[gpui::test] fn a_server_with_channels_and_people_fills_the_tree_with_its_rows(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); @@ -1011,7 +1014,8 @@ mod tests { assert_eq!((channel("Gaming").spacer, channel("Staff").spacer), (2, 3), "centred, right"); assert_eq!(rows.iter().find(|r| r.spacer == 4).map(|r| r.is_channel), Some(true)); assert!(channel("Officers").locked && !channel("Lobby").locked); - assert!(rows.iter().all(|r| !r.talking), "Kairo talks; the tree does not say so"); + let talking: Vec<&str> = rows.iter().filter(|r| r.talking).map(|r| &*r.name).collect(); + assert_eq!(talking, ["Kairo"], "Kairo talks, and the tree says so"); assert!(at(cx, "tree-empty").is_none()); for row in rows.iter() { let selector = if row.is_channel { @@ -1211,9 +1215,43 @@ mod tests { assert!(at(cx, "password-prompt").is_none(), "closed"); } + /// Escape closes the password prompt wherever the focus is in it, not only + /// while its field has it: a click on the card, off the field, moves the + /// focus away from the field (to the card), and the key must still reach + /// the prompt. + #[gpui::test] + fn escape_closes_the_password_prompt_after_a_click_on_its_card(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + shell.app.read_with(cx, |app, _| app.take_sent()); + let prompt_open = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, _| view.password_prompt().is_some()) + }; + for aim in ["the card's corner", "the card's disabled Join"] { + double_click(cx, "tree-channel-7"); + assert!(prompt_open(&shell, cx), "{aim}: asked for the password"); + if aim == "the card's corner" { + let card = at(cx, "password-card").expect("the card is on screen"); + let corner = card.origin + point(px(6.0), px(6.0)); + cx.simulate_click(corner, Default::default()); + frame(cx); + } else { + click(cx, "password-join"); + } + assert!(prompt_open(&shell, cx), "{aim}: a click inside the card closes nothing"); + cx.simulate_keystrokes("escape"); + frame(cx); + assert!(!prompt_open(&shell, cx), "{aim}: Escape closes the prompt"); + assert!(at(cx, "password-prompt").is_none()); + assert!(shell.app.read_with(cx, |app, _| app.vm.join_target.is_none())); + } + assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), "nothing joined"); + } + /// The channels with a banner picture are drawn with the veil of the /// surface colour over it (so that their text reads over any picture); the - /// others have none. + /// others have none. The picture covers the row's own background, so a + /// selected banner row is tinted by a child above the veil. #[gpui::test] fn a_banner_is_drawn_under_a_veil(cx: &mut TestAppContext) { let switches = Switches { demo_ui: true, demo_pictures: true, ..Switches::default() }; @@ -1234,6 +1272,31 @@ mod tests { let plain = plain.expect("a channel without a banner"); assert!(at(cx, &format!("tree-channel-{}", plain.id)).is_some(), "it is on screen"); assert!(at(cx, &format!("tree-scrim-{}", plain.id)).is_none(), "and has no veil"); + + // A click selects a row; a banner row shows it by a tint over its picture. + let tinted = + |cx: &mut VisualTestContext, id: i32| at(cx, &format!("tree-selected-{id}")).is_some(); + // (Our own channel has the accent tint of its own instead.) + let others: Vec = rows + .iter() + .filter(|r| r.is_channel && banners.contains(&r.id) && !r.own) + .map(|r| r.id) + .collect(); + let [first, second, ..] = others[..] else { panic!("two other banners: {others:?}") }; + assert!(!tinted(cx, first) && !tinted(cx, second), "nothing is selected yet"); + click(cx, &format!("tree-channel-{first}")); + assert!(tinted(cx, first), "the selected banner row is tinted"); + assert!(!tinted(cx, second)); + click(cx, &format!("tree-channel-{second}")); + assert!(tinted(cx, second) && !tinted(cx, first), "and the tint follows the selection"); + + // The sample pictures are files of a folder of the state's own in the + // temporary directory; the window's close, as the app ends, removes it + // (the entity of a test is not released when the test ends). + let folder = shell.app.read_with(cx, |app, _| app.demo_dir().cloned()); + assert!(folder.as_ref().is_some_and(|folder| folder.is_dir()), "{folder:?}"); + shell.app.update(cx, |app, cx| app.shutdown(cx)); + assert!(!folder.is_some_and(|folder| folder.exists()), "the close removes it"); } /// A person who changes channel makes the rows between the two places @@ -1253,8 +1316,11 @@ mod tests { .unwrap(); frame(cx); let dex = before.iter().position(|r| !r.is_channel && r.id == 5).unwrap(); - assert_eq!(rows_told(&log), [Changes(vec![Change::Update(dex)])]); + let told = rows_told(&log); + let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) }; + assert_eq!(*changes, Changes(vec![Change::Update(dex)])); assert!(before[dex].muted && !tree_rows(&shell, cx)[dex].muted); + assert_eq!(*carried, tree_rows(&shell, cx), "the event carries the rows it leads to"); // Zeph (7) leaves Raid Night for Gaming: its parent's count, his row // and the row of the sub-channel change; the rest stay. @@ -1271,7 +1337,8 @@ mod tests { ["C0 Gaming", "P1 Talon", "P1 Zeph", "C1 Raid Night", "C0 Music"], ); let told = rows_told(&log); - let [changes] = &told[..] else { panic!("{:?}", log.borrow()) }; + let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) }; + assert_eq!(*carried, after); let gaming = 8; assert_eq!( changes.0, @@ -1281,26 +1348,93 @@ mod tests { assert_eq!((after[gaming].members, after[gaming + 3].members), (2, 0)); } - /// Who talks changes the members panel and the sidebar's own card, not the - /// tree: its pane is not drawn for a talker, and its rows stay as they - /// were. + /// The gate's probe. A state change made by an observer while a flush is + /// running must not make a pane apply the first row operations to the + /// second rows: the events carry the rows their operations lead to. A + /// Presence event raises the toolbar and the tree; the model makes its + /// first rows on the toolbar, an observer of the toolbar that was made + /// after the model's puts the observed server on screen (it has no rows + /// yet), and the model makes its second rows, none, on the tree before + /// the panes are told of the first: a shrink under operations made for + /// the rows before it. #[gpui::test] - fn a_talker_does_not_draw_the_tree_again(cx: &mut TestAppContext) { + fn a_state_change_inside_a_flush_does_not_apply_old_operations_to_new_rows( + cx: &mut TestAppContext, + ) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); sample_server(&shell, cx); - let rows = tree_rows(&shell, cx); + assert!(!tree_rows(&shell, cx).is_empty()); + let toolbar = shell.app.read_with(cx, |app, _| app.signals().of(Area::Toolbar).clone()); + let fired = Rc::new(Cell::new(false)); + let _observer = cx.update(|_, cx| { + let (app, fired) = (shell.app.clone(), fired.clone()); + cx.observe(&toolbar, move |_, cx| { + if !fired.replace(true) { + app.update(cx, |app, cx| app.select_server(sample::DEMO + 1, cx)); + } + }) + }); + let (log, _subscription) = tree_events(&shell, cx); + let unmute = presence_changed!(p => p.clients.get_mut(&5).unwrap().input_muted = false); + shell.events.send(unmute).unwrap(); + frame(cx); + assert!(fired.get(), "the observer ran inside the flush"); + assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(sample::DEMO + 1)); + + // The model told its panes twice, and each time with the rows its + // operations lead to: the first leaves the server's rows with dex + // unmuted, the second takes them all away. + let told = rows_told(&log); + let [first, second] = &told[..] else { panic!("{:?}", log.borrow()) }; + assert_eq!(first.1.len(), 18, "the first rows are the sample server's"); + assert!(!first.1.iter().any(|r| !r.is_channel && r.id == 5 && r.muted)); + assert_eq!((first.0.updated(), first.0.removed(), first.0.inserted()), (1, 0, 0)); + assert!(second.1.is_empty() && second.0.removed() == 18, "{:?}", second.0); + + // The panes end with the model's rows, in the order they were told. + assert!(tree_rows(&shell, cx).is_empty()); + let (tree, people) = shell.view.read_with(cx, |view, cx| { + (view.channel_tree().read(cx).rows().len(), view.members_pane().read(cx).rows().len()) + }); + assert_eq!((tree, people), (0, 0)); + assert!(at(cx, "tree-empty").is_some(), "the tree says it is loading"); + } + + /// Who talks is marked on the tree's row, as the Slint tree marks it (the + /// ring on the avatar, the bars on the row): each start and stop changes + /// exactly that person's row, the tree pane is drawn once for it, and the + /// row says so on screen. + #[gpui::test] + fn a_talker_changes_one_row_and_draws_the_tree_once(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let kairo = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| { + let tree = view.channel_tree().read(cx); + tree.rows().iter().position(|r| !r.is_channel && r.id == 3).unwrap() + }) + }; + let place = kairo(&shell, cx); + assert!(tree_rows(&shell, cx)[place].talking, "Kairo talks as the sample starts"); let (log, _subscription) = tree_events(&shell, cx); let drawn = |shell: &Shell| shell.counters.panes.tree.get(); - let before = drawn(&shell); for talking in [false, true, false, true] { + let before = drawn(&shell); + log.borrow_mut().clear(); let event = Event::Talking { session: sample::DEMO as u64, client: 3, talking }; shell.events.send(event).unwrap(); frame(cx); + let told = rows_told(&log); + let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) }; + assert_eq!(*changes, Changes(vec![Change::Update(place)]), "only Kairo's row"); + assert_eq!(carried[place].talking, talking); + assert_eq!(drawn(&shell), before + 1, "the tree pane was drawn once"); + let pane = shell + .view + .read_with(cx, |view, cx| view.channel_tree().read(cx).rows()[place].talking); + assert_eq!(pane, talking, "the pane has it"); + assert_eq!(at(cx, "tree-speaking-3").is_some(), talking, "and the bars are on screen"); } - assert!(rows_told(&log).is_empty(), "the model told the tree nothing: {:?}", log.borrow()); - assert_eq!(log.borrow().len(), 4, "and the members panel four times"); - assert_eq!(drawn(&shell), before, "the tree pane was not rendered"); - assert_eq!(tree_rows(&shell, cx), rows); assert!( shell.app.read_with(cx, |app, _| app.vm.sessions[&sample::DEMO].talking.contains(&3)) ); @@ -1369,11 +1503,80 @@ mod tests { assert_eq!(shell.app.read_with(cx, |app, _| app.vm.member_filter.clone()), ""); } - /// Someone who starts or stops talking redraws the members panel and no - /// other pane: not the tree, the rail, the top bar nor the main area. The + /// A search that matches nobody on a server that has people says so, where + /// "Connect to see who is here." would be false; the tree is not told (it + /// is not searched), and closing the search shows everyone again. + #[gpui::test] + fn a_search_with_no_match_says_nobody_matches(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let emptiness = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| { + ( + view.members_pane().read(cx).emptiness(), + view.channel_tree().read(cx).emptiness(), + view.tree_model().read(cx).people_emptiness(), + ) + }) + }; + assert_eq!(emptiness(&shell, cx).0, Emptiness::Connect, "full: only said when empty"); + assert!(at(cx, "members-empty").is_none()); + + click(cx, "members-search"); + // The first key typed draws the tree once whatever it is (the field's + // focus: not the search's doing); what follows must not. + cx.simulate_input("z"); + frame(cx); + assert_eq!(members_shape(&shell, cx), ["Streaming — 1: Zeph", "Guest — 1: Blaze"]); + let tree_drawn = shell.counters.panes.tree.get(); + cx.simulate_input("zz"); + frame(cx); + assert!(members_shape(&shell, cx).is_empty(), "nobody is called zzz"); + let (panel, tree, model) = emptiness(&shell, cx); + assert_eq!((panel, model), (Emptiness::NoMatch, Emptiness::NoMatch)); + assert_eq!(tree, Emptiness::Connect, "the tree is not searched and says nothing new"); + assert!(at(cx, "members-empty").is_some(), "the panel says so"); + assert_eq!(shell.counters.panes.tree.get(), tree_drawn, "and the tree was not drawn"); + + // Closing the search shows everyone again, with no word for emptiness. + click(cx, "members-search"); + assert_eq!(members_shape(&shell, cx).len(), 9); + assert!(at(cx, "members-empty").is_none()); + assert_eq!(emptiness(&shell, cx).0, Emptiness::Connect); + } + + /// A server whose voice is connecting has its people and channels on the + /// way: both panes say they are loading, not that one has to connect. + #[gpui::test] + fn a_server_being_connected_says_it_is_loading(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let third = sample::DEMO + 2; + shell.app.update(cx, |app, cx| app.select_server(third, cx)); + frame(cx); + let words = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| { + (view.members_pane().read(cx).emptiness(), view.channel_tree().read(cx).emptiness()) + }) + }; + assert_eq!(words(&shell, cx), (Emptiness::Connect, Emptiness::Connect), "not connected"); + let voice = |voice| Event::State { + session: third as u64, + state: SessionState { voice, ..Default::default() }, + }; + shell.events.send(voice(VoiceState::Connecting)).unwrap(); + frame(cx); + assert_eq!(words(&shell, cx), (Emptiness::Loading, Emptiness::Loading), "connecting"); + shell.events.send(voice(VoiceState::Disconnected)).unwrap(); + frame(cx); + assert_eq!(words(&shell, cx), (Emptiness::Connect, Emptiness::Connect), "gave up"); + } + + /// Someone who starts or stops talking redraws the members panel and the + /// tree and no other pane: not the rail, the top bar nor the main area. The /// row says so while they talk. #[gpui::test] - fn a_talker_redraws_the_members_panel_and_no_other_pane(cx: &mut TestAppContext) { + fn a_talker_redraws_the_tree_and_the_members_panel_and_no_other_pane(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); sample_server(&shell, cx); let panes = &shell.counters.panes; @@ -1396,10 +1599,11 @@ mod tests { } let after = seen(); assert!(after[4] > before[4], "the members panel was drawn: {before:?} -> {after:?}"); + assert!(after[2] > before[2], "and the tree: {before:?} -> {after:?}"); assert_eq!( - [after[0], after[1], after[2], after[3]], - [before[0], before[1], before[2], before[3]], - "the rail, the top bar, the tree and the main area were not" + [after[0], after[1], after[3]], + [before[0], before[1], before[3]], + "the rail, the top bar and the main area were not" ); } @@ -1506,6 +1710,41 @@ mod tests { assert!(cx.update(|_, cx| crate::pictures::is_cached(&second, cx)), "the new one is drawn"); } + /// A change that raises three of the model's signals (a picture that + /// arrives raises the toolbar, the tree and the member card) builds the + /// rows once: the signals are raised together, and the model's first + /// refresh sees all of them. + #[gpui::test] + fn a_picture_that_arrives_builds_the_rows_once(cx: &mut TestAppContext) { + let dir = TempDir::new("refresh-once"); + std::fs::create_dir_all(&dir.0).unwrap(); + let path = dir.0.join("avatar-demo-3"); + std::fs::write(&path, sample::demo_picture(40, 40, 1)).unwrap(); + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let refreshes = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| view.tree_model().read(cx).refreshes()) + }; + let before = refreshes(&shell, cx); + let arrives = Event::AvatarReady { + session: sample::DEMO as u64, + client_uid: "demo-3".into(), + path, + hash: String::new(), + }; + shell.events.send(arrives).unwrap(); + frame(cx); + assert_eq!(refreshes(&shell, cx), before + 1, "three signals, one build"); + + // A batch of two events that raise the same signals is one build as + // well. + let (a, b) = (presence_changed!(p => p.server.name = "A".into()), connected(sample::DEMO)); + shell.events.send(a).unwrap(); + shell.events.send(b).unwrap(); + frame(cx); + assert_eq!(refreshes(&shell, cx), before + 2, "a batch of events: one build"); + } + /// What the context menus offer that has no slice yet (the channel editor, /// a person's volume dialog, moving a client) is logged and sends nothing. #[gpui::test] diff --git a/docs/ui.md b/docs/ui.md index f9523cb..dfd68cf 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -1053,8 +1053,8 @@ crates/voelin-gpui/ not told), the channel tree and the members panel on the sample server's events (the rows, folds kept in the settings and found by the next run, a double-click that joins, the password prompt, a move and a mute as their - exact row operations, a talker that redraws the members panel and no other - pane, the member card, an avatar written again), a connect through a real + 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 directory of its own, the theme (it reaches gpui-component, follows the window's @@ -1237,7 +1237,7 @@ front end](#shared-with-the-slint-front-end)): | `edit_bookmark` | `EditServer { id }` | opens the form with `servers::form` | | `save_bookmark` | `SaveServer` | `logic::bookmark_from_form`, the store, the secrets; shows the server | | `save_and_connect` | `SaveAndConnect` | saves, then connects into the form's channel or the default one (`servers::connect_to`) | -| `delete_bookmark` | `DeleteServer { id }` | `CloseSession`, the secrets and the store, `logic::forget_server` | +| `delete_bookmark` | `DeleteServer { id }` | `CloseSession`, the secrets and the store, `logic::forget_server`; the server that comes on screen has its remembered folds put back (as has any server a transition puts on screen: a save, a connect) | | `invite` | `Invite` | `logic::invite_link`, the link on the clipboard, the status line's note | The others of that file: `join_channel`, `join_with_password`, `toggle_collapse`, @@ -1425,6 +1425,15 @@ through Vulkan on Xvfb `:201` of 3840 by 2160 with openbox, 1440 by 960): the banner rows, Raid Night and Music, are under the veil, and the avatars of the tree show one letter. +![the tree with a banner row selected and one under the pointer, dark](ui/gpui-tree-banner-selected-dark.png) + +`gpui-tree-banner-selected-dark.png` is the same window with Raid Night selected +(a click) and the pointer on Music: a banner row shows its selection and its +hover as a tint over the picture, as the speaking ring and bars show on Kairo's +row (release build of the commit that tinted them, lavapipe through Vulkan on +Xvfb `:233` of 3840 by 2160 with openbox, 1440 by 960, two `xdotool` moves and +`xwd`, the state under the checkout's `.scratch/`). + What is on screen: - **The channel tree** (`channels.rs`, in the sidebar between the server card @@ -1437,9 +1446,14 @@ What is on screen: the banner picture behind it and our channel highlighted. The banner has the veil of `components/banner-picture.slint` over it (`widgets::banner_scrim`: the surface colour, 74 % opaque on the left to 66 % on the right, under the - tint of our channel), so the name keeps more than 4.5 to 1 against any + tints of the row), so the name keeps more than 4.5 to 1 against any picture in both themes (a test states it for the weakest end over a black - and a white picture). A person's row has their avatar (the first letter + and a white picture). The row's own background (the selected one's and the + hover's) is under the picture, which covers it from the indent on, so a row + with a banner shows its states as translucent tints over the veil: our + channel's accent tint, the selected row's (surface 3 at 75 %) and the hover's + (surface 3 at 50 %, as `channels.slint` tints it). A person's row has their + avatar (the first letter only, at half the size, under 28 pixels as `avatar.slint` does), name (ours in the accent colour, someone away muted), badges, a LIVE tag while they stream, the marks of local mute (or volume) and of their @@ -1467,13 +1481,14 @@ What is on screen: 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 Slint dialog, Join is off and Enter does nothing while the field is empty - (the prompt stays), and Escape closes it without joining. + (the prompt stays), and Escape closes it without joining, wherever in the + prompt the last click was (below). #### Per-area signals and cached panes The foundation's and the shell's reviews left the design for this slice: a -change of the channel tree must not draw the rail, and a talker must not draw -the tree. Two parts of it came from reading gpui-pre 0.3.10 and were checked by +change of the channel tree must not draw the rail, and a talker draws the tree +and the members panel and nothing else (the gate's parity ruling, below). Two parts of it came from reading gpui-pre 0.3.10 and were checked by the tests: - **`Update.refresh` is raised as signals** (`signals.rs`). The root state @@ -1502,15 +1517,24 @@ the tests: entity builds the rows for both panes on the tree, toolbar and member-card signals, compares them with the rows it had (`voelin_ui_vm::list::diff`, the operations the Slint front end applies to its `VecModel`) and emits what - differs. A pane applies the operations to its list state (`gpui::ListState`: - a person who joins is a row inserted and the scroll stays where it was), and a - change that moves none of the rows of a pane emits nothing to it. -- **The tree carries no `talking`.** Its rows are built with the flag cleared, - so someone who starts or stops talking changes the members panel (and the - sidebar's own card when it is us) and not the tree: its pane is not rendered - (the `a_talker_does_not_draw_the_tree_again` test counts it). The Slint tree - draws speaking bars on the row, which would redraw the tree with every start - and stop of someone's voice; this front end leaves them to the members panel. + differs, with the rows the operations lead to (`TreeEvent::Rows(Changes, + Arc>)`, `People` the same). A pane applies the operations to its + list state (`gpui::ListState`: a person who joins is a row inserted and the + scroll stays where it was) and to the rows it has, and keeps the rows the + event carries, not the model's at the moment it hears of them; a change that + moves none of the rows of a pane emits nothing to it. +- **The tree marks who talks, and is drawn once for each start and stop.** Its + rows keep `talking`, so the avatar has the green ring and the row the three + speaking bars, as `channels.slint` draws them (the bars stand still: nothing + here draws the window with the clock). Someone who starts or stops talking + changes one row of the tree and one of the members panel, and each of those + two panes is rendered once for it, with the sidebar, which every frame + renders; no other pane is (the `a_talker_changes_one_row_and_draws_the_tree_once` + and `a_talker_redraws_the_tree_and_the_members_panel_and_no_other_pane` tests + count it). The first version of the slice cleared the flag to keep the tree out + of it; the gate ruled for parity with the Slint tree, and the cost was + measured: 9.97 renders of the tree a second for 9.97 starts and stops a second + ([what a change costs](#what-a-change-costs)). #### What a change costs @@ -1532,20 +1556,18 @@ window's frames, and each pane's passes): A window nobody touches is not drawn, with the tree and the panel on screen as before (the shell alone was 192.7 MiB; the pictures and the two panes' state are the difference, not itemized). Someone who talks is one engine event and so -one frame: the members panel is the only pane that is rendered for it, and the -sidebar, which every frame renders (its cards are small and have no size of -their own to cache at); the rail, the top bar, the main area and the tree are -not rendered at all in the 570 events of the run. GPUI's own thread spends 5 % +one frame: the members panel was the only pane that was rendered for it (the +tree carried no `talking` then; the figures of the talking marks are below), +and the sidebar, which every frame renders (its cards are small and have no size +of their own to cache at); the rail, the top bar, the main area and the tree +were not rendered at all in the 570 events of the run. GPUI's own thread spends 5 % of a core on the 9.7 frames a second (the first run, of the `aa640cf` tree on a quieter machine, 3.4 % at 10.0 frames, with `llvmpipe` at 100.9 % and 105.4 % in all; the loaded machine starved the process of a frame in ten). The rest is the software device: `llvmpipe` draws the whole 1440 by 960 window again for every frame, about 90 ms of CPU a frame on this machine, which a GPU does; so the figure that says what a talker costs the app is the thread's, and -the one that says what a window nobody touches costs is the idle row. (The -Slint tree draws speaking bars on its rows; with them the tree pane would be -rendered for each of those frames too, which is why this one does not: not -measured.) +the one that says what a window nobody touches costs is the idle row. **Again after the review's fixes** (the banner veil, one letter on small avatars and the password prompt change what a row draws, not when a pane is rendered): @@ -1556,6 +1578,23 @@ person talking 10 times a second: 106.4 % (111 %) in all, `llvmpipe` 102.3 %, GPUI's thread 3.1 %, 225.9 MiB, 10.0 frames a second, rendered per second 0, 0, 10.0, 0, 0, 10.0 (the sidebar and the members panel only, as above). +**Again with the talking marks on the tree** (the speaking ring and bars on the +tree's rows, which the gate's ruling restored; they make the tree pane change +with every start and stop): the talking run on the release build of the commit +that restored them, lavapipe (Mesa 26.2.5, `llvmpipe (LLVM 21.1.8, 256 bits)` +through Vulkan) on Xvfb `:231` of 3840 by 2160 with openbox, 1440 by 960, the +state under the checkout's `.scratch/`, the machine at a load average of 83 at +the start and 41 at the end, 60 samples after the first 15 of 75. A sample person +talking 10 times a second (`VOELIN_DEMO_TALK=10`): 102.2 % (112 %) in all, +`llvmpipe` 95.6 %, GPUI's thread 5.0 % (8 % at most), 224.0 MiB, 9.97 engine +events and 9.97 window frames a second, rendered per second 0, 0, 9.97, 9.97, 0, +9.97 (rail, top bar, sidebar, tree, main, members): the tree pane is rendered +once for each start and stop, as the members panel is, and the rail, the top bar +and the main area not at all. The tree's pane costs no measurable CPU on top: the +thread's 5.0 % is the figure of the first run (5.0 %) and above the second's +(3.1 %), a spread the load of the machine makes, and `llvmpipe` draws the whole +window for a frame whichever pane asked for it. + **Seen against a server** (the TeamSpeak 3 development server of `dev/docker-compose.yml`, 3.13.8, release build of the tree committed as `aa640cf` (built just before that commit, whose own changes to the tests came @@ -1595,6 +1634,34 @@ Alt+F4 ended the app with status 0, 3.3 s after the key, and left no ghost client on the server. Against the TeamSpeak 6 server the form showed "1 online · 1 channel", the tree and the panel, and the close ended with status 0. +**Seen again after the minors round** (`phase5/gpui-tree-minors`, the release +build of `1dbe5d5`; one Xvfb of 3840 by 2160 with openbox for each run, `:236` +(the prompt), `:239` (TeamSpeak 3), `:242` (TeamSpeak 6), `:243` (the sample +server's tree) and `:245` (the talking run), after runs on `:235`, `:237` and +`:238` that only found where to click; Mesa 26.2.5's lavapipe, +`llvmpipe (LLVM 21.1.8, 256 bits)` through Vulkan, 1440 by 960; the state under +the checkout's `.scratch/`, no Wayland, no session bus and no XDG directory of +the desktop in any run; the load average 16 to 25; the two development servers +used read-only, nothing created, deleted or reset on them, and one connect to +each). On the sample +server (`VOELIN_DEMO_UI=1`, nobody talks on the real ones): Kairo's row in the +tree has the green ring and the three bars; a click on Raid Night tints the row +over its picture and the pointer on Music tints that one (the picture above); a +double-click on the locked Officers opens the password prompt, a click on the +card's corner takes the focus from the field and the prompt stays, and Escape +closes it. Against the TeamSpeak 3 server (3.13.8, `127.0.0.1:9987`, a nickname +set in the form, Save and connect): "1 online · 1 channel", Default Channel with +the client in it, "Members — 1"; the members search with `zzz` typed says "Nobody +matches." where it said to connect; Alt+F4 ended the app with status 0 and +`clientlist` over ServerQuery after the close showed the query client only, no +ghost. Against the TeamSpeak 6 server (6.0.0-beta13.1, `127.0.0.1:9988`) the +same tree, panel and "Nobody matches.", and the close ended with status 0 (its +ghosts were not looked for: its ServerQuery is SSH). The talking run again on +this build (`VOELIN_DEMO_TALK=10`, 60 samples after the first 15 of 75, load +average 24 to 17): 106 % (114 %) in all, `llvmpipe` 100.7 %, GPUI's thread +4.2 % (7 % at most), 221.8 MiB, 9.98 engine events and frames a second, rendered +per second 0, 0, 9.98, 9.98, 0, 9.98: the tree once for each start and stop. + #### The callbacks and the properties The plan counts "about 13 properties and 6 callbacks" for the two panes. The @@ -1631,13 +1698,13 @@ seventh standing in for the chat. The callbacks are GPUI actions | Slint property (used by) | Here | |---|---| -| `tree` (`channels.slint`) | `TreeModel::rows`, the `talking` flag cleared | +| `tree` (`channels.slint`) | `TreeModel::rows` | | `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 | | `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 ("No server yet.", "Loading the channels…", "Connect to see the channels.") | +| `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) | @@ -1647,7 +1714,7 @@ seventh standing in for the chat. The callbacks are GPUI actions dialog) are the other server callbacks of the Bridge that these panes will meet later; neither file uses them. -What differs from the Slint tree and panel, beside the tree's talkers above: +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 @@ -1766,6 +1833,60 @@ the slices that meet it; none of it is a defect of what exists today. 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`. +- **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 + what it emitted the first time is delivered after the second refresh has + run. An observer that changes the state in that window (`select_server`, + say, in the observer of a signal) makes the second refresh a different list + from the one the first operations were made for. The events carry their rows + for that reason, and the panes check in debug builds that the operations lead + from the rows they have to the rows carried (`debug_check`); a probe in the + tests makes exactly this change, from the observer of the toolbar signal + during a Presence flush, and found the old code indexing past the end of the + rows (`a_state_change_inside_a_flush_does_not_apply_old_operations_to_new_rows`). + The rule for a new part is that an observer of a signal reads the state and + sets its own fields, and a change of the root state belongs to an action's + handler or a task of its own, not to a signal's observer. The events that + carry no rows (`Selection`, `Lists`, `Card`) are read from the model at + delivery and end right whatever the order. +- **The model builds everything for every batch it hears of.** A raised batch + builds the whole `tree_view` again: every channel and every person, O(people + + channels) rows, and for each picture a row refers to the stat of its file + (`ImageSource::file`'s stamp, the review counted two per picture); then + `list::diff` against the rows it had. A talker's start or stop is one row of + change and the whole list built. The batches themselves are one build each + now (the model keeps the generations of its three signals it last built at, + so the signals of one change, three for a picture that arrives, are one + 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. +- **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 + (`signals.rs`, the per-area signals). A transition of `voelin-ui-vm` that + changes what they show and forgets to set `servers` leaves them stale, and + the Slint front end, which redraws by the same flags, is stale with it: the + flags of `Refresh` are the contract between the transitions and both front + ends, and a new transition sets every flag of what it touches. Nothing tests + that for the transitions that exist; a test per front end that plays the + events through `events::handle` and compares the parts with a rebuild from + the state would. +- **The members search's caret blink draws the window twice a second.** While + the search box is open and focused, the widget's caret blinks every 500 ms and + notifies its input, which the members panel and the window draw again: on the + first sample server, 2.00 window frames a second, 2.00 renders of the sidebar + and of the members panel and none of the others, `llvmpipe` at 21 % of a + core and GPUI's thread at 0.6 % (the release build of `f28c02a`, Xvfb `:234` + with openbox and lavapipe, the search opened with a click, 27 samples after + the first 15 of 42, load average 8 to 12). On a GPU that is two frames a second + of a mostly static window; the software device pays 90 ms of CPU for each. The + field of the chat's composer (slice 4) has the same blink; turning it off or + slowing it is the widget's option, if gpui-component has one, else a + property of the field the slice decides. - **A click renders every pane; a hover only the pane it is over.** In gpui-pre 0.3.10 pressing a clickable element and releasing it call `window.refresh()` (`elements/div.rs`), which ignores every cache for that frame, so a click on a @@ -1786,7 +1907,13 @@ the slices that meet it; none of it is a defect of what exists today. `join_with_password` and its `connect_into`), the card `refresh_member_card` builds inline (`tree::member_card`), and `open_member` setting the session's field (`logic::open_member`). They go with Slint (step 9), or each is a call - of the shared one when the Slint crate is next touched. + of the shared one when the Slint crate is next touched. Until then the + shared versions in `voelin-ui-vm` (`sequence::join_channel`, + `join_with_password` and `connect_into`, `logic::join_channel`, + `join_with_password` and `open_member`, `tree::member_card`) are called by + 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 @@ -1808,7 +1935,19 @@ the slices that meet it; none of it is a defect of what exists today. start and takes the focus back when the element that had it is gone (`on_focus_lost`: the form closed, a button replaced by another). A later window (the Stream Studio's) does the same, and a new page's buttons dispatch - actions the root handles rather than listeners of their own. + actions the root handles rather than listeners of their own. A key that + belongs to an overlay needs the overlay on that path. The root's handle takes + the focus on every mouse down inside the window (GPUI transfers it to the + element under the pointer that has a handle, the root being under all of + them), and the overlay is a child of the root, not an ancestor of the root's + handle: a click on the overlay that no handle inside it takes leaves the + focus on the root, and the overlay's key context is off the path. The + password prompt therefore holds a focus handle of its own on its scrim (the + card is on it), and Escape is a key binding of its key context + (`shell::bind_keys`, called beside `gpui_kit::init`), not a listener on the + 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 @@ -1861,6 +2000,17 @@ the slices that meet it; none of it is a defect of what exists today. `overlay` gets `scrim`), and gpui-base's non-colour tokens (radii, spacing, type, shadows, motion) are not written: gpui-base 0.8.1 has no storage to write them to, so those live in `VoelinTheme::metrics` only. +- **The TeamSpeak 3 development server bans an address that connects in a + burst** (tooling, not the app). `dev/docker-compose.yml` allowlists the + private ranges so that the addresses clients reach it from skip the + anti-flood bans "that rapid test connections would otherwise trigger"; a + client that is not in them, or a script that connects and closes many times + in a few seconds, gets banned by it for a while, and its connects are refused + until the ban ends (ServerQuery's `banlist` shows it, `banclear` lifts it, + which is for whoever owns the server). A live run of the front end connects + once, and runs that follow one another are spaced; the servers are used + read-only by a run, never reset (`docker compose down` or `-v` is not part of + one). - **The close grace is seen end to end now** (the shell opens sessions): a connected window closed with Alt+F4 leaves no ghost client on the TeamSpeak 3 development server and exits with status 0 ([The desktop diff --git a/docs/ui/gpui-tree-banner-selected-dark.png b/docs/ui/gpui-tree-banner-selected-dark.png new file mode 100644 index 0000000..29197ef Binary files /dev/null and b/docs/ui/gpui-tree-banner-selected-dark.png differ