Files
VoelinClient/crates/voelin-gpui/src/app.rs
T
faumarayandClaude Sonnet 5.5 6b4341ab8c voelin-gpui: the desktop shell, the server rail, the sidebar, the top bar and the main area
Slice 1 of plan section 6 step 3 (docs/ui.md, "The GPUI front end"). The window
is the shell of ui/shells/desktop.slint, as entities that observe the root
state and tell the window only when what they show changed (they compare their
view of the state, so an engine event about a talker, a tick or a setting that
is not the theme's draws nothing):

- shell/rail.rs: the saved servers as avatars with their tints, initials,
  presence dots, unread and live marks, the selection pill and ring, the plus
  that adds a server and the settings button; a second click edits a server,
  as the Slint rail's double click does.
- shell/sidebar.rs: the server on screen with its stats, the place of the
  channel tree (slice 2), the voice card (disconnect, copy an invite, hold to
  talk) while voice is connecting or connected, and the user card with the
  microphone and sound buttons.
- shell/topbar.rs: the page's title, the search box and the settings button;
  the last two are logged until their slices exist.
- shell/main_panel.rs: "No server selected" with the way to add one, or the
  server on screen with Connect, Disconnect and Edit.
- shell/form.rs: the server form (address, name, nickname, password; Save,
  Save and connect, Cancel, and a Remove that asks twice) in the place of the
  main area until the dialogs slice.
- shell/toast.rs: the status line as a toast for a few seconds.

The eleven callbacks of bind/servers.rs that the shell has are GPUI actions
(shell/actions.rs: select, connect, disconnect, mute the microphone, mute the
sound, push to talk, edit, save, save and connect, delete, invite): a click
dispatches one, the window's root view handles it by asking the root state.
The window takes its title from the server on screen ("Voelin - Nightfall"),
keeps a focus of its own so that actions always find their handlers, tells the
root state where it is (ui.window), and opens where it was left (the size
always; the position where a screen still shows it and the window manager
honours one). The logo is served by the assets.

scripts/gpui-shot.sh finds the window by its title's prefix now that the title
follows the server.

Tests on GPUI's test platform draw the window and click it: a server added
appears in the rail, a click selects it and titles the window, a connect
reaches the engine, an engine event updates the rail and the cards, the form
adds, edits and removes, the toast goes, the window's place round-trips, an
idle window is not told, the sample servers fill the shell.

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

1587 lines
55 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;
//! it is the views (`crate::shell`) that decide whether what they show changed
//! and draw again 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 and the warnings are
//! logged; the redraw flags, the notices, the pictures to decode and the
//! streams' capture and decoder are for the slices that have those parts.
use std::task::Poll;
use std::time::{Duration, Instant};
use gpui_kit::{ClipboardItem, Context};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tracing::{debug, info, warn};
use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings};
use voelin_core::{Command, Engine, Event, ObserveState, VoiceState};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, QueryTransport, Store};
use voelin_ui_vm::bridge::{BookmarkForm, ChatLine};
use voelin_ui_vm::events;
use voelin_ui_vm::host::{Cx, Host, Persist, Update};
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic::{self, GatewayFound, ObservePlan};
use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ThemeChoice, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, UI_WINDOW,
WindowState,
};
use voelin_ui_vm::social::logic::Social;
use crate::backend::Backend;
use crate::dev::Switches;
use crate::meter::Counters;
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>,
}
/// 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,
engine: Option<Engine>,
backend: Backend,
switches: Switches,
window: WindowKeeper,
counters: Counters,
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 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,
engine,
backend,
switches,
window: WindowKeeper { latest: None, saved },
counters,
later: Later(later),
#[cfg(test)]
sent: Default::default(),
};
if state.switches.demo_ui {
state.load_demo();
}
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 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>,
) {
for event in events {
self.events_handled += 1;
self.counters.engine_events.incr();
let update = self.handle(event);
self.perform(update, cx);
}
self.counters.connections.set(self.connections() as u64);
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 {
let host = ShellHost {
demo_ui: self.switches.demo_ui,
store: &self.backend.store,
prefs: &self.backend.prefs,
};
let mut transition = Cx::new(&host);
let result = f(&mut self.vm, &mut transition);
let update = transition.update;
self.perform(update, 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.
fn perform(&mut self, update: Update, cx: &mut Context<Self>) {
let Update { status, commands, persist, warnings, rest, password, .. } = update;
self.log_warnings(warnings);
for command in commands {
self.send(command);
}
if let Some(text) = status {
self.set_status(text);
}
for what in persist {
self.keep(what);
}
if let Some(prompt) = password {
debug!(channel = %prompt.name, "the password dialog comes with the channel tree");
}
// What the front end keeps itself comes before the drawing.
if let Some(Event::SettingChanged { key }) = rest {
self.setting_changed(&key, cx);
}
}
/// 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.
pub fn window_moved(&mut self, state: WindowState) {
if self.switches.window.is_none() && !self.switches.demo_ui {
self.window.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)
}
/// 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.
/// Show a server, and observe it.
pub fn select_server(&mut self, id: i64, cx: &mut Context<Self>) {
self.transition(cx, |state, cx| logic::select_server(state, cx, id));
self.observe(id, cx);
cx.notify();
}
/// Connect the server on screen with voice, into its default channel.
pub fn connect_voice(&mut self, cx: &mut Context<Self>) {
let channel = self.current_bookmark().and_then(|b| b.default_channel.clone());
self.connect_voice_to(channel, None, None, cx);
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 {
let Some(b) = self.current_bookmark().cloned() else { return false };
if self.switches.demo_ui {
return false;
}
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
Ok(options) => options,
Err(error) => {
self.set_status(error);
return false;
}
};
options.identity =
Some(voelin_core::ts::identity::to_blob(&self.backend.identity_for(Some(&b))));
options.server_password = self.backend.secrets.get(&b.server_password_key()).ok().flatten();
// `options.stream_peer` stays the engine's default: what this front
// end can decode is for the slice with the stream viewer to say.
self.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
self.discover_gateway(b.id, cx);
true
}
/// 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 server dialog's form for a server (id -1: a new one).
pub fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id) else {
return BookmarkForm {
id: -1,
nickname: self.backend.default_nickname().into(),
..Default::default()
};
};
let password = self.backend.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.vm.sessions.get(&b.id).map(|view| &view.state);
voelin_ui_vm::servers::form(b, state, password.as_deref().unwrap_or_default())
}
/// 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 self.switches.demo_ui {
self.set_status("The sample servers are not kept");
cx.notify();
return None;
}
let old = self.vm.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned();
let mut bookmark =
logic::bookmark_from_form(old.as_ref(), form, || self.backend.default_nickname());
if bookmark.address.is_empty() {
self.set_status("A server needs an address");
cx.notify();
return None;
}
let result = if bookmark.id < 0 {
self.backend.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.backend.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
cx.notify();
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.backend.secrets.delete(&key)
} else {
self.backend.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its gateway
// is looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = self.backend.secrets.delete(&old.query_password_key());
}
self.vm.gateways_looked_up.remove(&bookmark.id);
self.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.vm.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.vm.bookmarks = self.backend.store.bookmarks().unwrap_or_default();
let id = bookmark.id;
self.select_server(id, cx);
Some(id)
}
/// 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 {
let saved = self.save_bookmark(form, cx);
let bookmark = saved.and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id));
let Some(to) = voelin_ui_vm::servers::connect_to(form, bookmark) else { return false };
self.connect_voice_to(to.channel, to.channel_password, to.token, cx);
cx.notify();
true
}
/// 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.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() {
let _ = self.backend.secrets.delete(&b.server_password_key());
let _ = self.backend.secrets.delete(&b.query_password_key());
}
let _ = self.backend.store.delete_bookmark(id);
let bookmarks = self.backend.store.bookmarks().unwrap_or_default();
self.transition(cx, |state, cx| logic::forget_server(state, cx, id, bookmarks));
cx.notify();
}
/// Observe the server invisibly ([`logic::observe_plan`]): through its
/// gateway, else its own query login. Without either the gateway is looked
/// up first, and observing starts when it is found.
fn observe(&mut self, id: i64, cx: &mut Context<Self>) {
let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() else { return };
let session = b.id as u64;
let gateway = |app: &Self, urls| Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&app.backend.identity_for(Some(&b)),
)),
};
match self.transition(cx, |state, cx| logic::observe_plan(state, cx, id)) {
ObservePlan::Nothing => return,
ObservePlan::Retry(urls) => {
debug!(server = %b.address, "still connecting to the gateway: try now");
self.send(gateway(self, urls));
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
self.send(gateway(self, urls));
// Still the one the server publishes?
self.discover_gateway(b.id, cx);
}
ObservePlan::Query(q) => {
let secret = self.backend.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
self.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
self.discover_gateway(b.id, cx);
return;
}
}
self.set_status("Observing invisibly…");
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a run
/// ([`logic::discover_wanted`]), on the engine's runtime; what is found
/// comes back through [`Later`].
fn discover_gateway(&mut self, id: i64, cx: &mut Context<Self>) {
let Some(address) = self.transition(cx, |state, cx| logic::discover_wanted(state, cx, id))
else {
return;
};
let Some(engine) = &self.engine else { return };
let later = self.later();
engine.runtime().spawn(async move {
let started = Instant::now();
let urls = voelin_core::discover::gateways(&address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later.run(move |app, cx| app.gateway_found(id, &address, urls, elapsed_ms, cx));
}
});
}
/// Gateways were found for the server at `address` (best first); they are
/// kept unless the server changed meanwhile ([`logic::gateway_found`]), and
/// the server is observed through them if it is the one shown. Users never
/// hear of them (logged only).
fn gateway_found(
&mut self,
id: i64,
address: &str,
urls: Vec<String>,
elapsed_ms: u64,
cx: &mut Context<Self>,
) {
let found =
self.transition(cx, |state, cx| logic::gateway_found(state, cx, id, address, urls));
match found {
GatewayFound::Same => debug!(server = %address, elapsed_ms, "gateway found, as kept"),
GatewayFound::Kept { observe } => {
info!(server = %address, elapsed_ms, kept = true, "gateway found");
if observe {
self.observe(id, cx);
}
}
GatewayFound::Changed { stop, observe, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
self.send(Command::StopObserving { session: id as u64 });
}
if observe {
self.observe(id, cx);
}
}
}
}
/// 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;
use gpui::TestAppContext;
use gpui_kit::{AppContext as _, Entity, Subscription, WindowAppearance};
use voelin_core::{Backends, Command, Event, 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;
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);
}
/// 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 nothing leaves the machine and no
/// sound device opens) takes it and answers with its events, which the
/// entity's loop turns into the state the rail shows.
#[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.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 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));
}
}
}