Files
VoelinClient/crates/voelin-gpui/src/view.rs
T
faumarayandClaude Sonnet 5.5 9ab56ec973 voelin-gpui: the maximize guard covers the first two reports only
A window opened to be maximized dropped every windowed report until it
was seen maximized, so a resize the user made before the window manager
answered (or under one that never maximizes, a tiling one) was never
kept. The guard is now a budget of OPENING_REPORTS = 2 windowed reports,
the place the window opened with and the configure an X11 window manager
may send at the map; a maximized report ends it, and the reports after
it are the user's. Tests on the GPUI test platform: the root state keeps
the third report, the shell keeps a resize that follows the two. The
sentence in docs/ui.md says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:22:40 +03:00

945 lines
35 KiB
Rust

//! 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::{
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<WindowState> {
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<AppState>,
page: Page,
counters: Counters,
rail: Entity<ServerRail>,
topbar: Entity<TopBar>,
sidebar: Entity<Sidebar>,
main: Entity<MainPanel>,
toast: Entity<Toast>,
form: Option<Entity<ServerForm>>,
title: String,
focus: FocusHandle,
_subscriptions: Vec<Subscription>,
}
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<AppState>,
page: Page,
counters: Counters,
window: &mut Window,
cx: &mut Context<Self>,
) -> 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 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);
// 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);
}
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<ServerForm>> {
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>,
) {
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>) {
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>) {
self.app.update(cx, |app, cx| app.connect_voice(cx));
}
fn disconnect_voice(&mut self, _: &DisconnectVoice, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.disconnect_voice(cx));
}
fn set_input_muted(&mut self, action: &SetInputMuted, _: &mut Window, cx: &mut Context<Self>) {
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>,
) {
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>) {
self.app.update(cx, |app, cx| app.push_to_talk(action.on, cx));
}
fn invite(&mut self, _: &Invite, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.invite(cx));
}
fn add_server(&mut self, _: &AddServer, window: &mut Window, cx: &mut Context<Self>) {
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<Self>) {
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<Self>) {
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>) {
self.save(false, cx);
}
fn save_and_connect(&mut self, _: &SaveAndConnect, _: &mut Window, cx: &mut Context<Self>) {
self.save(true, cx);
}
fn cancel_form(&mut self, _: &CancelServerForm, _: &mut Window, cx: &mut Context<Self>) {
self.form = None;
cx.notify();
}
fn delete_server(&mut self, action: &DeleteServer, _: &mut Window, cx: &mut Context<Self>) {
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<Self>) {
tracing::info!("the search comes with its slice (docs/ui.md, \"What is next\")");
}
fn open_settings(&mut self, _: &OpenSettings, _: &mut Window, _: &mut Context<Self>) {
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<AppState>, 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<Self>) -> impl IntoElement {
// One render of the window is one frame. A part that has something new
// tells the window, and the window then renders every part (gpui-pre
// renders each uncached child view on 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));
}
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()
.flex_1()
.min_w_0()
.h_full()
.flex()
.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;
thread_local! {
/// How many times a window asked to be zoomed (`zoom` in this module).
pub(super) static ZOOMS: Cell<usize> = 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<AppState>,
view: Entity<MainView>,
events: UnboundedSender<Event>,
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<Bounds<gpui_kit::Pixels>> {
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<i64> {
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<String> = 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::<i64>::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<WindowState>| {
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()));
}
}