//! The window's content: the desktop shell, or with `VOELIN_OPEN=swatch` the //! swatch page. [`MainView`] is the window's root view: it puts the shell's //! entities (`crate::shell`) in place, handles the actions the user's moves //! dispatch ([`crate::shell::actions`]) by asking the root state for what the //! Slint callbacks did, owns the server form, titles the window with the //! server on screen and reports where the window is. use gpui_kit::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::{UI_MEMBERS_WIDTH, WindowState}; use crate::app::AppState; use crate::dev::Page; use crate::meter::Counters; use crate::shell::actions::{ AddServer, CancelChannelPassword, CancelServerForm, ConnectVoice, DeleteServer, DisconnectVoice, EditChannel, EditServer, Invite, JoinChannel, MoveClient, OpenClient, OpenMember, OpenSearch, OpenSettings, PushToTalk, SaveAndConnect, SaveServer, SearchMembers, SelectChannel, SelectServer, SetInputMuted, SetOutputMuted, SubmitChannelPassword, ToggleChannel, }; use crate::shell::{ ChannelPassword, ChannelTree, Emptiness, MainPanel, MemberCardView, MembersPane, ServerForm, ServerRail, Sidebar, Toast, TopBar, TreeEvent, TreeModel, }; use crate::swatch::swatch; use crate::theme::{VoelinTheme, hsla}; /// Where `window` is, as the setting `ui.window` keeps it: the size, the /// position where the platform tells one (not Wayland's) and whether it is /// maximized; none in full screen, and none for what cannot be a window. pub fn window_state(window: &Window, cx: &App) -> Option { let (bounds, maximized) = match window.window_bounds() { WindowBounds::Windowed(bounds) => (bounds, false), WindowBounds::Maximized(bounds) => (bounds, true), WindowBounds::Fullscreen(_) => return None, }; let whole = |pixels: gpui_kit::Pixels| f32::from(pixels).round() as i32; let positioned = cx.compositor_name() != "Wayland"; let state = WindowState { width: whole(bounds.size.width).max(0) as u32, height: whole(bounds.size.height).max(0) as u32, x: positioned.then(|| whole(bounds.origin.x)), y: positioned.then(|| whole(bounds.origin.y)), maximized, }; state.is_sane().then_some(state) } /// What the main window draws, from the root state and the theme. pub struct MainView { app: Entity, page: Page, counters: Counters, rail: Entity, topbar: Entity, sidebar: Entity, 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>, /// 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, } impl MainView { /// A view of `app`. It keeps the theme in `system` mode in step with the /// window's appearance, the window's title with the server on screen, and /// tells `app` where the window is. pub fn new( app: Entity, page: Page, counters: Counters, window: &mut Window, cx: &mut Context, ) -> Self { let title = app.read(cx).window_title(); window.set_window_title(&title); // The window's own focus: actions dispatch from the focused element up, // so the handlers sit on an element that has it, and it comes back to // it whenever the element that had it is gone (the form closed, a // button replaced by another). let focus = cx.focus_handle(); window.focus(&focus, cx); let 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()); }), cx.observe_in(&app, window, |this, app, window, cx| { let title = app.read(cx).window_title(); if title != this.title { window.set_window_title(&title); this.title = title; } // A form for a server that is gone (removed from another place) // has nothing to edit. let editing = this.form.as_ref().map(|form| form.read(cx).id()); let known = |id: i64| app.read(cx).vm.bookmarks.iter().any(|b| b.id == id); if editing.is_some_and(|id| id >= 0 && !known(id)) { this.form = None; cx.notify(); } // 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)), ]; report(&app, window, cx); // The window is mapped by now: a window the last run left maximized // is maximized when its first frame is drawn. if app.read(cx).awaiting_maximize() { 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, page, counters, form: None, prompt: None, prompt_generation, title, focus, _subscriptions: subscriptions, } } /// The server form on screen, if one is. pub fn form(&self) -> Option<&Entity> { 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 } /// 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, form: voelin_ui_vm::bridge::BookmarkForm, window: &mut Window, cx: &mut Context, ) { self.form = Some(cx.new(|cx| ServerForm::new(&form, window, cx))); cx.notify(); } fn select_server(&mut self, action: &SelectServer, _: &mut Window, cx: &mut Context) { self.form = None; self.app.update(cx, |app, cx| app.select_server(action.id, cx)); cx.notify(); } fn connect_voice(&mut self, _: &ConnectVoice, _: &mut Window, cx: &mut Context) { self.app.update(cx, |app, cx| app.connect_voice(cx)); } fn disconnect_voice(&mut self, _: &DisconnectVoice, _: &mut Window, cx: &mut Context) { self.app.update(cx, |app, cx| app.disconnect_voice(cx)); } fn set_input_muted(&mut self, action: &SetInputMuted, _: &mut Window, cx: &mut Context) { self.app.update(cx, |app, cx| app.set_input_muted(action.muted, cx)); } fn set_output_muted( &mut self, action: &SetOutputMuted, _: &mut Window, cx: &mut Context, ) { self.app.update(cx, |app, cx| app.set_output_muted(action.muted, cx)); } fn push_to_talk(&mut self, action: &PushToTalk, _: &mut Window, cx: &mut Context) { self.app.update(cx, |app, cx| app.push_to_talk(action.on, cx)); } fn invite(&mut self, _: &Invite, _: &mut Window, cx: &mut Context) { self.app.update(cx, |app, cx| app.invite(cx)); } fn add_server(&mut self, _: &AddServer, window: &mut Window, cx: &mut Context) { let form = self.app.read(cx).bookmark_form(-1); self.open_form(form, window, cx); } fn edit_server(&mut self, action: &EditServer, window: &mut Window, cx: &mut Context) { let form = self.app.read(cx).bookmark_form(action.id); self.open_form(form, window, cx); } /// Save the form's server; the form closes when it was saved, stays /// (with the toast saying why) when it was not. fn save(&mut self, connect: bool, cx: &mut Context) { let Some(form) = &self.form else { return }; let values = form.read(cx).to_form(cx); let saved = self.app.update(cx, |app, cx| { if connect { app.save_and_connect(&values, cx) } else { app.save_bookmark(&values, cx).is_some() } }); if saved { self.form = None; cx.notify(); } } fn save_server(&mut self, _: &SaveServer, _: &mut Window, cx: &mut Context) { self.save(false, cx); } fn save_and_connect(&mut self, _: &SaveAndConnect, _: &mut Window, cx: &mut Context) { self.save(true, cx); } fn cancel_form(&mut self, _: &CancelServerForm, _: &mut Window, cx: &mut Context) { self.form = None; cx.notify(); } fn delete_server(&mut self, action: &DeleteServer, _: &mut Window, cx: &mut Context) { self.form = None; self.app.update(cx, |app, cx| app.delete_bookmark(action.id, cx)); cx.notify(); } fn 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 move_client(&mut self, action: &MoveClient, _: &mut Window, _: &mut Context) { tracing::info!( client = action.client, "moving a client needs a command the engine does not have yet" ); } 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. An /// empty field joins nothing and the prompt stays open, as the Slint dialog /// (its Join is off and its Enter ignored while the field is empty). fn submit_channel_password( &mut self, _: &SubmitChannelPassword, _: &mut Window, cx: &mut Context, ) { let Some(prompt) = self.prompt.as_ref() else { return }; let password = prompt.read(cx).text(cx); if password.is_empty() { return; } self.prompt = None; 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\")"); } fn open_settings(&mut self, _: &OpenSettings, _: &mut Window, _: &mut Context) { tracing::info!("the settings come with their slice (docs/ui.md, \"What is next\")"); } } /// Maximize a window the last run left maximized, once it is shown. GPUI asks /// for it when it creates the window (`WindowBounds::Maximized`), before the /// window is mapped, and an X11 window manager manages a window only from its /// map: the request is lost there (openbox), and the window opens at its /// restored size. `zoom_window` toggles on X11, so one that is maximized by now /// (Wayland, a window manager that honours the early request) is left alone. fn maximize(window: &mut Window, _: &mut App) { if !window.is_maximized() { zoom(window); } } #[cfg(not(test))] fn zoom(window: &Window) { window.zoom_window(); } /// GPUI's test platform has no zoom (`unimplemented!`): the tests count it. #[cfg(test)] fn zoom(_: &Window) { tests::ZOOMS.with(|zooms| zooms.set(zooms.get() + 1)); } /// Tell `app` where `window` is: it keeps the place at the next tick. fn report(app: &Entity, window: &Window, cx: &mut App) { if let Some(state) = window_state(window, cx) { app.update(cx, |app, _| app.window_moved(state)); } } impl Render for MainView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { // One render of the window is one frame. The panes that have a size of // their own (the rail, the top bar, the main area) are embedded cached: // gpui-pre 0.3.10 renders them again only when their entity was // notified, so a change in one of them is not paid for by the others. // The sidebar and the toast are rendered with every frame. A window // nobody tells is not drawn. self.counters.renders.incr(); let theme = VoelinTheme::global(cx).clone(); let (c, m) = (&theme.colors, &theme.metrics); let frame = div() .id("window") .relative() .size_full() .text_color(hsla(c.text)) .font_family(crate::theme::FONT_FAMILY); 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 .main .clone() .cached(StyleRefinement::default().flex_1().min_w_0().h_full()) .into_any_element(), }; frame .key_context("Shell") .track_focus(&self.focus) .bg(theme.backdrop.to_gpui()) .flex() .flex_row() .on_action(cx.listener(Self::select_server)) .on_action(cx.listener(Self::connect_voice)) .on_action(cx.listener(Self::disconnect_voice)) .on_action(cx.listener(Self::set_input_muted)) .on_action(cx.listener(Self::set_output_muted)) .on_action(cx.listener(Self::push_to_talk)) .on_action(cx.listener(Self::invite)) .on_action(cx.listener(Self::add_server)) .on_action(cx.listener(Self::edit_server)) .on_action(cx.listener(Self::save_server)) .on_action(cx.listener(Self::save_and_connect)) .on_action(cx.listener(Self::cancel_form)) .on_action(cx.listener(Self::delete_server)) .on_action(cx.listener(Self::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::move_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( self.rail .clone() .cached(StyleRefinement::default().w(px(m.rail_width)).h_full().flex_none()), ) .child( div() .flex_1() .min_w_0() .h_full() .flex() .flex_col() .child(self.topbar.clone().cached( StyleRefinement::default().w_full().h(px(m.topbar_height)).flex_none(), )) .child( div() .flex_1() .min_h_0() .flex() .flex_row() .px(px(m.space_3)) .pb(px(m.space_3)) .gap(px(m.space_3)) .child(self.sidebar.clone()) .child(main) .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()) } } #[cfg(test)] mod tests { use std::cell::Cell; use std::rc::Rc; use std::time::Duration; use std::cell::RefCell; use std::sync::Arc; use gpui::{TestAppContext, VisualTestContext}; 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, TreeItem}; use voelin_ui_vm::dev::logic as sample; use voelin_ui_vm::list::{Change, Changes}; use voelin_ui_vm::settings::{TreeState, TreeStates, UI_TREE, UI_WINDOW}; use super::*; use crate::app::Setup; use crate::backend::Backend; use crate::backend::testing::TempDir; use crate::dev::Switches; use crate::pictures::PictureKey; use crate::shell::actions::{EditChannel, MoveClient, OpenClient}; use crate::shell::{RailView, TreeEvent}; use crate::signals::Area; use crate::theme::Choice; use crate::window_bounds; thread_local! { /// How many times a window asked to be zoomed (`zoom` in this module). pub(super) static ZOOMS: Cell = const { Cell::new(0) }; } fn zooms() -> usize { ZOOMS.with(Cell::get) } /// What a test of the shell holds: the root state, the window's view, the /// engine's events and the meter's counters. struct Shell { app: Entity, view: Entity, events: UnboundedSender, counters: Counters, } fn bookmark(name: &str, address: &str) -> Bookmark { Bookmark { name: name.into(), address: address.into(), nickname: "Nova".into(), ..Default::default() } } fn backend_with(servers: &[(&str, &str)]) -> Backend { let backend = Backend::in_memory().unwrap(); for (name, address) in servers { backend.store.add_bookmark(&bookmark(name, address)).unwrap(); } backend } /// Open the window of the shell on `backend`, with the theme and the /// components set up as `run` sets them. fn open( cx: &mut TestAppContext, backend: Backend, switches: Switches, ) -> (Shell, &mut VisualTestContext) { cx.update(|cx| { gpui_kit::init(cx); VoelinTheme::init(cx, Choice::Dark, WindowAppearance::Dark, 1.0); }); let (events, rx) = mpsc::unbounded_channel(); let counters = Counters::default(); let page = switches.open; let setup = Setup { engine: None, events: rx, counters: counters.clone(), backend, switches }; let app = cx.new(|cx| AppState::new(setup, cx)); let (view, vcx) = cx.add_window_view({ let (app, counters) = (app.clone(), counters.clone()); move |window, cx| MainView::new(app, page, counters, window, cx) }); let shell = Shell { app, view, events, counters }; frame(vcx); (shell, vcx) } /// Run what is queued and draw the window. fn frame(cx: &mut VisualTestContext) { cx.run_until_parked(); cx.update(|window, cx| window.draw(cx).clear(cx)); } /// Where the element with this debug selector is on screen. fn at(cx: &mut VisualTestContext, selector: &str) -> Option> { cx.debug_bounds(Box::leak(selector.to_owned().into_boxed_str())) } fn click(cx: &mut VisualTestContext, selector: &str) { let bounds = at(cx, selector).unwrap_or_else(|| panic!("{selector} is not on screen")); cx.simulate_click(bounds.center(), Default::default()); frame(cx); } fn ids(shell: &Shell, cx: &mut VisualTestContext) -> Vec { shell.app.read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.id).collect()) } fn rail(shell: &Shell, cx: &mut VisualTestContext) -> RailView { shell.view.read_with(cx, |view, cx| view.rail.read(cx).view().clone()) } fn form(address: &str) -> BookmarkForm { BookmarkForm { id: -1, address: address.into(), ..Default::default() } } fn connected(id: i64) -> Event { Event::State { session: id as u64, state: SessionState { voice: VoiceState::Connected, ..Default::default() }, } } /// A saved server shows in the rail, as an icon the user can click. #[gpui::test] fn a_server_added_shows_in_the_rail(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); assert_eq!(rail(&shell, cx).servers, []); let id = shell .app .update(cx, |app, cx| { app.save_bookmark( &BookmarkForm { name: "Nightfall".into(), ..form("ts.example") }, cx, ) }) .unwrap(); frame(cx); let view = rail(&shell, cx); assert_eq!(view.servers.len(), 1); assert_eq!( (i64::from(view.servers[0].id), view.servers[0].name.as_ref()), (id, "Nightfall") ); assert_eq!(view.servers[0].initials.as_ref(), "NI"); assert_eq!(view.current, Some(id), "and it is the one on screen"); assert!(at(cx, &format!("rail-server-{id}")).is_some(), "drawn"); } /// A click on a server of the rail shows it: the window's title, the top /// bar and the sidebar name it. #[gpui::test] fn clicking_a_server_selects_it_and_titles_the_window(cx: &mut TestAppContext) { let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]); let (shell, cx) = open(cx, backend, Switches::default()); let [first, second] = ids(&shell, cx)[..] else { panic!("two servers") }; assert_eq!( cx.window_title().as_deref(), Some("Voelin - Nightfall"), "the first is shown at start" ); click(cx, &format!("rail-server-{second}")); assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(second)); assert_eq!(cx.window_title().as_deref(), Some("Voelin - Lounge")); shell.view.read_with(cx, |view, cx| { assert_eq!(view.topbar.read(cx).title(), "Lounge"); let sidebar = view.sidebar.read(cx).view(); assert_eq!(sidebar.server.as_ref().map(|s| s.name.as_ref()), Some("Lounge")); }); assert_eq!(rail(&shell, cx).current, Some(second)); click(cx, &format!("rail-server-{first}")); assert_eq!(cx.window_title().as_deref(), Some("Voelin - Nightfall")); } /// Nothing on screen is the "no server selected" state with the way to /// add one, and the title is the app's. #[gpui::test] fn without_a_server_the_main_area_says_so(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); assert_eq!(cx.window_title().as_deref(), Some("Voelin")); shell.view.read_with(cx, |view, cx| { assert_eq!(view.main.read(cx).state(), &crate::shell::MainState::NoServer); assert_eq!(view.topbar.read(cx).title(), "Voelin"); }); assert!(at(cx, "main-empty").is_some()); assert!(at(cx, "sidebar-server").is_none(), "no server card"); } /// The connect button of a server on screen asks the engine to connect it. #[gpui::test] fn the_connect_button_connects_the_server_on_screen(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); let id = ids(&shell, cx)[0]; shell.app.read_with(cx, |app, _| app.take_sent()); click(cx, "main-connect"); let sent = shell.app.read_with(cx, |app, _| app.take_sent()); assert!( matches!(sent.as_slice(), [Command::ConnectVoice { session, options, .. }, ..] if *session == id as u64 && options.address == "ts.example"), "{sent:?}" ); } /// What the engine says about a session shows in the rail, the sidebar's /// voice card and the main area's buttons. #[gpui::test] fn an_engine_event_updates_the_rail_and_the_cards(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); let id = ids(&shell, cx)[0]; assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "offline"); assert!(at(cx, "sidebar-voice").is_none() && at(cx, "main-connect").is_some()); shell.events.send(connected(id)).unwrap(); frame(cx); assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "connected"); assert!(at(cx, "sidebar-voice").is_some(), "the voice card"); assert!(at(cx, "main-disconnect").is_some() && at(cx, "main-connect").is_none()); shell .events .send(Event::State { session: id as u64, state: SessionState::default() }) .unwrap(); frame(cx); assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "offline"); assert!(at(cx, "sidebar-voice").is_none()); } /// The mute buttons of the user card, and the disconnect of the voice card, /// go to the session as commands once voice is up. #[gpui::test] fn the_voice_buttons_send_their_commands_once_voice_is_up(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); let id = ids(&shell, cx)[0]; click(cx, "user-mic"); assert!( shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), "disabled without voice" ); shell.events.send(connected(id)).unwrap(); frame(cx); click(cx, "user-mic"); click(cx, "user-sound"); click(cx, "voice-disconnect"); let sent = shell.app.read_with(cx, |app, _| app.take_sent()); assert!( matches!( sent.as_slice(), [ Command::SetInputMuted { session: a, muted: true }, Command::SetOutputMuted { session: b, muted: true }, Command::DisconnectVoice { session: c }, ] if [*a, *b, *c] == [id as u64; 3] ), "{sent:?}" ); } /// Hold to talk transmits while the button is held down. #[gpui::test] fn hold_to_talk_transmits_while_it_is_held(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); let id = ids(&shell, cx)[0]; shell.events.send(connected(id)).unwrap(); frame(cx); let button = at(cx, "hold-to-talk").expect("push-to-talk is the default transmit mode"); cx.simulate_mouse_down(button.center(), gpui_kit::MouseButton::Left, Default::default()); cx.simulate_mouse_up(button.center(), gpui_kit::MouseButton::Left, Default::default()); let sent = shell.app.read_with(cx, |app, _| app.take_sent()); assert!( matches!( sent.as_slice(), [Command::SetTransmitting { session: a, on: true }, Command::SetTransmitting { session: b, on: false }] if [*a, *b] == [id as u64; 2] ), "{sent:?}" ); } /// What changes nothing the shell shows tells no part, so draws nothing: an /// engine event about a talker, a setting that is not the theme's, a tick. /// The root is told every time; the parts compare what they would show. #[gpui::test] fn what_changes_nothing_shown_draws_nothing(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); let id = ids(&shell, cx)[0]; let (rail, topbar, sidebar, main, toast) = shell.view.read_with(cx, |v, _| { (v.rail.clone(), v.topbar.clone(), v.sidebar.clone(), v.main.clone(), v.toast.clone()) }); let (root_told, parts_told) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0))); macro_rules! count { ($cx:expr, $entity:expr, $told:expr) => {{ let told = $told.clone(); $cx.observe(&$entity, move |_, _| told.set(told.get() + 1)) }}; } let _subscriptions = cx.update(|_, cx| { vec![ count!(cx, shell.app, root_told), count!(cx, rail, parts_told), count!(cx, topbar, parts_told), count!(cx, sidebar, parts_told), count!(cx, main, parts_told), count!(cx, toast, parts_told), ] }); for event in [ Event::Talking { session: id as u64, client: 3, talking: true }, Event::SettingChanged { key: "stream.fps".into() }, ] { shell.events.send(event).unwrap(); frame(cx); } cx.executor().advance_clock(Duration::from_secs(3)); frame(cx); assert_eq!(root_told.get(), 2, "the root hears every batch of events"); assert_eq!(parts_told.get(), 0, "no part has anything new to show"); assert_eq!(shell.counters.ticks.get(), 3, "though the clock ran"); // What does show tells the parts. shell.events.send(connected(id)).unwrap(); frame(cx); assert!(parts_told.get() >= 2, "the rail and the sidebar at least: {}", parts_told.get()); } /// The panes that were rendered: a pane drawn cached renders again only /// when its entity was told something changed, so what changes the voice /// card costs the sidebar (rendered with every frame) and not the rail, the /// top bar or the main area. #[gpui::test] fn a_change_of_the_voice_card_renders_the_sidebar_and_no_cached_pane(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); let id = ids(&shell, cx)[0]; shell.events.send(connected(id)).unwrap(); frame(cx); let panes = &shell.counters.panes; let seen = || { [&shell.counters.renders, &panes.rail, &panes.topbar, &panes.sidebar, &panes.main] .map(|pane| pane.get()) }; let before = seen(); assert!(before.iter().all(|&n| n >= 1), "every pane has been drawn: {before:?}"); // Our microphone muted: the voice card changes, nothing else does. let state = SessionState { voice: VoiceState::Connected, input_muted: true, ..Default::default() }; shell.events.send(Event::State { session: id as u64, state }).unwrap(); frame(cx); let after = seen(); let frames = after[0] - before[0]; assert!(frames >= 1, "the window was drawn"); assert_eq!(after[3] - before[3], frames, "the sidebar with every frame"); assert_eq!( [after[1], after[2], after[4]], [before[1], before[2], before[4]], "the rail, the top bar and the main area stay as they were" ); } /// 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, with the rows they lead to. fn rows_told(log: &Rc>>) -> Vec<(Changes, Arc>)> { log.borrow() .iter() .filter_map(|event| match event { TreeEvent::Rows(changes, rows) => Some((changes.clone(), rows.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; Kairo, who talks as the sample /// starts, is marked. #[gpui::test] fn a_server_with_channels_and_people_fills_the_tree_with_its_rows(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); 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); let talking: Vec<&str> = rows.iter().filter(|r| r.talking).map(|r| &*r.name).collect(); assert_eq!(talking, ["Kairo"], "Kairo talks, and the tree says so"); assert!(at(cx, "tree-empty").is_none()); for row in rows.iter() { let selector = if row.is_channel { 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. As in the /// Slint dialog an empty field joins nothing and leaves the prompt open /// (Join and Enter), and Escape closes it. #[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) ); // Nothing in the field: Join and Enter do nothing and the prompt stays. click(cx, "password-join"); cx.simulate_keystrokes("enter"); frame(cx); assert!(at(cx, "password-prompt").is_some(), "an empty password closes nothing"); assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(), "and joins nothing"); assert!(shell.app.read_with(cx, |app, _| app.vm.join_target.is_some()), "still asking"); // Escape closes it, and the channel is no longer the one to join. cx.simulate_keystrokes("escape"); frame(cx); assert!(at(cx, "password-prompt").is_none(), "Escape closes the prompt"); 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())); // Asked again, with something typed, Join sends it. double_click(cx, "tree-channel-7"); let prompt = shell .view .read_with(cx, |view, _| view.password_prompt().cloned()) .expect("the prompt is open again"); 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())); // Typed and entered with the keyboard, the same. double_click(cx, "tree-channel-7"); assert!(at(cx, "password-prompt").is_some()); cx.simulate_input("again"); cx.simulate_keystrokes("enter"); frame(cx); 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("again")), "{sent:?}" ); assert!(at(cx, "password-prompt").is_none(), "closed"); } /// The channels with a banner picture are drawn with the veil of the /// surface colour over it (so that their text reads over any picture); the /// others have none. #[gpui::test] fn a_banner_is_drawn_under_a_veil(cx: &mut TestAppContext) { let switches = Switches { demo_ui: true, demo_pictures: true, ..Switches::default() }; let (shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); let rows = tree_rows(&shell, cx); let banners: Vec<_> = rows .iter() .filter(|r| r.is_channel && PictureKey::of(&r.banner).is_some()) .map(|r| r.id) .collect(); assert!(banners.len() >= 2, "the sample server has banners: {banners:?}"); for id in &banners { assert!(at(cx, &format!("tree-scrim-{id}")).is_some(), "channel {id} has a veil"); } let plain = rows.iter().find(|r| { r.is_channel && r.spacer == 0 && !banners.contains(&r.id) && !r.name.is_empty() }); let plain = plain.expect("a channel without a banner"); assert!(at(cx, &format!("tree-channel-{}", plain.id)).is_some(), "it is on screen"); assert!(at(cx, &format!("tree-scrim-{}", plain.id)).is_none(), "and has no veil"); } /// A 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(); let told = rows_told(&log); let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) }; assert_eq!(*changes, Changes(vec![Change::Update(dex)])); assert!(before[dex].muted && !tree_rows(&shell, cx)[dex].muted); assert_eq!(*carried, tree_rows(&shell, cx), "the event carries the rows it leads to"); // Zeph (7) leaves Raid Night for Gaming: its parent's count, his row // and the row of the sub-channel change; the rest stay. 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, carried)] = &told[..] else { panic!("{:?}", log.borrow()) }; assert_eq!(*carried, after); 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)); } /// The gate's probe. A state change made by an observer while a flush is /// running must not make a pane apply the first row operations to the /// second rows: the events carry the rows their operations lead to. A /// Presence event raises the toolbar and the tree; the model makes its /// first rows on the toolbar, an observer of the toolbar that was made /// after the model's puts the observed server on screen (it has no rows /// yet), and the model makes its second rows, none, on the tree before /// the panes are told of the first: a shrink under operations made for /// the rows before it. #[gpui::test] fn a_state_change_inside_a_flush_does_not_apply_old_operations_to_new_rows( cx: &mut TestAppContext, ) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); sample_server(&shell, cx); assert!(!tree_rows(&shell, cx).is_empty()); let toolbar = shell.app.read_with(cx, |app, _| app.signals().of(Area::Toolbar).clone()); let fired = Rc::new(Cell::new(false)); let _observer = cx.update(|_, cx| { let (app, fired) = (shell.app.clone(), fired.clone()); cx.observe(&toolbar, move |_, cx| { if !fired.replace(true) { app.update(cx, |app, cx| app.select_server(sample::DEMO + 1, cx)); } }) }); let (log, _subscription) = tree_events(&shell, cx); let unmute = presence_changed!(p => p.clients.get_mut(&5).unwrap().input_muted = false); shell.events.send(unmute).unwrap(); frame(cx); assert!(fired.get(), "the observer ran inside the flush"); assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(sample::DEMO + 1)); // The model told its panes twice, and each time with the rows its // operations lead to: the first leaves the server's rows with dex // unmuted, the second takes them all away. let told = rows_told(&log); let [first, second] = &told[..] else { panic!("{:?}", log.borrow()) }; assert_eq!(first.1.len(), 18, "the first rows are the sample server's"); assert!(!first.1.iter().any(|r| !r.is_channel && r.id == 5 && r.muted)); assert_eq!((first.0.updated(), first.0.removed(), first.0.inserted()), (1, 0, 0)); assert!(second.1.is_empty() && second.0.removed() == 18, "{:?}", second.0); // The panes end with the model's rows, in the order they were told. assert!(tree_rows(&shell, cx).is_empty()); let (tree, people) = shell.view.read_with(cx, |view, cx| { (view.channel_tree().read(cx).rows().len(), view.members_pane().read(cx).rows().len()) }); assert_eq!((tree, people), (0, 0)); assert!(at(cx, "tree-empty").is_some(), "the tree says it is loading"); } /// Who talks is marked on the tree's row, as the Slint tree marks it (the /// ring on the avatar, the bars on the row): each start and stop changes /// exactly that person's row, the tree pane is drawn once for it, and the /// row says so on screen. #[gpui::test] fn a_talker_changes_one_row_and_draws_the_tree_once(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); sample_server(&shell, cx); let kairo = |shell: &Shell, cx: &mut VisualTestContext| { shell.view.read_with(cx, |view, cx| { let tree = view.channel_tree().read(cx); tree.rows().iter().position(|r| !r.is_channel && r.id == 3).unwrap() }) }; let place = kairo(&shell, cx); assert!(tree_rows(&shell, cx)[place].talking, "Kairo talks as the sample starts"); let (log, _subscription) = tree_events(&shell, cx); let drawn = |shell: &Shell| shell.counters.panes.tree.get(); for talking in [false, true, false, true] { let before = drawn(&shell); log.borrow_mut().clear(); let event = Event::Talking { session: sample::DEMO as u64, client: 3, talking }; shell.events.send(event).unwrap(); frame(cx); let told = rows_told(&log); let [(changes, carried)] = &told[..] else { panic!("{:?}", log.borrow()) }; assert_eq!(*changes, Changes(vec![Change::Update(place)]), "only Kairo's row"); assert_eq!(carried[place].talking, talking); assert_eq!(drawn(&shell), before + 1, "the tree pane was drawn once"); let pane = shell .view .read_with(cx, |view, cx| view.channel_tree().read(cx).rows()[place].talking); assert_eq!(pane, talking, "the pane has it"); assert_eq!(at(cx, "tree-speaking-3").is_some(), talking, "and the bars are on screen"); } assert!( shell.app.read_with(cx, |app, _| app.vm.sessions[&sample::DEMO].talking.contains(&3)) ); } /// 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 the /// tree and no other pane: not the rail, the top bar nor the main area. The /// row says so while they talk. #[gpui::test] fn a_talker_redraws_the_tree_and_the_members_panel_and_no_other_pane(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); sample_server(&shell, cx); let panes = &shell.counters.panes; 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!(after[2] > before[2], "and the tree: {before:?} -> {after:?}"); assert_eq!( [after[0], after[1], after[3]], [before[0], before[1], before[3]], "the rail, the top bar 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"); } /// What the context menus offer that has no slice yet (the channel editor, /// a person's volume dialog, moving a client) is logged and sends nothing. #[gpui::test] fn the_menu_entries_of_later_slices_are_logged_and_send_nothing(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()); cx.dispatch_action(EditChannel { channel: 2 }); cx.dispatch_action(OpenClient { client: 3 }); cx.dispatch_action(MoveClient { client: 3 }); frame(cx); assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty()); // A click on a person is the volume dialog's: logged too, and not on us. click(cx, "tree-client-3"); click(cx, "tree-client-1"); assert!(shell.app.read_with(cx, |app, _| app.take_sent()).is_empty()); } /// What the caches cannot save: GPUI refreshes the window (every view renders /// again, cached ones too) when a clickable element is pressed and when it is /// released, so a click renders every pane; a pointer that moves onto another /// row renders only the pane that holds the row. #[gpui::test] fn a_click_renders_every_pane_and_a_hover_only_the_pane_it_is_over(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.sidebar, &panes.tree, &panes.main, &panes.members] .map(|pane| pane.get()) }; let before = seen(); click(cx, "tree-channel-6"); let after = seen(); assert!( before.iter().zip(&after).all(|(before, after)| after > before), "every pane: {before:?} -> {after:?}" ); // A pointer onto a row of the tree: the tree, and nothing cached beside it. let before = seen(); let position = at(cx, "tree-channel-8").expect("a row").center(); cx.simulate_mouse_move(position, None, Default::default()); frame(cx); let after = seen(); assert_eq!(after[3], before[3] + 1, "the tree: {before:?} -> {after:?}"); assert_eq!( [after[0], after[1], after[4], after[5]], [before[0], before[1], before[4], before[5]], "not the rail, the top bar, the main area or the members panel" ); } /// The plus of the rail opens the form; Save with an address adds the /// server, selects it and closes the form. #[gpui::test] fn the_add_button_opens_the_form_and_save_adds_the_server(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); click(cx, "main-add"); let form = shell.view.read_with(cx, |view, _| view.form().cloned()).expect("the form is open"); assert!(at(cx, "server-form").is_some()); cx.update(|window, cx| { form.update(cx, |form, cx| form.set_address("ts.example.com", window, cx)) }); click(cx, "form-save"); shell.view.read_with(cx, |view, _| assert!(view.form().is_none(), "closed")); let names: Vec = shell .app .read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.name.clone()).collect()); assert_eq!(names, ["ts.example.com"]); assert_eq!(cx.window_title().as_deref(), Some("Voelin - ts.example.com")); assert!(at(cx, "server-form").is_none() && at(cx, "main-server").is_some()); } /// What is typed after the form opens goes to its address field, and Enter /// there saves: the form takes the focus from the button that opened it, /// and the window's own focus does not take it back. #[gpui::test] fn typing_in_the_form_fills_the_address_and_enter_saves(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); click(cx, "main-add"); cx.simulate_input("ts.example.com"); frame(cx); let form = shell.view.read_with(cx, |view, _| view.form().cloned()).expect("the form is open"); assert_eq!( form.read_with(cx, |form, cx| form.to_form(cx).address.to_string()), "ts.example.com" ); cx.simulate_keystrokes("enter"); frame(cx); shell.view.read_with(cx, |view, _| assert!(view.form().is_none(), "saved and closed")); assert_eq!(cx.window_title().as_deref(), Some("Voelin - ts.example.com")); } /// Saving a form with no address keeps the form open and says why. #[gpui::test] fn a_form_without_an_address_stays_open_and_says_why(cx: &mut TestAppContext) { let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default()); click(cx, "main-add"); click(cx, "form-save"); shell.view.read_with(cx, |view, _| assert!(view.form().is_some())); assert_eq!( shell.app.read_with(cx, |app, _| app.vm.status.clone()), "A server needs an address" ); assert_eq!( shell.view.read_with(cx, |view, cx| view.toast.read(cx).text().to_owned()), "A server needs an address" ); click(cx, "form-cancel"); shell.view.read_with(cx, |view, _| assert!(view.form().is_none())); } /// Removing asks twice, then the server goes from the rail and the store. #[gpui::test] fn removing_a_server_takes_two_clicks(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); click(cx, "main-edit"); shell.view.read_with(cx, |view, _| assert!(view.form().is_some())); click(cx, "form-remove"); assert_eq!(ids(&shell, cx).len(), 1, "once is not enough"); click(cx, "form-remove"); assert_eq!(ids(&shell, cx), Vec::::new()); assert!( shell.app.read_with(cx, |app, _| app.backend().store.bookmarks().unwrap().is_empty()) ); assert_eq!(cx.window_title().as_deref(), Some("Voelin")); assert!(at(cx, "main-empty").is_some()); } /// The status line is a toast that goes after a few seconds. #[gpui::test] fn the_status_line_is_a_toast_that_goes(cx: &mut TestAppContext) { let (shell, cx) = open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); let toast = |shell: &Shell, cx: &mut VisualTestContext| { shell.view.read_with(cx, |view, cx| view.toast.read(cx).text().to_owned()) }; assert_eq!(toast(&shell, cx), ""); click(cx, "main-connect"); assert_eq!(toast(&shell, cx), "Connecting to ts.example…"); cx.executor().advance_clock(crate::shell::TOAST_TIME + Duration::from_secs(1)); frame(cx); assert_eq!(toast(&shell, cx), ""); } /// The window's size and position are kept in `ui.window` when it changes, /// and the next run opens where they say. #[gpui::test] fn the_windows_size_round_trips_through_the_settings(cx: &mut TestAppContext) { let dir = TempDir::new("shell-window"); let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); let (shell, vcx) = open(cx, backend, Switches::default()); let handle = vcx.update(|window, _| window.window_handle()); vcx.simulate_window_resize(handle, size(px(900.0), px(600.0))); frame(vcx); vcx.executor().advance_clock(Duration::from_secs(1)); frame(vcx); let kept = shell.app.read_with(vcx, |app, _| app.backend().prefs.get(&UI_WINDOW)).expect("kept"); assert_eq!((kept.width, kept.height), (900, 600)); assert!(!kept.maximized); let closed = shell.app.update(vcx, |app, cx| app.shutdown(cx)); assert_eq!(closed, 0); let remembered = shell.app.read_with(vcx, |app, _| app.remembered_window()); assert_eq!(remembered, Some(kept)); let opens = vcx.update(|_, cx| window_bounds(&Switches::default(), remembered, cx)); let WindowBounds::Windowed(bounds) = opens else { panic!("{opens:?}") }; assert_eq!(bounds.size, size(px(900.0), px(600.0))); } /// A window the last run left maximized is maximized once, when it is /// shown (X11 ignores the request GPUI makes before the map), and what it /// reports before the window manager has answered does not overwrite the /// setting: `maximized: true` survives a run that ends first. (GPUI's test /// platform cannot zoom, so the request is counted, and the window manager's /// answer is the test's own report; on X11 openbox it was seen at run time, /// docs/ui.md.) #[gpui::test] fn a_window_left_maximized_asks_to_be_maximized_once_and_stays_remembered( cx: &mut TestAppContext, ) { let dir = TempDir::new("shell-maximized"); let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap(); let left = WindowState { width: 1000, height: 700, x: Some(20), y: Some(30), maximized: true }; backend.prefs.set(&UI_WINDOW, Some(left)).unwrap(); ZOOMS.with(|zooms| zooms.set(0)); let (shell, vcx) = open(cx, backend, Switches::default()); assert_eq!(zooms(), 0, "not before the window's first frame"); // The test platform draws without delivering the platform's next-frame // callbacks: this is the first frame of a real window. let delivered = vcx.update(|window, cx| window.simulate_next_frame(cx)); assert_eq!((delivered, zooms()), (1, 1), "asked at the first frame"); let kept = |shell: &Shell, vcx: &mut VisualTestContext| { shell.app.read_with(vcx, |app, _| app.backend().prefs.get(&UI_WINDOW)) }; // The window as it opened (windowed, not yet maximized: the first // report) and the configure a window manager sends when it maps the // window (the second) are not what the user left. let handle = vcx.update(|window, _| window.window_handle()); vcx.simulate_window_resize(handle, size(px(900.0), px(600.0))); frame(vcx); vcx.executor().advance_clock(Duration::from_secs(2)); frame(vcx); assert_eq!(vcx.update(|window, cx| window.simulate_next_frame(cx)), 0); assert_eq!(zooms(), 1, "once"); assert_eq!(kept(&shell, vcx), Some(left), "still maximized"); // The close of a run the window manager never answered keeps it too. assert_eq!(shell.app.update(vcx, |app, cx| app.shutdown(cx)), 0); assert_eq!(kept(&shell, vcx), Some(left)); // The guard is for those two reports. The user's own resize after them // is kept, though the window manager still has not maximized the // window (a tiling one never does). assert!(!shell.app.read_with(vcx, |app, _| app.awaiting_maximize())); vcx.simulate_window_resize(handle, size(px(700.0), px(500.0))); frame(vcx); vcx.executor().advance_clock(Duration::from_secs(2)); frame(vcx); let resized = kept(&shell, vcx).expect("kept"); assert_eq!((resized.width, resized.height, resized.maximized), (700, 500, false)); } /// A window that was not left maximized is not zoomed. #[gpui::test] fn a_window_not_left_maximized_is_not_zoomed(cx: &mut TestAppContext) { let backend = Backend::in_memory().unwrap(); let left = WindowState { width: 1000, height: 700, x: None, y: None, maximized: false }; backend.prefs.set(&UI_WINDOW, Some(left)).unwrap(); ZOOMS.with(|zooms| zooms.set(0)); let (shell, vcx) = open(cx, backend, Switches::default()); frame(vcx); assert_eq!(zooms(), 0); assert!(!shell.app.read_with(vcx, |app, _| app.awaiting_maximize())); } /// A development switch that sets the size wins over a maximized window. #[gpui::test] fn a_size_switch_wins_over_a_maximized_window(cx: &mut TestAppContext) { let backend = Backend::in_memory().unwrap(); let left = WindowState { width: 1000, height: 700, x: None, y: None, maximized: true }; backend.prefs.set(&UI_WINDOW, Some(left)).unwrap(); ZOOMS.with(|zooms| zooms.set(0)); let switches = Switches { window: Some((1440.0, 960.0)), ..Switches::default() }; let (shell, vcx) = open(cx, backend, switches); frame(vcx); assert_eq!(zooms(), 0); assert!(!shell.app.read_with(vcx, |app, _| app.wants_maximized())); } /// Where the window opens: a remembered position that no screen shows is /// the middle of a screen; a maximized window stays maximized; a size the /// development switch names wins; nothing remembered is the default size. #[gpui::test] fn the_window_opens_where_it_was_left_if_a_screen_shows_it(cx: &mut TestAppContext) { let place = |x: i32, y: i32, maximized: bool| WindowState { width: 1000, height: 700, x: Some(x), y: Some(y), maximized, }; let opens = |cx: &mut TestAppContext, switches: &Switches, state: Option| { cx.update(|cx| window_bounds(switches, state, cx)) }; let none = Switches::default(); let WindowBounds::Windowed(on_screen) = opens(cx, &none, Some(place(20, 30, false))) else { panic!() }; assert_eq!( (on_screen.origin, on_screen.size), (point(px(20.0), px(30.0)), size(px(1000.0), px(700.0))) ); let WindowBounds::Windowed(lost) = opens(cx, &none, Some(place(90_000, 30, false))) else { panic!() }; assert_eq!(lost.size, size(px(1000.0), px(700.0))); assert_ne!( lost.origin, point(px(90_000.0), px(30.0)), "no screen shows it: the middle of one" ); assert!(matches!(opens(cx, &none, Some(place(20, 30, true))), WindowBounds::Maximized(_))); let default = opens(cx, &none, None); assert!( matches!(default, WindowBounds::Windowed(b) if b.size == size(px(1280.0), px(800.0))) ); let sized = Switches { window: Some((1440.0, 960.0)), ..Switches::default() }; let forced = opens(cx, &sized, Some(place(20, 30, true))); assert!( matches!(forced, WindowBounds::Windowed(b) if b.size == size(px(1440.0), px(960.0))) ); let tiny = WindowState { width: 320, height: 240, ..place(0, 0, false) }; let WindowBounds::Windowed(small) = opens(cx, &none, Some(tiny)) else { panic!() }; assert_eq!(small.size, size(px(640.0), px(480.0)), "never under the minimum"); } /// The sample servers fill the rail and the cards, with the first one /// connected. #[gpui::test] fn the_sample_servers_fill_the_shell(cx: &mut TestAppContext) { let switches = Switches { demo_ui: true, ..Switches::default() }; let (shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); let view = rail(&shell, cx); let names: Vec<&str> = view.servers.iter().map(|s| s.name.as_ref()).collect(); assert_eq!(names, ["Nightfall Guild", "Pixel Lounge", "Dev TS3"]); let statuses: Vec<&str> = view.servers.iter().map(|s| s.status.as_ref()).collect(); assert_eq!(statuses, ["connected", "observing", "offline"]); assert_eq!(view.current, Some(sample::DEMO)); assert!(at(cx, "sidebar-voice").is_some()); assert_eq!(cx.window_title().as_deref(), Some("Voelin - Nightfall Guild")); } /// `VOELIN_OPEN=swatch` shows the swatch in place of the shell. #[gpui::test] fn the_swatch_page_replaces_the_shell(cx: &mut TestAppContext) { let switches = Switches { open: Page::Swatch, ..Switches::default() }; let (_shell, cx) = open(cx, Backend::in_memory().unwrap(), switches); assert!(at(cx, "rail").is_none() && at(cx, "sidebar").is_none()); } /// An action dispatched without a click does what the click does: the /// keys and menus of later slices use the same handlers. #[gpui::test] fn an_action_dispatched_is_handled_as_a_click_is(cx: &mut TestAppContext) { let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]); let (shell, cx) = open(cx, backend, Switches::default()); let second = ids(&shell, cx)[1]; cx.dispatch_action(SelectServer { id: second }); frame(cx); assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(second)); cx.dispatch_action(AddServer); frame(cx); shell.view.read_with(cx, |view, _| assert!(view.form().is_some())); cx.dispatch_action(CancelServerForm); frame(cx); shell.view.read_with(cx, |view, _| assert!(view.form().is_none())); } }