diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index 11ab4c8..7dc3c08 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -32,6 +32,7 @@ //! flags, the notices, the pictures to decode and the streams' capture and //! decoder are for the slices that have those parts. +use std::collections::HashSet; use std::task::Poll; use std::time::Duration; @@ -43,21 +44,22 @@ use voelin_core::{Command, Engine, Event, VoiceState}; use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, Store}; use voelin_ui_vm::bridge::{BookmarkForm, ChatLine}; use voelin_ui_vm::events; -use voelin_ui_vm::host::{Cx, Host, Persist, Refresh, Update}; +use voelin_ui_vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update}; use voelin_ui_vm::image::ImageRef; use voelin_ui_vm::servers::logic; use voelin_ui_vm::servers::sequence::{self, Backing}; use voelin_ui_vm::settings::{ - CLIENT_PLAYBACK, ThemeChoice, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, UI_WINDOW, - WindowState, + CLIENT_PLAYBACK, ThemeChoice, TreeStates, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, + UI_TREE, UI_WINDOW, WindowState, }; use voelin_ui_vm::social::logic::Social; +use voelin_ui_vm::tree::ChannelId; use crate::backend::Backend; use crate::dev::Switches; use crate::meter::Counters; use crate::pictures; -use crate::signals::Signals; +use crate::signals::{Area, Signals}; use crate::theme::{Choice, VoelinTheme}; /// The toolkit-free state of the client, with the chat lines of a tab as plain @@ -230,12 +232,20 @@ pub struct AppState { /// toast sees a new text by this number changing, even when the text is /// the same as the last. pub status_generation: u64, + /// How many times a channel's password was asked for: the window opens the + /// prompt ([`AppState::password_prompt`]) when this changes. + pub password_generation: u64, engine: Option, backend: Backend, switches: Switches, window: WindowKeeper, counters: Counters, signals: Signals, + password: Option, + /// What each server's tree remembers (`ui.tree`), by bookmark id. + tree_states: TreeStates, + /// The servers whose remembered folds are in their sessions. + tree_restored: HashSet, 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). @@ -301,12 +311,14 @@ impl AppState { let loaded = backend.load(); let saved = backend.prefs.get(&UI_WINDOW); + let tree_states = backend.prefs.get(&UI_TREE); let mut state = Self { vm: VmState::new(loaded.bookmarks, loaded.settings, loaded.audio, loaded.playback), social: Social::default(), events_handled: 0, ticks: 0, status_generation: 0, + password_generation: 0, engine, backend, switches, @@ -318,6 +330,9 @@ impl AppState { }, counters, signals: Signals::new(cx), + password: None, + tree_states, + tree_restored: HashSet::new(), later: Later(later), #[cfg(test)] sent: Default::default(), @@ -325,6 +340,8 @@ impl AppState { state.window.opening_reports = if state.wants_maximized() { OPENING_REPORTS } else { 0 }; if state.switches.demo_ui { state.load_demo(); + } else if let Some(id) = state.vm.current { + state.restore_tree(id); } state } @@ -522,7 +539,8 @@ impl AppState { self.keep(what); } if let Some(prompt) = password { - debug!(channel = %prompt.name, "the password dialog comes with the channel tree"); + self.password = Some(prompt); + self.password_generation += 1; } // What the front end keeps itself comes before the drawing. if let Some(Event::SettingChanged { key }) = rest { @@ -700,6 +718,7 @@ 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) }); @@ -773,6 +792,124 @@ impl AppState { Some(link) } + // The callbacks of the channel tree and the members panel. + + /// Join a channel of the server on screen (`join_channel` of + /// `bind/servers.rs`, through [`sequence::join_channel`]): the move there + /// with voice, the password prompt for a locked channel, a connect into + /// the channel without voice. `stream_peer` stays the engine's default, as + /// in [`AppState::connect_voice`]. + pub fn join_channel(&mut self, channel: ChannelId, cx: &mut Context) { + let Some(session) = self.vm.current else { return }; + self.transition_with(cx, |state, cx, backing| { + sequence::join_channel(state, cx, backing, session, channel, None) + }); + cx.notify(); + } + + /// The password prompt's Join ([`sequence::join_with_password`]). + pub fn join_with_password(&mut self, password: String, cx: &mut Context) { + self.password = None; + self.transition_with(cx, |state, cx, backing| { + sequence::join_with_password(state, cx, backing, password, None) + }); + cx.notify(); + } + + /// The password prompt was closed without joining. + pub fn cancel_password(&mut self, cx: &mut Context) { + self.password = None; + self.vm.join_target = None; + cx.notify(); + } + + /// The password prompt that is open: the locked channel's name as the tree + /// shows it, and whether the password given before was refused. + pub fn password_prompt(&self) -> Option<&PasswordPrompt> { + self.password.as_ref() + } + + /// Fold or unfold a channel of the tree (`toggle_collapse`), and remember + /// it for the server ([`UI_TREE`]). + pub fn toggle_collapse(&mut self, channel: ChannelId, cx: &mut Context) { + self.transition(cx, |state, cx| logic::toggle_collapse(state, cx, channel)); + self.remember_folds(); + cx.notify(); + } + + /// Select a channel of the tree, and remember it for the server. + pub fn select_channel(&mut self, channel: ChannelId, cx: &mut Context) { + let Some(id) = self.vm.current else { return }; + let state = self.tree_states.entry(id.to_string()).or_default(); + if state.selected == Some(channel) { + return; + } + state.selected = Some(channel); + self.keep_tree_states(); + self.signals.raise_area(Area::Tree, cx); + } + + /// The channel selected in the tree of the server on screen. + pub fn selected_channel(&self) -> Option { + let id = self.vm.current?; + self.tree_states.get(&id.to_string()).and_then(|state| state.selected) + } + + /// The members panel's search (`search_members`). + pub fn search_members(&mut self, text: String, cx: &mut Context) { + self.transition(cx, |state, cx| logic::search_members(state, cx, text)); + } + + /// Open the card of a client of the server on screen over the members + /// panel (`None` closes it). + pub fn open_member(&mut self, client: Option, cx: &mut Context) { + self.transition(cx, |state, cx| logic::open_member(state, cx, client)); + } + + /// Put the folds a server's tree remembered into its session, once. + fn restore_tree(&mut self, id: i64) { + if self.switches.demo_ui || !self.tree_restored.insert(id) { + return; + } + let Some(state) = self.tree_states.get(&id.to_string()).filter(|s| !s.collapsed.is_empty()) + else { + return; + }; + let collapsed = state.collapsed.iter().copied().collect(); + self.vm.sessions.entry(id).or_default().collapsed = collapsed; + } + + /// Remember which channels of the server on screen are folded. + fn remember_folds(&mut self) { + let Some(id) = self.vm.current else { return }; + let mut collapsed: Vec = self + .vm + .sessions + .get(&id) + .map(|view| view.collapsed.iter().copied().collect()) + .unwrap_or_default(); + collapsed.sort_unstable(); + let state = self.tree_states.entry(id.to_string()).or_default(); + if state.collapsed == collapsed { + return; + } + state.collapsed = collapsed; + if state.is_empty() { + self.tree_states.remove(&id.to_string()); + } + self.keep_tree_states(); + } + + /// Write what the trees remember to the settings (nothing in demo mode). + fn keep_tree_states(&self) { + if self.switches.demo_ui { + return; + } + if let Err(e) = self.backend.prefs.set(&UI_TREE, self.tree_states.clone()) { + warn!(%e, "could not store what the trees remember"); + } + } + /// The server dialog's form for a server (id -1: a new one). pub fn bookmark_form(&self, id: i64) -> BookmarkForm { sequence::bookmark_form(&self.vm, &self.backend.store, &*self.backend.secrets, id) @@ -833,6 +970,10 @@ impl AppState { self.transition_with(cx, |state, cx, backing| { sequence::delete_bookmark(state, cx, backing, id) }); + self.tree_restored.remove(&id); + if self.tree_states.remove(&id.to_string()).is_some() { + self.keep_tree_states(); + } cx.notify(); } diff --git a/crates/voelin-gpui/src/backend.rs b/crates/voelin-gpui/src/backend.rs index 914a76c..722367c 100644 --- a/crates/voelin-gpui/src/backend.rs +++ b/crates/voelin-gpui/src/backend.rs @@ -21,7 +21,9 @@ use voelin_core::settings::{AUDIO, Settings}; use voelin_core::{AudioSettings, Command, Engine, History, IdentityBlob}; use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store}; use voelin_ui_vm::servers::logic::CREATED_IDENTITY; -use voelin_ui_vm::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_WINDOW, UiSettings}; +use voelin_ui_vm::settings::{ + CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_TREE, UI_WINDOW, UiSettings, +}; /// The client's database, its settings and its secrets. pub struct Backend { @@ -67,10 +69,11 @@ fn open_settings(dir: &Path) -> Settings { voelin_ui_vm::settings::open_settings(dir, &[], register_own_keys) } -/// The key that only this front end uses: where the window was -/// (`ui.window`). +/// The keys that only this front end uses: where the window was +/// (`ui.window`) and what the channel trees remember (`ui.tree`). fn register_own_keys(prefs: &Settings) { prefs.register(&UI_WINDOW); + prefs.register(&UI_TREE); } impl Backend { diff --git a/crates/voelin-gpui/src/shell/actions.rs b/crates/voelin-gpui/src/shell/actions.rs index 243e153..15838ad 100644 --- a/crates/voelin-gpui/src/shell/actions.rs +++ b/crates/voelin-gpui/src/shell/actions.rs @@ -6,12 +6,13 @@ //! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings //! and menus come to the same handlers later. //! -//! The callbacks of `bind/servers.rs` that are not here belong to the slices -//! after this one: `search_members`, `show_voice_view`, `join_channel`, -//! `join_with_password`, `toggle_collapse`, `open_client` and -//! `client_audio_changed` to the channel tree and the voice page, and `copied` -//! (the toast that follows a copy) to whichever copies: [`Invite`] sets it -//! itself. +//! The channel tree and the members panel add `join_channel`, +//! `join_with_password`, `toggle_collapse`, `search_members`, `open_member` and +//! `open_client` (the last one only logs: the client's volume dialog is a +//! dialog of its own slice). The callbacks of `bind/servers.rs` that are +//! still not here belong to the slices after: `show_voice_view` to the voice +//! page, `client_audio_changed` to the dialogs, and `copied` (the toast that +//! follows a copy) to whichever copies: [`Invite`] sets it itself. use gpui_kit::{Action, actions}; @@ -36,6 +37,10 @@ actions!( OpenSearch, /// The settings buttons: the settings come with their slice, today it is logged. OpenSettings, + /// `join_with_password`: the password prompt's Join, with what it holds. + SubmitChannelPassword, + /// Close the password prompt without joining. + CancelChannelPassword, ] ); @@ -86,3 +91,63 @@ pub struct PushToTalk { /// Transmitting from now on. pub on: bool, } + +/// `join_channel`: join a channel of the server on screen (a double-click on +/// its row, the context menu's Join). +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct JoinChannel { + /// The channel's id on the server. + pub channel: u64, +} + +/// A click on a channel's row: select it (the Slint tree opens the channel's +/// chat, which comes with the chat slice). +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SelectChannel { + /// The channel's id on the server. + pub channel: u64, +} + +/// `toggle_collapse`: fold or unfold a channel of the tree. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct ToggleChannel { + /// The channel's id on the server. + pub channel: u64, +} + +/// The context menu's Edit channel: the channel editor is a slice of its own, +/// today it is logged. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct EditChannel { + /// The channel's id on the server. + pub channel: u64, +} + +/// `open_client`: a click on a person in the tree opens their volume dialog, +/// which is a dialog of its own slice: today it is logged. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct OpenClient { + /// The client's id on the server. + pub client: u16, +} + +/// `search_members`: the members panel's search text. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SearchMembers { + /// What the box holds; empty shows everyone. + pub text: String, +} + +/// `open_member`: open the card of a person over the members panel; -1 closes it. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct OpenMember { + /// The client's id on the server, or -1. + pub client: i32, +} diff --git a/crates/voelin-gpui/src/shell/channels.rs b/crates/voelin-gpui/src/shell/channels.rs new file mode 100644 index 0000000..c451820 --- /dev/null +++ b/crates/voelin-gpui/src/shell/channels.rs @@ -0,0 +1,427 @@ +//! The channel tree of the sidebar (`ChannelTree` of `screens/channels.slint`): +//! the channels of the server on screen with the people in them, nested, with +//! their spacers, pictures, passwords and counts, and the person's marks. +//! +//! A cached pane ([`gpui_kit::Entity::cached`], which needs the size the +//! sidebar gives it) over a virtual list ([`gpui_kit::list`]: only the rows in +//! view are built, the rows differ in height) that follows [`TreeModel`]: the +//! model says which rows changed ([`TreeEvent::Rows`]) and the pane tells its +//! list, so a person who joins is a row inserted and the scroll stays where it +//! was. The pane reads nothing but its own fields while it renders, so +//! nothing but its own notify draws it again. A click selects a channel, a +//! double-click joins it, the chevron folds it, a right-click offers the +//! same; a click on a person is logged (their volume dialog is a slice of +//! its own). + +use std::sync::Arc; + +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, +}; +use voelin_ui_vm::bridge::TreeItem; +use voelin_ui_vm::tree::ChannelId; + +use super::actions::{ + EditChannel, JoinChannel, OpenClient, OpenMember, SelectChannel, ToggleChannel, +}; +use super::tree_model::{Emptiness, TreeEvent, TreeModel}; +use super::widgets::{Avatar, icon, live_badge, small_picture}; +use crate::meter::Counters; +use crate::pictures::{PictureKey, picture}; +use crate::theme::{VoelinTheme, hsla}; + +/// How far each level of the tree is indented. +const INDENT: f32 = 14.0; + +/// The channel tree. +pub struct ChannelTree { + rows: Arc>, + selected: Option, + emptiness: Emptiness, + list: ListState, + /// The text size factor the list measured its rows at. + measured_at: f32, + counters: Counters, + _subscription: Subscription, +} + +impl ChannelTree { + /// A tree that follows `model`. + pub fn new(model: &Entity, counters: Counters, cx: &mut Context) -> Self { + let (rows, selected, emptiness) = { + let model = model.read(cx); + (model.rows().clone(), model.selected(), model.emptiness()) + }; + 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::Selection => this.selected = model.read(cx).selected(), + TreeEvent::Lists => this.emptiness = model.read(cx).emptiness(), + TreeEvent::People(_) | TreeEvent::Card => return, + } + cx.notify(); + }); + Self { + list: ListState::new(rows.len(), ListAlignment::Top, px(240.0)), + rows, + selected, + emptiness, + measured_at: 0.0, + counters, + _subscription: subscription, + } + } + + /// The rows it shows. + pub fn rows(&self) -> &[TreeItem] { + &self.rows + } + + /// The channel it shows selected. + pub fn selected(&self) -> Option { + 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). + fn apply(&mut self, changes: &voelin_ui_vm::list::Changes, new: Arc>) { + use voelin_ui_vm::list::Change; + + let mut channels: Vec = self.rows.iter().map(|row| row.is_channel).collect(); + for change in &changes.0 { + match *change { + Change::Update(i) => { + if channels[i] != new[i].is_channel { + self.list.splice(i..i + 1, 1); + } + channels[i] = new[i].is_channel; + } + Change::Remove(i) => { + channels.remove(i); + self.list.splice(i..i + 1, 0); + } + Change::Insert(i) => { + channels.insert(i, new[i].is_channel); + self.list.splice(i..i, 1); + } + } + } + self.rows = new; + } + + /// The row at `ix`, for the list. + fn row(&mut self, ix: usize, cx: &mut Context) -> AnyElement { + let theme = VoelinTheme::global(cx).clone(); + match self.rows.get(ix) { + Some(item) if item.is_channel => { + channel_row(&theme, item, self.selected == Some(item.id as ChannelId)) + } + Some(item) => client_row(&theme, item), + None => div().into_any_element(), + } + } +} + +/// The words of a tree with no rows. +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 chevron of a channel, which folds it. +fn chevron(item: &TreeItem, covered: bool, theme: &VoelinTheme) -> impl IntoElement { + let c = &theme.colors; + let id = item.id as ChannelId; + div() + .id(("tree-toggle", id)) + .debug_selector(move || format!("tree-toggle-{id}")) + .w(px(18.0)) + .h(px(18.0)) + .flex_none() + .flex() + .items_center() + .justify_center() + .on_click(move |_, window, cx| { + cx.stop_propagation(); + window.dispatch_action(Box::new(ToggleChannel { channel: id }), cx); + }) + .child(icon( + if item.collapsed { "chevron-right" } else { "chevron-down" }, + 14.0, + if covered { c.text } else { c.text_muted }, + )) +} + +/// One channel: its icon (or a speaker, or a lock), its name as the server +/// set it out, how many are in it, and the chevron. +fn channel_row(theme: &VoelinTheme, item: &TreeItem, selected: bool) -> AnyElement { + let (c, m) = (&theme.colors, &theme.metrics); + let id = item.id as ChannelId; + let indent = item.depth as f32 * INDENT; + let banner = PictureKey::of(&item.banner); + let covered = banner.is_some(); + let strong = item.own || covered; + let (hover, accent_soft, accent, selected_fill) = + (hsla(c.surface_3), hsla(c.accent_soft), hsla(c.accent), hsla(c.surface_3)); + let own = item.own; + let has_icon = PictureKey::of(&item.icon).is_some(); + let name_color = if strong { c.text } else { c.text_secondary }; + let weight = if strong { FontWeight::SEMIBOLD } else { FontWeight::MEDIUM }; + let name = div() + .flex_1() + .min_w_0() + .text_size(px(m.font_body)) + .font_weight(weight) + .text_color(hsla(name_color)) + .when(item.spacer == 2, |name| name.text_center()) + .when(item.spacer == 3, |name| name.text_right()) + // A line is cut where the row ends; it does not widen the list. + .when(item.spacer == 4, |name| name.overflow_hidden().whitespace_nowrap()) + .when(item.spacer != 4, |name| name.truncate()) + .child(item.name.to_string()); + let counted = item.spacer == 0 && (item.members > 0 || item.max_members >= 0); + let count = if item.max_members >= 0 { + format!("{}/{}", item.members, item.max_members) + } else { + item.members.to_string() + }; + let row = div() + .id(("tree-channel", id)) + .debug_selector(move || format!("tree-channel-{id}")) + .relative() + .w_full() + .h(px(34.0 * m.font_scale)) + .flex_none() + .overflow_hidden() + .rounded(px(m.radius_md)) + .cursor_pointer() + .when(own, |row| row.bg(accent_soft).border_1().border_color(accent)) + .when(!own && selected, |row| row.bg(selected_fill)) + .when(!own && !selected, |row| row.hover(move |style| style.bg(hover))) + // Artwork behind the same compact row as its title, from the indent on. + .when_some(banner, |row, key| { + row.child( + div() + .absolute() + .top(px(0.0)) + .bottom(px(0.0)) + .left(px(indent)) + .right(px(0.0)) + .child(picture(key).size_full().object_fit(ObjectFit::Cover)), + ) + .when(own, |row| { + row.child( + div() + .absolute() + .top(px(0.0)) + .bottom(px(0.0)) + .left(px(indent)) + .right(px(0.0)) + .rounded(px(m.radius_md)) + .bg(accent_soft.opacity(0.65)), + ) + }) + }) + .flex() + .flex_row() + .items_center() + .pl(px(m.space_2 + indent)) + .pr(px(m.space_3)) + .gap(px(m.space_2)) + // A centred spacer is balanced against the chevron. + .when(item.spacer == 2, |row| row.child(div().w(px(18.0)).flex_none())) + .when(item.spacer == 0, |row| match small_picture(&item.icon, 16.0) { + Some(picture) => row.child(picture), + None => row.child(icon( + if item.locked { "lock" } else { "volume-2" }, + 18.0, + if strong { c.text } else { c.icon }, + )), + }) + .child(name) + .when(item.locked && (has_icon || item.spacer != 0), |row| { + row.child(icon("lock", 14.0, if covered { c.text } else { c.icon })) + }) + .when(counted, |row| { + row.child( + div() + .flex_none() + .flex() + .flex_row() + .items_center() + .gap(px(3.0)) + .when(own, |count| count.child(icon("users", 14.0, c.text_secondary))) + .child( + div() + .text_size(px(m.font_sm)) + .text_color(hsla(if strong { c.text } else { c.text_muted })) + .child(count), + ), + ) + }) + .child(chevron(item, covered, theme)) + .on_click(move |event, window, cx| { + if event.click_count() >= 2 { + window.dispatch_action(Box::new(JoinChannel { channel: id }), cx); + } else { + window.dispatch_action(Box::new(SelectChannel { channel: id }), cx); + } + }) + .context_menu(move |menu, _, _| { + menu.menu("Join channel", Box::new(JoinChannel { channel: id })) + .menu("Fold or unfold", Box::new(ToggleChannel { channel: id })) + .separator() + .menu("Edit channel…", Box::new(EditChannel { channel: id })) + }); + row.into_any_element() +} + +/// One person: their avatar, name and badges, and the marks of what they do. +fn client_row(theme: &VoelinTheme, item: &TreeItem) -> AnyElement { + let (c, m) = (&theme.colors, &theme.metrics); + let id = item.id as u64; + let indent = item.depth as f32 * INDENT; + let (hover, myself) = (hsla(c.surface_3), item.myself); + let name_color = if item.away { + c.text_muted + } else if myself { + c.accent_text + } else { + c.text_secondary + }; + let mark = |name: &'static str, color| icon(name, 14.0, color); + div() + .id(("tree-client", id)) + .debug_selector(move || format!("tree-client-{id}")) + .w_full() + .h(px(30.0 * m.font_scale)) + .flex_none() + .rounded(px(m.radius_md)) + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .flex() + .flex_row() + .items_center() + .pl(px(m.space_2 + indent + 12.0)) + .pr(px(m.space_3)) + .gap(px(m.space_3)) + .child( + Avatar::new(("tree-avatar", id), 22.0, &item.initials, item.tint) + .image(item.avatar.clone()), + ) + .child( + div() + .min_w_0() + .truncate() + .text_size(px(m.font_body)) + .font_weight(if myself { FontWeight::SEMIBOLD } else { FontWeight::NORMAL }) + .text_color(hsla(name_color)) + .child(item.name.to_string()), + ) + // Badges after the name, then the free room. + .child( + div().flex_1().min_w_0().flex().flex_row().items_center().gap(px(2.0)).children( + [&item.badge, &item.badge_2, &item.badge_3] + .into_iter() + .filter_map(|badge| small_picture(badge, 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| { + row.child( + div() + .text_size(px(m.font_xs)) + .text_color(hsla(c.text_muted)) + .child(format!("{}%", item.local_volume)), + ) + }) + .when(item.muted, |row| row.child(mark("mic-off", c.danger))) + .when(item.sound_off, |row| row.child(mark("headphone-off", c.danger))) + .when(item.away, |row| { + row.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child("away")) + }) + .children( + [&item.icon, &item.icon_2, &item.icon_3] + .into_iter() + .filter_map(|i| small_picture(i, 16.0)), + ) + .on_click(move |_, window, cx| { + if !myself { + window.dispatch_action(Box::new(OpenClient { client: id as u16 }), cx); + } + }) + .context_menu(move |menu, _, _| { + menu.menu("Show the card", Box::new(OpenMember { client: id as i32 })) + .menu("Volume…", Box::new(OpenClient { client: id as u16 })) + }) + .into_any_element() +} + +impl Render for ChannelTree { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.counters.panes.tree.incr(); + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + // A new text size makes the rows another height. + 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; + } + div() + .id("sidebar-channels") + .debug_selector(|| "sidebar-channels".into()) + .size_full() + .flex() + .flex_col() + .gap(px(m.space_2)) + .px(px(m.space_2)) + .child( + div() + .min_h(px(24.0)) + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .text_size(px(m.font_sm)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text_secondary)) + .child(icon("volume-2", m.icon_sm, c.text_secondary)) + .child("Channels"), + ) + .map(|pane| { + if self.rows.is_empty() { + pane.child( + div() + .id("tree-empty") + .debug_selector(|| "tree-empty".into()) + .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.row(ix, cx)), + ) + .flex_1() + .w_full() + .min_h_0(), + ) + } + }) + } +} diff --git a/crates/voelin-gpui/src/shell/main_panel.rs b/crates/voelin-gpui/src/shell/main_panel.rs index 4d90ed1..596844b 100644 --- a/crates/voelin-gpui/src/shell/main_panel.rs +++ b/crates/voelin-gpui/src/shell/main_panel.rs @@ -1,8 +1,9 @@ -//! The main area. Until the chat, the voice page and the rest come, it is the +//! The main area. Until the voice page, the chat and the rest come, it is the //! empty page: the "no server selected" state with the way to add one, and for //! a server on screen its name, address and state with the buttons that -//! connect, disconnect and edit it. An entity of its own: it observes the root -//! state and tells the window only when what it shows changed. +//! connect, disconnect and edit it. An entity of its own, drawn as a cached +//! pane: it listens to the servers' signal and tells the window only when +//! what it shows changed. use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::prelude::FluentBuilder as _; @@ -172,7 +173,7 @@ impl Render for MainPanel { .text_center() .text_size(px(m.font_body)) .text_color(hsla(c.text_muted)) - .child("Its channels and its chat come with the next slices."), + .child("Its chat and its voice page come with the next slices."), ) .child( div() @@ -212,13 +213,8 @@ impl Render for MainPanel { ) } }; - panel(&theme) - .id("main") - .flex_1() - .min_w_0() - .h_full() - .items_center() - .justify_center() - .child(body) + // The root of a cached pane takes the size its place gives it: laid out + // on its own, `flex_1` would be as wide as its contents. + panel(&theme).id("main").size_full().items_center().justify_center().child(body) } } diff --git a/crates/voelin-gpui/src/shell/mod.rs b/crates/voelin-gpui/src/shell/mod.rs index f389cf9..b5a577a 100644 --- a/crates/voelin-gpui/src/shell/mod.rs +++ b/crates/voelin-gpui/src/shell/mod.rs @@ -9,17 +9,23 @@ //! changed; [`crate::view::MainView`] puts them in the window. pub mod actions; +mod channels; mod form; mod main_panel; +mod password; mod rail; mod sidebar; mod toast; mod topbar; +mod tree_model; pub mod widgets; +pub use channels::ChannelTree; pub use form::ServerForm; pub use main_panel::{MainPanel, MainState}; +pub use password::ChannelPassword; pub use rail::{RailView, ServerRail}; pub use sidebar::{Sidebar, SidebarView}; pub use toast::{TOAST_TIME, Toast}; pub use topbar::TopBar; +pub use tree_model::{Emptiness, TreeEvent, TreeModel}; diff --git a/crates/voelin-gpui/src/shell/password.rs b/crates/voelin-gpui/src/shell/password.rs new file mode 100644 index 0000000..627dbca --- /dev/null +++ b/crates/voelin-gpui/src/shell/password.rs @@ -0,0 +1,139 @@ +//! The password prompt of a locked channel (`ChannelPasswordDialog` of +//! `screens/dialogs.slint`): what the transitions ask for with +//! `Update::password` when a channel with a password is joined and the one +//! given this connection (if any) is not at hand, or was refused. It is a +//! card over the window with a scrim; until the dialogs slice makes every +//! dialog one, it is this view's own. + +use gpui_kit::component::button::{Button, ButtonVariants as _}; +use gpui_kit::component::input::{Input, InputEvent, InputState}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + App, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement, + ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Window, + div, px, +}; +use voelin_ui_vm::host::PasswordPrompt; + +use super::actions::{CancelChannelPassword, SubmitChannelPassword}; +use super::widgets::tagged; +use crate::theme::{VoelinTheme, hsla}; + +/// The prompt for the password of one channel. +pub struct ChannelPassword { + channel: String, + wrong: bool, + input: Entity, +} + +impl ChannelPassword { + /// A prompt for what `ask` names, with the field focused: Enter joins. + pub fn new(ask: &PasswordPrompt, window: &mut Window, cx: &mut Context) -> Self { + let input = cx.new(|cx| { + InputState::new(window, cx).placeholder(SharedString::from("Password")).masked(true) + }); + cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + window.dispatch_action(Box::new(SubmitChannelPassword), cx); + } + }) + .detach(); + input.update(cx, |input, cx| input.focus(window, cx)); + Self { channel: ask.name.clone(), wrong: ask.wrong, input } + } + + /// The channel it asks for. + pub fn channel(&self) -> &str { + &self.channel + } + + /// Whether it says that the last password was refused. + pub fn wrong(&self) -> bool { + self.wrong + } + + /// What the field holds. + pub fn text(&self, cx: &App) -> String { + self.input.read(cx).value().to_string() + } + + /// Type `text` in the field (the tests type here). + pub fn set_text(&self, text: &str, window: &mut Window, cx: &mut App) { + self.input.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx)); + } +} + +impl Render for ChannelPassword { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let (c, m) = (&theme.colors, &theme.metrics); + div() + .id("password-prompt") + .debug_selector(|| "password-prompt".into()) + .absolute() + .top(px(0.0)) + .left(px(0.0)) + .size_full() + .flex() + .items_center() + .justify_center() + .bg(hsla(c.scrim)) + // A click outside the card closes the prompt. + .on_click(|_, window, cx| window.dispatch_action(Box::new(CancelChannelPassword), cx)) + .child( + div() + .id("password-card") + .w(px(380.0)) + .flex() + .flex_col() + .gap(px(m.space_4)) + .p(px(m.space_5)) + .rounded(px(m.radius_lg)) + .border_1() + .border_color(hsla(c.border_popup)) + .bg(hsla(c.surface_3)) + .on_click(|_, _, cx| cx.stop_propagation()) + .child( + div() + .text_size(px(m.font_lg)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(format!("{} has a password", self.channel)), + ) + .when(self.wrong, |card| { + card.child( + div() + .id("password-wrong") + .debug_selector(|| "password-wrong".into()) + .text_size(px(m.font_sm)) + .text_color(hsla(c.danger)) + .child("That password was not accepted. Try again."), + ) + }) + .child(Input::new(&self.input)) + .child( + div() + .flex() + .flex_row() + .justify_end() + .gap(px(m.space_3)) + .child(tagged( + "password-cancel", + Button::new("password-cancel").ghost().label("Cancel").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(CancelChannelPassword), cx) + }, + ), + )) + .child(tagged( + "password-join", + Button::new("password-join").primary().label("Join").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(SubmitChannelPassword), cx) + }, + ), + )), + ), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/sidebar.rs b/crates/voelin-gpui/src/shell/sidebar.rs index 7e1cba7..e9edad2 100644 --- a/crates/voelin-gpui/src/shell/sidebar.rs +++ b/crates/voelin-gpui/src/shell/sidebar.rs @@ -1,14 +1,15 @@ //! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of -//! `shells/common.slint`): the server on screen, the place of its channel tree -//! (the next slice), the voice card while voice is connecting or connected, and -//! the user's own card with the voice buttons. An entity of its own: it -//! observes the root state and tells the window only when what it shows changed. +//! `shells/common.slint`): the server on screen, its channel tree +//! ([`super::ChannelTree`], a cached pane of its own), the voice card while +//! voice is connecting or connected, and the user's own card with the voice +//! buttons. An entity of its own: it listens to the servers' and the toolbar's +//! signals and tells the window only when what it shows changed. use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent, - ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, Subscription, Window, - div, px, + ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Subscription, Window, div, px, }; use voelin_core::TransmitMode; use voelin_ui_vm::Rgb; @@ -19,6 +20,7 @@ use voelin_ui_vm::servers::logic; use super::actions::{ DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted, }; +use super::channels::ChannelTree; use super::widgets::{Avatar, IconButton, Presence, card, icon, panel}; use crate::app::AppState; use crate::meter::Counters; @@ -83,6 +85,9 @@ impl SidebarView { /// The sidebar. pub struct Sidebar { view: SidebarView, + /// The channel tree, a pane of its own between the server card and the + /// voice card. + tree: Entity, /// The hold-to-talk button is held down. holding: bool, counters: Counters, @@ -91,8 +96,8 @@ pub struct Sidebar { impl Sidebar { /// A sidebar that follows the server on screen and the voice state in - /// `app`. - pub fn new(app: &Entity, cx: &mut Context) -> Self { + /// `app`, with `tree` between its cards. + pub fn new(app: &Entity, tree: Entity, cx: &mut Context) -> Self { let (view, counters, signals) = { let state = app.read(cx); (SidebarView::of(state), state.counters().clone(), state.signals().clone()) @@ -105,7 +110,7 @@ impl Sidebar { cx.notify(); } }); - Self { view, holding: false, counters, _subscriptions: subscriptions } + Self { view, tree, holding: false, counters, _subscriptions: subscriptions } } /// What it shows now. @@ -162,36 +167,6 @@ fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> im ) } -/// Where the channel tree goes: the next slice. -fn channels(theme: &VoelinTheme, has_server: bool) -> impl IntoElement { - let (c, m) = (&theme.colors, &theme.metrics); - div() - .id("sidebar-channels") - .flex_1() - .min_h_0() - .flex() - .flex_col() - .gap(px(m.space_2)) - .px(px(m.space_2)) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(px(m.space_2)) - .text_size(px(m.font_xs)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(hsla(c.text_secondary)) - .child(icon("volume-2", m.icon_sm, c.text_secondary)) - .child("Channels"), - ) - .child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(if has_server { - "The channel tree comes with the next slice." - } else { - "Add a server to see its channels." - })) -} - /// "Voice Connected" and our channel, disconnect and hold to talk. fn voice_card( theme: &VoelinTheme, @@ -422,7 +397,8 @@ impl Render for Sidebar { .when_some(view.server.as_ref(), |sidebar, item| { sidebar.child(server_card(&theme, view, item)) }) - .child(channels(&theme, view.server.is_some())) + // The tree has the room the cards leave, whatever their height. + .child(self.tree.clone().cached(StyleRefinement::default().flex_1().min_h_0().w_full())) .when(view.voice_connected || view.voice_connecting, |sidebar| { sidebar.child(voice_card(&theme, view, cx)) }) diff --git a/crates/voelin-gpui/src/shell/tree_model.rs b/crates/voelin-gpui/src/shell/tree_model.rs new file mode 100644 index 0000000..dd881cb --- /dev/null +++ b/crates/voelin-gpui/src/shell/tree_model.rs @@ -0,0 +1,211 @@ +//! The narrow entity behind the channel tree and the members panel: what +//! `voelin_ui_vm::servers::logic::tree_view` makes of the state, kept between +//! one change and the next so that the two panes can be told what changed. +//! +//! It listens to the tree, toolbar and member-card signals +//! ([`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. +//! +//! **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. + +use std::sync::Arc; + +use gpui_kit::{Context, Entity, EventEmitter, Subscription}; +use voelin_core::ObserveState; +use voelin_ui_vm::bridge::{MemberCard, MemberItem, TreeItem}; +use voelin_ui_vm::list::{Changes, diff}; +use voelin_ui_vm::servers::logic; +use voelin_ui_vm::tree::{ChannelId, member_card}; + +use crate::app::{AppState, VmState}; +use crate::signals::Area; + +/// Why a list has no rows, which the pane says in words. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Emptiness { + /// No server is on screen. + NoServer, + /// The server is observed and its presence is on the way. + Loading, + /// Nothing is known of the server until it is connected. + Connect, +} + +impl Emptiness { + /// Why the lists of the server on screen are empty. + 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, + _ => Self::Connect, + }, + } + } +} + +/// What changed in the model, as the panes need it. +#[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 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`]). + Lists, +} + +/// 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, + rows: Arc>, + people: Arc>, + total: i32, + card: Option, + selected: Option, + emptiness: Emptiness, + _subscriptions: Vec, +} + +impl EventEmitter for TreeModel {} + +/// Everything the model keeps, as the state gives it now. +struct Snapshot { + rows: Vec, + people: Vec, + total: i32, + card: Option, + selected: Option, + 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) { + 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 { + rows, + people, + total, + card: view + .and_then(|view| view.member_card.map(|id| (view, id))) + .and_then(|(view, id)| member_card(view, id, &vm.contacts, &vm.playback)), + selected: app.selected_channel(), + emptiness: Emptiness::of(vm), + } + } +} + +impl TreeModel { + /// A model of what `app` shows now, following its tree signals. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let (snapshot, signals) = { + 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), + ); + Self { + app: app.clone(), + rows: Arc::new(snapshot.rows), + people: Arc::new(snapshot.people), + total: snapshot.total, + card: snapshot.card, + selected: snapshot.selected, + emptiness: snapshot.emptiness, + _subscriptions: subscriptions, + } + } + + /// The rows of the channel tree: channels with the clients in them. + pub fn rows(&self) -> &Arc> { + &self.rows + } + + /// The rows of the members panel: everyone on the server, in sections. + pub fn people(&self) -> &Arc> { + &self.people + } + + /// How many are on the server (the query clients not counted). + pub fn total(&self) -> i32 { + self.total + } + + /// The card over a member row, when one is open. + pub fn card(&self) -> Option<&MemberCard> { + self.card.as_ref() + } + + /// The channel selected in the tree. + pub fn selected(&self) -> Option { + self.selected + } + + /// Why the lists are empty, were they. + pub fn emptiness(&self) -> Emptiness { + self.emptiness + } + + /// Build the rows again, and tell the panes what differs. + fn refresh(&mut self, cx: &mut Context) { + let new = Snapshot::of(self.app.read(cx)); + let rows = diff(&self.rows, &new.rows); + let people = diff(&self.people, &new.people); + if !rows.is_empty() { + self.rows = Arc::new(new.rows); + } + 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 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)); + } + if !people.is_empty() { + cx.emit(TreeEvent::People(people)); + } + if lists { + cx.emit(TreeEvent::Lists); + } + if card { + cx.emit(TreeEvent::Card); + } + if selection { + cx.emit(TreeEvent::Selection); + } + } +} diff --git a/crates/voelin-gpui/src/shell/widgets.rs b/crates/voelin-gpui/src/shell/widgets.rs index e7af93e..249ac05 100644 --- a/crates/voelin-gpui/src/shell/widgets.rs +++ b/crates/voelin-gpui/src/shell/widgets.rs @@ -5,8 +5,9 @@ //! `shells/common.slint`'s `Panel`. use gpui_kit::{ - App, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, - RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px, svg, + AnyElement, App, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, + ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, + Window, div, px, svg, }; use gpui_kit::{ElementId, ObjectFit, StyledImage as _}; use voelin_ui_vm::Rgb; @@ -356,3 +357,88 @@ pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div { pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement { div().flex_none().debug_selector(|| selector.into()).child(element) } + +/// A picture of the cache in its own colours, `size` pixels square (a group's +/// or a client's icon, a badge); none when it is no picture that shows. +pub fn small_picture(image: &ImageRef, size: f32) -> Option { + let key = PictureKey::of(image)?; + Some( + picture(key) + .w(px(size)) + .h(px(size)) + .flex_none() + .object_fit(ObjectFit::Contain) + .into_any_element(), + ) +} + +/// The red LIVE tag. +pub fn live_badge(theme: &VoelinTheme) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .h(px(18.0)) + .px(px(5.0)) + .flex_none() + .flex() + .items_center() + .rounded(px(m.radius_xs)) + .bg(hsla(c.live)) + .text_size(px(m.font_xs)) + .font_weight(FontWeight::BOLD) + .text_color(hsla(Rgba(0xffff_ffff))) + .child("LIVE") +} + +/// Three bars: someone speaks. (The Slint bars move; these stand still, as +/// nothing here may draw the window anew with the clock.) +pub fn speaking_bars(theme: &VoelinTheme, size: f32) -> impl IntoElement { + let c = &theme.colors; + let bar = move |height: f32| { + div() + .w(px(size * 3.0 / 14.0)) + .h(px(size * height)) + .rounded(px(size / 9.0)) + .bg(hsla(c.success)) + }; + div() + .w(px(size)) + .h(px(size)) + .flex_none() + .flex() + .flex_row() + .items_center() + .justify_between() + .child(bar(1.0)) + .child(bar(0.6)) + .child(bar(0.8)) +} + +/// A small rounded label: a role, a fact (talk power, a country), a badge. +/// `picture` is a badge's own picture, `icon` a Lucide icon in the label's +/// colour. +pub fn chip( + theme: &VoelinTheme, + text: impl Into, + icon_name: Option<&'static str>, + picture: Option, +) -> gpui_kit::Div { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .h(px(22.0)) + .px(px(m.space_3)) + .flex_none() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .rounded(px(m.radius_pill)) + .border_1() + .border_color(hsla(c.border_strong)) + .bg(hsla(c.surface_3)) + .text_size(px(m.font_xs)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(c.text_secondary)) + .children(icon_name.map(|name| icon(name, 12.0, c.text_secondary).into_any_element())) + .children(picture) + .child(text.into()) +} diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index 463dae1..f6f8b4a 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -16,11 +16,15 @@ use crate::app::AppState; use crate::dev::Page; use crate::meter::Counters; use crate::shell::actions::{ - AddServer, CancelServerForm, ConnectVoice, DeleteServer, DisconnectVoice, EditServer, Invite, - OpenSearch, OpenSettings, PushToTalk, SaveAndConnect, SaveServer, SelectServer, SetInputMuted, - SetOutputMuted, + AddServer, CancelChannelPassword, CancelServerForm, ConnectVoice, DeleteServer, + DisconnectVoice, EditChannel, EditServer, Invite, JoinChannel, OpenClient, OpenMember, + OpenSearch, OpenSettings, PushToTalk, SaveAndConnect, SaveServer, SearchMembers, SelectChannel, + SelectServer, SetInputMuted, SetOutputMuted, SubmitChannelPassword, ToggleChannel, +}; +use crate::shell::{ + ChannelPassword, ChannelTree, MainPanel, ServerForm, ServerRail, Sidebar, Toast, TopBar, + TreeModel, }; -use crate::shell::{MainPanel, ServerForm, ServerRail, Sidebar, Toast, TopBar}; use crate::swatch::swatch; use crate::theme::{VoelinTheme, hsla}; @@ -53,9 +57,15 @@ pub struct MainView { rail: Entity, topbar: Entity, sidebar: Entity, + model: Entity, + tree: Entity, main: Entity, toast: Entity, form: Option>, + /// The prompt for a locked channel's password, when one is open, and how + /// many prompts the root state had asked for when it was made. + prompt: Option>, + prompt_generation: u64, title: String, focus: FocusHandle, _subscriptions: Vec, @@ -99,6 +109,17 @@ impl MainView { this.form = None; cx.notify(); } + // A channel's password was asked for. + let (generation, ask) = { + let app = app.read(cx); + (app.password_generation, app.password_prompt().cloned()) + }; + if generation != this.prompt_generation { + this.prompt_generation = generation; + this.prompt = + ask.map(|ask| cx.new(|cx| ChannelPassword::new(&ask, window, cx))); + cx.notify(); + } }), cx.observe_window_bounds(window, |this, window, cx| report(&this.app, window, cx)), ]; @@ -108,16 +129,23 @@ impl MainView { if app.read(cx).awaiting_maximize() { window.on_next_frame(maximize); } + let prompt_generation = app.read(cx).password_generation; + let model = cx.new(|cx| TreeModel::new(&app, cx)); + let tree = cx.new(|cx| ChannelTree::new(&model, counters.clone(), cx)); Self { rail: cx.new(|cx| ServerRail::new(&app, cx)), topbar: cx.new(|cx| TopBar::new(&app, cx)), - sidebar: cx.new(|cx| Sidebar::new(&app, cx)), + sidebar: cx.new(|cx| Sidebar::new(&app, tree.clone(), cx)), + model, + tree, main: cx.new(|cx| MainPanel::new(&app, cx)), toast: cx.new(|cx| Toast::new(&app, cx)), app, page, counters, form: None, + prompt: None, + prompt_generation, title, focus, _subscriptions: subscriptions, @@ -129,6 +157,16 @@ impl MainView { self.form.as_ref() } + /// What the channel tree and the members panel are made from. + pub fn tree_model(&self) -> &Entity { + &self.model + } + + /// The channel tree. + pub fn channel_tree(&self) -> &Entity { + &self.tree + } + /// Open the form with `form`'s values. fn open_form( &mut self, @@ -222,6 +260,70 @@ impl MainView { cx.notify(); } + fn join_channel(&mut self, action: &JoinChannel, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.join_channel(action.channel, cx)); + } + + fn select_channel(&mut self, action: &SelectChannel, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.select_channel(action.channel, cx)); + } + + fn toggle_channel(&mut self, action: &ToggleChannel, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.toggle_collapse(action.channel, cx)); + } + + fn edit_channel(&mut self, action: &EditChannel, _: &mut Window, _: &mut Context) { + tracing::info!( + channel = action.channel, + "the channel editor comes with its slice (docs/ui.md, \"What is next\")" + ); + } + + fn open_client(&mut self, action: &OpenClient, _: &mut Window, _: &mut Context) { + tracing::info!( + client = action.client, + "the client's volume dialog comes with the dialogs slice (docs/ui.md, \"What is next\")" + ); + } + + fn search_members(&mut self, action: &SearchMembers, _: &mut Window, cx: &mut Context) { + self.app.update(cx, |app, cx| app.search_members(action.text.clone(), cx)); + } + + fn open_member(&mut self, action: &OpenMember, _: &mut Window, cx: &mut Context) { + let client = u16::try_from(action.client).ok(); + self.app.update(cx, |app, cx| app.open_member(client, cx)); + } + + /// The prompt's Join: the password in its field goes with the join. + fn submit_channel_password( + &mut self, + _: &SubmitChannelPassword, + _: &mut Window, + cx: &mut Context, + ) { + let Some(prompt) = self.prompt.take() else { return }; + let password = prompt.read(cx).text(cx); + self.app.update(cx, |app, cx| app.join_with_password(password, cx)); + cx.notify(); + } + + fn cancel_channel_password( + &mut self, + _: &CancelChannelPassword, + _: &mut Window, + cx: &mut Context, + ) { + self.prompt = None; + self.app.update(cx, |app, cx| app.cancel_password(cx)); + cx.notify(); + } + + /// The prompt for a locked channel's password, when one is open. + pub fn password_prompt(&self) -> Option<&Entity> { + self.prompt.as_ref() + } + fn open_search(&mut self, _: &OpenSearch, _: &mut Window, _: &mut Context) { tracing::info!("the search comes with its slice (docs/ui.md, \"What is next\")"); } @@ -308,6 +410,15 @@ impl Render for MainView { .on_action(cx.listener(Self::save_and_connect)) .on_action(cx.listener(Self::cancel_form)) .on_action(cx.listener(Self::delete_server)) + .on_action(cx.listener(Self::join_channel)) + .on_action(cx.listener(Self::select_channel)) + .on_action(cx.listener(Self::toggle_channel)) + .on_action(cx.listener(Self::edit_channel)) + .on_action(cx.listener(Self::open_client)) + .on_action(cx.listener(Self::search_members)) + .on_action(cx.listener(Self::open_member)) + .on_action(cx.listener(Self::submit_channel_password)) + .on_action(cx.listener(Self::cancel_channel_password)) .on_action(cx.listener(Self::open_search)) .on_action(cx.listener(Self::open_settings)) .child( @@ -338,6 +449,7 @@ impl Render for MainView { .child(main), ), ) + .children(self.prompt.clone()) .child(self.toast.clone()) } } @@ -348,21 +460,25 @@ mod tests { use std::rc::Rc; use std::time::Duration; + use std::cell::RefCell; + use std::sync::Arc; + use gpui::{TestAppContext, VisualTestContext}; - use gpui_kit::{Bounds, WindowAppearance, point, size}; + use gpui_kit::{Bounds, MouseDownEvent, MouseUpEvent, WindowAppearance, point, size}; use tokio::sync::mpsc::{self, UnboundedSender}; use voelin_core::{Command, Event, SessionState, VoiceState}; use voelin_store::{Bookmark, MemorySecrets}; - use voelin_ui_vm::bridge::BookmarkForm; + use voelin_ui_vm::bridge::{BookmarkForm, TreeItem}; use voelin_ui_vm::dev::logic as sample; - use voelin_ui_vm::settings::UI_WINDOW; + use voelin_ui_vm::list::{Change, Changes}; + use voelin_ui_vm::settings::{TreeState, TreeStates, UI_TREE, UI_WINDOW}; use super::*; use crate::app::Setup; use crate::backend::Backend; use crate::backend::testing::TempDir; use crate::dev::Switches; - use crate::shell::RailView; + use crate::shell::{RailView, TreeEvent}; use crate::theme::Choice; use crate::window_bounds; @@ -701,6 +817,374 @@ mod tests { ); } + /// A server as an engine reports one: the sample server's events (nested + /// channels, spacers, a locked channel, people with groups) played into the + /// window, its bookmark the one shown. Voice is up and we are in Chill Zone. + fn sample_server(shell: &Shell, cx: &mut VisualTestContext) { + shell.app.update(cx, |app, _| { + app.vm.bookmarks = sample::bookmarks(); + app.vm.current = Some(sample::DEMO); + }); + for event in sample::server_events() { + shell.events.send(event).unwrap(); + } + frame(cx); + } + + /// The tree's rows as the model has them. + fn tree_rows(shell: &Shell, cx: &mut VisualTestContext) -> Arc> { + shell.view.read_with(cx, |view, cx| view.tree_model().read(cx).rows().clone()) + } + + /// What the rows are: `C` a channel and `P` a person, the depth, the name + /// (the line of a fill spacer is `-`). + fn shape(rows: &[TreeItem]) -> Vec { + rows.iter() + .map(|r| { + let name = if r.spacer == 4 { "-" } else { r.name.as_ref() }; + format!("{}{} {name}", if r.is_channel { "C" } else { "P" }, r.depth) + }) + .collect() + } + + /// The sample server's `Event::Presence` with `$body` applied to the + /// presence, named `$p` (a macro: `voelin_core` does not name its type). + macro_rules! presence_changed { + ($p:ident => $body:expr) => {{ + let Some(Event::Presence { session, mut presence }) = + sample::server_events().into_iter().find(|e| matches!(e, Event::Presence { .. })) + else { + panic!("the sample server has a presence") + }; + { + let $p = Arc::make_mut(&mut presence); + $body; + } + Event::Presence { session, presence } + }}; + } + + /// What the model tells its panes from now on. + fn tree_events( + shell: &Shell, + cx: &mut VisualTestContext, + ) -> (Rc>>, gpui_kit::Subscription) { + let log: Rc>> = Rc::default(); + let model = shell.view.read_with(cx, |view, _| view.tree_model().clone()); + let subscription = cx.update(|_, cx| { + let log = log.clone(); + cx.subscribe(&model, move |_, event: &TreeEvent, _| { + log.borrow_mut().push(event.clone()) + }) + }); + (log, subscription) + } + + /// The row operations the model told the tree. + fn rows_told(log: &Rc>>) -> Vec { + log.borrow() + .iter() + .filter_map(|event| match event { + TreeEvent::Rows(changes) => Some(changes.clone()), + _ => None, + }) + .collect() + } + + /// Two clicks on the element: a double-click as the platform counts one. + fn double_click(cx: &mut VisualTestContext, selector: &str) { + let position = + at(cx, selector).unwrap_or_else(|| panic!("{selector} is not on screen")).center(); + for click_count in [1, 2] { + cx.simulate_event(MouseDownEvent { + position, + modifiers: Default::default(), + button: gpui_kit::MouseButton::Left, + click_count, + first_mouse: false, + }); + cx.simulate_event(MouseUpEvent { + position, + modifiers: Default::default(), + button: gpui_kit::MouseButton::Left, + click_count, + }); + } + frame(cx); + } + + /// 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. + #[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()); + assert!(at(cx, "tree-empty").is_some(), "no server: the tree says so"); + sample_server(&shell, cx); + let rows = tree_rows(&shell, cx); + assert_eq!( + shape(&rows), + [ + "C0 Lobby", + "P1 Rin", + "C0 Chill Zone", + "P1 dex", + "P1 Kairo", + "P1 Lumen", + "P1 Mira", + "P1 Nova", + "C0 Gaming", + "P1 Talon", + "C1 Raid Night", + "P2 Zeph", + "C0 Music", + "C0 Staff", + "C0 Officers", + "C0 -", + "C0 AFK", + "P1 Blaze", + ] + ); + let channel = |name: &str| rows.iter().find(|r| &*r.name == name).unwrap(); + let chill = channel("Chill Zone"); + assert!(chill.own, "we are in Chill Zone"); + assert_eq!((chill.members, chill.max_members), (5, 50)); + 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"); + assert!(at(cx, "tree-empty").is_none()); + for row in rows.iter() { + let selector = if row.is_channel { + format!("tree-channel-{}", row.id) + } else { + format!("tree-client-{}", row.id) + }; + assert!(at(cx, &selector).is_some(), "{selector} is on screen"); + } + // The rows the sidebar holds are the model's. + let pane = + shell.view.read_with(cx, |view, cx| view.channel_tree().read(cx).rows().to_vec()); + assert_eq!(pane, *rows); + } + + /// Folding a channel takes its people out of the tree and the chevron + /// brings them back; what is folded is remembered for the server in + /// `ui.tree`, and a click on the chevron selects nothing. + #[gpui::test] + fn a_folded_channel_hides_its_people_and_is_kept_in_the_settings(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let all = tree_rows(&shell, cx); + let kept = |shell: &Shell, cx: &mut VisualTestContext| { + shell.app.read_with(cx, |app, _| app.backend().prefs.get(&UI_TREE)) + }; + assert!(kept(&shell, cx).is_empty()); + + click(cx, "tree-toggle-2"); + let folded = tree_rows(&shell, cx); + assert_eq!(folded.len(), all.len() - 5, "Chill Zone's five people are out"); + assert!(folded.iter().any(|r| &*r.name == "Chill Zone" && r.collapsed)); + assert_eq!( + kept(&shell, cx), + TreeStates::from([( + sample::DEMO.to_string(), + TreeState { collapsed: vec![2], selected: None } + )]) + ); + assert_eq!(shell.app.read_with(cx, |app, _| app.selected_channel()), None); + + click(cx, "tree-toggle-2"); + assert_eq!(tree_rows(&shell, cx), all, "unfolded: the rows are back"); + assert!(kept(&shell, cx).is_empty(), "nothing remembered when nothing is folded"); + } + + /// What a tree remembers of a server (the channels folded, the channel + /// selected) is in the settings, and the next run finds the tree as it was + /// left. + #[gpui::test] + fn what_the_tree_remembers_round_trips_through_the_settings(cx: &mut TestAppContext) { + let dir = TempDir::new("tree-memory"); + let first = { + let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); + let (shell, vcx) = open(cx, backend, Switches::default()); + sample_server(&shell, vcx); + click(vcx, "tree-toggle-2"); + click(vcx, "tree-channel-5"); + assert_eq!(shell.app.read_with(vcx, |app, _| app.selected_channel()), Some(5)); + let selected = + shell.view.read_with(vcx, |view, cx| view.tree_model().read(cx).selected()); + assert_eq!(selected, Some(5), "the model has it, and so the pane"); + shell.app.update(vcx, |app, cx| app.shutdown(cx)); + tree_rows(&shell, vcx) + }; + + // The next run: the same data directory, the server shown again. + let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); + assert_eq!( + backend.prefs.get(&UI_TREE), + TreeStates::from([( + sample::DEMO.to_string(), + TreeState { collapsed: vec![2], selected: Some(5) } + )]) + ); + let (shell, vcx) = open(cx, backend, Switches::default()); + shell.app.update(vcx, |app, cx| { + app.vm.bookmarks = sample::bookmarks(); + app.select_server(sample::DEMO, cx); + }); + sample_server(&shell, vcx); + let again = tree_rows(&shell, vcx); + assert_eq!(again, first, "the same rows: Chill Zone is folded"); + assert!(again.iter().any(|r| &*r.name == "Chill Zone" && r.collapsed)); + assert_eq!(shell.app.read_with(vcx, |app, _| app.selected_channel()), Some(5)); + } + + /// A double-click on a channel asks the engine to move there, with the + /// session on screen; a single click only selects. + #[gpui::test] + fn a_double_click_on_a_channel_joins_it(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()); + click(cx, "tree-channel-6"); + assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), "a click is no join"); + assert_eq!(shell.app.read_with(cx, |app, _| app.selected_channel()), Some(6)); + + double_click(cx, "tree-channel-6"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::MoveToChannel { session, channel: 6, password: None }] + if *session == sample::DEMO as u64), + "{sent:?}" + ); + // The same through the action, as a menu or a key would. + cx.dispatch_action(JoinChannel { channel: 1 }); + frame(cx); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!(matches!(sent.as_slice(), [Command::MoveToChannel { channel: 1, .. }]), "{sent:?}"); + } + + /// A locked channel asks for its password first; the prompt's Join sends it + /// with the move; one the server refuses asks again, in words. + #[gpui::test] + fn a_locked_channel_asks_for_its_password(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()); + assert!(at(cx, "password-prompt").is_none()); + double_click(cx, "tree-channel-7"); + assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), "nothing yet"); + let prompt = shell.view.read_with(cx, |view, _| view.password_prompt().cloned()); + let prompt = prompt.expect("the prompt is open"); + assert!(at(cx, "password-prompt").is_some()); + assert_eq!( + prompt.read_with(cx, |p, _| (p.channel().to_owned(), p.wrong())), + ("Officers".to_owned(), false) + ); + + cx.update(|window, cx| prompt.update(cx, |p, cx| p.set_text("secret", window, cx))); + click(cx, "password-join"); + let sent = shell.app.read_with(cx, |app, _| app.take_sent()); + assert!( + matches!(sent.as_slice(), [Command::MoveToChannel { channel: 7, password, .. }] + if password.as_deref() == Some("secret")), + "{sent:?}" + ); + assert!(at(cx, "password-prompt").is_none(), "closed"); + + // The server says no: asked again, the password given forgotten. + shell + .events + .send(Event::JoinFailed { + session: sample::DEMO as u64, + channel: 7, + reason: voelin_core::JoinFailure::Password, + }) + .unwrap(); + frame(cx); + let prompt = shell + .view + .read_with(cx, |view, _| view.password_prompt().cloned()) + .expect("asked again"); + assert!(prompt.read_with(cx, |p, _| p.wrong())); + assert!(at(cx, "password-wrong").is_some()); + click(cx, "password-cancel"); + assert!(at(cx, "password-prompt").is_none()); + assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty()); + assert!(shell.app.read_with(cx, |app, _| app.vm.join_target.is_none())); + } + + /// A person who changes channel makes the rows between the two places + /// change and none outside them: the channels' counts, the person's row + /// moved; a person who mutes their microphone changes one row. + #[gpui::test] + fn a_move_changes_the_rows_between_and_a_mute_one_row(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let before = tree_rows(&shell, cx); + let (log, _subscription) = tree_events(&shell, cx); + + // dex (5) mutes: one row. + shell + .events + .send(presence_changed!(p => p.clients.get_mut(&5).unwrap().input_muted = false)) + .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)])]); + assert!(before[dex].muted && !tree_rows(&shell, cx)[dex].muted); + + // Zeph (7) leaves Raid Night for Gaming: its parent's count, his row + // and the row of the sub-channel change; the rest stay. + log.borrow_mut().clear(); + let moved = presence_changed!(p => { + p.clients.get_mut(&5).unwrap().input_muted = false; + p.clients.get_mut(&7).unwrap().channel = 3; + }); + shell.events.send(moved).unwrap(); + frame(cx); + let after = tree_rows(&shell, cx); + assert_eq!( + shape(&after)[8..13], + ["C0 Gaming", "P1 Talon", "P1 Zeph", "C1 Raid Night", "C0 Music"], + ); + let told = rows_told(&log); + let [changes] = &told[..] else { panic!("{:?}", log.borrow()) }; + let gaming = 8; + assert_eq!( + changes.0, + [Change::Update(gaming), Change::Update(gaming + 2), Change::Update(gaming + 3)], + "Gaming's count, Zeph's place, Raid Night's count" + ); + 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. + #[gpui::test] + fn a_talker_does_not_draw_the_tree_again(cx: &mut TestAppContext) { + let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); + sample_server(&shell, cx); + let rows = tree_rows(&shell, cx); + 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 event = Event::Talking { session: sample::DEMO as u64, client: 3, talking }; + shell.events.send(event).unwrap(); + frame(cx); + } + 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)) + ); + } + /// The plus of the rail opens the form; Save with an address adds the /// server, selects it and closes the form. #[gpui::test] diff --git a/crates/voelin-ui-vm/src/tree.rs b/crates/voelin-ui-vm/src/tree.rs index eab8884..2762bc0 100644 --- a/crates/voelin-ui-vm/src/tree.rs +++ b/crates/voelin-ui-vm/src/tree.rs @@ -4,11 +4,10 @@ use std::collections::{HashMap, HashSet}; use std::path::PathBuf; -pub use voelin_model::channel_title; use voelin_model::{ - BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges, - tree_rows, + BannerMode, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges, tree_rows, }; +pub use voelin_model::{ChannelId, channel_title}; use voelin_core::{Contact, Relation};