Slice 2, first half: the sidebar's placeholder becomes the selected server's channel tree from voelin-ui-vm's rows (tree_view): nested channels with their spacers, icons, banners, lock and counts, and the people in them with their avatar, badges and marks. A TreeModel entity builds the rows once for both panes on the tree, toolbar and member-card signals and tells what differs (list::diff, the row operations the Slint front end applies to its VecModel); ChannelTree is a cached pane over a virtual list that applies them, so a person who joins is a row inserted and the scroll stays. The rows carry no `talking`: a talker redraws the members panel, not the tree (docs/ui.md says so). A click selects a channel, a double-click joins it (sequence::join_channel: the move, the prompt for a locked channel's password, a connect into it without voice), the chevron folds it, a right-click offers Join, fold and Edit channel (logged: the channel editor is another slice), a click on a person is logged (their volume dialog is another slice). The password prompt (Update::password) is a card over the window, asking again when the server refuses the password. The folds and the selection are kept per server in ui.tree and found again by the next run. The shell's cached panes lay out their root at the size the place gives them (size_full), which the main area needed. Tests: the sample server's rows, folding and its settings, the round trip through a closed run, double-click and action join, the password prompt and its refusal, a move (the exact row operations) and a mute (one row), a talker leaves the tree alone. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1857 lines
65 KiB
Rust
1857 lines
65 KiB
Rust
//! The root state of the window, `Entity<AppState>`: everything the client
|
|
//! knows (the toolkit-free [`voelin_ui_vm`] state and the friends and pokes
|
|
//! beside it), the store and the settings it was read from, and the three
|
|
//! loops that keep it current on GPUI's thread:
|
|
//!
|
|
//! - the **engine's events**: a foreground task awaits the receiver of
|
|
//! [`crate::engine::HostedEngine`] (a tokio channel needs no reactor, so
|
|
//! GPUI's executor can poll it), takes what is queued (up to [`BATCH`]
|
|
//! events) in one go, hands every event to [`events::handle`], tells the
|
|
//! entity to redraw once (`cx.notify()`) and then yields to GPUI's
|
|
//! executor, so that a burst (a server's first sync) neither starves the
|
|
//! window nor draws it once per event;
|
|
//! - the **tick**, once a second, a loop of `background_executor().timer`
|
|
//! (the Slint front end's `slint::Timer` calling `App::tick`): it keeps
|
|
//! what is due (the window's place) and notifies nobody, since nothing the
|
|
//! shell shows moves with the clock;
|
|
//! - **later**: other threads (a hotkey, a camera, a decoder) cannot touch the
|
|
//! entity, and GPUI's `AsyncApp` is not `Send`, so they hold a [`Later`], a
|
|
//! channel of jobs a third foreground task runs on GPUI's thread, as
|
|
//! `later(|app| ...)` does in the Slint front end.
|
|
//!
|
|
//! The root notifies on every batch of events and on every move of the user's
|
|
//! (the window's title and the toast follow it). What a transition's
|
|
//! `refresh` flags name is raised as per-area signals ([`crate::signals`],
|
|
//! once per batch of events) that the parts of the window observe, and it is
|
|
//! the parts (`crate::shell`) that decide whether what they show changed and
|
|
//! tell the window only then. What a transition asks for besides the state
|
|
//! (`Update`) is carried out as far as this front end has the parts: the
|
|
//! engine's commands go out, the status line is set, what is to be kept goes
|
|
//! to the store, a setting the theme follows is applied, the warnings are
|
|
//! logged and the flags of the areas that have a part are raised; the other
|
|
//! flags, the notices, the pictures to decode and the streams' capture and
|
|
//! decoder are for the slices that have those parts.
|
|
|
|
use std::collections::HashSet;
|
|
use std::task::Poll;
|
|
use std::time::Duration;
|
|
|
|
use gpui_kit::{ClipboardItem, Context};
|
|
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
|
|
use tracing::{debug, warn};
|
|
use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings};
|
|
use voelin_core::{Command, Engine, Event, VoiceState};
|
|
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, Store};
|
|
use voelin_ui_vm::bridge::{BookmarkForm, ChatLine};
|
|
use voelin_ui_vm::events;
|
|
use voelin_ui_vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update};
|
|
use voelin_ui_vm::image::ImageRef;
|
|
use voelin_ui_vm::servers::logic;
|
|
use voelin_ui_vm::servers::sequence::{self, Backing};
|
|
use voelin_ui_vm::settings::{
|
|
CLIENT_PLAYBACK, ThemeChoice, TreeStates, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME,
|
|
UI_TREE, UI_WINDOW, WindowState,
|
|
};
|
|
use voelin_ui_vm::social::logic::Social;
|
|
use voelin_ui_vm::tree::ChannelId;
|
|
|
|
use crate::backend::Backend;
|
|
use crate::dev::Switches;
|
|
use crate::meter::Counters;
|
|
use crate::pictures;
|
|
use crate::signals::{Area, Signals};
|
|
use crate::theme::{Choice, VoelinTheme};
|
|
|
|
/// The toolkit-free state of the client, with the chat lines of a tab as plain
|
|
/// rows (what a front end that draws again from the list needs).
|
|
pub type VmState = voelin_ui_vm::state::AppState<Vec<ChatLine>>;
|
|
|
|
/// How many engine events one update of the entity takes at most: a burst
|
|
/// is handled in steps of this size, with a yield to GPUI's executor between
|
|
/// them.
|
|
pub const BATCH: usize = 64;
|
|
|
|
/// A job for GPUI's thread, from any thread.
|
|
type Job = Box<dyn FnOnce(&mut AppState, &mut Context<AppState>) + Send>;
|
|
|
|
/// How other threads reach the root state: `later.run(|app, cx| ...)` runs
|
|
/// the closure on GPUI's thread with the entity (the Slint front end's
|
|
/// `later`). Cloneable and `Send`; the closure must be `Send` too.
|
|
#[derive(Clone)]
|
|
pub struct Later(UnboundedSender<Job>);
|
|
|
|
impl Later {
|
|
/// Run `job` on GPUI's thread soon. `false` once a job has found the
|
|
/// window gone (the entity released): the loop that runs the jobs notices
|
|
/// that only when a job reaches it, ends and drops the channel, so the
|
|
/// first job sent after the window went answers `true` and is never run.
|
|
/// `true` is a promise of nothing more than that the job was queued.
|
|
pub fn run(
|
|
&self,
|
|
job: impl FnOnce(&mut AppState, &mut Context<AppState>) + Send + 'static,
|
|
) -> bool {
|
|
self.0.send(Box::new(job)).is_ok()
|
|
}
|
|
}
|
|
|
|
/// What the transitions of the state ask of this front end while they run:
|
|
/// the store's read marks and the settings they depend on.
|
|
struct ShellHost<'a> {
|
|
demo_ui: bool,
|
|
store: &'a Store,
|
|
prefs: &'a Settings,
|
|
}
|
|
|
|
impl Host for ShellHost<'_> {
|
|
fn demo_ui(&self) -> bool {
|
|
self.demo_ui
|
|
}
|
|
|
|
// No page shows a chat yet, nothing is watched and the Stream Studio does
|
|
// not exist: the slices that have them answer from their own state.
|
|
fn chat_shown(&self) -> bool {
|
|
false
|
|
}
|
|
|
|
fn watching(&self) -> bool {
|
|
false
|
|
}
|
|
|
|
fn autowatch(&self) -> bool {
|
|
false
|
|
}
|
|
|
|
fn studio_streams_to(&self, _session: i64) -> bool {
|
|
false
|
|
}
|
|
|
|
fn preview_limit(&self) -> u64 {
|
|
u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024
|
|
}
|
|
|
|
fn fetch_images(&self) -> bool {
|
|
self.prefs.get(&CACHE_FETCH_IMAGES)
|
|
}
|
|
|
|
fn dm_shown(&self, _session: i64, _uid: &str) -> bool {
|
|
false
|
|
}
|
|
|
|
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
|
|
self.store.chat_reads(server_uid).map_err(|e| e.to_string())
|
|
}
|
|
|
|
fn set_chat_read(
|
|
&self,
|
|
server_uid: &str,
|
|
target: &StoredTarget,
|
|
read: &ChatRead,
|
|
) -> Result<(), String> {
|
|
self.store.set_chat_read(server_uid, target, read).map_err(|e| e.to_string())
|
|
}
|
|
}
|
|
|
|
/// What [`AppState::new`] starts from.
|
|
pub struct Setup {
|
|
/// The engine commands go to; none in the tests that need none.
|
|
pub engine: Option<Engine>,
|
|
/// The engine's events (`tx` stands in for it in tests).
|
|
pub events: UnboundedReceiver<Event>,
|
|
/// What the meter counts.
|
|
pub counters: Counters,
|
|
/// The store, the settings and the secrets.
|
|
pub backend: Backend,
|
|
/// The development switches.
|
|
pub switches: Switches,
|
|
}
|
|
|
|
/// The theme mode and the text size factor: a development switch first, else
|
|
/// the settings' (`ui.theme`, `ui.font_scale`).
|
|
pub fn appearance(prefs: &Settings, switches: &Switches) -> (Choice, f32) {
|
|
let choice = switches.theme.unwrap_or(match prefs.get(&UI_THEME) {
|
|
ThemeChoice::Dark => Choice::Dark,
|
|
ThemeChoice::Light => Choice::Light,
|
|
ThemeChoice::System => Choice::System,
|
|
});
|
|
(choice, switches.font_scale.unwrap_or_else(|| prefs.get(&UI_FONT_SCALE)))
|
|
}
|
|
|
|
/// Where the window's place is kept between ticks.
|
|
#[derive(Debug, Default)]
|
|
struct WindowKeeper {
|
|
/// The latest place the window reported and the store has not got.
|
|
latest: Option<WindowState>,
|
|
/// What the settings hold.
|
|
saved: Option<WindowState>,
|
|
/// Where the window returns to when it is not maximized: the latest
|
|
/// windowed place of this run, else the remembered one. (X11 reports the
|
|
/// screen's size for a maximized window, Wayland the size it returns to.)
|
|
restore: Option<WindowState>,
|
|
/// The window was opened to be maximized and has not been seen maximized
|
|
/// yet: how many of its windowed reports are still the place it opened
|
|
/// with, not one the user chose, and are not kept ([`OPENING_REPORTS`] at
|
|
/// start, none once the window was seen maximized or the reports ran out).
|
|
opening_reports: u8,
|
|
}
|
|
|
|
/// How many windowed reports of a window opened to be maximized are taken to
|
|
/// be the place it opened with, not the user's: the first is the window's
|
|
/// own at its creation, the second the configure an X11 window manager may
|
|
/// send when it maps the window. A later one is the user's own move or
|
|
/// resize, kept even if the window manager has still not maximized the window
|
|
/// (a tiling one never does).
|
|
pub const OPENING_REPORTS: u8 = 2;
|
|
|
|
/// Give up the foreground thread once, so that GPUI's executor runs what is
|
|
/// queued before this task goes on.
|
|
async fn yield_now() {
|
|
let mut yielded = false;
|
|
std::future::poll_fn(|task| {
|
|
if yielded {
|
|
Poll::Ready(())
|
|
} else {
|
|
yielded = true;
|
|
task.waker().wake_by_ref();
|
|
Poll::Pending
|
|
}
|
|
})
|
|
.await;
|
|
}
|
|
|
|
/// The root entity.
|
|
pub struct AppState {
|
|
/// What the client knows apart from the window.
|
|
pub vm: VmState,
|
|
/// The friends, pokes and notices the social screens keep.
|
|
pub social: Social<()>,
|
|
/// Engine events handled since the window opened.
|
|
pub events_handled: u64,
|
|
/// One-second ticks since the window opened.
|
|
pub ticks: u64,
|
|
/// How many times the status line was set: a view that shows it as a
|
|
/// toast sees a new text by this number changing, even when the text is
|
|
/// the same as the last.
|
|
pub status_generation: u64,
|
|
/// How many times a channel's password was asked for: the window opens the
|
|
/// prompt ([`AppState::password_prompt`]) when this changes.
|
|
pub password_generation: u64,
|
|
engine: Option<Engine>,
|
|
backend: Backend,
|
|
switches: Switches,
|
|
window: WindowKeeper,
|
|
counters: Counters,
|
|
signals: Signals,
|
|
password: Option<PasswordPrompt>,
|
|
/// What each server's tree remembers (`ui.tree`), by bookmark id.
|
|
tree_states: TreeStates,
|
|
/// The servers whose remembered folds are in their sessions.
|
|
tree_restored: HashSet<i64>,
|
|
later: Later,
|
|
/// What went to the engine (tests look at it: an engine of the test's
|
|
/// own would have to be asked what it was sent).
|
|
#[cfg(test)]
|
|
sent: std::cell::RefCell<Vec<Command>>,
|
|
}
|
|
|
|
impl AppState {
|
|
/// The state at start, with its three loops running: the engine's
|
|
/// `events`, the tick and the jobs of [`Later`]. They end when the entity
|
|
/// is released. The saved servers, the settings and the identity are the
|
|
/// `backend`'s; the sample servers replace the saved ones with
|
|
/// `VOELIN_DEMO_UI`.
|
|
pub fn new(setup: Setup, cx: &mut Context<Self>) -> Self {
|
|
let Setup { engine, events, counters, backend, switches } = setup;
|
|
let (later, mut jobs) = mpsc::unbounded_channel::<Job>();
|
|
|
|
cx.spawn(async move |this, cx| {
|
|
let mut events = events;
|
|
let mut batch = Vec::with_capacity(BATCH);
|
|
while let Some(first) = events.recv().await {
|
|
batch.push(first);
|
|
while batch.len() < BATCH {
|
|
let Ok(event) = events.try_recv() else { break };
|
|
batch.push(event);
|
|
}
|
|
if this.update(cx, |state, cx| state.handle_events(batch.drain(..), cx)).is_err() {
|
|
break;
|
|
}
|
|
// A tokio receiver that has more is ready at once, outside a
|
|
// tokio runtime too: without this the loop would not give GPUI
|
|
// a turn until the burst is over.
|
|
yield_now().await;
|
|
}
|
|
})
|
|
.detach();
|
|
|
|
cx.spawn(async move |this, cx| {
|
|
loop {
|
|
cx.background_executor().timer(Duration::from_secs(1)).await;
|
|
if this.update(cx, |state, _| state.tick()).is_err() {
|
|
break;
|
|
}
|
|
}
|
|
})
|
|
.detach();
|
|
|
|
cx.spawn(async move |this, cx| {
|
|
while let Some(job) = jobs.recv().await {
|
|
if this
|
|
.update(cx, |state, cx| {
|
|
state.counters.later_jobs.incr();
|
|
job(state, cx);
|
|
cx.notify();
|
|
})
|
|
.is_err()
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
})
|
|
.detach();
|
|
|
|
let loaded = backend.load();
|
|
let saved = backend.prefs.get(&UI_WINDOW);
|
|
let tree_states = backend.prefs.get(&UI_TREE);
|
|
let mut state = Self {
|
|
vm: VmState::new(loaded.bookmarks, loaded.settings, loaded.audio, loaded.playback),
|
|
social: Social::default(),
|
|
events_handled: 0,
|
|
ticks: 0,
|
|
status_generation: 0,
|
|
password_generation: 0,
|
|
engine,
|
|
backend,
|
|
switches,
|
|
window: WindowKeeper {
|
|
latest: None,
|
|
saved,
|
|
restore: saved.filter(WindowState::is_sane),
|
|
opening_reports: 0,
|
|
},
|
|
counters,
|
|
signals: Signals::new(cx),
|
|
password: None,
|
|
tree_states,
|
|
tree_restored: HashSet::new(),
|
|
later: Later(later),
|
|
#[cfg(test)]
|
|
sent: Default::default(),
|
|
};
|
|
state.window.opening_reports = if state.wants_maximized() { OPENING_REPORTS } else { 0 };
|
|
if state.switches.demo_ui {
|
|
state.load_demo();
|
|
} else if let Some(id) = state.vm.current {
|
|
state.restore_tree(id);
|
|
}
|
|
state
|
|
}
|
|
|
|
/// The sample servers of `VOELIN_DEMO_UI`, through the same events a server
|
|
/// would send ([`voelin_ui_vm::dev::logic`]): the first is connected, the
|
|
/// second observed.
|
|
fn load_demo(&mut self) {
|
|
use voelin_ui_vm::dev::logic as sample;
|
|
self.vm.bookmarks = sample::bookmarks();
|
|
self.vm.settings.last_voice = Some(sample::last_voice());
|
|
self.vm.current = Some(sample::DEMO);
|
|
for event in sample::server_events() {
|
|
let update = self.handle(event);
|
|
self.counters.engine_events.incr();
|
|
self.events_handled += 1;
|
|
// Nothing of it goes out: `send` is silent in demo mode, and the
|
|
// settings and bookmarks are not kept.
|
|
self.log_warnings(update.warnings);
|
|
}
|
|
self.vm.status.clear();
|
|
self.counters.connections.set(self.connections() as u64);
|
|
}
|
|
|
|
/// The handle other threads use to run something on GPUI's thread.
|
|
pub fn later(&self) -> Later {
|
|
self.later.clone()
|
|
}
|
|
|
|
/// What the development switches say.
|
|
pub fn switches(&self) -> &Switches {
|
|
&self.switches
|
|
}
|
|
|
|
/// The engine, when there is one.
|
|
pub fn engine(&self) -> Option<&Engine> {
|
|
self.engine.as_ref()
|
|
}
|
|
|
|
/// The store, the settings and the secrets.
|
|
pub fn backend(&self) -> &Backend {
|
|
&self.backend
|
|
}
|
|
|
|
/// What the meter counts.
|
|
pub fn counters(&self) -> &Counters {
|
|
&self.counters
|
|
}
|
|
|
|
/// The per-area signals the parts of the window observe
|
|
/// ([`crate::signals`]).
|
|
pub fn signals(&self) -> &Signals {
|
|
&self.signals
|
|
}
|
|
|
|
/// What an engine event does to the state ([`events::handle`], the one
|
|
/// dispatch of both front ends), and what asks to be done of it.
|
|
fn handle(&mut self, event: Event) -> Update {
|
|
let host = ShellHost {
|
|
demo_ui: self.switches.demo_ui,
|
|
store: &self.backend.store,
|
|
prefs: &self.backend.prefs,
|
|
};
|
|
events::handle(&mut self.vm, &mut self.social, &host, event)
|
|
}
|
|
|
|
/// Take engine events in, in order: each changes the state and is carried
|
|
/// out, and the entity notifies once for all of them.
|
|
pub fn handle_events(
|
|
&mut self,
|
|
events: impl IntoIterator<Item = Event>,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
let mut refresh = Refresh::default();
|
|
for event in events {
|
|
self.events_handled += 1;
|
|
self.counters.engine_events.incr();
|
|
let update = self.handle(event);
|
|
refresh.merge(self.perform(update, cx));
|
|
}
|
|
self.counters.connections.set(self.connections() as u64);
|
|
// Each area once for the whole batch.
|
|
self.signals.raise(&refresh, cx);
|
|
cx.notify();
|
|
}
|
|
|
|
/// One engine event ([`AppState::handle_events`]).
|
|
pub fn handle_event(&mut self, event: Event, cx: &mut Context<Self>) {
|
|
self.handle_events([event], cx);
|
|
}
|
|
|
|
/// Run a transition of the view model on the state and carry out what it
|
|
/// says.
|
|
fn transition<R>(
|
|
&mut self,
|
|
cx: &mut Context<Self>,
|
|
f: impl FnOnce(&mut VmState, &mut Cx<'_>) -> R,
|
|
) -> R {
|
|
self.transition_with(cx, |state, transition, _| f(state, transition))
|
|
}
|
|
|
|
/// Like [`AppState::transition`], for a sequence that also reads and writes
|
|
/// the store and the secrets and picks the identity
|
|
/// (`voelin_ui_vm::servers::sequence`): the [`Backing`] is the backend's.
|
|
fn transition_with<R>(
|
|
&mut self,
|
|
cx: &mut Context<Self>,
|
|
f: impl FnOnce(&mut VmState, &mut Cx<'_>, &Backing<'_>) -> R,
|
|
) -> R {
|
|
let host = ShellHost {
|
|
demo_ui: self.switches.demo_ui,
|
|
store: &self.backend.store,
|
|
prefs: &self.backend.prefs,
|
|
};
|
|
let identity = |named| self.backend.identity_blob(named);
|
|
let backing = Backing {
|
|
store: &self.backend.store,
|
|
secrets: &*self.backend.secrets,
|
|
identity: &identity,
|
|
};
|
|
let mut transition = Cx::new(&host);
|
|
let result = f(&mut self.vm, &mut transition, &backing);
|
|
let update = transition.update;
|
|
let refresh = self.perform(update, cx);
|
|
self.signals.raise(&refresh, cx);
|
|
result
|
|
}
|
|
|
|
/// An engine command; none in demo mode (the engine would open the sample
|
|
/// sessions for real) and none without an engine.
|
|
fn send(&self, command: Command) {
|
|
if self.switches.demo_ui {
|
|
return;
|
|
}
|
|
#[cfg(test)]
|
|
self.sent.borrow_mut().push(command.clone());
|
|
if let Some(engine) = &self.engine {
|
|
engine.send(command);
|
|
}
|
|
}
|
|
|
|
/// The commands sent since the last call.
|
|
#[cfg(test)]
|
|
pub(crate) fn take_sent(&self) -> Vec<Command> {
|
|
std::mem::take(&mut *self.sent.borrow_mut())
|
|
}
|
|
|
|
/// A command for the session on screen.
|
|
fn command(&self, f: impl FnOnce(u64) -> Command) {
|
|
if let Some(id) = self.vm.current {
|
|
self.send(f(id as u64));
|
|
}
|
|
}
|
|
|
|
fn log_warnings(&self, warnings: Vec<String>) {
|
|
for text in warnings {
|
|
warn!("{text}");
|
|
}
|
|
}
|
|
|
|
/// Do what an update asks that this front end has the parts for, and say
|
|
/// which areas of the window it asks to draw again (`refresh`, and what
|
|
/// the front end's own settings change): the caller raises them
|
|
/// ([`Signals::raise`]) once for as many updates as it has handled.
|
|
fn perform(&mut self, update: Update, cx: &mut Context<Self>) -> Refresh {
|
|
let Update {
|
|
refresh,
|
|
status,
|
|
commands,
|
|
persist,
|
|
warnings,
|
|
rest,
|
|
password,
|
|
discover,
|
|
reloaded,
|
|
..
|
|
} = update;
|
|
self.log_warnings(warnings);
|
|
// The pictures the engine wrote again: what was decoded of the old
|
|
// ones goes ([`crate::pictures`]); the lists that show them compare
|
|
// the new reference unequal and draw the rows again.
|
|
for path in &reloaded {
|
|
pictures::forget_stale(path, cx);
|
|
}
|
|
for command in commands {
|
|
self.send(command);
|
|
}
|
|
for (id, address) in discover {
|
|
self.look_up_gateway(id, address);
|
|
}
|
|
if let Some(text) = status {
|
|
self.set_status(text);
|
|
}
|
|
for what in persist {
|
|
self.keep(what);
|
|
}
|
|
if let Some(prompt) = password {
|
|
self.password = Some(prompt);
|
|
self.password_generation += 1;
|
|
}
|
|
// What the front end keeps itself comes before the drawing.
|
|
if let Some(Event::SettingChanged { key }) = rest {
|
|
self.setting_changed(&key, cx);
|
|
}
|
|
refresh
|
|
}
|
|
|
|
/// The status line says this from now on.
|
|
pub fn set_status(&mut self, text: impl Into<String>) {
|
|
self.vm.status = text.into();
|
|
self.status_generation += 1;
|
|
}
|
|
|
|
/// Keep what a transition changed (nothing in demo mode).
|
|
fn keep(&mut self, what: Persist) {
|
|
if self.switches.demo_ui {
|
|
return;
|
|
}
|
|
match what {
|
|
Persist::Bookmark { id, what } => {
|
|
let Some(bookmark) = self.vm.bookmarks.iter().find(|b| b.id == id) else {
|
|
return;
|
|
};
|
|
match self.backend.store.update_bookmark(bookmark) {
|
|
Ok(()) => debug!(server = %bookmark.address, "{what}"),
|
|
Err(e) => warn!(%e, "could not keep the bookmark: {what}"),
|
|
}
|
|
}
|
|
Persist::Settings => {
|
|
if let Err(e) = self.backend.prefs.set(&UI, self.vm.settings.clone()) {
|
|
warn!(%e, "could not store settings");
|
|
}
|
|
}
|
|
Persist::Audio => {
|
|
if let Err(e) = self.backend.prefs.set(&AUDIO, self.vm.audio.clone()) {
|
|
warn!(%e, "could not store audio settings");
|
|
}
|
|
}
|
|
Persist::Playback => {
|
|
if let Err(e) = self.backend.prefs.set(&CLIENT_PLAYBACK, self.vm.playback.clone()) {
|
|
warn!(%e, "could not store client volumes");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A setting changed, maybe elsewhere (a command, another window): take
|
|
/// the values the window keeps copies of. Today that is what the theme
|
|
/// follows; the development switches keep what they set.
|
|
fn setting_changed(&mut self, key: &str, cx: &mut Context<Self>) {
|
|
if key == UI_THEME.name() || key == UI_FONT_SCALE.name() {
|
|
let (choice, scale) = appearance(&self.backend.prefs, &self.switches);
|
|
let appearance = cx.window_appearance();
|
|
VoelinTheme::set_choice(cx, choice, appearance);
|
|
VoelinTheme::set_font_scale(cx, scale);
|
|
}
|
|
}
|
|
|
|
/// The once-a-second work: what the Slint front end's `App::tick` will be
|
|
/// here (stream statistics, stored settings). Today it counts and keeps
|
|
/// the window's place. It does not notify: nothing the shell shows changes
|
|
/// with the clock, so a window that is not touched is not drawn.
|
|
pub fn tick(&mut self) {
|
|
self.ticks += 1;
|
|
self.counters.ticks.incr();
|
|
self.flush_window();
|
|
}
|
|
|
|
/// The window moved or changed size: remember it, to keep at the next tick
|
|
/// (and at close). Not with a development switch that sets the size, and
|
|
/// not with the sample data: neither is the user's window.
|
|
///
|
|
/// A window that was opened to be maximized ([`Self::wants_maximized`])
|
|
/// reports the place it opened with first (the window manager maximizes it
|
|
/// after it is shown, on X11 when [`crate::view::MainView`] asks): its
|
|
/// first [`OPENING_REPORTS`] windowed reports are not kept, or a run that
|
|
/// ended before the window was maximized would overwrite `maximized: true`
|
|
/// with `false`. Once it has been seen maximized, or after those reports,
|
|
/// what it reports is the user's (a resize before the window manager
|
|
/// answered, or with one that never maximizes, is kept). A maximized
|
|
/// window is kept with the place it returns to, not the screen's size.
|
|
pub fn window_moved(&mut self, state: WindowState) {
|
|
if self.switches.window.is_some() || self.switches.demo_ui {
|
|
return;
|
|
}
|
|
let keeper = &mut self.window;
|
|
let state = if state.maximized {
|
|
keeper.opening_reports = 0;
|
|
keeper.restore.map_or(state, |back| WindowState { maximized: true, ..back })
|
|
} else if keeper.opening_reports > 0 {
|
|
keeper.opening_reports -= 1;
|
|
return;
|
|
} else {
|
|
keeper.restore = Some(state);
|
|
state
|
|
};
|
|
keeper.latest = Some(state);
|
|
}
|
|
|
|
/// The window's place as the last run left it.
|
|
pub fn remembered_window(&self) -> Option<WindowState> {
|
|
self.window.saved.filter(WindowState::is_sane)
|
|
}
|
|
|
|
/// Whether the window is opened to be maximized: the last run left it so
|
|
/// and no development switch sets its size.
|
|
pub fn wants_maximized(&self) -> bool {
|
|
self.switches.window.is_none() && self.remembered_window().is_some_and(|w| w.maximized)
|
|
}
|
|
|
|
/// Whether the window was opened to be maximized, has not been seen so yet
|
|
/// (the window manager has not answered, or cannot) and has not reported
|
|
/// more than [`OPENING_REPORTS`] places.
|
|
pub fn awaiting_maximize(&self) -> bool {
|
|
self.window.opening_reports > 0
|
|
}
|
|
|
|
/// Write the window's place to the settings if it changed.
|
|
fn flush_window(&mut self) {
|
|
let Some(latest) = self.window.latest.take() else { return };
|
|
if self.window.saved == Some(latest) {
|
|
return;
|
|
}
|
|
match self.backend.prefs.set(&UI_WINDOW, Some(latest)) {
|
|
Ok(()) => self.window.saved = Some(latest),
|
|
Err(e) => warn!(%e, "could not store the window's place"),
|
|
}
|
|
}
|
|
|
|
/// Voice connections that are up.
|
|
pub fn connections(&self) -> usize {
|
|
self.vm.sessions.values().filter(|view| view.state.voice == VoiceState::Connected).count()
|
|
}
|
|
|
|
/// The window's title: the app's name, and the server shown.
|
|
pub fn window_title(&self) -> String {
|
|
let shown = self
|
|
.vm
|
|
.current
|
|
.and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id))
|
|
.map(|b| b.name.as_str());
|
|
match shown {
|
|
Some(name) => format!("{} - {name}", voelin_platform::APP_NAME),
|
|
None => voelin_platform::APP_NAME.to_owned(),
|
|
}
|
|
}
|
|
|
|
/// The server on screen.
|
|
pub fn current_bookmark(&self) -> Option<&Bookmark> {
|
|
self.vm.current.and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id))
|
|
}
|
|
|
|
/// A server's icon: what its session fetched, else what the engine cached.
|
|
pub fn server_icon(&self, bookmark: &Bookmark) -> ImageRef {
|
|
let current = self
|
|
.vm
|
|
.sessions
|
|
.get(&bookmark.id)
|
|
.map(|view| view.server_icon_for(&bookmark.address))
|
|
.unwrap_or_default();
|
|
if current.size().width > 0 {
|
|
return current;
|
|
}
|
|
match &self.engine {
|
|
Some(engine) => voelin_ui_vm::servers::cached_icon(bookmark, &engine.cache()),
|
|
None => ImageRef::default(),
|
|
}
|
|
}
|
|
|
|
// The callbacks of `bind/servers.rs` that the shell has: what the
|
|
// actions of `crate::shell` do. The ones that read or write the store, the
|
|
// secrets or the engine's commands are the sequences of
|
|
// `voelin_ui_vm::servers::sequence`, the Slint front end's too.
|
|
|
|
/// Show a server, and observe it.
|
|
pub fn select_server(&mut self, id: i64, cx: &mut Context<Self>) {
|
|
self.restore_tree(id);
|
|
self.transition_with(cx, |state, cx, backing| {
|
|
sequence::select_server(state, cx, backing, id)
|
|
});
|
|
cx.notify();
|
|
}
|
|
|
|
/// Connect the server on screen with voice, into its default channel.
|
|
pub fn connect_voice(&mut self, cx: &mut Context<Self>) {
|
|
// `stream_peer` stays the engine's default: what this front end can
|
|
// decode is for the slice with the stream viewer to say.
|
|
self.transition_with(cx, |state, cx, backing| {
|
|
sequence::connect_voice(state, cx, backing, None)
|
|
});
|
|
cx.notify();
|
|
}
|
|
|
|
/// Connect the current server with voice, into `channel` (a path, or
|
|
/// `/<id>`, with its password) if given, with a privilege key if given;
|
|
/// whether it was asked for.
|
|
pub fn connect_voice_to(
|
|
&mut self,
|
|
channel: Option<String>,
|
|
channel_password: Option<String>,
|
|
token: Option<String>,
|
|
cx: &mut Context<Self>,
|
|
) -> bool {
|
|
self.transition_with(cx, |state, cx, backing| {
|
|
sequence::connect_voice_to(state, cx, backing, channel, channel_password, token, None)
|
|
})
|
|
}
|
|
|
|
/// Leave voice on the server on screen.
|
|
pub fn disconnect_voice(&mut self, cx: &mut Context<Self>) {
|
|
self.command(|session| Command::DisconnectVoice { session });
|
|
cx.notify();
|
|
}
|
|
|
|
/// Mute or unmute our microphone on the server on screen.
|
|
pub fn set_input_muted(&mut self, muted: bool, cx: &mut Context<Self>) {
|
|
self.command(|session| Command::SetInputMuted { session, muted });
|
|
cx.notify();
|
|
}
|
|
|
|
/// Mute or unmute the sound of the server on screen.
|
|
pub fn set_output_muted(&mut self, muted: bool, cx: &mut Context<Self>) {
|
|
self.command(|session| Command::SetOutputMuted { session, muted });
|
|
cx.notify();
|
|
}
|
|
|
|
/// Start or stop transmitting (the window's hold-to-talk button).
|
|
pub fn push_to_talk(&mut self, on: bool, cx: &mut Context<Self>) {
|
|
self.command(|session| Command::SetTransmitting { session, on });
|
|
cx.notify();
|
|
}
|
|
|
|
/// A link to the voice channel we are in, copied to the clipboard with a
|
|
/// note in the status line; the reason in the status line without one.
|
|
pub fn invite(&mut self, cx: &mut Context<Self>) -> Option<String> {
|
|
let link = match logic::invite_link(&mut self.vm) {
|
|
Ok(link) => link,
|
|
Err(why) => {
|
|
self.set_status(why);
|
|
cx.notify();
|
|
return None;
|
|
}
|
|
};
|
|
cx.write_to_clipboard(ClipboardItem::new_string(link.clone()));
|
|
let note = self.vm.copy_note.take().unwrap_or_else(|| "Copied".to_owned());
|
|
self.set_status(note);
|
|
cx.notify();
|
|
Some(link)
|
|
}
|
|
|
|
// The callbacks of the channel tree and the members panel.
|
|
|
|
/// Join a channel of the server on screen (`join_channel` of
|
|
/// `bind/servers.rs`, through [`sequence::join_channel`]): the move there
|
|
/// with voice, the password prompt for a locked channel, a connect into
|
|
/// the channel without voice. `stream_peer` stays the engine's default, as
|
|
/// in [`AppState::connect_voice`].
|
|
pub fn join_channel(&mut self, channel: ChannelId, cx: &mut Context<Self>) {
|
|
let Some(session) = self.vm.current else { return };
|
|
self.transition_with(cx, |state, cx, backing| {
|
|
sequence::join_channel(state, cx, backing, session, channel, None)
|
|
});
|
|
cx.notify();
|
|
}
|
|
|
|
/// The password prompt's Join ([`sequence::join_with_password`]).
|
|
pub fn join_with_password(&mut self, password: String, cx: &mut Context<Self>) {
|
|
self.password = None;
|
|
self.transition_with(cx, |state, cx, backing| {
|
|
sequence::join_with_password(state, cx, backing, password, None)
|
|
});
|
|
cx.notify();
|
|
}
|
|
|
|
/// The password prompt was closed without joining.
|
|
pub fn cancel_password(&mut self, cx: &mut Context<Self>) {
|
|
self.password = None;
|
|
self.vm.join_target = None;
|
|
cx.notify();
|
|
}
|
|
|
|
/// The password prompt that is open: the locked channel's name as the tree
|
|
/// shows it, and whether the password given before was refused.
|
|
pub fn password_prompt(&self) -> Option<&PasswordPrompt> {
|
|
self.password.as_ref()
|
|
}
|
|
|
|
/// Fold or unfold a channel of the tree (`toggle_collapse`), and remember
|
|
/// it for the server ([`UI_TREE`]).
|
|
pub fn toggle_collapse(&mut self, channel: ChannelId, cx: &mut Context<Self>) {
|
|
self.transition(cx, |state, cx| logic::toggle_collapse(state, cx, channel));
|
|
self.remember_folds();
|
|
cx.notify();
|
|
}
|
|
|
|
/// Select a channel of the tree, and remember it for the server.
|
|
pub fn select_channel(&mut self, channel: ChannelId, cx: &mut Context<Self>) {
|
|
let Some(id) = self.vm.current else { return };
|
|
let state = self.tree_states.entry(id.to_string()).or_default();
|
|
if state.selected == Some(channel) {
|
|
return;
|
|
}
|
|
state.selected = Some(channel);
|
|
self.keep_tree_states();
|
|
self.signals.raise_area(Area::Tree, cx);
|
|
}
|
|
|
|
/// The channel selected in the tree of the server on screen.
|
|
pub fn selected_channel(&self) -> Option<ChannelId> {
|
|
let id = self.vm.current?;
|
|
self.tree_states.get(&id.to_string()).and_then(|state| state.selected)
|
|
}
|
|
|
|
/// The members panel's search (`search_members`).
|
|
pub fn search_members(&mut self, text: String, cx: &mut Context<Self>) {
|
|
self.transition(cx, |state, cx| logic::search_members(state, cx, text));
|
|
}
|
|
|
|
/// Open the card of a client of the server on screen over the members
|
|
/// panel (`None` closes it).
|
|
pub fn open_member(&mut self, client: Option<u16>, cx: &mut Context<Self>) {
|
|
self.transition(cx, |state, cx| logic::open_member(state, cx, client));
|
|
}
|
|
|
|
/// Put the folds a server's tree remembered into its session, once.
|
|
fn restore_tree(&mut self, id: i64) {
|
|
if self.switches.demo_ui || !self.tree_restored.insert(id) {
|
|
return;
|
|
}
|
|
let Some(state) = self.tree_states.get(&id.to_string()).filter(|s| !s.collapsed.is_empty())
|
|
else {
|
|
return;
|
|
};
|
|
let collapsed = state.collapsed.iter().copied().collect();
|
|
self.vm.sessions.entry(id).or_default().collapsed = collapsed;
|
|
}
|
|
|
|
/// Remember which channels of the server on screen are folded.
|
|
fn remember_folds(&mut self) {
|
|
let Some(id) = self.vm.current else { return };
|
|
let mut collapsed: Vec<ChannelId> = self
|
|
.vm
|
|
.sessions
|
|
.get(&id)
|
|
.map(|view| view.collapsed.iter().copied().collect())
|
|
.unwrap_or_default();
|
|
collapsed.sort_unstable();
|
|
let state = self.tree_states.entry(id.to_string()).or_default();
|
|
if state.collapsed == collapsed {
|
|
return;
|
|
}
|
|
state.collapsed = collapsed;
|
|
if state.is_empty() {
|
|
self.tree_states.remove(&id.to_string());
|
|
}
|
|
self.keep_tree_states();
|
|
}
|
|
|
|
/// Write what the trees remember to the settings (nothing in demo mode).
|
|
fn keep_tree_states(&self) {
|
|
if self.switches.demo_ui {
|
|
return;
|
|
}
|
|
if let Err(e) = self.backend.prefs.set(&UI_TREE, self.tree_states.clone()) {
|
|
warn!(%e, "could not store what the trees remember");
|
|
}
|
|
}
|
|
|
|
/// The server dialog's form for a server (id -1: a new one).
|
|
pub fn bookmark_form(&self, id: i64) -> BookmarkForm {
|
|
sequence::bookmark_form(&self.vm, &self.backend.store, &*self.backend.secrets, id)
|
|
}
|
|
|
|
/// Why a form is not saved here, if it is not: the sample servers are not
|
|
/// kept, and a server needs an address.
|
|
fn save_refused(&self, form: &BookmarkForm) -> Option<&'static str> {
|
|
if self.switches.demo_ui {
|
|
Some("The sample servers are not kept")
|
|
} else if form.address.trim().is_empty() {
|
|
Some("A server needs an address")
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
/// Save the server the form describes, and show it: its id, none when it
|
|
/// could not be saved (the status line says why).
|
|
pub fn save_bookmark(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> Option<i64> {
|
|
if let Some(why) = self.save_refused(form) {
|
|
self.set_status(why);
|
|
cx.notify();
|
|
return None;
|
|
}
|
|
let saved = self.transition_with(cx, |state, cx, backing| {
|
|
sequence::save_bookmark(state, cx, backing, form)
|
|
});
|
|
cx.notify();
|
|
saved
|
|
}
|
|
|
|
/// The server dialog's Connect: save the server, then connect it with
|
|
/// voice, into the channel of the link that filled the form if one did.
|
|
/// Only once saved: connecting what is shown after a failed save would
|
|
/// connect the server shown before. Whether it was saved.
|
|
pub fn save_and_connect(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> bool {
|
|
if let Some(why) = self.save_refused(form) {
|
|
self.set_status(why);
|
|
cx.notify();
|
|
return false;
|
|
}
|
|
let saved = self.transition_with(cx, |state, cx, backing| {
|
|
sequence::save_and_connect(state, cx, backing, form, None)
|
|
});
|
|
cx.notify();
|
|
saved
|
|
}
|
|
|
|
/// Remove a server: its session is closed, its passwords and the bookmark
|
|
/// go, and the first server is shown.
|
|
pub fn delete_bookmark(&mut self, id: i64, cx: &mut Context<Self>) {
|
|
if self.switches.demo_ui {
|
|
self.set_status("The sample servers are not kept");
|
|
cx.notify();
|
|
return;
|
|
}
|
|
self.transition_with(cx, |state, cx, backing| {
|
|
sequence::delete_bookmark(state, cx, backing, id)
|
|
});
|
|
self.tree_restored.remove(&id);
|
|
if self.tree_states.remove(&id.to_string()).is_some() {
|
|
self.keep_tree_states();
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
/// Look the gateway of a server up ([`sequence::find_gateways`]) on the
|
|
/// engine's runtime, as `Update::discover` asks; what is found comes back
|
|
/// through [`Later`].
|
|
fn look_up_gateway(&self, id: i64, address: String) {
|
|
let Some(engine) = &self.engine else { return };
|
|
let later = self.later();
|
|
engine.runtime().spawn(async move {
|
|
if let Some(found) = sequence::find_gateways(&address).await {
|
|
later.run(move |app, cx| {
|
|
app.gateway_found(id, &address, found.urls, found.elapsed_ms, cx)
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Gateways were found for the server at `address`
|
|
/// ([`sequence::gateway_found`]).
|
|
fn gateway_found(
|
|
&mut self,
|
|
id: i64,
|
|
address: &str,
|
|
urls: Vec<String>,
|
|
elapsed_ms: u64,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
self.transition_with(cx, |state, cx, backing| {
|
|
sequence::gateway_found(state, cx, backing, id, address, urls, elapsed_ms)
|
|
});
|
|
}
|
|
|
|
/// Leave the servers properly, so no ghost client stays behind until it
|
|
/// times out (the window is closing): tell the engine to close every
|
|
/// session, keep the window's place and the settings, and the chats' read
|
|
/// marks. Returns how many sessions it told, so that the caller can give
|
|
/// the engine time to act on them before the runtime goes (none without an
|
|
/// engine, none in demo mode).
|
|
pub fn shutdown(&mut self, cx: &mut Context<Self>) -> usize {
|
|
self.flush_window();
|
|
let ids: Vec<i64> = self.vm.sessions.keys().copied().collect();
|
|
for id in &ids {
|
|
self.transition(cx, |state, cx| voelin_ui_vm::chat::logic::save_reads(state, cx, *id));
|
|
}
|
|
self.backend.flush();
|
|
if self.switches.demo_ui || self.engine.is_none() {
|
|
return 0;
|
|
}
|
|
for id in &ids {
|
|
self.send(Command::CloseSession { session: *id as u64 });
|
|
}
|
|
ids.len()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::cell::Cell;
|
|
use std::rc::Rc;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use gpui::TestAppContext;
|
|
use gpui_kit::{AppContext as _, Entity, Subscription, WindowAppearance};
|
|
use voelin_core::{Backends, Command, Event, ObserveState, SessionState, VoiceState};
|
|
use voelin_store::MemorySecrets;
|
|
use voelin_ui_vm::dev::logic as sample;
|
|
|
|
use super::*;
|
|
use crate::backend::testing::TempDir;
|
|
use crate::engine::HostedEngine;
|
|
use crate::signals::Area;
|
|
|
|
fn voice(voice: VoiceState) -> Event {
|
|
Event::State { session: 1, state: SessionState { voice, ..Default::default() } }
|
|
}
|
|
|
|
fn bookmark(name: &str, address: &str) -> Bookmark {
|
|
Bookmark {
|
|
name: name.into(),
|
|
address: address.into(),
|
|
nickname: "Nova".into(),
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
/// The entity of a test over `backend` with no engine behind it: `tx`
|
|
/// stands in for the engine's events.
|
|
fn entity_over(
|
|
cx: &mut TestAppContext,
|
|
backend: Backend,
|
|
switches: Switches,
|
|
) -> (Entity<AppState>, UnboundedSender<Event>, Counters) {
|
|
let (tx, rx) = mpsc::unbounded_channel();
|
|
let counters = Counters::default();
|
|
let setup =
|
|
Setup { engine: None, events: rx, counters: counters.clone(), backend, switches };
|
|
let app = cx.new(|cx| AppState::new(setup, cx));
|
|
(app, tx, counters)
|
|
}
|
|
|
|
/// The entity of a test with nothing stored and no engine.
|
|
fn entity(cx: &mut TestAppContext) -> (Entity<AppState>, UnboundedSender<Event>, Counters) {
|
|
entity_over(cx, Backend::in_memory().unwrap(), Switches::default())
|
|
}
|
|
|
|
/// An in-memory backend whose store has these servers.
|
|
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
|
|
}
|
|
|
|
/// How many times `app` notified, and the subscription that counts.
|
|
fn notifications(
|
|
cx: &mut TestAppContext,
|
|
app: &Entity<AppState>,
|
|
) -> (Rc<Cell<usize>>, Subscription) {
|
|
let seen = Rc::new(Cell::new(0));
|
|
let subscription = cx.update(|cx| {
|
|
let seen = seen.clone();
|
|
cx.observe(app, move |_, _| seen.set(seen.get() + 1))
|
|
});
|
|
(seen, subscription)
|
|
}
|
|
|
|
fn form(address: &str) -> BookmarkForm {
|
|
BookmarkForm { id: -1, address: address.into(), ..Default::default() }
|
|
}
|
|
|
|
#[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(), app.events_handled), (0, 0)));
|
|
|
|
tx.send(voice(VoiceState::Connected)).unwrap();
|
|
cx.run_until_parked();
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.events_handled, 1);
|
|
assert_eq!(app.connections(), 1);
|
|
assert_eq!(app.vm.status, "Connected", "the transition's status line");
|
|
});
|
|
assert_eq!(counters.engine_events.get(), 1);
|
|
assert_eq!(counters.connections.get(), 1);
|
|
|
|
tx.send(voice(VoiceState::Disconnected)).unwrap();
|
|
cx.run_until_parked();
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!((app.events_handled, app.connections()), (2, 0));
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn the_entity_redraws_on_an_event(cx: &mut TestAppContext) {
|
|
let (app, tx, _) = entity(cx);
|
|
let (seen, _subscription) = notifications(cx, &app);
|
|
tx.send(voice(VoiceState::Connecting)).unwrap();
|
|
cx.run_until_parked();
|
|
assert_eq!(seen.get(), 1);
|
|
}
|
|
|
|
/// A burst (a server's first sync) is taken `BATCH` events at a time: one
|
|
/// update and one redraw for each, and a turn of GPUI's executor between
|
|
/// them, not one pass over the whole burst.
|
|
#[gpui::test]
|
|
fn a_burst_of_events_is_taken_in_steps_with_one_redraw_each(cx: &mut TestAppContext) {
|
|
let (app, tx, counters) = entity(cx);
|
|
let (seen, _subscription) = notifications(cx, &app);
|
|
let total = BATCH * 3 + 5;
|
|
for i in 0..total {
|
|
tx.send(Event::Talking { session: 1, client: (i % 50) as u16, talking: true }).unwrap();
|
|
}
|
|
let handled = |cx: &mut TestAppContext| app.read_with(cx, |app, _| app.events_handled);
|
|
while handled(cx) == 0 {
|
|
assert!(cx.executor().tick(), "the events task is runnable");
|
|
}
|
|
assert_eq!(handled(cx), BATCH as u64, "one step, then GPUI's turn");
|
|
assert_eq!(seen.get(), 1);
|
|
|
|
cx.run_until_parked();
|
|
assert_eq!(handled(cx), total as u64);
|
|
assert_eq!(seen.get(), total.div_ceil(BATCH));
|
|
assert_eq!(counters.engine_events.get(), total as u64);
|
|
}
|
|
|
|
/// A batch of events raises each area its updates name once, not once per
|
|
/// event: the parts that listen to an area are told once per batch.
|
|
#[gpui::test]
|
|
fn a_burst_raises_each_area_once_per_batch(cx: &mut TestAppContext) {
|
|
let (app, tx, _) = entity(cx);
|
|
let signals = app.read_with(cx, |app, _| app.signals().clone());
|
|
let generation = |cx: &mut TestAppContext, area: Area| {
|
|
signals.of(area).read_with(cx, |signal, _| signal.generation())
|
|
};
|
|
for i in 0..BATCH * 2 {
|
|
let state = SessionState {
|
|
voice: VoiceState::Connected,
|
|
input_muted: i % 2 == 0,
|
|
..Default::default()
|
|
};
|
|
tx.send(Event::State { session: 1, state }).unwrap();
|
|
}
|
|
cx.run_until_parked();
|
|
// A session's state names the servers, the toolbar and the tree; none
|
|
// names a member card.
|
|
for area in [Area::Servers, Area::Toolbar, Area::Tree] {
|
|
assert_eq!(generation(cx, area), 2, "{area:?}: two batches of {BATCH}");
|
|
}
|
|
assert_eq!(generation(cx, Area::MemberCard), 0);
|
|
}
|
|
|
|
/// The tick counts and keeps what is due, and draws nothing: a window left
|
|
/// alone is not redrawn once a second.
|
|
#[gpui::test]
|
|
fn the_tick_runs_once_a_second_and_notifies_nobody(cx: &mut TestAppContext) {
|
|
let (app, _tx, counters) = entity(cx);
|
|
let (seen, _subscription) = notifications(cx, &app);
|
|
cx.run_until_parked();
|
|
assert_eq!(app.read_with(cx, |app, _| app.ticks), 0);
|
|
for second in 1..=3 {
|
|
cx.executor().advance_clock(Duration::from_secs(1));
|
|
cx.run_until_parked();
|
|
assert_eq!(app.read_with(cx, |app, _| app.ticks), second);
|
|
}
|
|
assert_eq!(counters.ticks.get(), 3);
|
|
assert_eq!(seen.get(), 0, "no redraw");
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn another_thread_runs_a_job_on_the_entity_through_later(cx: &mut TestAppContext) {
|
|
let (app, _tx, counters) = entity(cx);
|
|
let later = app.read_with(cx, |app, _| app.later());
|
|
let sent = std::thread::spawn(move || {
|
|
later.run(|app, _| app.vm.status = "from another thread".into())
|
|
})
|
|
.join()
|
|
.unwrap();
|
|
assert!(sent);
|
|
cx.run_until_parked();
|
|
assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "from another thread");
|
|
assert_eq!(counters.later_jobs.get(), 1);
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn a_job_sent_after_the_window_went_is_dropped_and_the_next_one_is_refused(
|
|
cx: &mut TestAppContext,
|
|
) {
|
|
let (app, _tx, counters) = entity(cx);
|
|
let later = app.read_with(cx, |app, _| app.later());
|
|
drop(app);
|
|
cx.update(|_| {});
|
|
cx.run_until_parked();
|
|
assert!(later.run(|_, _| {}), "queued: nothing has found the entity gone yet");
|
|
cx.run_until_parked();
|
|
assert_eq!(counters.later_jobs.get(), 0, "never run");
|
|
assert!(!later.run(|_, _| {}), "the first job found the entity gone");
|
|
}
|
|
|
|
/// What closing the window hands the runtime's shutdown: the number of
|
|
/// sessions the engine was told to close, which `run` gives time to act
|
|
/// on (the Slint front end does the same). The engine ignores a close for
|
|
/// a session it never opened, so the sessions here are only the state's.
|
|
#[gpui::test]
|
|
fn closing_counts_the_sessions_the_engine_was_told_to_close(cx: &mut TestAppContext) {
|
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
|
.worker_threads(2)
|
|
.enable_all()
|
|
.build()
|
|
.unwrap();
|
|
let hosted = HostedEngine::start_with_backends(&runtime, Backends::empty());
|
|
let (tx, rx) = mpsc::unbounded_channel();
|
|
let setup = Setup {
|
|
engine: Some(hosted.engine.clone()),
|
|
events: rx,
|
|
counters: Counters::default(),
|
|
backend: Backend::in_memory().unwrap(),
|
|
switches: Switches::default(),
|
|
};
|
|
let app = cx.new(|cx| AppState::new(setup, cx));
|
|
assert_eq!(app.update(cx, |app, cx| app.shutdown(cx)), 0, "no session open yet");
|
|
tx.send(voice(VoiceState::Connected)).unwrap();
|
|
cx.run_until_parked();
|
|
assert_eq!(app.update(cx, |app, cx| app.shutdown(cx)), 1);
|
|
runtime.shutdown_timeout(Duration::from_secs(2));
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn closing_without_an_engine_tells_nothing(cx: &mut TestAppContext) {
|
|
let (app, tx, _) = entity(cx);
|
|
tx.send(voice(VoiceState::Connected)).unwrap();
|
|
cx.run_until_parked();
|
|
assert_eq!(app.update(cx, |app, cx| (app.connections(), app.shutdown(cx))), (1, 0));
|
|
}
|
|
|
|
/// The whole path with a real engine: a command makes the engine report a
|
|
/// setting change, which its forwarder hands to the window's channel and
|
|
/// the foreground task to the entity. The engine's tasks run on tokio
|
|
/// threads, so the test looks again until the event is in (no bound on
|
|
/// how long the loaded machine takes, a generous one on the whole wait);
|
|
/// the test scheduler is told that other threads wake it
|
|
/// (`allow_parking`), which it otherwise reports as a test that is not
|
|
/// deterministic.
|
|
#[gpui::test]
|
|
fn a_real_engine_event_reaches_the_entity(cx: &mut TestAppContext) {
|
|
cx.executor().allow_parking();
|
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
|
.worker_threads(2)
|
|
.enable_all()
|
|
.build()
|
|
.unwrap();
|
|
let hosted = HostedEngine::start_with_backends(&runtime, Backends::empty());
|
|
let engine = hosted.engine.clone();
|
|
let setup = Setup {
|
|
engine: Some(engine.clone()),
|
|
events: hosted.events,
|
|
counters: Counters::default(),
|
|
backend: Backend::in_memory().unwrap(),
|
|
switches: Switches::default(),
|
|
};
|
|
let app = cx.new(|cx| AppState::new(setup, cx));
|
|
engine.send(Command::SetSetting { key: "stream.fps".into(), value: 144.into() });
|
|
let deadline = Instant::now() + Duration::from_secs(120);
|
|
while app.read_with(cx, |app, _| app.events_handled) == 0 {
|
|
assert!(Instant::now() < deadline, "the engine's event never arrived");
|
|
cx.run_until_parked();
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
assert!(app.read_with(cx, |app, _| app.events_handled) >= 1);
|
|
runtime.shutdown_timeout(Duration::from_secs(2));
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn the_servers_of_the_store_are_the_ones_shown_and_the_first_is_on_screen(
|
|
cx: &mut TestAppContext,
|
|
) {
|
|
let (app, _, _) = entity_over(
|
|
cx,
|
|
backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]),
|
|
Switches::default(),
|
|
);
|
|
app.read_with(cx, |app, _| {
|
|
let names: Vec<&str> = app.vm.bookmarks.iter().map(|b| b.name.as_str()).collect();
|
|
assert_eq!(names, ["Nightfall", "Lounge"]);
|
|
assert_eq!(app.current_bookmark().map(|b| b.name.as_str()), Some("Nightfall"));
|
|
assert_eq!(app.window_title(), "Voelin - Nightfall");
|
|
});
|
|
let (empty, _, _) = entity(cx);
|
|
empty.read_with(cx, |app, _| {
|
|
assert_eq!((app.vm.current, app.window_title().as_str()), (None, "Voelin"));
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn selecting_a_server_shows_it_and_names_it_in_the_title(cx: &mut TestAppContext) {
|
|
let (app, _, _) = entity_over(
|
|
cx,
|
|
backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]),
|
|
Switches::default(),
|
|
);
|
|
let (seen, _subscription) = notifications(cx, &app);
|
|
let lounge = app.read_with(cx, |app, _| app.vm.bookmarks[1].id);
|
|
app.update(cx, |app, cx| app.select_server(lounge, cx));
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.vm.current, Some(lounge));
|
|
assert_eq!(app.window_title(), "Voelin - Lounge");
|
|
});
|
|
assert!(seen.get() >= 1, "the views are told");
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn a_saved_server_is_stored_shown_and_selected(cx: &mut TestAppContext) {
|
|
let (app, _, _) = entity(cx);
|
|
let id = app
|
|
.update(cx, |app, cx| {
|
|
app.save_bookmark(
|
|
&BookmarkForm { name: "Nightfall".into(), ..form("ts.example") },
|
|
cx,
|
|
)
|
|
})
|
|
.expect("saved");
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.vm.current, Some(id));
|
|
assert_eq!(app.window_title(), "Voelin - Nightfall");
|
|
let kept = app.backend().store.bookmarks().unwrap();
|
|
assert_eq!(kept.iter().map(|b| b.address.as_str()).collect::<Vec<_>>(), ["ts.example"]);
|
|
assert_eq!(app.vm.bookmarks, kept, "the rail's list is the store's");
|
|
assert!(!kept[0].nickname.is_empty(), "a nickname was given");
|
|
});
|
|
// Another with no name is named by its address.
|
|
let second =
|
|
app.update(cx, |app, cx| app.save_bookmark(&form("other.example"), cx)).unwrap();
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.vm.bookmarks.len(), 2);
|
|
assert_eq!(app.window_title(), "Voelin - other.example");
|
|
assert_eq!(app.vm.current, Some(second));
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn a_server_without_an_address_is_not_saved(cx: &mut TestAppContext) {
|
|
let (app, _, _) = entity(cx);
|
|
assert_eq!(app.update(cx, |app, cx| app.save_bookmark(&form(" "), cx)), None);
|
|
app.read_with(cx, |app, _| {
|
|
assert!(
|
|
app.vm.bookmarks.is_empty() && app.backend().store.bookmarks().unwrap().is_empty()
|
|
);
|
|
assert_eq!(app.vm.status, "A server needs an address");
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn editing_a_server_keeps_its_place_and_changes_what_the_form_names(cx: &mut TestAppContext) {
|
|
let (app, _, _) = entity_over(
|
|
cx,
|
|
backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]),
|
|
Switches::default(),
|
|
);
|
|
let first = app.read_with(cx, |app, _| app.vm.bookmarks[0].id);
|
|
let form = app.read_with(cx, |app, _| app.bookmark_form(first));
|
|
assert_eq!((form.id as i64, form.name.as_ref()), (first, "Nightfall"));
|
|
let edited = BookmarkForm { name: "Nightfall Guild".into(), ..form };
|
|
assert_eq!(app.update(cx, |app, cx| app.save_bookmark(&edited, cx)), Some(first));
|
|
app.read_with(cx, |app, _| {
|
|
let names: Vec<&str> = app.vm.bookmarks.iter().map(|b| b.name.as_str()).collect();
|
|
assert_eq!(names, ["Nightfall Guild", "Lounge"], "the same place in the rail");
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn a_removed_server_goes_from_the_rail_and_the_store_and_the_first_is_shown(
|
|
cx: &mut TestAppContext,
|
|
) {
|
|
let (app, _, _) = entity_over(
|
|
cx,
|
|
backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]),
|
|
Switches::default(),
|
|
);
|
|
let (first, second) =
|
|
app.read_with(cx, |app, _| (app.vm.bookmarks[0].id, app.vm.bookmarks[1].id));
|
|
app.update(cx, |app, cx| app.select_server(second, cx));
|
|
app.update(cx, |app, cx| app.delete_bookmark(second, cx));
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.vm.bookmarks.len(), 1);
|
|
assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1);
|
|
assert_eq!(app.vm.current, Some(first), "the first server is shown");
|
|
});
|
|
app.update(cx, |app, cx| app.delete_bookmark(first, cx));
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!((app.vm.current, app.window_title().as_str()), (None, "Voelin"));
|
|
});
|
|
}
|
|
|
|
/// The real path of a connect: the action's method sends the command, the
|
|
/// engine (with no connector, so that no sound device opens) takes it and
|
|
/// answers with its events, which the entity's loop turns into the state
|
|
/// the rail shows. A connect also looks the server's gateway up, which is
|
|
/// DNS (SRV queries for the server's name) and docs/ci.md says tests use
|
|
/// none: the lookup is marked done before the connect, as a second connect
|
|
/// of a run finds it, so nothing leaves the machine.
|
|
#[gpui::test]
|
|
fn a_connect_reaches_the_engine_and_its_answer_reaches_the_rail(cx: &mut TestAppContext) {
|
|
cx.executor().allow_parking();
|
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
|
.worker_threads(2)
|
|
.enable_all()
|
|
.build()
|
|
.unwrap();
|
|
let hosted = HostedEngine::start_with_backends(&runtime, Backends::empty());
|
|
let setup = Setup {
|
|
engine: Some(hosted.engine.clone()),
|
|
events: hosted.events,
|
|
counters: Counters::default(),
|
|
backend: backend_with(&[("Nightfall", "ts.example")]),
|
|
switches: Switches::default(),
|
|
};
|
|
let app = cx.new(|cx| AppState::new(setup, cx));
|
|
let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id);
|
|
app.update(cx, |app, cx| {
|
|
app.vm.gateways_looked_up.insert(id);
|
|
app.connect_voice(cx)
|
|
});
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.vm.status, "Connecting to ts.example…");
|
|
});
|
|
// The engine's answer: the session was asked for, and the engine said
|
|
// why it did not open (no connector serves the address).
|
|
let deadline = Instant::now() + Duration::from_secs(120);
|
|
let answered = |cx: &mut TestAppContext| {
|
|
app.read_with(cx, |app, _| {
|
|
app.vm.status.contains("no connector for ts3server://ts.example")
|
|
})
|
|
};
|
|
while !answered(cx) {
|
|
assert!(
|
|
Instant::now() < deadline,
|
|
"the engine never answered: {}",
|
|
app.read_with(cx, |app, _| app.vm.status.clone())
|
|
);
|
|
cx.run_until_parked();
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
app.read_with(cx, |app, _| {
|
|
let session = &app.vm.sessions[&id];
|
|
assert_eq!(session.state.voice, VoiceState::Disconnected);
|
|
assert_eq!(app.connections(), 0);
|
|
});
|
|
runtime.shutdown_timeout(Duration::from_secs(2));
|
|
}
|
|
|
|
/// What a connect asks of the engine: the server on screen, its address and
|
|
/// nickname, the identity it connects with, its password from the secrets
|
|
/// and its default channel.
|
|
#[gpui::test]
|
|
fn a_connect_asks_the_engine_for_the_server_on_screen_with_what_it_knows(
|
|
cx: &mut TestAppContext,
|
|
) {
|
|
let (app, _, _) = entity(cx);
|
|
let id = app
|
|
.update(cx, |app, cx| {
|
|
app.save_bookmark(
|
|
&BookmarkForm {
|
|
name: "Nightfall".into(),
|
|
nickname: "Nova".into(),
|
|
server_password: "hunter2".into(),
|
|
..form("ts.example")
|
|
},
|
|
cx,
|
|
)
|
|
})
|
|
.unwrap();
|
|
app.read_with(cx, |app, _| app.take_sent());
|
|
app.update(cx, |app, cx| app.connect_voice(cx));
|
|
let sent = app.read_with(cx, |app, _| app.take_sent());
|
|
let [Command::ConnectVoice { session, options }] = sent.as_slice() else {
|
|
panic!("one connect: {sent:?}")
|
|
};
|
|
assert_eq!(*session, id as u64);
|
|
assert_eq!((options.address.as_str(), options.nickname.as_str()), ("ts.example", "Nova"));
|
|
assert_eq!(options.server_password.as_deref(), Some("hunter2"));
|
|
assert!(options.identity.is_some() && options.audio);
|
|
assert_eq!(options.channel, None);
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn a_connect_with_no_server_on_screen_asks_nothing(cx: &mut TestAppContext) {
|
|
let (app, _, _) = entity(cx);
|
|
app.update(cx, |app, cx| app.connect_voice(cx));
|
|
assert!(app.read_with(cx, |app, _| app.take_sent()).is_empty());
|
|
}
|
|
|
|
/// The server dialog's Connect: saved first, then connected into the
|
|
/// server's default channel; a form that cannot be saved connects nothing.
|
|
#[gpui::test]
|
|
fn save_and_connect_saves_the_server_and_then_connects_it(cx: &mut TestAppContext) {
|
|
let (app, _, _) = entity(cx);
|
|
assert!(!app.update(cx, |app, cx| app.save_and_connect(&form(""), cx)));
|
|
assert!(app.read_with(cx, |app, _| app.take_sent()).is_empty());
|
|
assert!(app.update(cx, |app, cx| app.save_and_connect(&form("ts.example"), cx)));
|
|
let sent = app.read_with(cx, |app, _| app.take_sent());
|
|
let connects: Vec<_> = sent
|
|
.iter()
|
|
.filter_map(|c| match c {
|
|
Command::ConnectVoice { options, .. } => Some(options.address.as_str()),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(connects, ["ts.example"], "{sent:?}");
|
|
app.read_with(cx, |app, _| assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1));
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn the_voice_controls_and_the_disconnect_go_to_the_session_on_screen(cx: &mut TestAppContext) {
|
|
let (app, _, _) =
|
|
entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
|
|
let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64;
|
|
app.read_with(cx, |app, _| app.take_sent());
|
|
app.update(cx, |app, cx| {
|
|
app.set_input_muted(true, cx);
|
|
app.set_output_muted(false, cx);
|
|
app.push_to_talk(true, cx);
|
|
app.disconnect_voice(cx);
|
|
});
|
|
let sent = app.read_with(cx, |app, _| app.take_sent());
|
|
assert!(
|
|
matches!(
|
|
sent.as_slice(),
|
|
[
|
|
Command::SetInputMuted { session: a, muted: true },
|
|
Command::SetOutputMuted { session: b, muted: false },
|
|
Command::SetTransmitting { session: c, on: true },
|
|
Command::DisconnectVoice { session: d },
|
|
] if [*a, *b, *c, *d] == [id; 4]
|
|
),
|
|
"{sent:?}"
|
|
);
|
|
let (empty, _, _) = entity(cx);
|
|
empty.update(cx, |app, cx| app.disconnect_voice(cx));
|
|
assert!(empty.read_with(cx, |app, _| app.take_sent()).is_empty(), "no session on screen");
|
|
}
|
|
|
|
/// Showing a server also observes it, invisibly, through the gateway it
|
|
/// published or its own query login, as the Slint front end does.
|
|
#[gpui::test]
|
|
fn selecting_a_server_observes_it_through_its_gateway_or_its_query_login(
|
|
cx: &mut TestAppContext,
|
|
) {
|
|
let backend = Backend::in_memory().unwrap();
|
|
let gateway = Bookmark {
|
|
gateway_url: Some("wss://gw.example/v1".into()),
|
|
..bookmark("Gw", "gw.example")
|
|
};
|
|
let query = Bookmark {
|
|
query: Some(voelin_store::QueryConfig {
|
|
host: "q.example".into(),
|
|
..Default::default()
|
|
}),
|
|
..bookmark("Q", "q.example")
|
|
};
|
|
for b in [&gateway, &query] {
|
|
backend.store.add_bookmark(b).unwrap();
|
|
}
|
|
let (app, _, _) = entity_over(cx, backend, Switches::default());
|
|
let (gw_id, q_id) =
|
|
app.read_with(cx, |app, _| (app.vm.bookmarks[0].id, app.vm.bookmarks[1].id));
|
|
app.update(cx, |app, cx| app.select_server(gw_id, cx));
|
|
let sent = app.read_with(cx, |app, _| app.take_sent());
|
|
assert!(
|
|
matches!(sent.as_slice(), [Command::ObserveGateway { session, urls, .. }]
|
|
if *session == gw_id as u64 && urls == &["wss://gw.example/v1"]),
|
|
"{sent:?}"
|
|
);
|
|
assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "Observing invisibly…");
|
|
app.update(cx, |app, cx| app.select_server(q_id, cx));
|
|
let sent = app.read_with(cx, |app, _| app.take_sent());
|
|
assert!(
|
|
matches!(sent.as_slice(), [Command::ObserveQuery { session, connect }]
|
|
if *session == q_id as u64 && connect.address.starts_with("q.example:")),
|
|
"{sent:?}"
|
|
);
|
|
}
|
|
|
|
/// Removing a server tells the engine to close its session.
|
|
#[gpui::test]
|
|
fn removing_a_server_closes_its_session(cx: &mut TestAppContext) {
|
|
let (app, _, _) =
|
|
entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
|
|
let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id);
|
|
app.update(cx, |app, cx| app.delete_bookmark(id, cx));
|
|
let sent = app.read_with(cx, |app, _| app.take_sent());
|
|
assert!(
|
|
matches!(sent.as_slice(), [Command::CloseSession { session }] if *session == id as u64),
|
|
"{sent:?}"
|
|
);
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn the_sample_servers_show_through_the_events_and_nothing_is_stored_or_sent(
|
|
cx: &mut TestAppContext,
|
|
) {
|
|
let switches = Switches { demo_ui: true, ..Switches::default() };
|
|
let (app, _, counters) =
|
|
entity_over(cx, backend_with(&[("Mine", "mine.example")]), switches);
|
|
app.read_with(cx, |app, _| {
|
|
let names: Vec<&str> = app.vm.bookmarks.iter().map(|b| b.name.as_str()).collect();
|
|
assert_eq!(names, ["Nightfall Guild", "Pixel Lounge", "Dev TS3"]);
|
|
assert_eq!(app.vm.current, Some(sample::DEMO));
|
|
assert_eq!(app.connections(), 1, "the first sample server is connected");
|
|
assert_eq!(app.vm.sessions[&(sample::DEMO + 1)].state.observe, ObserveState::Observing);
|
|
assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1, "the store has its own");
|
|
});
|
|
assert_eq!(counters.connections.get(), 1);
|
|
assert_eq!(app.update(cx, |app, cx| app.save_bookmark(&form("new.example"), cx)), None);
|
|
app.update(cx, |app, cx| app.delete_bookmark(sample::DEMO, cx));
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.vm.bookmarks.len(), 3, "the samples cannot be changed");
|
|
assert_eq!(app.backend().store.bookmarks().unwrap().len(), 1);
|
|
});
|
|
assert_eq!(
|
|
app.update(cx, |app, cx| app.shutdown(cx)),
|
|
0,
|
|
"no session of the samples is closed"
|
|
);
|
|
app.update(cx, |app, cx| {
|
|
app.select_server(sample::DEMO + 1, cx);
|
|
app.connect_voice(cx);
|
|
});
|
|
assert!(
|
|
app.read_with(cx, |app, _| app.take_sent()).is_empty(),
|
|
"nothing goes to the engine"
|
|
);
|
|
}
|
|
|
|
/// The theme follows the settings (`ui.theme`, `ui.font_scale`) when the
|
|
/// engine says one changed, and a development switch keeps what it set.
|
|
#[gpui::test]
|
|
fn the_theme_follows_the_settings_unless_a_switch_set_it(cx: &mut TestAppContext) {
|
|
cx.update(|cx| {
|
|
gpui_kit::init(cx);
|
|
VoelinTheme::init(cx, Choice::Dark, WindowAppearance::Dark, 1.0);
|
|
});
|
|
let (app, tx, _) = entity(cx);
|
|
let theme = |cx: &mut TestAppContext| {
|
|
cx.update(|cx| {
|
|
let theme = VoelinTheme::global(cx);
|
|
(theme.choice(), theme.metrics.font_scale)
|
|
})
|
|
};
|
|
assert_eq!(theme(cx), (Choice::Dark, 1.0));
|
|
app.read_with(cx, |app, _| {
|
|
app.backend().prefs.set(&UI_THEME, ThemeChoice::Light).unwrap();
|
|
app.backend().prefs.set(&UI_FONT_SCALE, 1.25).unwrap();
|
|
});
|
|
tx.send(Event::SettingChanged { key: "ui.theme".into() }).unwrap();
|
|
cx.run_until_parked();
|
|
assert_eq!(theme(cx), (Choice::Light, 1.25));
|
|
|
|
// With a switch for the mode, the settings' value is not applied.
|
|
let switches = Switches { theme: Some(Choice::Dark), ..Switches::default() };
|
|
let (switched, tx, _) = entity_over(cx, Backend::in_memory().unwrap(), switches);
|
|
switched.read_with(cx, |app, _| {
|
|
app.backend().prefs.set(&UI_THEME, ThemeChoice::System).unwrap()
|
|
});
|
|
tx.send(Event::SettingChanged { key: "ui.theme".into() }).unwrap();
|
|
cx.run_until_parked();
|
|
assert_eq!(theme(cx).0, Choice::Dark);
|
|
}
|
|
|
|
fn place() -> WindowState {
|
|
WindowState { width: 1100, height: 700, x: Some(30), y: Some(40), maximized: false }
|
|
}
|
|
|
|
/// The window's place goes to the settings at the next tick, and a later
|
|
/// run finds it where the first left it.
|
|
#[gpui::test]
|
|
fn the_windows_place_is_kept_at_the_tick_and_found_by_the_next_run(cx: &mut TestAppContext) {
|
|
let dir = TempDir::new("window-place");
|
|
let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
|
|
let (app, _, _) = entity_over(cx, backend, Switches::default());
|
|
app.read_with(cx, |app, _| assert_eq!(app.remembered_window(), None));
|
|
app.update(cx, |app, _| app.window_moved(place()));
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.backend().prefs.get(&UI_WINDOW), None, "not before the tick");
|
|
});
|
|
cx.executor().advance_clock(Duration::from_secs(1));
|
|
cx.run_until_parked();
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.backend().prefs.get(&UI_WINDOW), Some(place()));
|
|
assert_eq!(app.remembered_window(), Some(place()));
|
|
});
|
|
// The close keeps a place that moved after the last tick.
|
|
let moved = WindowState { x: Some(60), ..place() };
|
|
app.update(cx, |app, cx| {
|
|
app.window_moved(moved);
|
|
app.shutdown(cx)
|
|
});
|
|
drop(app);
|
|
cx.update(|_| {});
|
|
|
|
let again = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
|
|
let (next, _, _) = entity_over(cx, again, Switches::default());
|
|
next.read_with(cx, |app, _| assert_eq!(app.remembered_window(), Some(moved)));
|
|
}
|
|
|
|
/// A window opened to be maximized reports the place it opened with first;
|
|
/// that is not what the user left, so `maximized: true` stays until the
|
|
/// window has been seen maximized. After that it is the user's: restoring
|
|
/// is kept, and a maximized window is kept with the size it returns to
|
|
/// (X11 reports the screen's).
|
|
#[gpui::test]
|
|
fn a_maximized_window_is_not_overwritten_before_it_was_seen_maximized(cx: &mut TestAppContext) {
|
|
let dir = TempDir::new("window-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();
|
|
let (app, _, _) = entity_over(cx, backend, Switches::default());
|
|
let tick = |cx: &mut TestAppContext| {
|
|
cx.executor().advance_clock(Duration::from_secs(1));
|
|
cx.run_until_parked();
|
|
};
|
|
let kept = |cx: &mut TestAppContext| {
|
|
app.read_with(cx, |app, _| app.backend().prefs.get(&UI_WINDOW)).unwrap()
|
|
};
|
|
app.read_with(cx, |app, _| {
|
|
assert!(app.wants_maximized() && app.awaiting_maximize());
|
|
});
|
|
|
|
// The window as it opened, before the window manager maximized it.
|
|
app.update(cx, |app, _| {
|
|
app.window_moved(WindowState { maximized: false, ..place() });
|
|
app.window_moved(WindowState { maximized: false, ..left });
|
|
});
|
|
tick(cx);
|
|
assert_eq!(kept(cx), left);
|
|
|
|
// Maximized: the screen's size is not the size it returns to.
|
|
let screen = WindowState { width: 1920, height: 1080, x: Some(0), y: Some(0), ..left };
|
|
app.update(cx, |app, _| app.window_moved(screen));
|
|
tick(cx);
|
|
assert_eq!(kept(cx), left, "kept as left, with the size it returns to");
|
|
app.read_with(cx, |app, _| assert!(!app.awaiting_maximize()));
|
|
|
|
// The user restores it and moves it: that is kept.
|
|
let restored = WindowState { width: 800, height: 600, maximized: false, ..place() };
|
|
app.update(cx, |app, _| app.window_moved(restored));
|
|
tick(cx);
|
|
assert_eq!(kept(cx), restored);
|
|
|
|
// Maximized again: the place it returns to is the last windowed one.
|
|
app.update(cx, |app, _| app.window_moved(screen));
|
|
tick(cx);
|
|
assert_eq!(kept(cx), WindowState { maximized: true, ..restored });
|
|
}
|
|
|
|
/// The guard of a window opened to be maximized is for its first reports
|
|
/// only: after them what the window reports is the user's even if it was
|
|
/// never seen maximized (a window manager that does not maximize, a user
|
|
/// who resizes before it does), so a resize is not lost for good.
|
|
#[gpui::test]
|
|
fn the_maximize_guard_covers_the_first_reports_only(cx: &mut TestAppContext) {
|
|
let dir = TempDir::new("window-guard");
|
|
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();
|
|
let (app, _, _) = entity_over(cx, backend, Switches::default());
|
|
let kept = |cx: &mut TestAppContext| {
|
|
cx.executor().advance_clock(Duration::from_secs(1));
|
|
cx.run_until_parked();
|
|
app.read_with(cx, |app, _| app.backend().prefs.get(&UI_WINDOW)).unwrap()
|
|
};
|
|
app.read_with(cx, |app, _| assert!(app.awaiting_maximize()));
|
|
|
|
// The place it opened with, then the window manager's configure.
|
|
for width in [1000, 1001] {
|
|
app.update(cx, |app, _| {
|
|
app.window_moved(WindowState { width, maximized: false, ..left });
|
|
});
|
|
assert_eq!(kept(cx), left, "report of {width} is not the user's");
|
|
}
|
|
app.read_with(cx, |app, _| assert!(!app.awaiting_maximize(), "the guard is spent"));
|
|
|
|
// The third is the user's own, and nothing maximized the window.
|
|
let resized = WindowState { width: 800, height: 600, maximized: false, ..place() };
|
|
app.update(cx, |app, _| app.window_moved(resized));
|
|
assert_eq!(kept(cx), resized);
|
|
}
|
|
|
|
/// A window that was not opened maximized keeps what it reports from the
|
|
/// first report on.
|
|
#[gpui::test]
|
|
fn a_window_not_opened_maximized_is_kept_from_its_first_report(cx: &mut TestAppContext) {
|
|
let (app, _, _) = entity_over(cx, Backend::in_memory().unwrap(), Switches::default());
|
|
app.read_with(cx, |app, _| assert!(!app.wants_maximized() && !app.awaiting_maximize()));
|
|
app.update(cx, |app, _| app.window_moved(place()));
|
|
cx.executor().advance_clock(Duration::from_secs(1));
|
|
cx.run_until_parked();
|
|
app.read_with(cx, |app, _| {
|
|
assert_eq!(app.backend().prefs.get(&UI_WINDOW), Some(place()));
|
|
});
|
|
}
|
|
|
|
/// A window sized by a development switch, or showing the sample data, is
|
|
/// not the user's: what it reports is not kept.
|
|
#[gpui::test]
|
|
fn a_window_the_switches_made_does_not_overwrite_the_remembered_place(cx: &mut TestAppContext) {
|
|
for switches in [
|
|
Switches { window: Some((1440.0, 960.0)), ..Switches::default() },
|
|
Switches { demo_ui: true, ..Switches::default() },
|
|
] {
|
|
let (app, _, _) = entity_over(cx, Backend::in_memory().unwrap(), switches);
|
|
app.update(cx, |app, _| app.window_moved(place()));
|
|
cx.executor().advance_clock(Duration::from_secs(1));
|
|
cx.run_until_parked();
|
|
app.read_with(cx, |app, _| assert_eq!(app.backend().prefs.get(&UI_WINDOW), None));
|
|
}
|
|
}
|
|
}
|