diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index af90360..003eed7 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -210,7 +210,6 @@ pub struct AppState { backend: Backend, switches: Switches, window: WindowKeeper, - started: Instant, counters: Counters, later: Later, /// What went to the engine (tests look at it: an engine of the test's @@ -287,7 +286,6 @@ impl AppState { backend, switches, window: WindowKeeper { latest: None, saved }, - started: Instant::now(), counters, later: Later(later), #[cfg(test)] @@ -406,7 +404,7 @@ impl AppState { /// The commands sent since the last call. #[cfg(test)] - fn take_sent(&self) -> Vec { + pub(crate) fn take_sent(&self) -> Vec { std::mem::take(&mut *self.sent.borrow_mut()) } @@ -537,11 +535,6 @@ impl AppState { self.vm.sessions.values().filter(|view| view.state.voice == VoiceState::Connected).count() } - /// Seconds since the window opened. - pub fn uptime(&self) -> Duration { - self.started.elapsed() - } - /// The window's title: the app's name, and the server shown. pub fn window_title(&self) -> String { let shown = self @@ -897,21 +890,6 @@ impl AppState { } ids.len() } - - /// The one line of state: the version, how many voice connections are up - /// and how many engine events came. - pub fn state_line(&self) -> String { - let connections = self.connections(); - format!( - "{} {} · {} connection{} · {} engine event{}", - voelin_platform::APP_NAME, - env!("CARGO_PKG_VERSION"), - connections, - if connections == 1 { "" } else { "s" }, - self.events_handled, - if self.events_handled == 1 { "" } else { "s" }, - ) - } } #[cfg(test)] @@ -992,10 +970,7 @@ mod tests { #[gpui::test] fn an_injected_engine_event_reaches_the_entity(cx: &mut TestAppContext) { let (app, tx, counters) = entity(cx); - app.read_with(cx, |app, _| { - assert_eq!(app.connections(), 0); - assert!(app.state_line().contains("0 connections · 0 engine events")); - }); + app.read_with(cx, |app, _| assert_eq!((app.connections(), app.events_handled), (0, 0))); tx.send(voice(VoiceState::Connected)).unwrap(); cx.run_until_parked(); @@ -1003,11 +978,6 @@ mod tests { assert_eq!(app.events_handled, 1); assert_eq!(app.connections(), 1); assert_eq!(app.vm.status, "Connected", "the transition's status line"); - assert!( - app.state_line().contains("1 connection · 1 engine event"), - "{}", - app.state_line() - ); }); assert_eq!(counters.engine_events.get(), 1); assert_eq!(counters.connections.get(), 1); diff --git a/crates/voelin-gpui/src/assets.rs b/crates/voelin-gpui/src/assets.rs index 9eb69bb..86f5170 100644 --- a/crates/voelin-gpui/src/assets.rs +++ b/crates/voelin-gpui/src/assets.rs @@ -25,11 +25,17 @@ pub fn client_icon_names() -> impl Iterator { ICONS.iter().map(|(name, _)| *name) } +/// The app's mark, the Slint front end's `logo.svg`. +const LOGO: &[u8] = include_bytes!("../../voelin-ui/ui/assets/logo.svg"); + impl AssetSource for Assets { fn load(&self, path: &str) -> Result>> { if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) { return Ok(Some(Cow::Borrowed(bytes))); } + if path == "logo.svg" { + return Ok(Some(Cow::Borrowed(LOGO))); + } gpui_kit::assets::AllAssets.load(path) } diff --git a/crates/voelin-gpui/src/lib.rs b/crates/voelin-gpui/src/lib.rs index c40fc38..40a6d77 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -12,6 +12,7 @@ pub mod dev; pub mod engine; pub mod fonts; pub mod meter; +pub mod shell; pub mod swatch; pub mod theme; pub mod view; diff --git a/crates/voelin-gpui/src/shell/actions.rs b/crates/voelin-gpui/src/shell/actions.rs new file mode 100644 index 0000000..243e153 --- /dev/null +++ b/crates/voelin-gpui/src/shell/actions.rs @@ -0,0 +1,88 @@ +//! What the user can ask of the shell, as GPUI actions: the callbacks of the +//! Slint front end's `bind/servers.rs` that the desktop shell has (the first +//! eleven below), and the shell's own affordances. A click dispatches the +//! action ([`gpui_kit::Window::dispatch_action`]), the window's root view +//! ([`crate::view::MainView`]) handles it, and the handler asks the root state +//! ([`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. + +use gpui_kit::{Action, actions}; + +actions!( + voelin, + [ + /// `connect_voice`: connect the server on screen with voice, into its default channel. + ConnectVoice, + /// `disconnect_voice`: leave voice on the server on screen. + DisconnectVoice, + /// `invite`: copy a link to the voice channel we are in. + Invite, + /// `save_bookmark`: save the server form (the form's own Save button). + SaveServer, + /// `save_and_connect`: save the server form, then connect. + SaveAndConnect, + /// Open the empty server form (the rail's plus button). + AddServer, + /// Close the server form without saving. + CancelServerForm, + /// The top bar's search box: the search comes with its slice, today it is logged. + OpenSearch, + /// The settings buttons: the settings come with their slice, today it is logged. + OpenSettings, + ] +); + +/// `select_server`: show a server (and observe it). +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SelectServer { + /// The bookmark's id. + pub id: i64, +} + +/// `edit_bookmark`: open the server form with a saved server. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct EditServer { + /// The bookmark's id. + pub id: i64, +} + +/// `delete_bookmark`: remove a server. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct DeleteServer { + /// The bookmark's id. + pub id: i64, +} + +/// `set_input_muted`: mute or unmute our microphone. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SetInputMuted { + /// Muted from now on. + pub muted: bool, +} + +/// `set_output_muted`: mute or unmute the sound. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct SetOutputMuted { + /// Muted from now on. + pub muted: bool, +} + +/// `push_to_talk`: transmit while the hold-to-talk button is held. +#[derive(Clone, Debug, PartialEq, Action)] +#[action(namespace = voelin, no_json)] +pub struct PushToTalk { + /// Transmitting from now on. + pub on: bool, +} diff --git a/crates/voelin-gpui/src/shell/form.rs b/crates/voelin-gpui/src/shell/form.rs new file mode 100644 index 0000000..116fad3 --- /dev/null +++ b/crates/voelin-gpui/src/shell/form.rs @@ -0,0 +1,211 @@ +//! The server form: where a server is added or edited (the server dialog of +//! the Slint front end, `bookmark_form` / `save_bookmark` / +//! `save_and_connect` / `delete_bookmark` of `bind/servers.rs`). The dialogs +//! come with their slice; until then the form takes the place of the main +//! area, with gpui-component's text inputs: the address (the only thing a +//! server needs), a name (empty: the server's own), the nickname and the +//! server's password. + +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, Styled as _, Window, div, px, +}; +use voelin_ui_vm::bridge::BookmarkForm; + +use super::actions::{CancelServerForm, DeleteServer, SaveAndConnect, SaveServer}; +use super::widgets::{panel, tagged}; +use crate::theme::{VoelinTheme, hsla}; + +/// The form. +pub struct ServerForm { + id: i64, + connected: bool, + address: Entity, + name: Entity, + nickname: Entity, + password: Entity, + confirm_remove: bool, +} + +impl ServerForm { + /// A form filled in with `form` (id -1: a new server). The address has the + /// focus; Enter in any field saves. + pub fn new(form: &BookmarkForm, window: &mut Window, cx: &mut Context) -> Self { + let field = |window: &mut Window, + cx: &mut Context, + placeholder: &str, + value: &str, + masked: bool| { + let input = cx.new(|cx| { + InputState::new(window, cx) + .placeholder(SharedString::from(placeholder.to_owned())) + .default_value(SharedString::from(value.to_owned())) + .masked(masked) + }); + cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + window.dispatch_action(Box::new(SaveServer), cx); + } + }) + .detach(); + input + }; + let address = + field(window, cx, "ts.example.com or ts.example.com:9987", &form.address, false); + let name = field(window, cx, "Optional: the server tells its own", &form.name, false); + let nickname = field(window, cx, "The name others see", &form.nickname, false); + let password = field(window, cx, "Optional", &form.server_password, true); + address.update(cx, |input, cx| input.focus(window, cx)); + Self { + id: i64::from(form.id), + connected: form.connected, + address, + name, + nickname, + password, + confirm_remove: false, + } + } + + /// The bookmark this form edits; -1 for a new server. + pub fn id(&self) -> i64 { + self.id + } + + /// The form as the fields hold it now, for `AppState::save_bookmark`. + pub fn to_form(&self, cx: &App) -> BookmarkForm { + let text = |input: &Entity| input.read(cx).value().to_string(); + BookmarkForm { + id: self.id as i32, + name: text(&self.name).into(), + address: text(&self.address).into(), + nickname: text(&self.nickname).into(), + server_password: text(&self.password).into(), + connected: self.connected, + ..Default::default() + } + } + + /// Put `text` in the address field (a link that fills the form comes with + /// its slice; the tests type here). + pub fn set_address(&self, text: &str, window: &mut Window, cx: &mut App) { + self.address.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx)); + } +} + +fn labelled( + theme: &VoelinTheme, + label: &'static str, + input: &Entity, +) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .flex() + .flex_col() + .gap(px(m.space_2)) + .child( + div() + .text_size(px(m.font_sm)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(c.text_secondary)) + .child(label), + ) + .child(Input::new(input)) +} + +impl Render for ServerForm { + 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); + let new = self.id < 0; + let id = self.id; + let confirm = self.confirm_remove; + panel(&theme) + .id("server-form") + .debug_selector(|| "server-form".into()) + .flex_1() + .min_w_0() + .h_full() + .items_center() + .justify_center() + .child( + div() + .w_full() + .max_w(px(440.0)) + .flex() + .flex_col() + .gap(px(m.space_4)) + .p(px(m.space_5)) + .child( + div() + .text_size(px(m.font_xl)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(if new { "Add a server" } else { "Edit the server" }), + ) + .child(labelled(&theme, "Address", &self.address)) + .child(labelled(&theme, "Name", &self.name)) + .child(labelled(&theme, "Nickname", &self.nickname)) + .child(labelled(&theme, "Server password", &self.password)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child(tagged( + "form-save", + Button::new("form-save").primary().label("Save").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(SaveServer), cx) + }, + ), + )) + .when(!self.connected, |row| { + row.child(tagged( + "form-connect", + Button::new("form-connect").label("Save and connect").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(SaveAndConnect), cx) + }, + ), + )) + }) + .child(tagged( + "form-cancel", + Button::new("form-cancel").ghost().label("Cancel").on_click( + |_, window, cx| { + window.dispatch_action(Box::new(CancelServerForm), cx) + }, + ), + )) + .when(!new, |row| { + row.child(div().flex_1()).child(tagged( + "form-remove", + Button::new("form-remove") + .danger() + .label(if confirm { + "Click again to remove" + } else { + "Remove" + }) + .on_click(cx.listener(move |this, _, window, cx| { + if this.confirm_remove { + window.dispatch_action( + Box::new(DeleteServer { id }), + cx, + ); + } else { + this.confirm_remove = true; + cx.notify(); + } + })), + )) + }), + ), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/main_panel.rs b/crates/voelin-gpui/src/shell/main_panel.rs new file mode 100644 index 0000000..0d84c59 --- /dev/null +++ b/crates/voelin-gpui/src/shell/main_panel.rs @@ -0,0 +1,217 @@ +//! The main area. Until the chat, the voice page 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 draws again only when what it shows changed. + +use gpui_kit::component::button::{Button, ButtonVariants as _}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render, + Styled as _, Subscription, Window, div, px, +}; +use voelin_ui_vm::bridge::ServerItem; +use voelin_ui_vm::servers::logic; + +use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer}; +use super::widgets::{Avatar, Presence, icon, panel, tagged}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// What the main area shows. +#[derive(Clone, Debug, PartialEq)] +pub enum MainState { + /// No server is on screen. + NoServer, + /// A server is. + Server(ServerItem), +} + +impl MainState { + /// The main area for the state. + pub fn of(app: &AppState) -> Self { + let current = app.vm.current; + logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)) + .into_iter() + .find(|item| Some(i64::from(item.id)) == current) + .map_or(Self::NoServer, Self::Server) + } +} + +/// The words for a server's state. +fn state_words(status: &str) -> &'static str { + match status { + "connected" => "Connected with voice", + "connecting" => "Connecting…", + "observing" => "Observed without joining", + _ => "Not connected", + } +} + +/// The main area. +pub struct MainPanel { + state: MainState, + _subscription: Subscription, +} + +impl MainPanel { + /// A main area that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let state = MainState::of(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let state = MainState::of(app.read(cx)); + if state != this.state { + this.state = state; + cx.notify(); + } + }); + Self { state, _subscription: subscription } + } + + /// What it shows now. + pub fn state(&self) -> &MainState { + &self.state + } +} + +impl Render for MainPanel { + 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); + let body = match &self.state { + MainState::NoServer => div() + .id("main-empty") + .debug_selector(|| "main-empty".into()) + .flex() + .flex_col() + .items_center() + .gap(px(m.space_4)) + .child( + div() + .size(px(72.0)) + .rounded(px(m.radius_xl)) + .bg(hsla(c.surface_2)) + .border_1() + .border_color(hsla(c.border)) + .flex() + .items_center() + .justify_center() + .child(icon("server", 32.0, c.text_muted)), + ) + .child( + div() + .text_size(px(m.font_xl)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child("No server selected"), + ) + .child( + div() + .max_w(px(360.0)) + .text_center() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_muted)) + .child("Pick a server in the list, or add one to start talking."), + ) + .child(tagged( + "main-add", + Button::new("main-add") + .primary() + .label("Add a server") + .on_click(|_, window, cx| window.dispatch_action(Box::new(AddServer), cx)), + )), + MainState::Server(item) => { + let id = i64::from(item.id); + let connected = item.status.as_ref() == "connected"; + let connecting = item.status.as_ref() == "connecting"; + div() + .id("main-server") + .debug_selector(|| "main-server".into()) + .flex() + .flex_col() + .items_center() + .gap(px(m.space_4)) + .child( + Avatar::new("main-server-avatar", 72.0, &item.initials, item.tint) + .image(item.icon.clone()) + .square() + .presence(Presence::of_server(&item.status)), + ) + .child( + div() + .max_w(px(480.0)) + .truncate() + .text_size(px(m.font_2xl)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(item.name.to_string()), + ) + .child( + div() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_secondary)) + .child(item.address.to_string()), + ) + .child( + div() + .id("main-server-state") + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_muted)) + .child(state_words(&item.status)), + ) + .child( + div() + .max_w(px(360.0)) + .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( + div() + .flex() + .flex_row() + .gap(px(m.space_3)) + .when(connected || connecting, |row| { + row.child(tagged( + "main-disconnect", + Button::new("main-disconnect") + .danger() + .label("Disconnect") + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(DisconnectVoice), cx); + }), + )) + }) + .when(!connected && !connecting, |row| { + row.child(tagged( + "main-connect", + Button::new("main-connect") + .primary() + .label("Connect") + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(ConnectVoice), cx); + }), + )) + }) + .child(tagged( + "main-edit", + Button::new("main-edit").label("Edit").on_click( + move |_, window, cx| { + window.dispatch_action(Box::new(EditServer { id }), cx); + }, + ), + )), + ) + } + }; + panel(&theme) + .id("main") + .flex_1() + .min_w_0() + .h_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 new file mode 100644 index 0000000..5ebc4bd --- /dev/null +++ b/crates/voelin-gpui/src/shell/mod.rs @@ -0,0 +1,22 @@ +//! The desktop shell of the GPUI front end (`ui/shells/desktop.slint` and +//! the server callbacks of `bind/servers.rs`): the server rail, the top bar, +//! the sidebar, the main area, the server form and the toast, each an entity +//! that observes the root state ([`crate::app::AppState`]) and draws again +//! only when what it shows changed, and the actions the user's moves are +//! ([`actions`]). [`crate::view::MainView`] puts them in the window. + +pub mod actions; +mod form; +mod main_panel; +mod rail; +mod sidebar; +mod toast; +mod topbar; +pub mod widgets; + +pub use form::ServerForm; +pub use main_panel::{MainPanel, MainState}; +pub use rail::{RailView, ServerRail}; +pub use sidebar::{Sidebar, SidebarView}; +pub use toast::{TOAST_TIME, Toast}; +pub use topbar::TopBar; diff --git a/crates/voelin-gpui/src/shell/rail.rs b/crates/voelin-gpui/src/shell/rail.rs new file mode 100644 index 0000000..dea9a2b --- /dev/null +++ b/crates/voelin-gpui/src/shell/rail.rs @@ -0,0 +1,242 @@ +//! The server rail: the saved servers as avatars with their state, the +//! selection, the add-server button and the settings button (`ServerRail` of +//! `ui/shells/desktop.slint`). An entity of its own: it observes the root +//! state and draws again only when the servers it lists changed. + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render, + StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px, +}; +use voelin_ui_vm::bridge::ServerItem; +use voelin_ui_vm::servers::logic; + +use super::actions::{AddServer, EditServer, OpenSettings, SelectServer}; +use super::widgets::{Avatar, IconButton, Presence}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// What the rail shows: the servers in order, and which is on screen. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RailView { + /// The saved servers, as `voelin_ui_vm::servers::logic::rail` has them. + pub servers: Vec, + /// The bookmark on screen. + pub current: Option, +} + +impl RailView { + /// The rail for the state. + pub fn of(app: &AppState) -> Self { + Self { + servers: logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)), + current: app.vm.current, + } + } +} + +/// The rail. +pub struct ServerRail { + view: RailView, + _subscription: Subscription, +} + +impl ServerRail { + /// A rail that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let view = RailView::of(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let view = RailView::of(app.read(cx)); + if view != this.view { + this.view = view; + cx.notify(); + } + }); + Self { view, _subscription: subscription } + } + + /// What it shows now. + pub fn view(&self) -> &RailView { + &self.view + } +} + +/// One server of the rail: the selection pill, the ring of the one on screen, +/// the avatar with its state, the unread count and the live mark. +fn server(theme: &VoelinTheme, item: &ServerItem, selected: bool) -> impl IntoElement + use<> { + let (c, m) = (&theme.colors, &theme.metrics); + let id = i64::from(item.id); + let group = format!("rail-server-{id}"); + let name = item.name.to_string(); + let tooltip = format!("{name}\n{}", item.address); + let pill = div() + .absolute() + .left(px(0.0)) + .w(px(4.0)) + .h(px(if selected { 36.0 } else { 0.0 })) + .rounded(px(2.0)) + .bg(hsla(c.text)) + .when(!selected, |pill| { + let group = group.clone(); + pill.group_hover(group, |style| style.h(px(18.0))) + }); + div() + .id(("rail-server", id as u64)) + .group(group) + .relative() + .w_full() + .h(px(56.0)) + .flex_none() + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .debug_selector(|| format!("rail-server-{id}")) + .tooltip(move |window, cx| { + gpui_kit::component::tooltip::Tooltip::new(tooltip.clone()).build(window, cx) + }) + .on_click(move |event, window, cx| { + // A second click on the server is the Slint rail's double click. + if event.click_count() >= 2 { + window.dispatch_action(Box::new(EditServer { id }), cx); + } else { + window.dispatch_action(Box::new(SelectServer { id }), cx); + } + }) + .child(pill) + .when(selected, |row| { + row.child( + div() + .absolute() + .size(px(52.0)) + .rounded(px(m.radius_lg + 2.0)) + .border_2() + .border_color(hsla(c.accent)) + .bg(hsla(c.glow.with_alpha(0x66))), + ) + }) + .child( + Avatar::new(("rail-avatar", id as u64), 46.0, &item.initials, item.tint) + .image(item.icon.clone()) + .square() + .presence(Presence::of_server(&item.status)), + ) + .when(item.unread > 0, |row| { + row.child( + div() + .absolute() + .top(px(0.0)) + .left(px(50.0)) + .min_w(px(18.0)) + .h(px(18.0)) + .px(px(5.0)) + .rounded(px(9.0)) + .bg(hsla(c.live)) + .border_2() + .border_color(hsla(c.bg_rail)) + .flex() + .items_center() + .justify_center() + .text_size(px(m.font_xs)) + .font_weight(FontWeight::BOLD) + .text_color(hsla(c.on_accent)) + .child(item.unread.to_string()), + ) + }) + .when(item.live && item.unread == 0, |row| { + row.child( + div() + .absolute() + .top(px(4.0)) + .left(px(52.0)) + .size(px(12.0)) + .rounded(px(6.0)) + .bg(hsla(c.live)) + .border_2() + .border_color(hsla(c.bg_rail)), + ) + }) +} + +impl Render for ServerRail { + 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); + let current = self.view.current; + let servers: Vec<_> = self + .view + .servers + .iter() + .map(|item| server(&theme, item, current == Some(i64::from(item.id)))) + .collect(); + div() + .id("rail") + .w(px(m.rail_width)) + .h_full() + .flex_none() + .flex() + .flex_col() + .items_center() + .py(px(m.space_3)) + .gap(px(m.space_2)) + .bg(hsla(c.bg_rail.with_alpha(230))) + .border_r_1() + .border_color(hsla(c.border)) + // The app's mark. (Home, which the Slint rail opens from it, comes + // with its slice.) + .child( + div() + .size(px(48.0)) + .flex_none() + .rounded(px(m.radius_lg)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface_2)) + .flex() + .items_center() + .justify_center() + .child(gpui_kit::img("logo.svg").size(px(30.0))), + ) + .child( + div() + .w(px(32.0)) + .h(px(2.0)) + .my(px(m.space_2)) + .rounded(px(1.0)) + .bg(hsla(c.border_strong)), + ) + .child( + div() + .id("rail-servers") + .flex_1() + .min_h_0() + .w_full() + .overflow_y_scroll() + .flex() + .flex_col() + .items_center() + .gap(px(m.space_2)) + .children(servers) + .child( + div().pt(px(m.space_2)).child( + IconButton::new("rail-add", "plus", "Add a server") + .size(46.0) + .round() + .filled() + .tint(c.success) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(AddServer), cx); + }), + ), + ), + ) + .child( + IconButton::new("rail-settings", "settings", "Settings") + .size(46.0) + .round() + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(OpenSettings), cx); + }), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/sidebar.rs b/crates/voelin-gpui/src/shell/sidebar.rs new file mode 100644 index 0000000..269c32f --- /dev/null +++ b/crates/voelin-gpui/src/shell/sidebar.rs @@ -0,0 +1,422 @@ +//! 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 draws again 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, +}; +use voelin_core::TransmitMode; +use voelin_ui_vm::Rgb; +use voelin_ui_vm::bridge::ServerItem; +use voelin_ui_vm::image::ImageRef; +use voelin_ui_vm::servers::logic; + +use super::actions::{ + DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted, +}; +use super::widgets::{Avatar, IconButton, Presence, card, icon, panel}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// What the sidebar shows. +#[derive(Clone, Debug, PartialEq)] +pub struct SidebarView { + /// The server on screen, as the rail has it. + pub server: Option, + /// "9 online · 7 channels" once its presence is known, else empty. + pub stats: String, + /// Our nickname there; empty without a server. + pub nickname: String, + /// The channel we are in; empty while connecting. + pub own_channel: String, + /// Our picture on the server. + pub own_avatar: ImageRef, + /// Voice is connected. + pub voice_connected: bool, + /// Voice is connecting. + pub voice_connecting: bool, + /// The server is observed. + pub observing: bool, + /// Our microphone is muted. + pub input_muted: bool, + /// Our sound is muted. + pub output_muted: bool, + /// Voice goes out. + pub transmitting: bool, + /// The transmit mode is push-to-talk, so the card has a hold-to-talk button. + pub hold_to_talk: bool, +} + +impl SidebarView { + /// The sidebar for the state. + pub fn of(app: &AppState) -> Self { + let card = logic::toolbar(&app.vm, |bookmark| app.server_icon(bookmark)); + let server = app.vm.current.and_then(|id| { + logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)) + .into_iter() + .find(|item| i64::from(item.id) == id) + }); + Self { + server, + stats: card.server_stats, + nickname: card.nickname, + own_channel: card.own_channel, + own_avatar: card.own_avatar, + voice_connected: card.voice_connected, + voice_connecting: card.voice_connecting, + observing: card.observing, + input_muted: card.input_muted, + output_muted: card.output_muted, + transmitting: card.transmitting, + hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk, + } + } +} + +/// The sidebar. +pub struct Sidebar { + view: SidebarView, + /// The hold-to-talk button is held down. + holding: bool, + _subscription: Subscription, +} + +impl Sidebar { + /// A sidebar that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let view = SidebarView::of(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let view = SidebarView::of(app.read(cx)); + if view != this.view { + this.view = view; + cx.notify(); + } + }); + Self { view, holding: false, _subscription: subscription } + } + + /// What it shows now. + pub fn view(&self) -> &SidebarView { + &self.view + } + + /// The hold-to-talk button was released, if it was held. + fn let_go(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context) { + if std::mem::take(&mut self.holding) { + window.dispatch_action(Box::new(PushToTalk { on: false }), cx); + } + } +} + +/// The server's name, its icon and how many are there. +fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let stats = if view.stats.is_empty() { item.address.to_string() } else { view.stats.clone() }; + card(theme, 0xff) + .id("sidebar-server") + .debug_selector(|| "sidebar-server".into()) + .p(px(m.space_3)) + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child( + Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint) + .image(item.icon.clone()) + .square(), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .truncate() + .text_size(px(m.font_lg)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(item.name.to_string()), + ) + .child( + div() + .truncate() + .text_size(px(m.font_sm)) + .text_color(hsla(c.text_muted)) + .child(stats), + ), + ) +} + +/// 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, + view: &SidebarView, + cx: &mut Context, +) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let (dot, words) = if view.voice_connected { + (c.success, "Voice Connected") + } else { + (c.warning, "Connecting…") + }; + let talking = view.transmitting; + card(theme, 0xff) + .id("sidebar-voice") + .debug_selector(|| "sidebar-voice".into()) + .p(px(m.space_3)) + .flex() + .flex_col() + .gap(px(m.space_3)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .child(div().size(px(10.0)).flex_none().rounded(px(5.0)).bg(hsla(dot))) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .text_size(px(m.font_sm)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(dot)) + .child(words), + ) + .when(!view.own_channel.is_empty(), |column| { + column.child( + div() + .truncate() + .text_size(px(m.font_xs)) + .text_color(hsla(c.text_muted)) + .child(view.own_channel.clone()), + ) + }), + ) + .when(view.voice_connected && !view.own_channel.is_empty(), |row| { + row.child( + IconButton::new("voice-invite", "link", "Copy an invite to this channel") + .size(32.0) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(Invite), cx); + }), + ) + }) + .child( + IconButton::new("voice-disconnect", "phone-off", "Disconnect") + .size(32.0) + .tint(c.danger) + .on_click(|_, window, cx| { + window.dispatch_action(Box::new(DisconnectVoice), cx); + }), + ), + ) + .when(view.voice_connected && view.hold_to_talk, |card| { + card.child( + div() + .id("hold-to-talk") + .debug_selector(|| "hold-to-talk".into()) + .h(px(m.control_height)) + .flex() + .flex_row() + .items_center() + .justify_center() + .gap(px(m.space_2)) + .rounded(px(m.radius_md)) + .border_1() + .border_color(hsla(if talking { c.success } else { c.border })) + .bg(hsla(if talking { c.success.with_alpha(0xcc) } else { c.surface_2 })) + .cursor_pointer() + .hover(move |style| { + style.bg(hsla(if talking { c.success } else { c.surface_3 })) + }) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, window, cx| { + this.holding = true; + window.dispatch_action(Box::new(PushToTalk { on: true }), cx); + }), + ) + // Let go on the button or off it: the end of what was started. + .on_mouse_up(MouseButton::Left, cx.listener(Sidebar::let_go)) + .on_mouse_up_out(MouseButton::Left, cx.listener(Sidebar::let_go)) + .child(icon( + "mic", + m.icon_sm, + if talking { c.on_accent } else { c.text_secondary }, + )) + .child( + div() + .text_size(px(m.font_sm)) + .font_weight(FontWeight::MEDIUM) + .text_color(hsla(if talking { c.on_accent } else { c.text_secondary })) + .child(if talking { "Talking…" } else { "Hold to talk" }), + ), + ) + }) +} + +/// Who we are, and the buttons for the microphone and the sound. +fn user_card(theme: &VoelinTheme, view: &SidebarView) -> impl IntoElement { + let (c, m) = (&theme.colors, &theme.metrics); + let (words, presence) = if view.voice_connected { + ("Online", Presence::Online) + } else if view.observing { + ("Observing", Presence::Info) + } else { + ("Offline", Presence::Offline) + }; + let name = if view.nickname.is_empty() { + voelin_platform::APP_NAME.to_owned() + } else { + view.nickname.clone() + }; + let (input_muted, output_muted) = (view.input_muted, view.output_muted); + card(theme, 0xb3) + .id("sidebar-user") + .debug_selector(|| "sidebar-user".into()) + .min_h(px(60.0)) + .p(px(m.space_2)) + .flex() + .flex_row() + .items_center() + .gap(px(m.space_2)) + .child( + div() + .id("sidebar-profile") + .flex_1() + .min_w_0() + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .px(px(m.space_2)) + .py(px(m.space_2)) + .rounded(px(m.radius_md)) + .cursor_pointer() + .hover(|style| style.bg(hsla(c.surface_3))) + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)) + .child( + Avatar::new("sidebar-own-avatar", 38.0, &name_initials(&name), Rgb(0x2d6bff)) + .image(view.own_avatar.clone()) + .presence(presence) + .speaking(view.transmitting), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .truncate() + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(name), + ) + .child( + div() + .truncate() + .text_size(px(m.font_xs)) + .text_color(hsla(c.text_muted)) + .child(words), + ), + ), + ) + .child( + IconButton::new( + "user-mic", + if input_muted { "mic-off" } else { "mic" }, + if input_muted { "Microphone off" } else { "Microphone on" }, + ) + .danger() + .checked(input_muted) + .enabled(view.voice_connected) + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx); + }), + ) + .child( + IconButton::new( + "user-sound", + if output_muted { "headphone-off" } else { "headphones" }, + if output_muted { "Sound off" } else { "Sound on" }, + ) + .danger() + .checked(output_muted) + .enabled(view.voice_connected) + .on_click(move |_, window, cx| { + window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx); + }), + ) +} + +/// The initials of a nickname, for the avatar. +fn name_initials(name: &str) -> String { + voelin_ui_vm::avatar::initials(name) +} + +impl Render for Sidebar { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = VoelinTheme::global(cx).clone(); + let m = &theme.metrics; + let view = &self.view; + panel(&theme) + .id("sidebar") + .w(px(m.sidebar_width)) + .h_full() + .flex_none() + .p(px(m.space_3)) + .gap(px(m.space_3)) + .when_some(view.server.as_ref(), |sidebar, item| { + sidebar.child(server_card(&theme, view, item)) + }) + .child(channels(&theme, view.server.is_some())) + .when(view.voice_connected || view.voice_connecting, |sidebar| { + sidebar.child(voice_card(&theme, view, cx)) + }) + .child(user_card(&theme, view)) + } +} diff --git a/crates/voelin-gpui/src/shell/toast.rs b/crates/voelin-gpui/src/shell/toast.rs new file mode 100644 index 0000000..1e30392 --- /dev/null +++ b/crates/voelin-gpui/src/shell/toast.rs @@ -0,0 +1,88 @@ +//! The status line as a toast: what the last move did ("Connecting to +//! ts.example…", why a server was not saved), shown at the bottom of the +//! window for a few seconds. It watches the root state's status line and its +//! generation, so that the same words said twice are two toasts. + +use std::time::Duration; + +use gpui_kit::{ + Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _, + Subscription, Window, div, px, +}; + +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// How long a toast stays. +pub const TOAST_TIME: Duration = Duration::from_secs(5); + +/// The toast. +pub struct Toast { + text: String, + generation: u64, + _subscription: Subscription, +} + +impl Toast { + /// A toast that follows `app`'s status line from now on (what it said + /// before is not shown). + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let generation = app.read(cx).status_generation; + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let (generation, text) = { + let app = app.read(cx); + (app.status_generation, app.vm.status.clone()) + }; + if generation == this.generation { + return; + } + this.generation = generation; + this.text = text; + cx.notify(); + if this.text.is_empty() { + return; + } + cx.spawn(async move |this, cx| { + cx.background_executor().timer(TOAST_TIME).await; + let _ = this.update(cx, |this, cx| { + if this.generation == generation && !this.text.is_empty() { + this.text.clear(); + cx.notify(); + } + }); + }) + .detach(); + }); + Self { text: String::new(), generation, _subscription: subscription } + } + + /// What it shows now; empty when nothing is. + pub fn text(&self) -> &str { + &self.text + } +} + +impl Render for Toast { + 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); + let toast = + div().id("toast").absolute().bottom(px(m.space_7)).w_full().flex().justify_center(); + if self.text.is_empty() { + return toast; + } + toast.child( + div() + .max_w(px(560.0)) + .px(px(m.space_5)) + .py(px(m.space_3)) + .rounded(px(m.radius_md)) + .border_1() + .border_color(hsla(c.border_popup)) + .bg(hsla(c.surface_3)) + .text_size(px(m.font_body)) + .text_color(hsla(c.text)) + .child(self.text.clone()), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/topbar.rs b/crates/voelin-gpui/src/shell/topbar.rs new file mode 100644 index 0000000..6a15ed5 --- /dev/null +++ b/crates/voelin-gpui/src/shell/topbar.rs @@ -0,0 +1,112 @@ +//! The bar at the top of the window: the page's title, the search box and the +//! settings button (`TopBar` of `ui/shells/desktop.slint`; the bell comes +//! with the notifications). The search and the settings are affordances until +//! their slices: a click is logged ([`OpenSearch`], [`OpenSettings`]). + +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render, + StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px, +}; + +use super::actions::{OpenSearch, OpenSettings}; +use super::widgets::{IconButton, icon}; +use crate::app::AppState; +use crate::theme::{VoelinTheme, hsla}; + +/// The page title: the server on screen, else the app's name. +pub fn title(app: &AppState) -> String { + match app.current_bookmark() { + Some(bookmark) => bookmark.name.clone(), + None => voelin_platform::APP_NAME.to_owned(), + } +} + +/// The top bar. +pub struct TopBar { + title: String, + _subscription: Subscription, +} + +impl TopBar { + /// A top bar that follows `app`. + pub fn new(app: &Entity, cx: &mut Context) -> Self { + let shown = title(app.read(cx)); + let subscription = cx.observe(app, |this: &mut Self, app, cx| { + let shown = title(app.read(cx)); + if shown != this.title { + this.title = shown; + cx.notify(); + } + }); + Self { title: shown, _subscription: subscription } + } + + /// The title it shows now. + pub fn title(&self) -> &str { + &self.title + } +} + +impl Render for TopBar { + 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("topbar") + .w_full() + .h(px(m.topbar_height)) + .flex_none() + .flex() + .flex_row() + .items_center() + // The main panel starts where the sidebar and the gaps around it end. + .pl(px(m.sidebar_width + 2.0 * m.space_3)) + .pr(px(m.space_4)) + .gap(px(m.space_4)) + .child( + div() + .id("topbar-title") + .max_w(px(280.0 * m.font_scale.max(1.0))) + .flex_none() + .truncate() + .text_size(px(m.font_lg)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(c.text)) + .child(self.title.clone()), + ) + .child( + div().flex_1().min_w_0().flex().justify_center().child( + div() + .id("topbar-search") + .w_full() + .max_w(px(680.0)) + .h(px(m.control_height)) + .px(px(m.space_3)) + .flex() + .flex_row() + .items_center() + .gap(px(m.space_3)) + .rounded(px(m.radius_md)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface_2)) + .cursor_text() + .hover(|style| style.border_color(hsla(c.border_strong))) + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSearch), cx)) + .child(icon("search", m.icon_sm, c.text_muted)) + .child( + div() + .flex_1() + .truncate() + .text_size(px(m.font_body)) + .text_color(hsla(c.text_muted)) + .child("Search servers, channels, people or settings…"), + ), + ), + ) + .child( + IconButton::new("topbar-settings", "settings", "Settings") + .on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)), + ) + } +} diff --git a/crates/voelin-gpui/src/shell/widgets.rs b/crates/voelin-gpui/src/shell/widgets.rs new file mode 100644 index 0000000..ab2e683 --- /dev/null +++ b/crates/voelin-gpui/src/shell/widgets.rs @@ -0,0 +1,358 @@ +//! The few pieces the shell is made of, drawn from the theme's tokens +//! (`VoelinTheme`, not gpui-component's colours): the avatar of a server or a +//! person, the icon button, the panel and the Lucide icon. They are the GPUI +//! counterparts of `ui/components/avatar.slint`, `button.slint` and +//! `shells/common.slint`'s `Panel`. + +use gpui_kit::{ + App, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, + RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, img, px, + svg, +}; +use gpui_kit::{ElementId, ObjectFit, StyledImage as _}; +use voelin_ui_vm::Rgb; +use voelin_ui_vm::image::{ImageRef, ImageSource}; + +use crate::theme::tokens::Rgba; +use crate::theme::{VoelinTheme, hsla}; + +/// A Lucide icon of the client's set, `size` pixels square, in `color`. +pub fn icon(name: &str, size: f32, color: Rgba) -> impl IntoElement { + svg().path(format!("icons/{name}.svg")).size(px(size)).flex_none().text_color(hsla(color)) +} + +/// What the dot on an avatar says (`Status` of `avatar.slint`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Presence { + /// No dot. + None, + /// Connected with voice. + Online, + /// Connecting. + Idle, + /// Observed invisibly. + Info, + /// Not connected. + Offline, +} + +impl Presence { + /// The dot of a server's state as the engine names it + /// (`voelin_ui_vm::servers::status`): connected is online, observing is + /// blue, connecting is idle, offline has none. + pub fn of_server(status: &str) -> Self { + match status { + "connected" => Self::Online, + "observing" => Self::Info, + "connecting" => Self::Idle, + _ => Self::None, + } + } + + /// The dot's colour. + fn color(self, theme: &VoelinTheme) -> Option { + let c = &theme.colors; + match self { + Self::None => None, + Self::Online => Some(c.success), + Self::Idle => Some(c.idle), + Self::Info => Some(c.info), + Self::Offline => Some(c.offline), + } + } +} + +/// The colour a server or person is drawn in. +pub fn tint(color: Rgb) -> Rgba { + Rgba(color.0 << 8 | 0xff) +} + +/// An avatar: the picture when there is one (a file of the engine's cache), +/// else the initials on `tint`, square with rounded corners for a server +/// and round for a person, with a presence dot and a green ring while the +/// person's voice goes out. Pictures other than files of the cache are drawn +/// as initials until the slices that decode them (the chat's, the members'). +#[derive(IntoElement)] +pub struct Avatar { + id: ElementId, + size: f32, + initials: SharedString, + tint: Rgb, + image: ImageRef, + square: bool, + presence: Presence, + speaking: bool, +} + +impl Avatar { + /// An avatar of `size` pixels with these initials on `tint`. + pub fn new(id: impl Into, size: f32, initials: &str, tint: Rgb) -> Self { + Self { + id: id.into(), + size, + initials: initials.to_owned().into(), + tint, + image: ImageRef::default(), + square: false, + presence: Presence::None, + speaking: false, + } + } + + /// Draw this picture when it is a file of the cache. + pub fn image(mut self, image: ImageRef) -> Self { + self.image = image; + self + } + + /// A server's rounded square, not a person's circle. + pub fn square(mut self) -> Self { + self.square = true; + self + } + + /// The dot at the corner. + pub fn presence(mut self, presence: Presence) -> Self { + self.presence = presence; + self + } + + /// The green ring. + pub fn speaking(mut self, speaking: bool) -> Self { + self.speaking = speaking; + self + } +} + +impl RenderOnce for Avatar { + fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = VoelinTheme::global(cx); + let (c, m) = (&theme.colors, &theme.metrics); + let radius = if self.square { m.radius_lg } else { self.size / 2.0 }; + let picture = match &*self.image { + ImageSource::File { path, .. } if self.image.size().width > 0 => Some(path.clone()), + _ => None, + }; + let face = div() + .size(px(self.size)) + .flex_none() + .rounded(px(radius)) + .overflow_hidden() + .flex() + .items_center() + .justify_center() + .bg(hsla(if picture.is_some() { c.surface_3 } else { tint(self.tint) })); + let face = match picture { + Some(path) => face.child(img(path).size_full().object_fit(ObjectFit::Cover)), + None => face.child( + div() + .text_size(px(self.size * 0.38)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(hsla(Rgba(0xffff_ffff))) + .child(self.initials), + ), + }; + let mut avatar = div().id(self.id).relative().size(px(self.size)).flex_none(); + if self.speaking { + avatar = avatar.child( + div() + .absolute() + .top(px(-3.0)) + .left(px(-3.0)) + .size(px(self.size + 6.0)) + .rounded(px(radius + 3.0)) + .border_2() + .border_color(hsla(c.success)), + ); + } + avatar = avatar.child(face); + if let Some(color) = self.presence.color(theme) { + let dot = (self.size * 0.3).max(10.0); + avatar = avatar.child( + div() + .absolute() + .top(px(self.size - dot + 1.0)) + .left(px(self.size - dot + 1.0)) + .size(px(dot)) + .rounded(px(dot / 2.0)) + .border_2() + .border_color(hsla(c.surface)) + .bg(hsla(color)), + ); + } + avatar + } +} + +type Handler = Box; + +/// A button that is an icon: 36 pixels (or `size`) square, round or with +/// rounded corners, with a tooltip. Without a handler or disabled it draws +/// dimmed and does nothing. +#[derive(IntoElement)] +pub struct IconButton { + id: ElementId, + icon: &'static str, + label: SharedString, + size: f32, + tint: Option, + danger: bool, + round: bool, + filled: bool, + checked: bool, + enabled: bool, + on_click: Option, +} + +impl IconButton { + /// The Lucide icon `icon` (a file name without `.svg`), named `label` for + /// the tooltip. + pub fn new( + id: impl Into, + icon: &'static str, + label: impl Into, + ) -> Self { + Self { + id: id.into(), + icon, + label: label.into(), + size: 34.0, + tint: None, + danger: false, + round: false, + filled: false, + checked: false, + enabled: true, + on_click: None, + } + } + + /// The button's side in pixels. + pub fn size(mut self, size: f32) -> Self { + self.size = size; + self + } + + /// The icon's colour, instead of the theme's icon colour. + pub fn tint(mut self, tint: Rgba) -> Self { + self.tint = Some(tint); + self + } + + /// A button that turns danger-coloured when checked (mute). + pub fn danger(mut self) -> Self { + self.danger = true; + self + } + + /// A circle. + pub fn round(mut self) -> Self { + self.round = true; + self + } + + /// A button with a border and a face of its own (the rail's plus). + pub fn filled(mut self) -> Self { + self.filled = true; + self + } + + /// Whether it is on. + pub fn checked(mut self, checked: bool) -> Self { + self.checked = checked; + self + } + + /// Whether it can be used. + pub fn enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// What a click does. + pub fn on_click( + mut self, + handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, + ) -> Self { + self.on_click = Some(Box::new(handler)); + self + } +} + +impl RenderOnce for IconButton { + fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = VoelinTheme::global(cx); + let (c, m) = (&theme.colors, &theme.metrics); + let (face, ink, hover) = match (self.checked, self.danger, self.filled) { + (true, true, _) => (c.danger_soft, c.danger, c.danger_soft), + (true, false, _) => (c.accent_soft, c.accent_text, c.accent_soft_hover), + (false, _, true) => { + let ink = self.tint.unwrap_or(c.icon); + (c.surface_2, ink, ink.with_alpha(0x33)) + } + (false, _, false) => (Rgba::TRANSPARENT, self.tint.unwrap_or(c.icon), c.surface_3), + }; + let radius = if self.round { self.size / 2.0 } else { m.radius_md }; + let icon_size = if self.size >= 40.0 { m.icon_md } else { m.icon_sm.max(self.size * 0.5) }; + let label = self.label.clone(); + let selector = self.id.to_string(); + let mut button = div() + .id(self.id) + .debug_selector(move || selector) + .size(px(self.size)) + .flex_none() + .flex() + .items_center() + .justify_center() + .rounded(px(radius)) + .bg(hsla(face)) + .child(icon(self.icon, icon_size, ink)); + if self.filled { + button = button.border_1().border_color(hsla(ink)); + } + if !self.enabled { + return button.opacity(0.4).into_any_element(); + } + button = button.cursor_pointer().hover(move |style| style.bg(hsla(hover))).tooltip( + move |window, cx| { + gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx) + }, + ); + match self.on_click { + Some(handler) => button.on_click(move |event, window, cx| handler(event, window, cx)), + None => button, + } + .into_any_element() + } +} + +/// A rounded panel of the frame (sidebar, main area): `surface` a little +/// see-through over the backdrop, a border, clipped. +pub fn panel(theme: &VoelinTheme) -> gpui_kit::Div { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .flex() + .flex_col() + .rounded(px(m.radius_xl)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface.with_alpha(235))) + .overflow_hidden() +} + +/// What a card of the sidebar is drawn on. +pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div { + let (c, m) = (&theme.colors, &theme.metrics); + div() + .rounded(px(m.radius_lg)) + .border_1() + .border_color(hsla(c.border)) + .bg(hsla(c.surface_2.with_alpha(alpha))) +} + +/// `element` in a box of its own that tests find by `selector` (a debug +/// selector costs nothing in a build without debug assertions): for the +/// components of gpui-component, which have none of their own. +pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement { + div().flex_none().debug_selector(|| selector.into()).child(element) +} diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index 2886a40..2810a61 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -1,28 +1,69 @@ -//! The window's content. The shell is not built yet (slice 1 of the -//! migration): the window is the theme's page with the one line of the root -//! state that proves the loops run in a status bar, or, with -//! `VOELIN_OPEN=swatch`, the swatch page above that bar. +//! 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::{ - Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px, + App, AppContext as _, Context, Entity, FocusHandle, InteractiveElement as _, IntoElement, + ParentElement as _, Render, Styled as _, Subscription, Window, WindowBounds, div, px, }; +use voelin_ui_vm::settings::WindowState; 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, +}; +use crate::shell::{MainPanel, ServerForm, ServerRail, Sidebar, Toast, TopBar}; 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, + main: Entity, + toast: Entity, + form: Option>, + title: String, + focus: FocusHandle, + _subscriptions: Vec, } impl MainView { - /// A view of `app` that draws again whenever it changes, and that keeps - /// the theme in `system` mode in step with the window's appearance. + /// 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, @@ -30,63 +71,756 @@ impl MainView { window: &mut Window, cx: &mut Context, ) -> Self { - cx.observe(&app, |_, _, cx| cx.notify()).detach(); - cx.observe_window_appearance(window, |_, window, cx| { - VoelinTheme::set_system_appearance(cx, window.appearance()); - }) - .detach(); - Self { app, page, counters } + 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 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(); + } + }), + cx.observe_window_bounds(window, |this, window, cx| report(&this.app, window, cx)), + ]; + report(&app, window, 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)), + main: cx.new(|cx| MainPanel::new(&app, cx)), + toast: cx.new(|cx| Toast::new(&app, cx)), + app, + page, + counters, + form: None, + title, + focus, + _subscriptions: subscriptions, + } + } + + /// The server form on screen, if one is. + pub fn form(&self) -> Option<&Entity> { + self.form.as_ref() + } + + /// 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 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\")"); + } +} + +/// 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 parts draw when they are + // told, and the window is drawn when one was. self.counters.renders.incr(); - let line = self.app.read(cx).state_line(); let theme = VoelinTheme::global(cx).clone(); let (c, m) = (&theme.colors, &theme.metrics); - let page = match self.page { - Page::Swatch => div().flex_1().overflow_hidden().child(swatch(&theme)), - Page::Shell => div() - .flex_1() - .flex() - .flex_col() - .items_center() - .justify_center() - .gap(px(m.space_3)) - .child( - div() - .text_size(px(m.font_3xl)) - .text_color(hsla(c.text)) - .child(voelin_platform::APP_NAME), - ) - .child( - div() - .text_size(px(m.font_body)) - .text_color(hsla(c.text_muted)) - .child("The desktop shell is the next slice."), - ), - }; - div() + let frame = div() + .id("window") + .relative() .size_full() - .flex() - .flex_col() - .bg(hsla(c.bg_app)) .text_color(hsla(c.text)) - .font_family(crate::theme::FONT_FAMILY) - .child(page) + .font_family(crate::theme::FONT_FAMILY); + if self.page == Page::Swatch { + return frame.bg(hsla(c.bg_app)).child(swatch(&theme)); + } + let main = match &self.form { + Some(form) => form.clone().into_any_element(), + None => self.main.clone().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::open_search)) + .on_action(cx.listener(Self::open_settings)) + .child(self.rail.clone()) .child( div() - .h(px(m.control_height_sm)) - .px(px(m.space_5)) + .flex_1() + .min_w_0() + .h_full() .flex() - .items_center() - .bg(hsla(c.surface)) - .border_t_1() - .border_color(hsla(c.border)) - .text_size(px(m.font_sm)) - .text_color(hsla(c.text_secondary)) - .child(line), + .flex_col() + .child(self.topbar.clone()) + .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), + ), ) + .child(self.toast.clone()) + } +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + use std::rc::Rc; + use std::time::Duration; + + use gpui::{TestAppContext, VisualTestContext}; + use gpui_kit::{Bounds, 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::dev::logic as sample; + use voelin_ui_vm::settings::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::theme::Choice; + use crate::window_bounds; + + /// 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 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))); + } + + /// 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())); } } diff --git a/scripts/gpui-shot.sh b/scripts/gpui-shot.sh index 89d5505..4ac5a7c 100755 --- a/scripts/gpui-shot.sh +++ b/scripts/gpui-shot.sh @@ -25,7 +25,8 @@ # # VOELIN_BIN: the binary (default target/release/voelin-gpui, else # target/debug); DELAY: seconds the window is shown before the picture -# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE and the other switches of +# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE, VOELIN_DEMO_UI (the sample +# servers: a picture of the shell with one on screen) and the other switches of # `src/dev.rs` are passed on as set. set -eu out=${1:?usage: gpui-shot.sh [ [x]]} @@ -70,7 +71,8 @@ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u XDG_SESSION_TYPE -u DBUS_SESSION_BUS "$bin" >"$work/app.log" 2>&1 & pid=$! i=0 -until win=$(xdotool search --name '^Voelin$' 2>/dev/null | head -1) && [ -n "$win" ]; do +# The title is the app's name, and ` - ` once a server is on screen. +until win=$(xdotool search --name '^Voelin( - |$)' 2>/dev/null | head -1) && [ -n "$win" ]; do i=$((i + 1)) kill -0 "$pid" 2>/dev/null || { echo "gpui-shot.sh: the app ended before its window:" >&2; tail -20 "$work/app.log" >&2; exit 1; } [ $i -lt 300 ] || { echo "gpui-shot.sh: no window after 30 s:" >&2; tail -20 "$work/app.log" >&2; exit 1; }