diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index 7dc3c08..545735a 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -33,6 +33,8 @@ //! decoder are for the slices that have those parts. use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::Poll; use std::time::Duration; @@ -66,6 +68,9 @@ use crate::theme::{Choice, VoelinTheme}; /// rows (what a front end that draws again from the list needs). pub type VmState = voelin_ui_vm::state::AppState>; +/// The sample person `VOELIN_DEMO_TALK` makes talk (Kairo, who talks at start). +const SAMPLE_TALKER: u16 = 3; + /// How many engine events one update of the entity takes at most: a burst /// is handled in steps of this size, with a yield to GPUI's executor between /// them. @@ -246,6 +251,9 @@ pub struct AppState { tree_states: TreeStates, /// The servers whose remembered folds are in their sessions. tree_restored: HashSet, + /// Where the sample servers' pictures were written (`VOELIN_DEMO_UI`), + /// removed with the state. + demo_dir: Option, later: Later, /// What went to the engine (tests look at it: an engine of the test's /// own would have to be asked what it was sent). @@ -309,6 +317,29 @@ impl AppState { }) .detach(); + // With the sample servers, a sample person starts and stops talking at a + // rate (`VOELIN_DEMO_TALK`), through the events a server would send. + if let (true, Some(rate)) = (switches.demo_ui, switches.demo_talk) { + // Microseconds: a rate of 10 is 100 ms, not 100.000001 of an f32. + let period = Duration::from_micros((1e6 / f64::from(rate)).round() as u64); + cx.spawn(async move |this, cx| { + let mut talking = true; + loop { + cx.background_executor().timer(period).await; + talking = !talking; + let event = Event::Talking { + session: voelin_ui_vm::dev::logic::DEMO as u64, + client: SAMPLE_TALKER, + talking, + }; + if this.update(cx, |state, cx| state.handle_event(event, cx)).is_err() { + break; + } + } + }) + .detach(); + } + let loaded = backend.load(); let saved = backend.prefs.get(&UI_WINDOW); let tree_states = backend.prefs.get(&UI_TREE); @@ -333,6 +364,7 @@ impl AppState { password: None, tree_states, tree_restored: HashSet::new(), + demo_dir: None, later: Later(later), #[cfg(test)] sent: Default::default(), @@ -348,13 +380,37 @@ impl AppState { /// The sample servers of `VOELIN_DEMO_UI`, through the same events a server /// would send ([`voelin_ui_vm::dev::logic`]): the first is connected, the - /// second observed. + /// second observed, and the first's avatars, icons, banners and badges + /// arrive as files of a folder of their own in the temporary directory. fn load_demo(&mut self) { use voelin_ui_vm::dev::logic as sample; + static FOLDERS: AtomicUsize = AtomicUsize::new(0); self.vm.bookmarks = sample::bookmarks(); self.vm.settings.last_voice = Some(sample::last_voice()); self.vm.current = Some(sample::DEMO); - for event in sample::server_events() { + let folder = std::env::temp_dir().join(format!( + "voelin-gpui-demo-{}-{}", + std::process::id(), + FOLDERS.fetch_add(1, Ordering::Relaxed) + )); + let address = self.vm.bookmarks.first().map(|b| b.address.clone()).unwrap_or_default(); + let pictures = match std::fs::create_dir_all(&folder) { + Ok(()) => { + self.demo_dir = Some(folder.clone()); + sample::pictures(&address, |name, png| { + let path = folder.join(name); + if let Err(e) = std::fs::write(&path, png) { + warn!(%e, "a sample picture was not written"); + } + path + }) + } + Err(e) => { + warn!(%e, "the sample pictures have no folder"); + Vec::new() + } + }; + for event in sample::server_events().into_iter().chain(pictures) { let update = self.handle(event); self.counters.engine_events.incr(); self.events_handled += 1; @@ -1030,6 +1086,14 @@ impl AppState { } } +impl Drop for AppState { + fn drop(&mut self) { + if let Some(folder) = self.demo_dir.take() { + let _ = std::fs::remove_dir_all(folder); + } + } +} + #[cfg(test)] mod tests { use std::cell::Cell; @@ -1631,6 +1695,52 @@ mod tests { ); } + /// The sample servers' pictures arrive as files of a folder of their own, + /// through the events a server would send, and go with the state. + #[gpui::test] + fn the_sample_servers_pictures_arrive_as_files_and_go_with_the_state(cx: &mut TestAppContext) { + let switches = Switches { demo_ui: true, ..Switches::default() }; + let (app, _, _) = entity_over(cx, Backend::in_memory().unwrap(), switches); + let folder = app.read_with(cx, |app, _| { + let view = &app.vm.sessions[&sample::DEMO]; + assert_eq!(view.avatars.len(), 5, "five people have a picture"); + assert!(view.pictures.len() > 5, "banners and badges"); + assert!(view.avatars.values().all(|path| path.is_file())); + app.demo_dir.clone().expect("the folder") + }); + assert!(folder.is_dir()); + drop(app); + cx.update(|_| {}); + assert!(!folder.exists(), "removed with the state"); + } + + /// With `VOELIN_DEMO_TALK` a sample person starts and stops talking at the + /// rate asked, through the events a server would send. + #[gpui::test] + fn the_sample_person_talks_at_the_rate_asked(cx: &mut TestAppContext) { + let switches = Switches { demo_ui: true, demo_talk: Some(10.0), ..Switches::default() }; + let (app, _, counters) = entity_over(cx, Backend::in_memory().unwrap(), switches); + let talking = |cx: &mut TestAppContext| { + app.read_with(cx, |app, _| app.vm.sessions[&sample::DEMO].talking.contains(&3)) + }; + assert!(talking(cx), "Kairo talks as the sample starts"); + cx.run_until_parked(); + let events = counters.engine_events.get(); + for expected in [false, true, false, true] { + cx.executor().advance_clock(Duration::from_millis(100)); + cx.run_until_parked(); + assert_eq!(talking(cx), expected); + } + assert_eq!(counters.engine_events.get(), events + 4, "one event a toggle"); + // Without the sample servers the switch does nothing. + let switches = Switches { demo_talk: Some(10.0), ..Switches::default() }; + let (quiet, _, counters) = entity_over(cx, Backend::in_memory().unwrap(), switches); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + assert_eq!(counters.engine_events.get(), 0); + drop(quiet); + } + #[gpui::test] fn the_sample_servers_show_through_the_events_and_nothing_is_stored_or_sent( cx: &mut TestAppContext, diff --git a/crates/voelin-gpui/src/dev.rs b/crates/voelin-gpui/src/dev.rs index 9d46f5c..2e5ba99 100644 --- a/crates/voelin-gpui/src/dev.rs +++ b/crates/voelin-gpui/src/dev.rs @@ -9,6 +9,9 @@ //! skipped. //! - `VOELIN_DEMO_UI=1`: the Slint front end's sample servers, shown through //! the app's own events; nothing is sent to the engine or kept in the store. +//! - `VOELIN_DEMO_TALK=10`: with `VOELIN_DEMO_UI`, one of the sample people +//! starts and stops talking this many times a second, 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 //! one the settings give (`ui.theme`). //! - `VOELIN_FONT_SCALE=1.25`: the text size factor, in place of the @@ -36,6 +39,9 @@ pub struct Switches { pub open: Page, /// Show the sample servers instead of the stored ones. pub demo_ui: bool, + /// How many times a second a sample person starts or stops talking (with + /// the sample servers), when the switch names a rate. + pub demo_talk: Option, /// The theme mode, when the switch names one. pub theme: Option, /// The text size factor, when the switch names one. @@ -51,6 +57,7 @@ impl Default for Switches { Self { open: Page::Shell, demo_ui: false, + demo_talk: None, theme: None, font_scale: None, window: None, @@ -97,6 +104,12 @@ impl Switches { None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"), } } + if let Some(text) = get("VOELIN_DEMO_TALK") { + match text.trim().parse::() { + Ok(rate) if (0.1..=100.0).contains(&rate) => switches.demo_talk = Some(rate), + _ => tracing::warn!("VOELIN_DEMO_TALK={text}: a rate from 0.1 to 100 a second"), + } + } let flag = |name: &str| get(name).is_some_and(|v| !matches!(v.trim(), "" | "0")); switches.demo_ui = flag("VOELIN_DEMO_UI"); switches.meter = flag("VOELIN_METER"); @@ -133,6 +146,7 @@ mod tests { let s = env(&[ ("VOELIN_OPEN", "swatch"), ("VOELIN_DEMO_UI", "1"), + ("VOELIN_DEMO_TALK", "10"), ("VOELIN_DEV_THEME", "light"), ("VOELIN_FONT_SCALE", "1.25"), ("VOELIN_WINDOW_SIZE", "1440x960"), @@ -140,6 +154,7 @@ mod tests { ]); assert_eq!(s.open, Page::Swatch); assert!(s.demo_ui); + assert_eq!(s.demo_talk, Some(10.0)); assert_eq!(s.theme, Some(Choice::Light)); assert_eq!(s.font_scale, Some(1.25)); assert_eq!(s.window, Some((1440.0, 960.0))); @@ -154,6 +169,7 @@ mod tests { ("VOELIN_FONT_SCALE", "9"), ("VOELIN_WINDOW_SIZE", "10x10"), ("VOELIN_DEMO_UI", "0"), + ("VOELIN_DEMO_TALK", "fast"), ("VOELIN_METER", "0"), ]); assert_eq!(s, Switches::default()); diff --git a/crates/voelin-gpui/src/meter.rs b/crates/voelin-gpui/src/meter.rs index 8a2e9ba..7b79432 100644 --- a/crates/voelin-gpui/src/meter.rs +++ b/crates/voelin-gpui/src/meter.rs @@ -272,6 +272,17 @@ pub fn start(counters: Counters) { mod tests { use super::*; + #[test] + fn the_panes_are_counted_by_name() { + let panes = Panes::default(); + 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"]); + 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"); + } + #[test] fn groups_drop_trailing_numbers() { assert_eq!(group_of("llvmpipe-12"), "llvmpipe"); diff --git a/crates/voelin-gpui/src/pictures.rs b/crates/voelin-gpui/src/pictures.rs index 62e01ed..0324043 100644 --- a/crates/voelin-gpui/src/pictures.rs +++ b/crates/voelin-gpui/src/pictures.rs @@ -116,6 +116,12 @@ pub fn forget_stale(path: &Path, cx: &mut App) { } } +/// Whether the decoded copy of `key` is in the asset cache (the tests ask). +#[cfg(test)] +pub(crate) fn is_cached(key: &PictureKey, cx: &App) -> bool { + cx.has_asset::(key) +} + #[cfg(test)] mod tests { use gpui::TestAppContext; diff --git a/crates/voelin-gpui/src/shell/members.rs b/crates/voelin-gpui/src/shell/members.rs new file mode 100644 index 0000000..6b7f62b --- /dev/null +++ b/crates/voelin-gpui/src/shell/members.rs @@ -0,0 +1,622 @@ +//! The members panel (`MembersPanel` and `MemberCardPopup` of +//! `screens/members.slint`): everyone on the server in sections (those +//! streaming first, then each server group), a search, and the card of one +//! person over the panel. +//! +//! [`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 +//! that a click outside closes; its buttons (the volume, 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::prelude::FluentBuilder as _; +use gpui_kit::{ + AnyElement, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, + ListAlignment, ListState, ParentElement as _, Render, SharedString, + StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, list, px, +}; +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::widgets::{ + Avatar, IconButton, Presence, chip, icon, live_badge, small_picture, speaking_bars, +}; +use crate::meter::Counters; +use crate::theme::tokens::Rgba; +use crate::theme::{VoelinTheme, hsla}; + +/// The colour of the shield of a moderator's role. +const ROLE: Rgba = Rgba(0xc06c_ffff); + +/// The members panel. +pub struct MembersPane { + rows: Arc>, + total: i32, + emptiness: Emptiness, + /// The person whose card is open. + open: Option, + list: ListState, + search: Entity, + searching: bool, + /// The text size factor the list measured its rows at. + measured_at: f32, + counters: Counters, + _subscriptions: Vec, +} + +impl MembersPane { + /// A panel that follows `model`. + pub fn new( + model: &Entity, + counters: Counters, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let (rows, total, emptiness, open) = { + let model = model.read(cx); + (model.people().clone(), model.total(), model.emptiness(), model.card().map(|c| c.id)) + }; + let search = cx.new(|cx| { + InputState::new(window, cx).placeholder(SharedString::from("Search members…")) + }); + 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::Lists => { + let model = model.read(cx); + (this.total, this.emptiness) = (model.total(), model.emptiness()); + } + TreeEvent::Card => this.open = model.read(cx).card().map(|card| card.id), + TreeEvent::Rows(_) | TreeEvent::Selection => return, + } + cx.notify(); + }), + cx.subscribe_in(&search, window, |_, input, event: &InputEvent, window, cx| { + if matches!(event, InputEvent::Change) { + let text = input.read(cx).value().to_string(); + window.dispatch_action(Box::new(SearchMembers { text }), cx); + } + }), + ]; + Self { + list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)), + rows, + total, + emptiness, + open, + search, + searching: false, + measured_at: 0.0, + counters, + _subscriptions: subscriptions, + } + } + + /// The rows it shows. + pub fn rows(&self) -> &[MemberItem] { + &self.rows + } + + /// The person whose card is open, as the panel marks them. + pub fn open(&self) -> Option { + self.open + } + + /// 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). + fn apply(&mut self, changes: &Changes, new: Arc>) { + use voelin_ui_vm::list::Change; + + let mut headed: Vec = self.rows.iter().map(|row| row.first_in_group).collect(); + for change in &changes.0 { + match *change { + Change::Update(i) => { + if headed[i] != new[i].first_in_group { + self.list.splice(i..i + 1, 1); + } + headed[i] = new[i].first_in_group; + } + Change::Remove(i) => { + headed.remove(i); + self.list.splice(i..i + 1, 0); + } + Change::Insert(i) => { + headed.insert(i, new[i].first_in_group); + self.list.splice(i..i, 1); + } + } + } + self.rows = new; + } + + /// The search box was opened or closed: closing it shows everyone again. + fn toggle_search(&mut self, window: &mut Window, cx: &mut Context) { + self.searching = !self.searching; + if self.searching { + self.search.update(cx, |input, cx| input.focus(window, cx)); + } else { + self.search.update(cx, |input, cx| input.set_value("", window, cx)); + window.dispatch_action(Box::new(SearchMembers { text: String::new() }), cx); + } + cx.notify(); + } + + /// The entry at `ix` for the list: the heading of its section if it opens + /// one, then the person. + fn entry(&mut self, ix: usize, cx: &mut Context) -> AnyElement { + let theme = VoelinTheme::global(cx).clone(); + let Some(item) = self.rows.get(ix) else { return div().into_any_element() }; + let m = &theme.metrics; + div() + .w_full() + .px(px(m.space_3)) + .flex() + .flex_col() + .when(item.first_in_group, |entry| entry.child(group_header(&theme, item))) + .child(member_row(&theme, item, self.open == Some(item.id))) + .into_any_element() + } +} + +/// The words of a panel with nobody in it. +fn empty_words(emptiness: Emptiness) -> &'static str { + match emptiness { + Emptiness::Loading => "Loading who is here…", + Emptiness::NoServer | Emptiness::Connect => "Connect to see who is here.", + } +} + +/// The heading above the first person of a section: "Moderator — 3". +fn group_header(theme: &VoelinTheme, item: &MemberItem) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let words = if item.group_count > 0 { + format!("{} — {}", item.group, item.group_count) + } else { + item.group.to_string() + }; + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .pt(px(m.space_5)) + .pb(px(m.space_2)) + .pl(px(m.space_2)) + .children(small_picture(&item.group_icon, 16.0)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(px(m.font_md)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(c.text_secondary)) + .child(words), + ) +} + +/// One person: avatar, name with their badges and role, what they are doing. +fn member_row(theme: &VoelinTheme, item: &MemberItem, open: bool) -> AnyElement { + let (c, m) = (&theme.colors, &theme.metrics); + let id = item.id; + let hover = hsla(c.surface_3); + let presence = if item.away { + Presence::Idle + } else if item.sound_off { + Presence::Dnd + } else { + Presence::Online + }; + let name_color = if item.myself { + c.accent_text + } else if !item.role.is_empty() { + c.name_text + } else { + c.text + }; + let crowns = div() + .flex() + .flex_row() + .items_center() + .gap(px(3.0)) + .when(item.admin, |row| row.child(icon("crown", 14.0, c.gold))) + .when(item.priority, |row| row.child(icon("star", 14.0, c.accent_text))) + .when(item.commander, |row| row.child(icon("flag", 14.0, c.info))) + .when(item.recording, |row| row.child(icon("circle-dot", 14.0, c.danger))); + let badges = div().flex().flex_row().items_center().gap(px(2.0)).children( + [&item.badge, &item.badge_2, &item.badge_3] + .into_iter() + .filter_map(|b| small_picture(b, 14.0)), + ); + div() + .id(("member", id as u64)) + .debug_selector(move || format!("member-{id}")) + .w_full() + .h(px(52.0 * m.font_scale)) + .flex_none() + .rounded(px(m.radius_md)) + .cursor_pointer() + .when(open, |row| row.bg(hsla(c.accent_soft))) + .when(!open, |row| row.hover(move |style| style.bg(hover))) + .when(item.away, |row| row.opacity(0.6)) + .flex() + .flex_row() + .items_center() + .px(px(m.space_2)) + .gap(px(m.space_3)) + .child( + Avatar::new(("member-avatar", id as u64), 40.0, &item.initials, item.tint) + .image(item.avatar.clone()) + .presence(presence) + .speaking(item.talking), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(1.0)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .child( + div() + .min_w_0() + .truncate() + .text_size(px(m.font_md)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(name_color)) + .child(item.name.to_string()), + ) + .child(crowns) + .child(badges), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .child( + div() + .min_w_0() + .truncate() + .text_size(px(m.font_sm)) + .text_color(hsla(if item.talking { + c.success + } else { + c.text_muted + })) + .child(item.status.to_string()), + ) + .when(item.talking, |row| row.child(speaking_bars(theme, 12.0))) + .when(item.streaming, |row| { + row.child(icon("monitor", 14.0, c.text_secondary)) + }), + ), + ) + .when(!item.role.is_empty(), |row| { + row.child(icon("shield-check", 18.0, ROLE)).child(chip( + theme, + item.role.to_string(), + None, + None, + )) + }) + .when(item.streaming, |row| row.child(live_badge(theme))) + .when(item.muted, |row| row.child(icon("mic-off", 16.0, c.danger))) + .when(item.sound_off, |row| row.child(icon("headphone-off", 16.0, c.danger))) + // A hand, as TeamSpeak asks for talk power; the card has the number. + .when(item.cannot_talk, |row| { + row.child( + div() + .id(("member-hand", id as u64)) + .tooltip(|window, cx| { + gpui_kit::component::tooltip::Tooltip::new("Needs talk power to speak") + .build(window, cx) + }) + .child(icon("hand", 16.0, c.text_muted)), + ) + }) + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(OpenMember { client: id }), cx) + }) + .into_any_element() +} + +impl Render for MembersPane { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.counters.panes.members.incr(); + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + if (self.measured_at - m.font_scale).abs() > f32::EPSILON { + if self.measured_at != 0.0 { + self.list.remeasure(); + } + self.measured_at = m.font_scale; + } + let searching = self.searching; + let this = cx.entity(); + let search_button = IconButton::new("members-search", "search", "Search members") + .size(32.0) + .checked(searching) + .on_click(move |_, window, cx| { + this.update(cx, |pane, cx| pane.toggle_search(window, cx)); + }); + div() + .id("members") + .debug_selector(|| "members".into()) + .size_full() + .flex() + .flex_col() + .gap(px(m.space_2)) + .pt(px(m.space_4)) + .pb(px(m.space_2)) + .rounded(px(m.radius_xl)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface.with_alpha(235))) + .overflow_hidden() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .pl(px(m.space_5)) + .pr(px(m.space_3)) + .child( + div() + .id("members-title") + .flex_1() + .min_w_0() + .truncate() + .text_size(px(m.font_lg)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(c.text)) + .child(format!("Members — {}", self.total)), + ) + .child(search_button), + ) + .when(searching, |pane| { + pane.child( + div() + .id("members-search-box") + .debug_selector(|| "members-search-box".into()) + .px(px(m.space_4)) + .child(Input::new(&self.search)), + ) + }) + .map(|pane| { + if self.rows.is_empty() { + pane.child( + div() + .id("members-empty") + .debug_selector(|| "members-empty".into()) + .px(px(m.space_5)) + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_muted)) + .child(empty_words(self.emptiness)), + ) + } else { + pane.child( + list( + self.list.clone(), + cx.processor(|this, ix, _window, cx| this.entry(ix, cx)), + ) + .flex_1() + .w_full() + .min_h_0(), + ) + } + }) + } +} + +/// 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. +pub struct MemberCardView { + card: Option, + /// How wide the members panel is: the card stands beside it. + panel_width: f32, + _subscription: Subscription, +} + +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 { + 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(); + } + }); + Self { card, panel_width, _subscription: subscription } + } + + /// The card that is open. + pub fn card(&self) -> Option<&MemberCard> { + self.card.as_ref() + } +} + +/// The heading of a part of the card: "Groups", "Badges". +fn caption(theme: &VoelinTheme, text: &'static str) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .text_size(px(m.font_xs)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text_muted)) + .child(text) +} + +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() }; + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + let facts = div() + .flex() + .flex_row() + .flex_wrap() + .gap(px(m.space_2)) + .when(person.talk_power > 0, |row| { + row.child(chip( + &theme, + format!("talk power {}", person.talk_power), + Some("mic"), + None, + )) + }) + .when(!person.country.is_empty(), |row| { + row.child(chip(&theme, person.country.to_string(), Some("globe"), None)) + }); + let body = div() + .id("member-card") + .debug_selector(|| "member-card".into()) + .w(px(300.0)) + .flex() + .flex_col() + .gap(px(m.space_3)) + .p(px(m.space_4)) + .rounded(px(m.radius_lg)) + .border_1() + .border_color(hsla(c.border_popup)) + .bg(hsla(c.surface_3)) + // Clicks inside stay inside. + .on_click(|_, _, cx| cx.stop_propagation()) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child( + Avatar::new("member-card-avatar", 52.0, &person.initials, person.tint) + .image(person.avatar.clone()), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.0)) + .child( + div() + .truncate() + .text_size(px(m.font_lg)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(person.name.to_string()), + ) + .child( + div() + .truncate() + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_muted)) + .child(person.status.to_string()), + ), + ) + .child(IconButton::new("member-card-close", "x", "Close").size(26.0).on_click( + |_, window, cx| { + window.dispatch_action(Box::new(OpenMember { client: -1 }), cx) + }, + )), + ) + .when(!person.description.is_empty(), |card| { + card.child( + div() + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_secondary)) + .child(person.description.to_string()), + ) + }) + .when(!person.groups.is_empty(), |card| { + card.child( + div() + .flex() + .flex_col() + .gap(px(m.space_2)) + .child(caption(&theme, "Groups")) + .children(person.groups.iter().map(|group| { + div() + .truncate() + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_secondary)) + .child(group.to_string()) + })), + ) + }) + .when(!person.badges.is_empty(), |card| { + card.child( + div() + .flex() + .flex_col() + .gap(px(m.space_2)) + .child(caption(&theme, "Badges")) + .child(div().flex().flex_row().flex_wrap().gap(px(m.space_2)).children( + person.badges.iter().enumerate().map(|(i, badge)| { + let description = badge.description.clone(); + div() + .id(("member-badge", i as u64)) + .tooltip(move |window, cx| { + gpui_kit::component::tooltip::Tooltip::new( + description.to_string(), + ) + .build(window, cx) + }) + .child(chip( + &theme, + badge.name.to_string(), + None, + small_picture(&badge.icon, 14.0), + )) + }), + )), + ) + }) + .child(facts); + // The card stands beside the panel, near the top. + div() + .id("member-card-scrim") + .debug_selector(|| "member-card-scrim".into()) + .absolute() + .top(px(0.0)) + .left(px(0.0)) + .size_full() + .bg(hsla(c.scrim_light)) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(OpenMember { client: -1 }), cx) + }) + .flex() + .flex_row() + .justify_end() + .items_start() + .pt(px(120.0)) + .pr(px(self.panel_width + 24.0)) + .child(body) + .into_any_element() + } +} diff --git a/crates/voelin-gpui/src/shell/mod.rs b/crates/voelin-gpui/src/shell/mod.rs index b5a577a..1fb78c7 100644 --- a/crates/voelin-gpui/src/shell/mod.rs +++ b/crates/voelin-gpui/src/shell/mod.rs @@ -12,6 +12,7 @@ pub mod actions; mod channels; mod form; mod main_panel; +mod members; mod password; mod rail; mod sidebar; @@ -23,6 +24,7 @@ pub mod widgets; pub use channels::ChannelTree; pub use form::ServerForm; pub use main_panel::{MainPanel, MainState}; +pub use members::{MemberCardView, MembersPane}; pub use password::ChannelPassword; pub use rail::{RailView, ServerRail}; pub use sidebar::{Sidebar, SidebarView}; diff --git a/crates/voelin-gpui/src/shell/widgets.rs b/crates/voelin-gpui/src/shell/widgets.rs index 249ac05..8fc3e2b 100644 --- a/crates/voelin-gpui/src/shell/widgets.rs +++ b/crates/voelin-gpui/src/shell/widgets.rs @@ -36,6 +36,8 @@ pub enum Presence { Info, /// Not connected. Offline, + /// Their sound is off (a person who does not hear). + Dnd, } impl Presence { @@ -60,6 +62,7 @@ impl Presence { Self::Idle => Some(c.idle), Self::Info => Some(c.info), Self::Offline => Some(c.offline), + Self::Dnd => Some(c.dnd), } } } diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index f6f8b4a..58ccb10 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -5,12 +5,13 @@ //! Slint callbacks did, owns the server form, titles the window with the //! server on screen and reports where the window is. +use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ App, AppContext as _, Context, Entity, FocusHandle, InteractiveElement as _, IntoElement, ParentElement as _, Render, StyleRefinement, Styled as _, Subscription, Window, WindowBounds, div, px, }; -use voelin_ui_vm::settings::WindowState; +use voelin_ui_vm::settings::{UI_MEMBERS_WIDTH, WindowState}; use crate::app::AppState; use crate::dev::Page; @@ -22,8 +23,8 @@ use crate::shell::actions::{ SelectServer, SetInputMuted, SetOutputMuted, SubmitChannelPassword, ToggleChannel, }; use crate::shell::{ - ChannelPassword, ChannelTree, MainPanel, ServerForm, ServerRail, Sidebar, Toast, TopBar, - TreeModel, + ChannelPassword, ChannelTree, Emptiness, MainPanel, MemberCardView, MembersPane, ServerForm, + ServerRail, Sidebar, Toast, TopBar, TreeEvent, TreeModel, }; use crate::swatch::swatch; use crate::theme::{VoelinTheme, hsla}; @@ -59,6 +60,10 @@ pub struct MainView { sidebar: Entity, model: Entity, tree: Entity, + members: Entity, + card: Entity, + /// How wide the members panel is (`ui.members_width`, read at start). + members_width: f32, main: Entity, toast: Entity, form: Option>, @@ -90,7 +95,7 @@ impl MainView { // button replaced by another). let focus = cx.focus_handle(); window.focus(&focus, cx); - let subscriptions = vec![ + let mut subscriptions = vec![ cx.on_focus_lost(window, |this, window, cx| window.focus(&this.focus, cx)), cx.observe_window_appearance(window, |_, window, cx| { VoelinTheme::set_system_appearance(cx, window.appearance()); @@ -130,14 +135,26 @@ impl MainView { window.on_next_frame(maximize); } let prompt_generation = app.read(cx).password_generation; + let members_width = app.read(cx).backend().prefs.get(&UI_MEMBERS_WIDTH) as f32; 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)); + // The members panel comes with the first server on screen. + subscriptions.push(cx.subscribe(&model, |_, _, event: &TreeEvent, cx| { + if matches!(event, TreeEvent::Lists) { + cx.notify(); + } + })); Self { rail: cx.new(|cx| ServerRail::new(&app, cx)), topbar: cx.new(|cx| TopBar::new(&app, cx)), sidebar: cx.new(|cx| Sidebar::new(&app, tree.clone(), cx)), model, tree, + members, + card, + members_width, main: cx.new(|cx| MainPanel::new(&app, cx)), toast: cx.new(|cx| Toast::new(&app, cx)), app, @@ -167,6 +184,16 @@ impl MainView { &self.tree } + /// The members panel. + pub fn members_pane(&self) -> &Entity { + &self.members + } + + /// The card over a member row. + pub fn member_card(&self) -> &Entity { + &self.card + } + /// Open the form with `form`'s values. fn open_form( &mut self, @@ -383,6 +410,10 @@ impl Render for MainView { if self.page == Page::Swatch { return frame.bg(hsla(c.bg_app)).child(swatch(&theme)); } + // The members panel is for a server on screen, as wide as the setting + // 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); let main = match &self.form { Some(form) => form.clone().into_any_element(), None => self @@ -446,9 +477,20 @@ impl Render for MainView { .pb(px(m.space_3)) .gap(px(m.space_3)) .child(self.sidebar.clone()) - .child(main), + .child(main) + .when(people, |row| { + row.child( + self.members.clone().cached( + StyleRefinement::default() + .w(px(members_width)) + .h_full() + .flex_none(), + ), + ) + }), ), ) + .child(self.card.clone()) .children(self.prompt.clone()) .child(self.toast.clone()) } @@ -478,6 +520,7 @@ mod tests { use crate::backend::Backend; use crate::backend::testing::TempDir; use crate::dev::Switches; + use crate::pictures::PictureKey; use crate::shell::{RailView, TreeEvent}; use crate::theme::Choice; use crate::window_bounds; @@ -1185,6 +1228,206 @@ mod tests { ); } + /// 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 { + shell.view.read_with(cx, |view, cx| { + view.members_pane() + .read(cx) + .rows() + .iter() + .map(|m| { + if m.first_in_group { + format!("{} — {}: {}", m.group, m.group_count, m.name) + } else { + m.name.to_string() + } + }) + .collect() + }) + } + + /// Everyone on the server is in the members panel, in sections, with how + /// many there are; the panel is for a server on screen, and its search + /// narrows the sections to the names it matches. + #[gpui::test] + fn the_members_panel_lists_everyone_in_sections_and_searches(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + assert!(at(cx, "members").is_none(), "no server, no members panel"); + sample_server(&shell, cx); + assert!(at(cx, "members").is_some()); + assert_eq!( + members_shape(&shell, cx), + [ + "Streaming — 3: Lumen", + "Talon", + "Zeph", + "Moderator — 2: Kairo", + "Nova", + "Member — 2: dex", + "Mira", + "Guest — 1: Blaze", + "Online — 1: Rin", + ] + ); + for id in [2, 6, 7, 3, 1, 5, 4, 8, 9] { + assert!(at(cx, &format!("member-{id}")).is_some(), "member-{id} is on screen"); + } + let total = shell.view.read_with(cx, |view, cx| view.tree_model().read(cx).total()); + assert_eq!(total, 9); + + // The search box opens with the button; what it holds narrows the list. + assert!(at(cx, "members-search-box").is_none()); + click(cx, "members-search"); + assert!(at(cx, "members-search-box").is_some()); + cx.simulate_input("RA"); + frame(cx); + assert_eq!(members_shape(&shell, cx), ["Member — 1: Mira"], "case does not matter"); + assert_eq!(shell.app.read_with(cx, |app, _| app.vm.member_filter.clone()), "RA"); + // Closing it shows everyone again. + click(cx, "members-search"); + assert!(at(cx, "members-search-box").is_none()); + assert_eq!(members_shape(&shell, cx).len(), 9); + 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 + /// row says so while they talk. + #[gpui::test] + fn a_talker_redraws_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; + let seen = || { + [&panes.rail, &panes.topbar, &panes.tree, &panes.main, &panes.members].map(|p| p.get()) + }; + let kairo = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| { + view.members_pane().read(cx).rows().iter().find(|m| m.id == 3).cloned().unwrap() + }) + }; + assert!(kairo(&shell, cx).talking, "Kairo talks as the sample starts"); + let before = seen(); + for (talking, words) in [(false, "Listening"), (true, "Speaking")] { + let event = Event::Talking { session: sample::DEMO as u64, client: 3, talking }; + shell.events.send(event).unwrap(); + frame(cx); + let row = kairo(&shell, cx); + assert_eq!((row.talking, &*row.status), (talking, words)); + } + let after = seen(); + assert!(after[4] > before[4], "the members panel was drawn: {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" + ); + } + + /// A click on a person opens their card over the panel with what is known + /// of them (name, status, groups, badges); a click outside, the close + /// button or their leaving the server takes it away. + #[gpui::test] + fn a_click_on_a_member_opens_their_card(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let card = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| view.member_card().read(cx).card().cloned()) + }; + assert!(card(&shell, cx).is_none() && at(cx, "member-card").is_none()); + + click(cx, "member-1"); + let nova = card(&shell, cx).expect("Nova's card"); + assert_eq!((nova.id, &*nova.name, &*nova.status), (1, "Nova", "Listening")); + assert_eq!(nova.groups.iter().map(|g| &**g).collect::>(), ["Moderator"]); + assert_eq!(nova.badges.len(), 2); + assert_eq!( + (nova.talk_power, &*nova.description), + (75, "Raid lead. Ask me about the Tuesday runs.") + ); + assert!(at(cx, "member-card").is_some()); + assert_eq!( + shell.view.read_with(cx, |view, cx| view.members_pane().read(cx).open()), + Some(1) + ); + + // The card follows what the person does while it is open. + let event = Event::Talking { session: sample::DEMO as u64, client: 1, talking: true }; + shell.events.send(event).unwrap(); + frame(cx); + assert_eq!(&*card(&shell, cx).unwrap().status, "Speaking"); + + click(cx, "member-card-close"); + assert!(card(&shell, cx).is_none() && at(cx, "member-card").is_none()); + click(cx, "member-3"); + assert_eq!(&*card(&shell, cx).unwrap().name, "Kairo"); + // A click on the scrim, outside the card, closes it. + let scrim = at(cx, "member-card-scrim").expect("the scrim"); + cx.simulate_click( + point(scrim.origin.x + px(8.0), scrim.origin.y + px(8.0)), + Default::default(), + ); + frame(cx); + assert!(card(&shell, cx).is_none()); + + // Someone who leaves takes their card with them. + click(cx, "member-5"); + assert_eq!(&*card(&shell, cx).unwrap().name, "dex"); + shell.events.send(presence_changed!(p => p.clients.remove(&5))).unwrap(); + frame(cx); + assert!(card(&shell, cx).is_none(), "dex is gone"); + } + + /// A picture the engine writes again into the same cache file shows: the + /// row's picture is another key, the copy decoded under the old one is + /// dropped from the asset cache, and the new key is what is drawn. + #[gpui::test] + fn an_avatar_written_again_shows_under_a_new_key_and_the_old_copy_goes( + cx: &mut TestAppContext, + ) { + let dir = TempDir::new("avatar-reload"); + std::fs::create_dir_all(&dir.0).unwrap(); + let path = dir.0.join("avatar-demo-3"); + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let avatar_of_kairo = |shell: &Shell, cx: &mut VisualTestContext| { + shell.view.read_with(cx, |view, cx| { + let pane = view.members_pane().read(cx); + let row = pane.rows().iter().find(|m| m.id == 3).unwrap(); + PictureKey::of(&row.avatar) + }) + }; + assert_eq!(avatar_of_kairo(&shell, cx), None, "initials until a picture arrives"); + let arrives = |path: &std::path::Path| Event::AvatarReady { + session: sample::DEMO as u64, + client_uid: "demo-3".into(), + path: path.to_owned(), + hash: String::new(), + }; + + std::fs::write(&path, sample::demo_picture(40, 40, 1)).unwrap(); + shell.events.send(arrives(&path)).unwrap(); + frame(cx); + cx.run_until_parked(); + frame(cx); + let first = avatar_of_kairo(&shell, cx).expect("the picture shows"); + assert!(cx.update(|_, cx| crate::pictures::is_cached(&first, cx)), "drawn: decoded once"); + + std::fs::write(&path, sample::demo_picture(64, 64, 2)).unwrap(); + shell.events.send(arrives(&path)).unwrap(); + frame(cx); + cx.run_until_parked(); + frame(cx); + let second = avatar_of_kairo(&shell, cx).expect("the new picture shows"); + assert_ne!(second, first, "the file was written again: another key"); + assert!( + !cx.update(|_, cx| crate::pictures::is_cached(&first, cx)), + "the copy decoded under the old key is gone" + ); + assert!(cx.update(|_, cx| crate::pictures::is_cached(&second, cx)), "the new one is drawn"); + } + /// The plus of the rail opens the form; Save with an address adds the /// server, selects it and closes the form. #[gpui::test]