Merge phase5/gpui-shell: slice 1 of the GPUI front end, the desktop shell (the store at start, the server rail, the sidebar, the top bar, the main area, window state in ui.window, the bookmark and connect actions through voelin-ui-vm)
CI / Linux checks (push) Successful in 40m16s

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5.1 committed 2026-10-27 19:07:32 +03:00
commit 0d32ac25f0
30 files changed
+4690 -292

No files matched your search

+11 -3
View File
@@ -9,9 +9,7 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Added
- `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a
window titled Voelin with one line of the app's state in it (the version,
the voice connections that are up, the engine events handled, the seconds
up), fed by the same engine and the same view models as the Slint app
window fed by the same engine and the same view models as the Slint app
(`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour,
radius, size and type token of the Slint app's `theme.slint`, light and dark
(a test reads the Slint file and fails when the two differ), written into
@@ -26,6 +24,16 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
stays the app; both run on one engine until the GPUI one reaches parity
(docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders
in software); no package ships it yet.
- The GPUI front end's desktop shell: the server rail, the top bar, the
sidebar and the main area, on the client's own database (the servers saved in
the Slint app are there, and the other way round). Add, edit, select and
remove a server, connect and disconnect voice, mute the microphone and the
sound, hold to talk and copy an invite link, as in the Slint app; the window's
title names the server on screen, and its size is kept for the next run
(setting `ui.window`). The channel tree, the chat and the other pages are the
next slices; the search and the settings buttons only log that. `VOELIN_DEMO_UI=1`
shows the Slint app's sample servers without sending or keeping anything
(docs/ui.md, "The desktop shell").
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
opens the folder.
Generated
+1
View File
@@ -12587,6 +12587,7 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"tsclientlib",
"voelin-core",
"voelin-platform",
"voelin-store",
+5 -2
View File
@@ -25,14 +25,17 @@ gpui-kit = { workspace = true }
tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
# The TeamSpeak identity a connection is made with (the store hands it out).
tsclientlib = { path = "../proto/tsclientlib" }
# The engine, with the desktop's capture and codecs: ashpd on async-io (the
# commit that moved voelin-media and voelin-platform to it) lets this binary
# hold both the portals and gpui-kit.
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] }
# The app's name and id, the hotkeys and portals of the slices to come.
voelin-platform = { path = "../voelin-platform" }
# The Host trait's types (what the store knows of a chat's read marker).
voelin-store = { path = "../voelin-store" }
# The client's database (bookmarks, identities, settings, chat reads) and the
# secrets: the OS keyring, as the Slint front end keeps them.
voelin-store = { path = "../voelin-store", features = ["keyring"] }
# The view models and the state, shared with the Slint front end.
voelin-ui-vm = { path = "../voelin-ui-vm" }
File diff suppressed because it is too large. Load diff
+6
View File
@@ -25,11 +25,17 @@ pub fn client_icon_names() -> impl Iterator<Item = &'static str> {
ICONS.iter().map(|(name, _)| *name)
}
/// The app's mark, the Slint front end's `logo.svg`.
const LOGO: &[u8] = include_bytes!("../../voelin-ui/ui/assets/logo.svg");
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
return Ok(Some(Cow::Borrowed(bytes)));
}
if path == "logo.svg" {
return Ok(Some(Cow::Borrowed(LOGO)));
}
gpui_kit::assets::AllAssets.load(path)
}
+317
View File
@@ -0,0 +1,317 @@
//! What the window keeps besides the engine and the state, and opens at start
//! as the Slint front end's `run()` does (`crates/voelin-ui/src/app.rs`): the
//! client's database (the bookmarks, the identities, the chats' read marks),
//! the settings service on the same file, the secrets, and the identity a
//! connection is made with. The directory is the platform's data directory
//! (`voelin_platform::paths::data_dir`, which `VOELIN_DATA_DIR` overrides, so
//! that the two front ends share the store); everything below [`Backend::open`]
//! takes the directory, so that no test reaches the user's own.
//!
//! Left out against the Slint front end: importing the identities of the
//! official TeamSpeak clients at start (it reads the user's own files; the
//! slice with the identities page brings it), the crash reports and the
//! configuration of `--set` on the command line.
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result};
use tracing::warn;
use tsclientlib::Identity;
use voelin_core::settings::{AUDIO, Settings};
use voelin_core::{AudioSettings, Command, Engine, History};
use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store};
use voelin_ui_vm::servers::logic::CREATED_IDENTITY;
use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_WINDOW, UiSettings, appearance_keys, page_keys,
};
/// The client's database, its settings and its secrets.
pub struct Backend {
/// The bookmarks, the identities and the chats' read marks.
pub store: Store,
/// The settings service, on the same file as the store (its own
/// connection); shared with the engine once [`Backend::attach`] ran.
pub prefs: Settings,
/// The servers' passwords.
pub secrets: Box<dyn Secrets>,
/// The identity of a server whose bookmark names none that exists, and
/// the store has no default for.
identity: Identity,
/// The database file, for the engine's chat history.
database: Option<PathBuf>,
}
/// What the store and the settings hold at start, for the state.
#[derive(Debug)]
pub struct Loaded {
/// The saved servers, in the rail's order.
pub bookmarks: Vec<Bookmark>,
/// The UI's own settings (the `ui` key).
pub settings: UiSettings,
/// The audio settings.
pub audio: AudioSettings,
/// The clients' local volumes.
pub playback: ClientPlaybackMap,
}
/// The data directory of this process: `VOELIN_DATA_DIR`, else the platform's.
pub fn data_dir() -> PathBuf {
voelin_platform::paths::data_dir()
}
/// The settings service on the client database in `dir`: the UI's keys
/// registered, then a config file (`VOELIN_CONFIG`, else `<dir>/config.toml`
/// if it exists) and `VOELIN_SETTING_*` variables below the stored values.
/// Without the database the settings live in memory.
fn open_settings(dir: &Path) -> Settings {
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
warn!(%e, "settings are not stored this time");
Settings::in_memory()
});
register_keys(&prefs);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
Some(Ok(errors)) => errors,
Some(Err(e)) => vec![e],
None => Vec::new(),
};
errors.extend(prefs.apply_env(std::env::vars()));
for e in errors {
warn!(%e, "setting ignored");
}
prefs
}
/// Make the keys this front end reads known to `prefs`.
fn register_keys(prefs: &Settings) {
prefs.register(&UI);
prefs.register(&CLIENT_PLAYBACK);
prefs.register(&UI_WINDOW);
for key in appearance_keys() {
prefs.register(key);
}
for key in page_keys() {
prefs.register(key);
}
}
impl Backend {
/// Open the database in `dir` (created if need be), its settings and the
/// default identity (made, and kept, when the store has none). `secrets`
/// are where passwords go.
pub fn open(dir: &Path, secrets: Box<dyn Secrets>) -> Result<Self> {
let database = dir.join("client.db");
let store = Store::open(&database).context("failed to open the client database")?;
let prefs = open_settings(dir);
let identity = match store.default_identity()? {
Some(entry) => store.identity(entry.id)?,
None => {
let identity = Identity::create();
store.add_identity(CREATED_IDENTITY, &identity, IdentityOrigin::Created)?;
identity
}
};
Ok(Self { store, prefs, secrets, identity, database: Some(database) })
}
/// A backend that stores nothing and keeps its secrets in memory, with a
/// fresh identity: the tests', and the sample data's.
pub fn in_memory() -> Result<Self> {
let prefs = Settings::in_memory();
register_keys(&prefs);
Ok(Self {
store: Store::open_in_memory()?,
prefs,
secrets: Box::new(MemorySecrets::default()),
identity: Identity::create(),
database: None,
})
}
/// What the store and the settings hold now.
pub fn load(&self) -> Loaded {
Loaded {
bookmarks: self.store.bookmarks().unwrap_or_else(|e| {
warn!(%e, "the bookmarks cannot be read");
Vec::new()
}),
settings: (*self.prefs.get_arc(&UI)).clone(),
audio: self.prefs.get(&AUDIO),
playback: self.prefs.get(&CLIENT_PLAYBACK),
}
}
/// Hand the engine what it keeps for the window: the chat history in the
/// same database (without it the engine keeps chats for this run only),
/// the settings service and the audio settings.
pub fn attach(&self, engine: &Engine) {
if let Some(database) = &self.database {
match History::open(database) {
Ok(history) => engine.send(Command::AttachHistory(history)),
Err(e) => warn!(%e, "chat history is not stored this time"),
}
}
engine.send(Command::AttachSettings(self.prefs.clone()));
engine.send(Command::SetAudioSettings(Box::new(self.prefs.get(&AUDIO))));
}
/// The identity a connection to the bookmark `bookmark` uses: its own if
/// it names one the store has, else the store's default, else the one made
/// at start.
pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity {
let entries = self.store.identities().unwrap_or_default();
let id = bookmark
.and_then(|b| b.identity)
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| self.store.default_identity().ok().flatten().map(|e| e.id));
id.and_then(|id| self.store.identity(id).ok()).unwrap_or_else(|| self.identity.clone())
}
/// The nickname a new server gets: the default identity's (one imported
/// from TeamSpeak keeps the nickname used there), else the system user's.
pub fn default_nickname(&self) -> String {
self.store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname.
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
}
/// Write what the settings service holds to the database.
pub fn flush(&self) {
if let Err(e) = self.prefs.flush() {
warn!(%e, "could not store settings");
}
}
}
/// The secrets of this run: the OS keyring, and memory for what the keyring
/// refuses (no Secret Service on a headless Linux); the sample data's never
/// reach the keyring.
pub fn default_secrets(demo: bool) -> Box<dyn Secrets> {
if demo {
Box::new(MemorySecrets::default())
} else {
Box::new(FallbackSecrets {
keyring: voelin_store::KeyringSecrets::new("voelin"),
memory: MemorySecrets::default(),
})
}
}
/// The keyring first, memory when it cannot keep a secret (the Slint front
/// end's `FallbackSecrets`, repeated: both go into `voelin-store` when the
/// Slint front end is retired).
struct FallbackSecrets {
keyring: voelin_store::KeyringSecrets,
memory: MemorySecrets,
}
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> voelin_store::Result<Option<String>> {
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
}
}
fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> {
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> voelin_store::Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
}
/// What the tests of this crate need to open a store of their own.
#[cfg(test)]
pub(crate) mod testing {
use std::path::PathBuf;
/// A directory of its own under the temporary one (`TMPDIR`), removed with
/// the guard: no test reaches the user's data directory.
pub(crate) struct TempDir(pub PathBuf);
impl TempDir {
/// An empty directory path named `name` and this process.
pub(crate) fn new(name: &str) -> Self {
let dir =
std::env::temp_dir().join(format!("voelin-gpui-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
Self(dir)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
#[cfg(test)]
mod tests {
use voelin_ui_vm::settings::WindowState;
use super::testing::TempDir;
use super::*;
fn bookmark(name: &str, address: &str) -> Bookmark {
Bookmark { name: name.into(), address: address.into(), ..Default::default() }
}
/// What a run leaves in the directory is what the next one starts from: the
/// bookmarks, the identity (the same one, not a new one) and the settings.
#[test]
fn a_second_start_finds_what_the_first_kept() {
let dir = TempDir::new("backend");
let first = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
assert_eq!(first.load().bookmarks, Vec::new(), "a new store has no servers");
let id = first.store.add_bookmark(&bookmark("Nightfall", "ts.example")).unwrap();
let uid = first.identity_for(None).key().to_pub().get_uid();
let window = WindowState { width: 1000, height: 700, x: None, y: None, maximized: false };
first.prefs.set(&UI_WINDOW, Some(window)).unwrap();
first.flush();
drop(first);
let second = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
let loaded = second.load();
assert_eq!(
loaded.bookmarks.iter().map(|b| (b.id, b.name.as_str())).collect::<Vec<_>>(),
[(id, "Nightfall")]
);
assert_eq!(second.identity_for(None).key().to_pub().get_uid(), uid, "the identity is kept");
assert_eq!(second.prefs.get(&UI_WINDOW), Some(window));
assert!(dir.0.join("client.db").is_file(), "the database is in the directory given");
}
#[test]
fn a_server_names_its_identity_and_the_default_serves_the_rest() {
let backend = Backend::in_memory().unwrap();
let (default, alt) = (Identity::create(), Identity::create());
let uid = |identity: &Identity| identity.key().to_pub().get_uid();
backend.store.add_identity("Default", &default, IdentityOrigin::Created).unwrap();
let alt_id = backend.store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap();
assert_eq!(uid(&backend.identity_for(None)), uid(&default), "the first is the default");
let named = Bookmark { identity: Some(alt_id), ..bookmark("a", "a.test") };
assert_eq!(uid(&backend.identity_for(Some(&named))), uid(&alt));
let gone = Bookmark { identity: Some(alt_id + 100), ..bookmark("b", "b.test") };
assert_eq!(uid(&backend.identity_for(Some(&gone))), uid(&default));
}
}
+24 -6
View File
@@ -7,10 +7,14 @@
//! components, the icons) in place of the shell. The Slint front end's
//! other pages do not exist here yet; they are named in a warning and
//! skipped.
//! - `VOELIN_DEMO_UI=1`: the Slint front end's sample servers, shown through
//! the app's own events; nothing is sent to the engine or kept in the store.
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
//! one the settings will give (`ui.theme` in the Slint front end).
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`).
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size.
//! one the settings give (`ui.theme`).
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor, in place of the
//! settings' (`ui.font_scale`).
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size, in place of the
//! remembered one (`ui.window`), which it then leaves alone.
//! - `VOELIN_METER=1`: the cost meter, one log line a second
//! ([`crate::meter`]).
@@ -19,7 +23,7 @@ use crate::theme::Choice;
/// A page the window can be opened on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Page {
/// The shell. Today an empty window with the state line.
/// The desktop shell.
Shell,
/// Every theme token, a few components and the icons.
Swatch,
@@ -30,6 +34,8 @@ pub enum Page {
pub struct Switches {
/// The page to open on.
pub open: Page,
/// Show the sample servers instead of the stored ones.
pub demo_ui: bool,
/// The theme mode, when the switch names one.
pub theme: Option<Choice>,
/// The text size factor, when the switch names one.
@@ -42,7 +48,14 @@ pub struct Switches {
impl Default for Switches {
fn default() -> Self {
Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false }
Self {
open: Page::Shell,
demo_ui: false,
theme: None,
font_scale: None,
window: None,
meter: false,
}
}
}
@@ -84,7 +97,9 @@ impl Switches {
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
}
}
switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0"));
let flag = |name: &str| get(name).is_some_and(|v| !matches!(v.trim(), "" | "0"));
switches.demo_ui = flag("VOELIN_DEMO_UI");
switches.meter = flag("VOELIN_METER");
switches
}
}
@@ -117,12 +132,14 @@ mod tests {
fn every_switch_is_read() {
let s = env(&[
("VOELIN_OPEN", "swatch"),
("VOELIN_DEMO_UI", "1"),
("VOELIN_DEV_THEME", "light"),
("VOELIN_FONT_SCALE", "1.25"),
("VOELIN_WINDOW_SIZE", "1440x960"),
("VOELIN_METER", "1"),
]);
assert_eq!(s.open, Page::Swatch);
assert!(s.demo_ui);
assert_eq!(s.theme, Some(Choice::Light));
assert_eq!(s.font_scale, Some(1.25));
assert_eq!(s.window, Some((1440.0, 960.0)));
@@ -136,6 +153,7 @@ mod tests {
("VOELIN_DEV_THEME", "blue"),
("VOELIN_FONT_SCALE", "9"),
("VOELIN_WINDOW_SIZE", "10x10"),
("VOELIN_DEMO_UI", "0"),
("VOELIN_METER", "0"),
]);
assert_eq!(s, Switches::default());
+21 -2
View File
@@ -7,7 +7,8 @@
use tokio::runtime::{Handle, Runtime};
use tokio::sync::{broadcast, mpsc};
use voelin_core::{Engine, Event};
use voelin_core::settings::Settings;
use voelin_core::{Backends, Engine, Event, History};
/// An engine owned by the caller of [`crate::run`].
pub struct HostedEngine {
@@ -24,7 +25,25 @@ pub struct HostedEngine {
impl HostedEngine {
/// A new engine on `runtime`, all of whose events go to the window.
pub fn start(runtime: &Runtime) -> Self {
let engine = runtime.block_on(async { Engine::start() });
Self::forward(runtime, runtime.block_on(async { Engine::start() }))
}
/// A new engine on `runtime` that connects with `backends` only, and keeps
/// nothing (settings and chat history in memory): the tests' (with
/// [`Backends::empty`] a connect ends at once, saying that no connector
/// serves the address, and touches neither the network nor the sound
/// devices).
pub fn start_with_backends(runtime: &Runtime, backends: Backends) -> Self {
Self::forward(
runtime,
runtime.block_on(async {
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends)
}),
)
}
/// Forward the events of `engine` into the channel the window reads.
fn forward(runtime: &Runtime, engine: Engine) -> Self {
let (tx, events) = mpsc::unbounded_channel();
let mut rx = engine.subscribe();
runtime.spawn(async move {
+109 -27
View File
@@ -7,10 +7,12 @@
pub mod app;
pub mod assets;
pub mod backend;
pub mod dev;
pub mod engine;
pub mod fonts;
pub mod meter;
pub mod shell;
pub mod swatch;
pub mod theme;
pub mod view;
@@ -20,17 +22,27 @@ use std::rc::Rc;
use std::time::Duration;
use anyhow::{Context as _, Result};
use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size};
use gpui_kit::{
App, AppContext as _, Bounds, TitlebarOptions, WindowBounds, WindowOptions, point, px, size,
};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
use voelin_ui_vm::settings::WindowState;
use crate::app::AppState;
use crate::app::{AppState, Setup, appearance};
use crate::assets::Assets;
use crate::backend::Backend;
use crate::dev::Switches;
use crate::engine::HostedEngine;
use crate::meter::Counters;
use crate::theme::{Choice, VoelinTheme};
use crate::theme::VoelinTheme;
use crate::view::MainView;
/// The smallest size the window can be given.
const MIN_SIZE: (f32, f32) = (640.0, 480.0);
/// The size of a window that has no remembered one.
const DEFAULT_SIZE: (f32, f32) = (1280.0, 800.0);
/// How long the engine gets, after the window closed, to act on the
/// `CloseSession` commands the close sent (the Slint front end waits as long):
/// its tasks run on the runtime, and shutting the runtime down drops them.
@@ -58,18 +70,48 @@ pub fn init_logging() {
.try_init();
}
/// The main window's options: titled with the app's name, grouped by its id,
/// centred, 1280 by 800 unless `VOELIN_WINDOW_SIZE` says otherwise.
fn window_options(switches: &Switches, cx: &App) -> WindowOptions {
let (width, height) = switches.window.unwrap_or((1280.0, 800.0));
/// Where the window opens: the size a development switch names, else the
/// remembered place if a screen still shows its corner (a monitor can have
/// gone since), else the middle of the screen at the default size. A place
/// that has no position (Wayland does not tell one) is the remembered size
/// in the middle.
fn window_bounds(switches: &Switches, remembered: Option<WindowState>, cx: &App) -> WindowBounds {
let sized = |(width, height): (f32, f32)| size(px(width), px(height));
if let Some(forced) = switches.window {
return WindowBounds::centered(sized(forced), cx);
}
let Some(state) = remembered else {
return WindowBounds::centered(sized(DEFAULT_SIZE), cx);
};
let remembered_size =
sized(((state.width as f32).max(MIN_SIZE.0), (state.height as f32).max(MIN_SIZE.1)));
let at = state.x.zip(state.y).map(|(x, y)| point(px(x as f32), px(y as f32)));
let bounds = match at {
Some(origin)
if cx.displays().iter().any(|display| {
display.bounds().intersects(&Bounds::new(origin, size(px(64.0), px(32.0))))
}) =>
{
Bounds::new(origin, remembered_size)
}
_ => Bounds::centered(None, remembered_size, cx),
};
if state.maximized { WindowBounds::Maximized(bounds) } else { WindowBounds::Windowed(bounds) }
}
/// The main window's options: titled with the app's name (and the server
/// shown), grouped by its id, opened where [`window_bounds`] says.
fn window_options(
switches: &Switches,
remembered: Option<WindowState>,
title: String,
cx: &App,
) -> WindowOptions {
WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some(voelin_platform::APP_NAME.into()),
..Default::default()
}),
titlebar: Some(TitlebarOptions { title: Some(title.into()), ..Default::default() }),
app_id: Some(voelin_platform::APP_ID.to_owned()),
window_min_size: Some(size(px(640.0), px(480.0))),
window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)),
window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))),
window_bounds: Some(window_bounds(switches, remembered, cx)),
..Default::default()
}
}
@@ -81,6 +123,7 @@ fn open_main_window(
cx: &mut App,
switches: &Switches,
engine: HostedEngine,
backend: Backend,
counters: Counters,
closed_sessions: Rc<Cell<usize>>,
) -> Result<()> {
@@ -94,10 +137,19 @@ fn open_main_window(
}
let HostedEngine { engine, events, .. } = engine;
let app = cx.new({
let counters = counters.clone();
move |cx| AppState::new(Some(engine), events, counters, cx)
let setup = Setup {
engine: Some(engine),
events,
counters: counters.clone(),
backend,
switches: switches.clone(),
};
move |cx| AppState::new(setup, cx)
});
let options = window_options(switches, cx);
let options = {
let app = app.read(cx);
window_options(switches, app.remembered_window(), app.window_title(), cx)
};
let page = switches.open;
gpui_kit::open_window(options, cx, {
let app = app.clone();
@@ -108,7 +160,7 @@ fn open_main_window(
window.on_window_should_close(cx, {
let app = app.clone();
move |_, cx| {
closed_sessions.set(app.read(cx).shutdown());
closed_sessions.set(app.update(cx, |app, cx| app.shutdown(cx)));
cx.quit();
true
}
@@ -120,6 +172,14 @@ fn open_main_window(
Ok(())
}
/// Wait `grace` on `runtime`, so that the engine's tasks run (they send the
/// closes of the sessions) before the runtime drops them. The sleep is made
/// inside the runtime: a `Sleep` made outside it, as an argument of
/// `block_on`, panics ("there is no reactor running").
fn give_the_engine_time(runtime: &tokio::runtime::Runtime, grace: Duration) {
runtime.block_on(async move { tokio::time::sleep(grace).await });
}
/// Run the app on the current thread until its window closes.
pub fn run() -> Result<()> {
init_logging();
@@ -139,6 +199,13 @@ pub fn run() -> Result<()> {
.build()
.context("cannot start the engine's runtime")?;
let hosted = HostedEngine::start(&runtime);
// The store and the settings, in the platform's data directory
// (`VOELIN_DATA_DIR` moves it: every run of this binary that is not the
// user's own sets it, and the XDG directories with it).
let backend = Backend::open(&backend::data_dir(), backend::default_secrets(switches.demo_ui))
.context("cannot open the client's store")?;
backend.attach(&hosted.engine);
let (theme, font_scale) = appearance(&backend.prefs, &switches);
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
let closed_sessions: Rc<Cell<usize>> = Rc::default();
gpui_kit::application().with_assets(Assets).run({
@@ -147,15 +214,12 @@ pub fn run() -> Result<()> {
move |cx| {
gpui_kit::init(cx);
fonts::load(cx);
// Until the settings are read here (the shell slice), the mode and
// the text size are the development switches' or the defaults.
VoelinTheme::init(
cx,
switches.theme.unwrap_or(Choice::System),
cx.window_appearance(),
switches.font_scale.unwrap_or(1.0),
);
if let Err(e) = open_main_window(cx, &switches, hosted, counters, closed_sessions) {
// The mode and the text size are the settings', or a development
// switch's.
VoelinTheme::init(cx, theme, cx.window_appearance(), font_scale);
if let Err(e) =
open_main_window(cx, &switches, hosted, backend, counters, closed_sessions)
{
*failure.borrow_mut() = Some(e);
// Not `cx.quit()` here: GPUI's Linux platform runs this callback
// before it starts its event loop, and the loop forgets a stop
@@ -172,7 +236,7 @@ pub fn run() -> Result<()> {
// on the servers until they time out. Any other way to end the app that
// the slices add must call `AppState::shutdown` too.
if closed_sessions.get() > 0 {
runtime.block_on(tokio::time::sleep(CLOSE_GRACE));
give_the_engine_time(&runtime, CLOSE_GRACE);
}
runtime.shutdown_timeout(Duration::from_secs(2));
match failure.take() {
@@ -180,3 +244,21 @@ pub fn run() -> Result<()> {
None => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The grace after a close with open sessions is a wait on the engine's
/// runtime from the GPUI thread, which is no runtime thread: it must not
/// panic, and it must wait. (The first end-to-end close against a server,
/// the first slice that opens a session, found the panic.)
#[test]
fn the_close_grace_waits_on_the_runtime_from_a_thread_that_is_none() {
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
let started = std::time::Instant::now();
give_the_engine_time(&runtime, Duration::from_millis(30));
assert!(started.elapsed() >= Duration::from_millis(30));
runtime.shutdown_timeout(Duration::from_secs(2));
}
}
+88
View File
@@ -0,0 +1,88 @@
//! What the user can ask of the shell, as GPUI actions: the callbacks of the
//! Slint front end's `bind/servers.rs` that the desktop shell has (the first
//! eleven below), and the shell's own affordances. A click dispatches the
//! action ([`gpui_kit::Window::dispatch_action`]), the window's root view
//! ([`crate::view::MainView`]) handles it, and the handler asks the root state
//! ([`crate::app::AppState`]) for what the callback did in Slint: key bindings
//! and menus come to the same handlers later.
//!
//! The callbacks of `bind/servers.rs` that are not here belong to the slices
//! after this one: `search_members`, `show_voice_view`, `join_channel`,
//! `join_with_password`, `toggle_collapse`, `open_client` and
//! `client_audio_changed` to the channel tree and the voice page, and `copied`
//! (the toast that follows a copy) to whichever copies: [`Invite`] sets it
//! itself.
use gpui_kit::{Action, actions};
actions!(
voelin,
[
/// `connect_voice`: connect the server on screen with voice, into its default channel.
ConnectVoice,
/// `disconnect_voice`: leave voice on the server on screen.
DisconnectVoice,
/// `invite`: copy a link to the voice channel we are in.
Invite,
/// `save_bookmark`: save the server form (the form's own Save button).
SaveServer,
/// `save_and_connect`: save the server form, then connect.
SaveAndConnect,
/// Open the empty server form (the rail's plus button).
AddServer,
/// Close the server form without saving.
CancelServerForm,
/// The top bar's search box: the search comes with its slice, today it is logged.
OpenSearch,
/// The settings buttons: the settings come with their slice, today it is logged.
OpenSettings,
]
);
/// `select_server`: show a server (and observe it).
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SelectServer {
/// The bookmark's id.
pub id: i64,
}
/// `edit_bookmark`: open the server form with a saved server.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct EditServer {
/// The bookmark's id.
pub id: i64,
}
/// `delete_bookmark`: remove a server.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct DeleteServer {
/// The bookmark's id.
pub id: i64,
}
/// `set_input_muted`: mute or unmute our microphone.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetInputMuted {
/// Muted from now on.
pub muted: bool,
}
/// `set_output_muted`: mute or unmute the sound.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct SetOutputMuted {
/// Muted from now on.
pub muted: bool,
}
/// `push_to_talk`: transmit while the hold-to-talk button is held.
#[derive(Clone, Debug, PartialEq, Action)]
#[action(namespace = voelin, no_json)]
pub struct PushToTalk {
/// Transmitting from now on.
pub on: bool,
}
+211
View File
@@ -0,0 +1,211 @@
//! The server form: where a server is added or edited (the server dialog of
//! the Slint front end, `bookmark_form` / `save_bookmark` /
//! `save_and_connect` / `delete_bookmark` of `bind/servers.rs`). The dialogs
//! come with their slice; until then the form takes the place of the main
//! area, with gpui-component's text inputs: the address (the only thing a
//! server needs), a name (empty: the server's own), the nickname and the
//! server's password.
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
App, AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Window, div, px,
};
use voelin_ui_vm::bridge::BookmarkForm;
use super::actions::{CancelServerForm, DeleteServer, SaveAndConnect, SaveServer};
use super::widgets::{panel, tagged};
use crate::theme::{VoelinTheme, hsla};
/// The form.
pub struct ServerForm {
id: i64,
connected: bool,
address: Entity<InputState>,
name: Entity<InputState>,
nickname: Entity<InputState>,
password: Entity<InputState>,
confirm_remove: bool,
}
impl ServerForm {
/// A form filled in with `form` (id -1: a new server). The address has the
/// focus; Enter in any field saves.
pub fn new(form: &BookmarkForm, window: &mut Window, cx: &mut Context<Self>) -> Self {
let field = |window: &mut Window,
cx: &mut Context<Self>,
placeholder: &str,
value: &str,
masked: bool| {
let input = cx.new(|cx| {
InputState::new(window, cx)
.placeholder(SharedString::from(placeholder.to_owned()))
.default_value(SharedString::from(value.to_owned()))
.masked(masked)
});
cx.subscribe_in(&input, window, |_, _, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
window.dispatch_action(Box::new(SaveServer), cx);
}
})
.detach();
input
};
let address =
field(window, cx, "ts.example.com or ts.example.com:9987", &form.address, false);
let name = field(window, cx, "Optional: the server tells its own", &form.name, false);
let nickname = field(window, cx, "The name others see", &form.nickname, false);
let password = field(window, cx, "Optional", &form.server_password, true);
address.update(cx, |input, cx| input.focus(window, cx));
Self {
id: i64::from(form.id),
connected: form.connected,
address,
name,
nickname,
password,
confirm_remove: false,
}
}
/// The bookmark this form edits; -1 for a new server.
pub fn id(&self) -> i64 {
self.id
}
/// The form as the fields hold it now, for `AppState::save_bookmark`.
pub fn to_form(&self, cx: &App) -> BookmarkForm {
let text = |input: &Entity<InputState>| input.read(cx).value().to_string();
BookmarkForm {
id: self.id as i32,
name: text(&self.name).into(),
address: text(&self.address).into(),
nickname: text(&self.nickname).into(),
server_password: text(&self.password).into(),
connected: self.connected,
..Default::default()
}
}
/// Put `text` in the address field (a link that fills the form comes with
/// its slice; the tests type here).
pub fn set_address(&self, text: &str, window: &mut Window, cx: &mut App) {
self.address.update(cx, |input, cx| input.set_value(text.to_owned(), window, cx));
}
}
fn labelled(
theme: &VoelinTheme,
label: &'static str,
input: &Entity<InputState>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.flex()
.flex_col()
.gap(px(m.space_2))
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(c.text_secondary))
.child(label),
)
.child(Input::new(input))
}
impl Render for ServerForm {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let new = self.id < 0;
let id = self.id;
let confirm = self.confirm_remove;
panel(&theme)
.id("server-form")
.debug_selector(|| "server-form".into())
.flex_1()
.min_w_0()
.h_full()
.items_center()
.justify_center()
.child(
div()
.w_full()
.max_w(px(440.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_5))
.child(
div()
.text_size(px(m.font_xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(if new { "Add a server" } else { "Edit the server" }),
)
.child(labelled(&theme, "Address", &self.address))
.child(labelled(&theme, "Name", &self.name))
.child(labelled(&theme, "Nickname", &self.nickname))
.child(labelled(&theme, "Server password", &self.password))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(tagged(
"form-save",
Button::new("form-save").primary().label("Save").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(SaveServer), cx)
},
),
))
.when(!self.connected, |row| {
row.child(tagged(
"form-connect",
Button::new("form-connect").label("Save and connect").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(SaveAndConnect), cx)
},
),
))
})
.child(tagged(
"form-cancel",
Button::new("form-cancel").ghost().label("Cancel").on_click(
|_, window, cx| {
window.dispatch_action(Box::new(CancelServerForm), cx)
},
),
))
.when(!new, |row| {
row.child(div().flex_1()).child(tagged(
"form-remove",
Button::new("form-remove")
.danger()
.label(if confirm {
"Click again to remove"
} else {
"Remove"
})
.on_click(cx.listener(move |this, _, window, cx| {
if this.confirm_remove {
window.dispatch_action(
Box::new(DeleteServer { id }),
cx,
);
} else {
this.confirm_remove = true;
cx.notify();
}
})),
))
}),
),
)
}
}
+217
View File
@@ -0,0 +1,217 @@
//! The main area. Until the chat, the voice page and the rest come, it is the
//! empty page: the "no server selected" state with the way to add one, and for
//! a server on screen its name, address and state with the buttons that
//! connect, disconnect and edit it. An entity of its own: it observes the root
//! state and draws again only when what it shows changed.
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, ConnectVoice, DisconnectVoice, EditServer};
use super::widgets::{Avatar, Presence, icon, panel, tagged};
use crate::app::AppState;
use crate::theme::{VoelinTheme, hsla};
/// What the main area shows.
#[derive(Clone, Debug, PartialEq)]
pub enum MainState {
/// No server is on screen.
NoServer,
/// A server is.
Server(ServerItem),
}
impl MainState {
/// The main area for the state.
pub fn of(app: &AppState) -> Self {
let current = app.vm.current;
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
.into_iter()
.find(|item| Some(i64::from(item.id)) == current)
.map_or(Self::NoServer, Self::Server)
}
}
/// The words for a server's state.
fn state_words(status: &str) -> &'static str {
match status {
"connected" => "Connected with voice",
"connecting" => "Connecting…",
"observing" => "Observed without joining",
_ => "Not connected",
}
}
/// The main area.
pub struct MainPanel {
state: MainState,
_subscription: Subscription,
}
impl MainPanel {
/// A main area that follows `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let state = MainState::of(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let state = MainState::of(app.read(cx));
if state != this.state {
this.state = state;
cx.notify();
}
});
Self { state, _subscription: subscription }
}
/// What it shows now.
pub fn state(&self) -> &MainState {
&self.state
}
}
impl Render for MainPanel {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let body = match &self.state {
MainState::NoServer => div()
.id("main-empty")
.debug_selector(|| "main-empty".into())
.flex()
.flex_col()
.items_center()
.gap(px(m.space_4))
.child(
div()
.size(px(72.0))
.rounded(px(m.radius_xl))
.bg(hsla(c.surface_2))
.border_1()
.border_color(hsla(c.border))
.flex()
.items_center()
.justify_center()
.child(icon("server", 32.0, c.text_muted)),
)
.child(
div()
.text_size(px(m.font_xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child("No server selected"),
)
.child(
div()
.max_w(px(360.0))
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Pick a server in the list, or add one to start talking."),
)
.child(tagged(
"main-add",
Button::new("main-add")
.primary()
.label("Add a server")
.on_click(|_, window, cx| window.dispatch_action(Box::new(AddServer), cx)),
)),
MainState::Server(item) => {
let id = i64::from(item.id);
let connected = item.status.as_ref() == "connected";
let connecting = item.status.as_ref() == "connecting";
div()
.id("main-server")
.debug_selector(|| "main-server".into())
.flex()
.flex_col()
.items_center()
.gap(px(m.space_4))
.child(
Avatar::new("main-server-avatar", 72.0, &item.initials, item.tint)
.image(item.icon.clone())
.square()
.presence(Presence::of_server(&item.status)),
)
.child(
div()
.max_w(px(480.0))
.truncate()
.text_size(px(m.font_2xl))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(item.name.to_string()),
)
.child(
div()
.text_size(px(m.font_body))
.text_color(hsla(c.text_secondary))
.child(item.address.to_string()),
)
.child(
div()
.id("main-server-state")
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(state_words(&item.status)),
)
.child(
div()
.max_w(px(360.0))
.text_center()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Its channels and its chat come with the next slices."),
)
.child(
div()
.flex()
.flex_row()
.gap(px(m.space_3))
.when(connected || connecting, |row| {
row.child(tagged(
"main-disconnect",
Button::new("main-disconnect")
.danger()
.label("Disconnect")
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(DisconnectVoice), cx);
}),
))
})
.when(!connected && !connecting, |row| {
row.child(tagged(
"main-connect",
Button::new("main-connect")
.primary()
.label("Connect")
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(ConnectVoice), cx);
}),
))
})
.child(tagged(
"main-edit",
Button::new("main-edit").label("Edit").on_click(
move |_, window, cx| {
window.dispatch_action(Box::new(EditServer { id }), cx);
},
),
)),
)
}
};
panel(&theme)
.id("main")
.flex_1()
.min_w_0()
.h_full()
.items_center()
.justify_center()
.child(body)
}
}
+22
View File
@@ -0,0 +1,22 @@
//! The desktop shell of the GPUI front end (`ui/shells/desktop.slint` and
//! the server callbacks of `bind/servers.rs`): the server rail, the top bar,
//! the sidebar, the main area, the server form and the toast, each an entity
//! that observes the root state ([`crate::app::AppState`]) and draws again
//! only when what it shows changed, and the actions the user's moves are
//! ([`actions`]). [`crate::view::MainView`] puts them in the window.
pub mod actions;
mod form;
mod main_panel;
mod rail;
mod sidebar;
mod toast;
mod topbar;
pub mod widgets;
pub use form::ServerForm;
pub use main_panel::{MainPanel, MainState};
pub use rail::{RailView, ServerRail};
pub use sidebar::{Sidebar, SidebarView};
pub use toast::{TOAST_TIME, Toast};
pub use topbar::TopBar;
+242
View File
@@ -0,0 +1,242 @@
//! The server rail: the saved servers as avatars with their state, the
//! selection, the add-server button and the settings button (`ServerRail` of
//! `ui/shells/desktop.slint`). An entity of its own: it observes the root
//! state and draws again only when the servers it lists changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
};
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::servers::logic;
use super::actions::{AddServer, EditServer, OpenSettings, SelectServer};
use super::widgets::{Avatar, IconButton, Presence};
use crate::app::AppState;
use crate::theme::{VoelinTheme, hsla};
/// What the rail shows: the servers in order, and which is on screen.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RailView {
/// The saved servers, as `voelin_ui_vm::servers::logic::rail` has them.
pub servers: Vec<ServerItem>,
/// The bookmark on screen.
pub current: Option<i64>,
}
impl RailView {
/// The rail for the state.
pub fn of(app: &AppState) -> Self {
Self {
servers: logic::rail(&app.vm, |bookmark| app.server_icon(bookmark)),
current: app.vm.current,
}
}
}
/// The rail.
pub struct ServerRail {
view: RailView,
_subscription: Subscription,
}
impl ServerRail {
/// A rail that follows `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let view = RailView::of(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let view = RailView::of(app.read(cx));
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, _subscription: subscription }
}
/// What it shows now.
pub fn view(&self) -> &RailView {
&self.view
}
}
/// One server of the rail: the selection pill, the ring of the one on screen,
/// the avatar with its state, the unread count and the live mark.
fn server(theme: &VoelinTheme, item: &ServerItem, selected: bool) -> impl IntoElement + use<> {
let (c, m) = (&theme.colors, &theme.metrics);
let id = i64::from(item.id);
let group = format!("rail-server-{id}");
let name = item.name.to_string();
let tooltip = format!("{name}\n{}", item.address);
let pill = div()
.absolute()
.left(px(0.0))
.w(px(4.0))
.h(px(if selected { 36.0 } else { 0.0 }))
.rounded(px(2.0))
.bg(hsla(c.text))
.when(!selected, |pill| {
let group = group.clone();
pill.group_hover(group, |style| style.h(px(18.0)))
});
div()
.id(("rail-server", id as u64))
.group(group)
.relative()
.w_full()
.h(px(56.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.debug_selector(|| format!("rail-server-{id}"))
.tooltip(move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(tooltip.clone()).build(window, cx)
})
.on_click(move |event, window, cx| {
// A second click on the server is the Slint rail's double click.
if event.click_count() >= 2 {
window.dispatch_action(Box::new(EditServer { id }), cx);
} else {
window.dispatch_action(Box::new(SelectServer { id }), cx);
}
})
.child(pill)
.when(selected, |row| {
row.child(
div()
.absolute()
.size(px(52.0))
.rounded(px(m.radius_lg + 2.0))
.border_2()
.border_color(hsla(c.accent))
.bg(hsla(c.glow.with_alpha(0x66))),
)
})
.child(
Avatar::new(("rail-avatar", id as u64), 46.0, &item.initials, item.tint)
.image(item.icon.clone())
.square()
.presence(Presence::of_server(&item.status)),
)
.when(item.unread > 0, |row| {
row.child(
div()
.absolute()
.top(px(0.0))
.left(px(50.0))
.min_w(px(18.0))
.h(px(18.0))
.px(px(5.0))
.rounded(px(9.0))
.bg(hsla(c.live))
.border_2()
.border_color(hsla(c.bg_rail))
.flex()
.items_center()
.justify_center()
.text_size(px(m.font_xs))
.font_weight(FontWeight::BOLD)
.text_color(hsla(c.on_accent))
.child(item.unread.to_string()),
)
})
.when(item.live && item.unread == 0, |row| {
row.child(
div()
.absolute()
.top(px(4.0))
.left(px(52.0))
.size(px(12.0))
.rounded(px(6.0))
.bg(hsla(c.live))
.border_2()
.border_color(hsla(c.bg_rail)),
)
})
}
impl Render for ServerRail {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let current = self.view.current;
let servers: Vec<_> = self
.view
.servers
.iter()
.map(|item| server(&theme, item, current == Some(i64::from(item.id))))
.collect();
div()
.id("rail")
.w(px(m.rail_width))
.h_full()
.flex_none()
.flex()
.flex_col()
.items_center()
.py(px(m.space_3))
.gap(px(m.space_2))
.bg(hsla(c.bg_rail.with_alpha(230)))
.border_r_1()
.border_color(hsla(c.border))
// The app's mark. (Home, which the Slint rail opens from it, comes
// with its slice.)
.child(
div()
.size(px(48.0))
.flex_none()
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2))
.flex()
.items_center()
.justify_center()
.child(gpui_kit::img("logo.svg").size(px(30.0))),
)
.child(
div()
.w(px(32.0))
.h(px(2.0))
.my(px(m.space_2))
.rounded(px(1.0))
.bg(hsla(c.border_strong)),
)
.child(
div()
.id("rail-servers")
.flex_1()
.min_h_0()
.w_full()
.overflow_y_scroll()
.flex()
.flex_col()
.items_center()
.gap(px(m.space_2))
.children(servers)
.child(
div().pt(px(m.space_2)).child(
IconButton::new("rail-add", "plus", "Add a server")
.size(46.0)
.round()
.filled()
.tint(c.success)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(AddServer), cx);
}),
),
),
)
.child(
IconButton::new("rail-settings", "settings", "Settings")
.size(46.0)
.round()
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(OpenSettings), cx);
}),
)
}
}
+422
View File
@@ -0,0 +1,422 @@
//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of
//! `shells/common.slint`): the server on screen, the place of its channel tree
//! (the next slice), the voice card while voice is connecting or connected, and
//! the user's own card with the voice buttons. An entity of its own: it
//! observes the root state and draws again only when what it shows changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent,
ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, Subscription, Window,
div, px,
};
use voelin_core::TransmitMode;
use voelin_ui_vm::Rgb;
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic;
use super::actions::{
DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted,
};
use super::widgets::{Avatar, IconButton, Presence, card, icon, panel};
use crate::app::AppState;
use crate::theme::{VoelinTheme, hsla};
/// What the sidebar shows.
#[derive(Clone, Debug, PartialEq)]
pub struct SidebarView {
/// The server on screen, as the rail has it.
pub server: Option<ServerItem>,
/// "9 online · 7 channels" once its presence is known, else empty.
pub stats: String,
/// Our nickname there; empty without a server.
pub nickname: String,
/// The channel we are in; empty while connecting.
pub own_channel: String,
/// Our picture on the server.
pub own_avatar: ImageRef,
/// Voice is connected.
pub voice_connected: bool,
/// Voice is connecting.
pub voice_connecting: bool,
/// The server is observed.
pub observing: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// Voice goes out.
pub transmitting: bool,
/// The transmit mode is push-to-talk, so the card has a hold-to-talk button.
pub hold_to_talk: bool,
}
impl SidebarView {
/// The sidebar for the state.
pub fn of(app: &AppState) -> Self {
let card = logic::toolbar(&app.vm, |bookmark| app.server_icon(bookmark));
let server = app.vm.current.and_then(|id| {
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
.into_iter()
.find(|item| i64::from(item.id) == id)
});
Self {
server,
stats: card.server_stats,
nickname: card.nickname,
own_channel: card.own_channel,
own_avatar: card.own_avatar,
voice_connected: card.voice_connected,
voice_connecting: card.voice_connecting,
observing: card.observing,
input_muted: card.input_muted,
output_muted: card.output_muted,
transmitting: card.transmitting,
hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk,
}
}
}
/// The sidebar.
pub struct Sidebar {
view: SidebarView,
/// The hold-to-talk button is held down.
holding: bool,
_subscription: Subscription,
}
impl Sidebar {
/// A sidebar that follows `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let view = SidebarView::of(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let view = SidebarView::of(app.read(cx));
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, holding: false, _subscription: subscription }
}
/// What it shows now.
pub fn view(&self) -> &SidebarView {
&self.view
}
/// The hold-to-talk button was released, if it was held.
fn let_go(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
if std::mem::take(&mut self.holding) {
window.dispatch_action(Box::new(PushToTalk { on: false }), cx);
}
}
}
/// The server's name, its icon and how many are there.
fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let stats = if view.stats.is_empty() { item.address.to_string() } else { view.stats.clone() };
card(theme, 0xff)
.id("sidebar-server")
.debug_selector(|| "sidebar-server".into())
.p(px(m.space_3))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint)
.image(item.icon.clone())
.square(),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(item.name.to_string()),
)
.child(
div()
.truncate()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(stats),
),
)
}
/// Where the channel tree goes: the next slice.
fn channels(theme: &VoelinTheme, has_server: bool) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.id("sidebar-channels")
.flex_1()
.min_h_0()
.flex()
.flex_col()
.gap(px(m.space_2))
.px(px(m.space_2))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.text_size(px(m.font_xs))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text_secondary))
.child(icon("volume-2", m.icon_sm, c.text_secondary))
.child("Channels"),
)
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(if has_server {
"The channel tree comes with the next slice."
} else {
"Add a server to see its channels."
}))
}
/// "Voice Connected" and our channel, disconnect and hold to talk.
fn voice_card(
theme: &VoelinTheme,
view: &SidebarView,
cx: &mut Context<Sidebar>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (dot, words) = if view.voice_connected {
(c.success, "Voice Connected")
} else {
(c.warning, "Connecting…")
};
let talking = view.transmitting;
card(theme, 0xff)
.id("sidebar-voice")
.debug_selector(|| "sidebar-voice".into())
.p(px(m.space_3))
.flex()
.flex_col()
.gap(px(m.space_3))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(div().size(px(10.0)).flex_none().rounded(px(5.0)).bg(hsla(dot)))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(dot))
.child(words),
)
.when(!view.own_channel.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(view.own_channel.clone()),
)
}),
)
.when(view.voice_connected && !view.own_channel.is_empty(), |row| {
row.child(
IconButton::new("voice-invite", "link", "Copy an invite to this channel")
.size(32.0)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(Invite), cx);
}),
)
})
.child(
IconButton::new("voice-disconnect", "phone-off", "Disconnect")
.size(32.0)
.tint(c.danger)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(DisconnectVoice), cx);
}),
),
)
.when(view.voice_connected && view.hold_to_talk, |card| {
card.child(
div()
.id("hold-to-talk")
.debug_selector(|| "hold-to-talk".into())
.h(px(m.control_height))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(if talking { c.success } else { c.border }))
.bg(hsla(if talking { c.success.with_alpha(0xcc) } else { c.surface_2 }))
.cursor_pointer()
.hover(move |style| {
style.bg(hsla(if talking { c.success } else { c.surface_3 }))
})
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
this.holding = true;
window.dispatch_action(Box::new(PushToTalk { on: true }), cx);
}),
)
// Let go on the button or off it: the end of what was started.
.on_mouse_up(MouseButton::Left, cx.listener(Sidebar::let_go))
.on_mouse_up_out(MouseButton::Left, cx.listener(Sidebar::let_go))
.child(icon(
"mic",
m.icon_sm,
if talking { c.on_accent } else { c.text_secondary },
))
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(if talking { c.on_accent } else { c.text_secondary }))
.child(if talking { "Talking…" } else { "Hold to talk" }),
),
)
})
}
/// Who we are, and the buttons for the microphone and the sound.
fn user_card(theme: &VoelinTheme, view: &SidebarView) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (words, presence) = if view.voice_connected {
("Online", Presence::Online)
} else if view.observing {
("Observing", Presence::Info)
} else {
("Offline", Presence::Offline)
};
let name = if view.nickname.is_empty() {
voelin_platform::APP_NAME.to_owned()
} else {
view.nickname.clone()
};
let (input_muted, output_muted) = (view.input_muted, view.output_muted);
card(theme, 0xb3)
.id("sidebar-user")
.debug_selector(|| "sidebar-user".into())
.min_h(px(60.0))
.p(px(m.space_2))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.id("sidebar-profile")
.flex_1()
.min_w_0()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.px(px(m.space_2))
.py(px(m.space_2))
.rounded(px(m.radius_md))
.cursor_pointer()
.hover(|style| style.bg(hsla(c.surface_3)))
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
.child(
Avatar::new("sidebar-own-avatar", 38.0, &name_initials(&name), Rgb(0x2d6bff))
.image(view.own_avatar.clone())
.presence(presence)
.speaking(view.transmitting),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(name),
)
.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(words),
),
),
)
.child(
IconButton::new(
"user-mic",
if input_muted { "mic-off" } else { "mic" },
if input_muted { "Microphone off" } else { "Microphone on" },
)
.danger()
.checked(input_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx);
}),
)
.child(
IconButton::new(
"user-sound",
if output_muted { "headphone-off" } else { "headphones" },
if output_muted { "Sound off" } else { "Sound on" },
)
.danger()
.checked(output_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx);
}),
)
}
/// The initials of a nickname, for the avatar.
fn name_initials(name: &str) -> String {
voelin_ui_vm::avatar::initials(name)
}
impl Render for Sidebar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let m = &theme.metrics;
let view = &self.view;
panel(&theme)
.id("sidebar")
.w(px(m.sidebar_width))
.h_full()
.flex_none()
.p(px(m.space_3))
.gap(px(m.space_3))
.when_some(view.server.as_ref(), |sidebar, item| {
sidebar.child(server_card(&theme, view, item))
})
.child(channels(&theme, view.server.is_some()))
.when(view.voice_connected || view.voice_connecting, |sidebar| {
sidebar.child(voice_card(&theme, view, cx))
})
.child(user_card(&theme, view))
}
}
+88
View File
@@ -0,0 +1,88 @@
//! The status line as a toast: what the last move did ("Connecting to
//! ts.example…", why a server was not saved), shown at the bottom of the
//! window for a few seconds. It watches the root state's status line and its
//! generation, so that the same words said twice are two toasts.
use std::time::Duration;
use gpui_kit::{
Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _,
Subscription, Window, div, px,
};
use crate::app::AppState;
use crate::theme::{VoelinTheme, hsla};
/// How long a toast stays.
pub const TOAST_TIME: Duration = Duration::from_secs(5);
/// The toast.
pub struct Toast {
text: String,
generation: u64,
_subscription: Subscription,
}
impl Toast {
/// A toast that follows `app`'s status line from now on (what it said
/// before is not shown).
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let generation = app.read(cx).status_generation;
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let (generation, text) = {
let app = app.read(cx);
(app.status_generation, app.vm.status.clone())
};
if generation == this.generation {
return;
}
this.generation = generation;
this.text = text;
cx.notify();
if this.text.is_empty() {
return;
}
cx.spawn(async move |this, cx| {
cx.background_executor().timer(TOAST_TIME).await;
let _ = this.update(cx, |this, cx| {
if this.generation == generation && !this.text.is_empty() {
this.text.clear();
cx.notify();
}
});
})
.detach();
});
Self { text: String::new(), generation, _subscription: subscription }
}
/// What it shows now; empty when nothing is.
pub fn text(&self) -> &str {
&self.text
}
}
impl Render for Toast {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let toast =
div().id("toast").absolute().bottom(px(m.space_7)).w_full().flex().justify_center();
if self.text.is_empty() {
return toast;
}
toast.child(
div()
.max_w(px(560.0))
.px(px(m.space_5))
.py(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border_popup))
.bg(hsla(c.surface_3))
.text_size(px(m.font_body))
.text_color(hsla(c.text))
.child(self.text.clone()),
)
}
}
+112
View File
@@ -0,0 +1,112 @@
//! The bar at the top of the window: the page's title, the search box and the
//! settings button (`TopBar` of `ui/shells/desktop.slint`; the bell comes
//! with the notifications). The search and the settings are affordances until
//! their slices: a click is logged ([`OpenSearch`], [`OpenSettings`]).
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Render,
StatefulInteractiveElement as _, Styled as _, Subscription, Window, div, px,
};
use super::actions::{OpenSearch, OpenSettings};
use super::widgets::{IconButton, icon};
use crate::app::AppState;
use crate::theme::{VoelinTheme, hsla};
/// The page title: the server on screen, else the app's name.
pub fn title(app: &AppState) -> String {
match app.current_bookmark() {
Some(bookmark) => bookmark.name.clone(),
None => voelin_platform::APP_NAME.to_owned(),
}
}
/// The top bar.
pub struct TopBar {
title: String,
_subscription: Subscription,
}
impl TopBar {
/// A top bar that follows `app`.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let shown = title(app.read(cx));
let subscription = cx.observe(app, |this: &mut Self, app, cx| {
let shown = title(app.read(cx));
if shown != this.title {
this.title = shown;
cx.notify();
}
});
Self { title: shown, _subscription: subscription }
}
/// The title it shows now.
pub fn title(&self) -> &str {
&self.title
}
}
impl Render for TopBar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
div()
.id("topbar")
.w_full()
.h(px(m.topbar_height))
.flex_none()
.flex()
.flex_row()
.items_center()
// The main panel starts where the sidebar and the gaps around it end.
.pl(px(m.sidebar_width + 2.0 * m.space_3))
.pr(px(m.space_4))
.gap(px(m.space_4))
.child(
div()
.id("topbar-title")
.max_w(px(280.0 * m.font_scale.max(1.0)))
.flex_none()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(self.title.clone()),
)
.child(
div().flex_1().min_w_0().flex().justify_center().child(
div()
.id("topbar-search")
.w_full()
.max_w(px(680.0))
.h(px(m.control_height))
.px(px(m.space_3))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2))
.cursor_text()
.hover(|style| style.border_color(hsla(c.border_strong)))
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSearch), cx))
.child(icon("search", m.icon_sm, c.text_muted))
.child(
div()
.flex_1()
.truncate()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("Search servers, channels, people or settings…"),
),
),
)
.child(
IconButton::new("topbar-settings", "settings", "Settings")
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx)),
)
}
}
+358
View File
@@ -0,0 +1,358 @@
//! The few pieces the shell is made of, drawn from the theme's tokens
//! (`VoelinTheme`, not gpui-component's colours): the avatar of a server or a
//! person, the icon button, the panel and the Lucide icon. They are the GPUI
//! counterparts of `ui/components/avatar.slint`, `button.slint` and
//! `shells/common.slint`'s `Panel`.
use gpui_kit::{
App, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, img, px,
svg,
};
use gpui_kit::{ElementId, ObjectFit, StyledImage as _};
use voelin_ui_vm::Rgb;
use voelin_ui_vm::image::{ImageRef, ImageSource};
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
/// A Lucide icon of the client's set, `size` pixels square, in `color`.
pub fn icon(name: &str, size: f32, color: Rgba) -> impl IntoElement {
svg().path(format!("icons/{name}.svg")).size(px(size)).flex_none().text_color(hsla(color))
}
/// What the dot on an avatar says (`Status` of `avatar.slint`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presence {
/// No dot.
None,
/// Connected with voice.
Online,
/// Connecting.
Idle,
/// Observed invisibly.
Info,
/// Not connected.
Offline,
}
impl Presence {
/// The dot of a server's state as the engine names it
/// (`voelin_ui_vm::servers::status`): connected is online, observing is
/// blue, connecting is idle, offline has none.
pub fn of_server(status: &str) -> Self {
match status {
"connected" => Self::Online,
"observing" => Self::Info,
"connecting" => Self::Idle,
_ => Self::None,
}
}
/// The dot's colour.
fn color(self, theme: &VoelinTheme) -> Option<Rgba> {
let c = &theme.colors;
match self {
Self::None => None,
Self::Online => Some(c.success),
Self::Idle => Some(c.idle),
Self::Info => Some(c.info),
Self::Offline => Some(c.offline),
}
}
}
/// The colour a server or person is drawn in.
pub fn tint(color: Rgb) -> Rgba {
Rgba(color.0 << 8 | 0xff)
}
/// An avatar: the picture when there is one (a file of the engine's cache),
/// else the initials on `tint`, square with rounded corners for a server
/// and round for a person, with a presence dot and a green ring while the
/// person's voice goes out. Pictures other than files of the cache are drawn
/// as initials until the slices that decode them (the chat's, the members').
#[derive(IntoElement)]
pub struct Avatar {
id: ElementId,
size: f32,
initials: SharedString,
tint: Rgb,
image: ImageRef,
square: bool,
presence: Presence,
speaking: bool,
}
impl Avatar {
/// An avatar of `size` pixels with these initials on `tint`.
pub fn new(id: impl Into<ElementId>, size: f32, initials: &str, tint: Rgb) -> Self {
Self {
id: id.into(),
size,
initials: initials.to_owned().into(),
tint,
image: ImageRef::default(),
square: false,
presence: Presence::None,
speaking: false,
}
}
/// Draw this picture when it is a file of the cache.
pub fn image(mut self, image: ImageRef) -> Self {
self.image = image;
self
}
/// A server's rounded square, not a person's circle.
pub fn square(mut self) -> Self {
self.square = true;
self
}
/// The dot at the corner.
pub fn presence(mut self, presence: Presence) -> Self {
self.presence = presence;
self
}
/// The green ring.
pub fn speaking(mut self, speaking: bool) -> Self {
self.speaking = speaking;
self
}
}
impl RenderOnce for Avatar {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let radius = if self.square { m.radius_lg } else { self.size / 2.0 };
let picture = match &*self.image {
ImageSource::File { path, .. } if self.image.size().width > 0 => Some(path.clone()),
_ => None,
};
let face = div()
.size(px(self.size))
.flex_none()
.rounded(px(radius))
.overflow_hidden()
.flex()
.items_center()
.justify_center()
.bg(hsla(if picture.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match picture {
Some(path) => face.child(img(path).size_full().object_fit(ObjectFit::Cover)),
None => face.child(
div()
.text_size(px(self.size * 0.38))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(Rgba(0xffff_ffff)))
.child(self.initials),
),
};
let mut avatar = div().id(self.id).relative().size(px(self.size)).flex_none();
if self.speaking {
avatar = avatar.child(
div()
.absolute()
.top(px(-3.0))
.left(px(-3.0))
.size(px(self.size + 6.0))
.rounded(px(radius + 3.0))
.border_2()
.border_color(hsla(c.success)),
);
}
avatar = avatar.child(face);
if let Some(color) = self.presence.color(theme) {
let dot = (self.size * 0.3).max(10.0);
avatar = avatar.child(
div()
.absolute()
.top(px(self.size - dot + 1.0))
.left(px(self.size - dot + 1.0))
.size(px(dot))
.rounded(px(dot / 2.0))
.border_2()
.border_color(hsla(c.surface))
.bg(hsla(color)),
);
}
avatar
}
}
type Handler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
/// A button that is an icon: 36 pixels (or `size`) square, round or with
/// rounded corners, with a tooltip. Without a handler or disabled it draws
/// dimmed and does nothing.
#[derive(IntoElement)]
pub struct IconButton {
id: ElementId,
icon: &'static str,
label: SharedString,
size: f32,
tint: Option<Rgba>,
danger: bool,
round: bool,
filled: bool,
checked: bool,
enabled: bool,
on_click: Option<Handler>,
}
impl IconButton {
/// The Lucide icon `icon` (a file name without `.svg`), named `label` for
/// the tooltip.
pub fn new(
id: impl Into<ElementId>,
icon: &'static str,
label: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
icon,
label: label.into(),
size: 34.0,
tint: None,
danger: false,
round: false,
filled: false,
checked: false,
enabled: true,
on_click: None,
}
}
/// The button's side in pixels.
pub fn size(mut self, size: f32) -> Self {
self.size = size;
self
}
/// The icon's colour, instead of the theme's icon colour.
pub fn tint(mut self, tint: Rgba) -> Self {
self.tint = Some(tint);
self
}
/// A button that turns danger-coloured when checked (mute).
pub fn danger(mut self) -> Self {
self.danger = true;
self
}
/// A circle.
pub fn round(mut self) -> Self {
self.round = true;
self
}
/// A button with a border and a face of its own (the rail's plus).
pub fn filled(mut self) -> Self {
self.filled = true;
self
}
/// Whether it is on.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Whether it can be used.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// What a click does.
pub fn on_click(
mut self,
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_click = Some(Box::new(handler));
self
}
}
impl RenderOnce for IconButton {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let (face, ink, hover) = match (self.checked, self.danger, self.filled) {
(true, true, _) => (c.danger_soft, c.danger, c.danger_soft),
(true, false, _) => (c.accent_soft, c.accent_text, c.accent_soft_hover),
(false, _, true) => {
let ink = self.tint.unwrap_or(c.icon);
(c.surface_2, ink, ink.with_alpha(0x33))
}
(false, _, false) => (Rgba::TRANSPARENT, self.tint.unwrap_or(c.icon), c.surface_3),
};
let radius = if self.round { self.size / 2.0 } else { m.radius_md };
let icon_size = if self.size >= 40.0 { m.icon_md } else { m.icon_sm.max(self.size * 0.5) };
let label = self.label.clone();
let selector = self.id.to_string();
let mut button = div()
.id(self.id)
.debug_selector(move || selector)
.size(px(self.size))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(px(radius))
.bg(hsla(face))
.child(icon(self.icon, icon_size, ink));
if self.filled {
button = button.border_1().border_color(hsla(ink));
}
if !self.enabled {
return button.opacity(0.4).into_any_element();
}
button = button.cursor_pointer().hover(move |style| style.bg(hsla(hover))).tooltip(
move |window, cx| {
gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
},
);
match self.on_click {
Some(handler) => button.on_click(move |event, window, cx| handler(event, window, cx)),
None => button,
}
.into_any_element()
}
}
/// A rounded panel of the frame (sidebar, main area): `surface` a little
/// see-through over the backdrop, a border, clipped.
pub fn panel(theme: &VoelinTheme) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.flex()
.flex_col()
.rounded(px(m.radius_xl))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface.with_alpha(235)))
.overflow_hidden()
}
/// What a card of the sidebar is drawn on.
pub fn card(theme: &VoelinTheme, alpha: u8) -> gpui_kit::Div {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.rounded(px(m.radius_lg))
.border_1()
.border_color(hsla(c.border))
.bg(hsla(c.surface_2.with_alpha(alpha)))
}
/// `element` in a box of its own that tests find by `selector` (a debug
/// selector costs nothing in a build without debug assertions): for the
/// components of gpui-component, which have none of their own.
pub fn tagged(selector: &'static str, element: impl IntoElement) -> impl IntoElement {
div().flex_none().debug_selector(|| selector.into()).child(element)
}
+785 -51
View File
@@ -1,28 +1,69 @@
//! The window's content. The shell is not built yet (slice 1 of the
//! migration): the window is the theme's page with the one line of the root
//! state that proves the loops run in a status bar, or, with
//! `VOELIN_OPEN=swatch`, the swatch page above that bar.
//! The window's content: the desktop shell, or with `VOELIN_OPEN=swatch` the
//! swatch page. [`MainView`] is the window's root view: it puts the shell's
//! entities (`crate::shell`) in place, handles the actions the user's moves
//! dispatch ([`crate::shell::actions`]) by asking the root state for what the
//! Slint callbacks did, owns the server form, titles the window with the
//! server on screen and reports where the window is.
use gpui_kit::{
Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px,
App, AppContext as _, Context, Entity, FocusHandle, InteractiveElement as _, IntoElement,
ParentElement as _, Render, Styled as _, Subscription, Window, WindowBounds, div, px,
};
use voelin_ui_vm::settings::WindowState;
use crate::app::AppState;
use crate::dev::Page;
use crate::meter::Counters;
use crate::shell::actions::{
AddServer, CancelServerForm, ConnectVoice, DeleteServer, DisconnectVoice, EditServer, Invite,
OpenSearch, OpenSettings, PushToTalk, SaveAndConnect, SaveServer, SelectServer, SetInputMuted,
SetOutputMuted,
};
use crate::shell::{MainPanel, ServerForm, ServerRail, Sidebar, Toast, TopBar};
use crate::swatch::swatch;
use crate::theme::{VoelinTheme, hsla};
/// Where `window` is, as the setting `ui.window` keeps it: the size, the
/// position where the platform tells one (not Wayland's) and whether it is
/// maximized; none in full screen, and none for what cannot be a window.
pub fn window_state(window: &Window, cx: &App) -> Option<WindowState> {
let (bounds, maximized) = match window.window_bounds() {
WindowBounds::Windowed(bounds) => (bounds, false),
WindowBounds::Maximized(bounds) => (bounds, true),
WindowBounds::Fullscreen(_) => return None,
};
let whole = |pixels: gpui_kit::Pixels| f32::from(pixels).round() as i32;
let positioned = cx.compositor_name() != "Wayland";
let state = WindowState {
width: whole(bounds.size.width).max(0) as u32,
height: whole(bounds.size.height).max(0) as u32,
x: positioned.then(|| whole(bounds.origin.x)),
y: positioned.then(|| whole(bounds.origin.y)),
maximized,
};
state.is_sane().then_some(state)
}
/// What the main window draws, from the root state and the theme.
pub struct MainView {
app: Entity<AppState>,
page: Page,
counters: Counters,
rail: Entity<ServerRail>,
topbar: Entity<TopBar>,
sidebar: Entity<Sidebar>,
main: Entity<MainPanel>,
toast: Entity<Toast>,
form: Option<Entity<ServerForm>>,
title: String,
focus: FocusHandle,
_subscriptions: Vec<Subscription>,
}
impl MainView {
/// A view of `app` that draws again whenever it changes, and that keeps
/// the theme in `system` mode in step with the window's appearance.
/// A view of `app`. It keeps the theme in `system` mode in step with the
/// window's appearance, the window's title with the server on screen, and
/// tells `app` where the window is.
pub fn new(
app: Entity<AppState>,
page: Page,
@@ -30,63 +71,756 @@ impl MainView {
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
cx.observe(&app, |_, _, cx| cx.notify()).detach();
cx.observe_window_appearance(window, |_, window, cx| {
VoelinTheme::set_system_appearance(cx, window.appearance());
})
.detach();
Self { app, page, counters }
let title = app.read(cx).window_title();
window.set_window_title(&title);
// The window's own focus: actions dispatch from the focused element up,
// so the handlers sit on an element that has it, and it comes back to
// it whenever the element that had it is gone (the form closed, a
// button replaced by another).
let focus = cx.focus_handle();
window.focus(&focus, cx);
let subscriptions = vec![
cx.on_focus_lost(window, |this, window, cx| window.focus(&this.focus, cx)),
cx.observe_window_appearance(window, |_, window, cx| {
VoelinTheme::set_system_appearance(cx, window.appearance());
}),
cx.observe_in(&app, window, |this, app, window, cx| {
let title = app.read(cx).window_title();
if title != this.title {
window.set_window_title(&title);
this.title = title;
}
// A form for a server that is gone (removed from another place)
// has nothing to edit.
let editing = this.form.as_ref().map(|form| form.read(cx).id());
let known = |id: i64| app.read(cx).vm.bookmarks.iter().any(|b| b.id == id);
if editing.is_some_and(|id| id >= 0 && !known(id)) {
this.form = None;
cx.notify();
}
}),
cx.observe_window_bounds(window, |this, window, cx| report(&this.app, window, cx)),
];
report(&app, window, cx);
Self {
rail: cx.new(|cx| ServerRail::new(&app, cx)),
topbar: cx.new(|cx| TopBar::new(&app, cx)),
sidebar: cx.new(|cx| Sidebar::new(&app, cx)),
main: cx.new(|cx| MainPanel::new(&app, cx)),
toast: cx.new(|cx| Toast::new(&app, cx)),
app,
page,
counters,
form: None,
title,
focus,
_subscriptions: subscriptions,
}
}
/// The server form on screen, if one is.
pub fn form(&self) -> Option<&Entity<ServerForm>> {
self.form.as_ref()
}
/// Open the form with `form`'s values.
fn open_form(
&mut self,
form: voelin_ui_vm::bridge::BookmarkForm,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.form = Some(cx.new(|cx| ServerForm::new(&form, window, cx)));
cx.notify();
}
fn select_server(&mut self, action: &SelectServer, _: &mut Window, cx: &mut Context<Self>) {
self.form = None;
self.app.update(cx, |app, cx| app.select_server(action.id, cx));
cx.notify();
}
fn connect_voice(&mut self, _: &ConnectVoice, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.connect_voice(cx));
}
fn disconnect_voice(&mut self, _: &DisconnectVoice, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.disconnect_voice(cx));
}
fn set_input_muted(&mut self, action: &SetInputMuted, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.set_input_muted(action.muted, cx));
}
fn set_output_muted(
&mut self,
action: &SetOutputMuted,
_: &mut Window,
cx: &mut Context<Self>,
) {
self.app.update(cx, |app, cx| app.set_output_muted(action.muted, cx));
}
fn push_to_talk(&mut self, action: &PushToTalk, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.push_to_talk(action.on, cx));
}
fn invite(&mut self, _: &Invite, _: &mut Window, cx: &mut Context<Self>) {
self.app.update(cx, |app, cx| app.invite(cx));
}
fn add_server(&mut self, _: &AddServer, window: &mut Window, cx: &mut Context<Self>) {
let form = self.app.read(cx).bookmark_form(-1);
self.open_form(form, window, cx);
}
fn edit_server(&mut self, action: &EditServer, window: &mut Window, cx: &mut Context<Self>) {
let form = self.app.read(cx).bookmark_form(action.id);
self.open_form(form, window, cx);
}
/// Save the form's server; the form closes when it was saved, stays
/// (with the toast saying why) when it was not.
fn save(&mut self, connect: bool, cx: &mut Context<Self>) {
let Some(form) = &self.form else { return };
let values = form.read(cx).to_form(cx);
let saved = self.app.update(cx, |app, cx| {
if connect {
app.save_and_connect(&values, cx)
} else {
app.save_bookmark(&values, cx).is_some()
}
});
if saved {
self.form = None;
cx.notify();
}
}
fn save_server(&mut self, _: &SaveServer, _: &mut Window, cx: &mut Context<Self>) {
self.save(false, cx);
}
fn save_and_connect(&mut self, _: &SaveAndConnect, _: &mut Window, cx: &mut Context<Self>) {
self.save(true, cx);
}
fn cancel_form(&mut self, _: &CancelServerForm, _: &mut Window, cx: &mut Context<Self>) {
self.form = None;
cx.notify();
}
fn delete_server(&mut self, action: &DeleteServer, _: &mut Window, cx: &mut Context<Self>) {
self.form = None;
self.app.update(cx, |app, cx| app.delete_bookmark(action.id, cx));
cx.notify();
}
fn open_search(&mut self, _: &OpenSearch, _: &mut Window, _: &mut Context<Self>) {
tracing::info!("the search comes with its slice (docs/ui.md, \"What is next\")");
}
fn open_settings(&mut self, _: &OpenSettings, _: &mut Window, _: &mut Context<Self>) {
tracing::info!("the settings come with their slice (docs/ui.md, \"What is next\")");
}
}
/// Tell `app` where `window` is: it keeps the place at the next tick.
fn report(app: &Entity<AppState>, window: &Window, cx: &mut App) {
if let Some(state) = window_state(window, cx) {
app.update(cx, |app, _| app.window_moved(state));
}
}
impl Render for MainView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// One render of the window is one frame: the parts draw when they are
// told, and the window is drawn when one was.
self.counters.renders.incr();
let line = self.app.read(cx).state_line();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let page = match self.page {
Page::Swatch => div().flex_1().overflow_hidden().child(swatch(&theme)),
Page::Shell => div()
.flex_1()
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(m.space_3))
.child(
div()
.text_size(px(m.font_3xl))
.text_color(hsla(c.text))
.child(voelin_platform::APP_NAME),
)
.child(
div()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("The desktop shell is the next slice."),
),
};
div()
let frame = div()
.id("window")
.relative()
.size_full()
.flex()
.flex_col()
.bg(hsla(c.bg_app))
.text_color(hsla(c.text))
.font_family(crate::theme::FONT_FAMILY)
.child(page)
.font_family(crate::theme::FONT_FAMILY);
if self.page == Page::Swatch {
return frame.bg(hsla(c.bg_app)).child(swatch(&theme));
}
let main = match &self.form {
Some(form) => form.clone().into_any_element(),
None => self.main.clone().into_any_element(),
};
frame
.key_context("Shell")
.track_focus(&self.focus)
.bg(theme.backdrop.to_gpui())
.flex()
.flex_row()
.on_action(cx.listener(Self::select_server))
.on_action(cx.listener(Self::connect_voice))
.on_action(cx.listener(Self::disconnect_voice))
.on_action(cx.listener(Self::set_input_muted))
.on_action(cx.listener(Self::set_output_muted))
.on_action(cx.listener(Self::push_to_talk))
.on_action(cx.listener(Self::invite))
.on_action(cx.listener(Self::add_server))
.on_action(cx.listener(Self::edit_server))
.on_action(cx.listener(Self::save_server))
.on_action(cx.listener(Self::save_and_connect))
.on_action(cx.listener(Self::cancel_form))
.on_action(cx.listener(Self::delete_server))
.on_action(cx.listener(Self::open_search))
.on_action(cx.listener(Self::open_settings))
.child(self.rail.clone())
.child(
div()
.h(px(m.control_height_sm))
.px(px(m.space_5))
.flex_1()
.min_w_0()
.h_full()
.flex()
.items_center()
.bg(hsla(c.surface))
.border_t_1()
.border_color(hsla(c.border))
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(line),
.flex_col()
.child(self.topbar.clone())
.child(
div()
.flex_1()
.min_h_0()
.flex()
.flex_row()
.px(px(m.space_3))
.pb(px(m.space_3))
.gap(px(m.space_3))
.child(self.sidebar.clone())
.child(main),
),
)
.child(self.toast.clone())
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;
use gpui::{TestAppContext, VisualTestContext};
use gpui_kit::{Bounds, WindowAppearance, point, size};
use tokio::sync::mpsc::{self, UnboundedSender};
use voelin_core::{Command, Event, SessionState, VoiceState};
use voelin_store::{Bookmark, MemorySecrets};
use voelin_ui_vm::bridge::BookmarkForm;
use voelin_ui_vm::dev::logic as sample;
use voelin_ui_vm::settings::UI_WINDOW;
use super::*;
use crate::app::Setup;
use crate::backend::Backend;
use crate::backend::testing::TempDir;
use crate::dev::Switches;
use crate::shell::RailView;
use crate::theme::Choice;
use crate::window_bounds;
/// What a test of the shell holds: the root state, the window's view, the
/// engine's events and the meter's counters.
struct Shell {
app: Entity<AppState>,
view: Entity<MainView>,
events: UnboundedSender<Event>,
counters: Counters,
}
fn bookmark(name: &str, address: &str) -> Bookmark {
Bookmark {
name: name.into(),
address: address.into(),
nickname: "Nova".into(),
..Default::default()
}
}
fn backend_with(servers: &[(&str, &str)]) -> Backend {
let backend = Backend::in_memory().unwrap();
for (name, address) in servers {
backend.store.add_bookmark(&bookmark(name, address)).unwrap();
}
backend
}
/// Open the window of the shell on `backend`, with the theme and the
/// components set up as `run` sets them.
fn open(
cx: &mut TestAppContext,
backend: Backend,
switches: Switches,
) -> (Shell, &mut VisualTestContext) {
cx.update(|cx| {
gpui_kit::init(cx);
VoelinTheme::init(cx, Choice::Dark, WindowAppearance::Dark, 1.0);
});
let (events, rx) = mpsc::unbounded_channel();
let counters = Counters::default();
let page = switches.open;
let setup =
Setup { engine: None, events: rx, counters: counters.clone(), backend, switches };
let app = cx.new(|cx| AppState::new(setup, cx));
let (view, vcx) = cx.add_window_view({
let (app, counters) = (app.clone(), counters.clone());
move |window, cx| MainView::new(app, page, counters, window, cx)
});
let shell = Shell { app, view, events, counters };
frame(vcx);
(shell, vcx)
}
/// Run what is queued and draw the window.
fn frame(cx: &mut VisualTestContext) {
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
}
/// Where the element with this debug selector is on screen.
fn at(cx: &mut VisualTestContext, selector: &str) -> Option<Bounds<gpui_kit::Pixels>> {
cx.debug_bounds(Box::leak(selector.to_owned().into_boxed_str()))
}
fn click(cx: &mut VisualTestContext, selector: &str) {
let bounds = at(cx, selector).unwrap_or_else(|| panic!("{selector} is not on screen"));
cx.simulate_click(bounds.center(), Default::default());
frame(cx);
}
fn ids(shell: &Shell, cx: &mut VisualTestContext) -> Vec<i64> {
shell.app.read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.id).collect())
}
fn rail(shell: &Shell, cx: &mut VisualTestContext) -> RailView {
shell.view.read_with(cx, |view, cx| view.rail.read(cx).view().clone())
}
fn form(address: &str) -> BookmarkForm {
BookmarkForm { id: -1, address: address.into(), ..Default::default() }
}
fn connected(id: i64) -> Event {
Event::State {
session: id as u64,
state: SessionState { voice: VoiceState::Connected, ..Default::default() },
}
}
/// A saved server shows in the rail, as an icon the user can click.
#[gpui::test]
fn a_server_added_shows_in_the_rail(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
assert_eq!(rail(&shell, cx).servers, []);
let id = shell
.app
.update(cx, |app, cx| {
app.save_bookmark(
&BookmarkForm { name: "Nightfall".into(), ..form("ts.example") },
cx,
)
})
.unwrap();
frame(cx);
let view = rail(&shell, cx);
assert_eq!(view.servers.len(), 1);
assert_eq!(
(i64::from(view.servers[0].id), view.servers[0].name.as_ref()),
(id, "Nightfall")
);
assert_eq!(view.servers[0].initials.as_ref(), "NI");
assert_eq!(view.current, Some(id), "and it is the one on screen");
assert!(at(cx, &format!("rail-server-{id}")).is_some(), "drawn");
}
/// A click on a server of the rail shows it: the window's title, the top
/// bar and the sidebar name it.
#[gpui::test]
fn clicking_a_server_selects_it_and_titles_the_window(cx: &mut TestAppContext) {
let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]);
let (shell, cx) = open(cx, backend, Switches::default());
let [first, second] = ids(&shell, cx)[..] else { panic!("two servers") };
assert_eq!(
cx.window_title().as_deref(),
Some("Voelin - Nightfall"),
"the first is shown at start"
);
click(cx, &format!("rail-server-{second}"));
assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(second));
assert_eq!(cx.window_title().as_deref(), Some("Voelin - Lounge"));
shell.view.read_with(cx, |view, cx| {
assert_eq!(view.topbar.read(cx).title(), "Lounge");
let sidebar = view.sidebar.read(cx).view();
assert_eq!(sidebar.server.as_ref().map(|s| s.name.as_ref()), Some("Lounge"));
});
assert_eq!(rail(&shell, cx).current, Some(second));
click(cx, &format!("rail-server-{first}"));
assert_eq!(cx.window_title().as_deref(), Some("Voelin - Nightfall"));
}
/// Nothing on screen is the "no server selected" state with the way to
/// add one, and the title is the app's.
#[gpui::test]
fn without_a_server_the_main_area_says_so(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
assert_eq!(cx.window_title().as_deref(), Some("Voelin"));
shell.view.read_with(cx, |view, cx| {
assert_eq!(view.main.read(cx).state(), &crate::shell::MainState::NoServer);
assert_eq!(view.topbar.read(cx).title(), "Voelin");
});
assert!(at(cx, "main-empty").is_some());
assert!(at(cx, "sidebar-server").is_none(), "no server card");
}
/// The connect button of a server on screen asks the engine to connect it.
#[gpui::test]
fn the_connect_button_connects_the_server_on_screen(cx: &mut TestAppContext) {
let (shell, cx) =
open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = ids(&shell, cx)[0];
shell.app.read_with(cx, |app, _| app.take_sent());
click(cx, "main-connect");
let sent = shell.app.read_with(cx, |app, _| app.take_sent());
assert!(
matches!(sent.as_slice(), [Command::ConnectVoice { session, options, .. }, ..]
if *session == id as u64 && options.address == "ts.example"),
"{sent:?}"
);
}
/// What the engine says about a session shows in the rail, the sidebar's
/// voice card and the main area's buttons.
#[gpui::test]
fn an_engine_event_updates_the_rail_and_the_cards(cx: &mut TestAppContext) {
let (shell, cx) =
open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = ids(&shell, cx)[0];
assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "offline");
assert!(at(cx, "sidebar-voice").is_none() && at(cx, "main-connect").is_some());
shell.events.send(connected(id)).unwrap();
frame(cx);
assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "connected");
assert!(at(cx, "sidebar-voice").is_some(), "the voice card");
assert!(at(cx, "main-disconnect").is_some() && at(cx, "main-connect").is_none());
shell
.events
.send(Event::State { session: id as u64, state: SessionState::default() })
.unwrap();
frame(cx);
assert_eq!(rail(&shell, cx).servers[0].status.as_ref(), "offline");
assert!(at(cx, "sidebar-voice").is_none());
}
/// The mute buttons of the user card, and the disconnect of the voice card,
/// go to the session as commands once voice is up.
#[gpui::test]
fn the_voice_buttons_send_their_commands_once_voice_is_up(cx: &mut TestAppContext) {
let (shell, cx) =
open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = ids(&shell, cx)[0];
click(cx, "user-mic");
assert!(
shell.app.read_with(cx, |app, _| app.take_sent()).is_empty(),
"disabled without voice"
);
shell.events.send(connected(id)).unwrap();
frame(cx);
click(cx, "user-mic");
click(cx, "user-sound");
click(cx, "voice-disconnect");
let sent = shell.app.read_with(cx, |app, _| app.take_sent());
assert!(
matches!(
sent.as_slice(),
[
Command::SetInputMuted { session: a, muted: true },
Command::SetOutputMuted { session: b, muted: true },
Command::DisconnectVoice { session: c },
] if [*a, *b, *c] == [id as u64; 3]
),
"{sent:?}"
);
}
/// Hold to talk transmits while the button is held down.
#[gpui::test]
fn hold_to_talk_transmits_while_it_is_held(cx: &mut TestAppContext) {
let (shell, cx) =
open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = ids(&shell, cx)[0];
shell.events.send(connected(id)).unwrap();
frame(cx);
let button = at(cx, "hold-to-talk").expect("push-to-talk is the default transmit mode");
cx.simulate_mouse_down(button.center(), gpui_kit::MouseButton::Left, Default::default());
cx.simulate_mouse_up(button.center(), gpui_kit::MouseButton::Left, Default::default());
let sent = shell.app.read_with(cx, |app, _| app.take_sent());
assert!(
matches!(
sent.as_slice(),
[Command::SetTransmitting { session: a, on: true }, Command::SetTransmitting { session: b, on: false }]
if [*a, *b] == [id as u64; 2]
),
"{sent:?}"
);
}
/// What changes nothing the shell shows tells no part, so draws nothing: an
/// engine event about a talker, a setting that is not the theme's, a tick.
/// The root is told every time; the parts compare what they would show.
#[gpui::test]
fn what_changes_nothing_shown_draws_nothing(cx: &mut TestAppContext) {
let (shell, cx) =
open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let id = ids(&shell, cx)[0];
let (rail, topbar, sidebar, main, toast) = shell.view.read_with(cx, |v, _| {
(v.rail.clone(), v.topbar.clone(), v.sidebar.clone(), v.main.clone(), v.toast.clone())
});
let (root_told, parts_told) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)));
macro_rules! count {
($cx:expr, $entity:expr, $told:expr) => {{
let told = $told.clone();
$cx.observe(&$entity, move |_, _| told.set(told.get() + 1))
}};
}
let _subscriptions = cx.update(|_, cx| {
vec![
count!(cx, shell.app, root_told),
count!(cx, rail, parts_told),
count!(cx, topbar, parts_told),
count!(cx, sidebar, parts_told),
count!(cx, main, parts_told),
count!(cx, toast, parts_told),
]
});
for event in [
Event::Talking { session: id as u64, client: 3, talking: true },
Event::SettingChanged { key: "stream.fps".into() },
] {
shell.events.send(event).unwrap();
frame(cx);
}
cx.executor().advance_clock(Duration::from_secs(3));
frame(cx);
assert_eq!(root_told.get(), 2, "the root hears every batch of events");
assert_eq!(parts_told.get(), 0, "no part has anything new to show");
assert_eq!(shell.counters.ticks.get(), 3, "though the clock ran");
// What does show tells the parts.
shell.events.send(connected(id)).unwrap();
frame(cx);
assert!(parts_told.get() >= 2, "the rail and the sidebar at least: {}", parts_told.get());
}
/// The plus of the rail opens the form; Save with an address adds the
/// server, selects it and closes the form.
#[gpui::test]
fn the_add_button_opens_the_form_and_save_adds_the_server(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
click(cx, "main-add");
let form =
shell.view.read_with(cx, |view, _| view.form().cloned()).expect("the form is open");
assert!(at(cx, "server-form").is_some());
cx.update(|window, cx| {
form.update(cx, |form, cx| form.set_address("ts.example.com", window, cx))
});
click(cx, "form-save");
shell.view.read_with(cx, |view, _| assert!(view.form().is_none(), "closed"));
let names: Vec<String> = shell
.app
.read_with(cx, |app, _| app.vm.bookmarks.iter().map(|b| b.name.clone()).collect());
assert_eq!(names, ["ts.example.com"]);
assert_eq!(cx.window_title().as_deref(), Some("Voelin - ts.example.com"));
assert!(at(cx, "server-form").is_none() && at(cx, "main-server").is_some());
}
/// What is typed after the form opens goes to its address field, and Enter
/// there saves: the form takes the focus from the button that opened it,
/// and the window's own focus does not take it back.
#[gpui::test]
fn typing_in_the_form_fills_the_address_and_enter_saves(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
click(cx, "main-add");
cx.simulate_input("ts.example.com");
frame(cx);
let form =
shell.view.read_with(cx, |view, _| view.form().cloned()).expect("the form is open");
assert_eq!(
form.read_with(cx, |form, cx| form.to_form(cx).address.to_string()),
"ts.example.com"
);
cx.simulate_keystrokes("enter");
frame(cx);
shell.view.read_with(cx, |view, _| assert!(view.form().is_none(), "saved and closed"));
assert_eq!(cx.window_title().as_deref(), Some("Voelin - ts.example.com"));
}
/// Saving a form with no address keeps the form open and says why.
#[gpui::test]
fn a_form_without_an_address_stays_open_and_says_why(cx: &mut TestAppContext) {
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), Switches::default());
click(cx, "main-add");
click(cx, "form-save");
shell.view.read_with(cx, |view, _| assert!(view.form().is_some()));
assert_eq!(
shell.app.read_with(cx, |app, _| app.vm.status.clone()),
"A server needs an address"
);
assert_eq!(
shell.view.read_with(cx, |view, cx| view.toast.read(cx).text().to_owned()),
"A server needs an address"
);
click(cx, "form-cancel");
shell.view.read_with(cx, |view, _| assert!(view.form().is_none()));
}
/// Removing asks twice, then the server goes from the rail and the store.
#[gpui::test]
fn removing_a_server_takes_two_clicks(cx: &mut TestAppContext) {
let (shell, cx) =
open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
click(cx, "main-edit");
shell.view.read_with(cx, |view, _| assert!(view.form().is_some()));
click(cx, "form-remove");
assert_eq!(ids(&shell, cx).len(), 1, "once is not enough");
click(cx, "form-remove");
assert_eq!(ids(&shell, cx), Vec::<i64>::new());
assert!(
shell.app.read_with(cx, |app, _| app.backend().store.bookmarks().unwrap().is_empty())
);
assert_eq!(cx.window_title().as_deref(), Some("Voelin"));
assert!(at(cx, "main-empty").is_some());
}
/// The status line is a toast that goes after a few seconds.
#[gpui::test]
fn the_status_line_is_a_toast_that_goes(cx: &mut TestAppContext) {
let (shell, cx) =
open(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default());
let toast = |shell: &Shell, cx: &mut VisualTestContext| {
shell.view.read_with(cx, |view, cx| view.toast.read(cx).text().to_owned())
};
assert_eq!(toast(&shell, cx), "");
click(cx, "main-connect");
assert_eq!(toast(&shell, cx), "Connecting to ts.example…");
cx.executor().advance_clock(crate::shell::TOAST_TIME + Duration::from_secs(1));
frame(cx);
assert_eq!(toast(&shell, cx), "");
}
/// The window's size and position are kept in `ui.window` when it changes,
/// and the next run opens where they say.
#[gpui::test]
fn the_windows_size_round_trips_through_the_settings(cx: &mut TestAppContext) {
let dir = TempDir::new("shell-window");
let backend = Backend::open(&dir.0, Box::new(MemorySecrets::default())).unwrap();
let (shell, vcx) = open(cx, backend, Switches::default());
let handle = vcx.update(|window, _| window.window_handle());
vcx.simulate_window_resize(handle, size(px(900.0), px(600.0)));
frame(vcx);
vcx.executor().advance_clock(Duration::from_secs(1));
frame(vcx);
let kept =
shell.app.read_with(vcx, |app, _| app.backend().prefs.get(&UI_WINDOW)).expect("kept");
assert_eq!((kept.width, kept.height), (900, 600));
assert!(!kept.maximized);
let closed = shell.app.update(vcx, |app, cx| app.shutdown(cx));
assert_eq!(closed, 0);
let remembered = shell.app.read_with(vcx, |app, _| app.remembered_window());
assert_eq!(remembered, Some(kept));
let opens = vcx.update(|_, cx| window_bounds(&Switches::default(), remembered, cx));
let WindowBounds::Windowed(bounds) = opens else { panic!("{opens:?}") };
assert_eq!(bounds.size, size(px(900.0), px(600.0)));
}
/// Where the window opens: a remembered position that no screen shows is
/// the middle of a screen; a maximized window stays maximized; a size the
/// development switch names wins; nothing remembered is the default size.
#[gpui::test]
fn the_window_opens_where_it_was_left_if_a_screen_shows_it(cx: &mut TestAppContext) {
let place = |x: i32, y: i32, maximized: bool| WindowState {
width: 1000,
height: 700,
x: Some(x),
y: Some(y),
maximized,
};
let opens = |cx: &mut TestAppContext, switches: &Switches, state: Option<WindowState>| {
cx.update(|cx| window_bounds(switches, state, cx))
};
let none = Switches::default();
let WindowBounds::Windowed(on_screen) = opens(cx, &none, Some(place(20, 30, false))) else {
panic!()
};
assert_eq!(
(on_screen.origin, on_screen.size),
(point(px(20.0), px(30.0)), size(px(1000.0), px(700.0)))
);
let WindowBounds::Windowed(lost) = opens(cx, &none, Some(place(90_000, 30, false))) else {
panic!()
};
assert_eq!(lost.size, size(px(1000.0), px(700.0)));
assert_ne!(
lost.origin,
point(px(90_000.0), px(30.0)),
"no screen shows it: the middle of one"
);
assert!(matches!(opens(cx, &none, Some(place(20, 30, true))), WindowBounds::Maximized(_)));
let default = opens(cx, &none, None);
assert!(
matches!(default, WindowBounds::Windowed(b) if b.size == size(px(1280.0), px(800.0)))
);
let sized = Switches { window: Some((1440.0, 960.0)), ..Switches::default() };
let forced = opens(cx, &sized, Some(place(20, 30, true)));
assert!(
matches!(forced, WindowBounds::Windowed(b) if b.size == size(px(1440.0), px(960.0)))
);
let tiny = WindowState { width: 320, height: 240, ..place(0, 0, false) };
let WindowBounds::Windowed(small) = opens(cx, &none, Some(tiny)) else { panic!() };
assert_eq!(small.size, size(px(640.0), px(480.0)), "never under the minimum");
}
/// The sample servers fill the rail and the cards, with the first one
/// connected.
#[gpui::test]
fn the_sample_servers_fill_the_shell(cx: &mut TestAppContext) {
let switches = Switches { demo_ui: true, ..Switches::default() };
let (shell, cx) = open(cx, Backend::in_memory().unwrap(), switches);
let view = rail(&shell, cx);
let names: Vec<&str> = view.servers.iter().map(|s| s.name.as_ref()).collect();
assert_eq!(names, ["Nightfall Guild", "Pixel Lounge", "Dev TS3"]);
let statuses: Vec<&str> = view.servers.iter().map(|s| s.status.as_ref()).collect();
assert_eq!(statuses, ["connected", "observing", "offline"]);
assert_eq!(view.current, Some(sample::DEMO));
assert!(at(cx, "sidebar-voice").is_some());
assert_eq!(cx.window_title().as_deref(), Some("Voelin - Nightfall Guild"));
}
/// `VOELIN_OPEN=swatch` shows the swatch in place of the shell.
#[gpui::test]
fn the_swatch_page_replaces_the_shell(cx: &mut TestAppContext) {
let switches = Switches { open: Page::Swatch, ..Switches::default() };
let (_shell, cx) = open(cx, Backend::in_memory().unwrap(), switches);
assert!(at(cx, "rail").is_none() && at(cx, "sidebar").is_none());
}
/// An action dispatched without a click does what the click does: the
/// keys and menus of later slices use the same handlers.
#[gpui::test]
fn an_action_dispatched_is_handled_as_a_click_is(cx: &mut TestAppContext) {
let backend = backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]);
let (shell, cx) = open(cx, backend, Switches::default());
let second = ids(&shell, cx)[1];
cx.dispatch_action(SelectServer { id: second });
frame(cx);
assert_eq!(shell.app.read_with(cx, |app, _| app.vm.current), Some(second));
cx.dispatch_action(AddServer);
frame(cx);
shell.view.read_with(cx, |view, _| assert!(view.form().is_some()));
cx.dispatch_action(CancelServerForm);
frame(cx);
shell.view.read_with(cx, |view, _| assert!(view.form().is_none()));
}
}
+99
View File
@@ -113,6 +113,64 @@ pub static UI_VOICE_COMPACT: Key<bool> = Key::new(
|| false,
);
/// Where the main window was and how large, as the last run left it: size and
/// position in logical pixels, and whether it was maximized (then the size is
/// the one it returns to). The position is left out where the platform does
/// not tell it (Wayland). A front end keeps it in [`UI_WINDOW`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WindowState {
/// Width in logical pixels.
pub width: u32,
/// Height in logical pixels.
pub height: u32,
/// Distance of the window's left edge from the screen's, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x: Option<i32>,
/// Distance of the window's top edge from the screen's, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub y: Option<i32>,
/// The window was maximized.
#[serde(default)]
pub maximized: bool,
}
impl WindowState {
/// The smallest size a window can have been left at.
pub const MIN_SIZE: (u32, u32) = (320, 240);
/// The largest size and the farthest position taken as real: a value
/// beyond it is a damaged setting, not a screen.
pub const LIMIT: u32 = 16_384;
/// Whether the values can be a window: a size within [`Self::MIN_SIZE`]
/// and [`Self::LIMIT`], a position within it either way, and a position
/// that is given whole or not at all.
pub fn is_sane(&self) -> bool {
let limit = i64::from(Self::LIMIT);
(Self::MIN_SIZE.0..=Self::LIMIT).contains(&self.width)
&& (Self::MIN_SIZE.1..=Self::LIMIT).contains(&self.height)
&& self.x.is_some() == self.y.is_some()
&& [self.x, self.y].into_iter().flatten().all(|at| i64::from(at).abs() <= limit)
}
}
fn valid_window(state: &Option<WindowState>) -> Result<(), String> {
match state {
Some(state) if !state.is_sane() => Err("a window of 320x240 to 16384x16384".into()),
_ => Ok(()),
}
}
/// `ui.window`: the main window's size and position as the last run left them
/// (none until a run has). The GPUI front end writes it; the Slint one does
/// not read it.
pub static UI_WINDOW: Key<Option<WindowState>> = Key::new(
"ui.window",
Kind::Json,
"The main window's size and position as the last run left them (none: not stored yet).",
|| None,
)
.validated(valid_window);
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
[
@@ -616,6 +674,47 @@ mod tests {
assert!(settings.set_json("ui.voice_compact", "small".into()).is_err());
}
/// The window's state is stored as the setting `ui.window`, comes back as it
/// went, and a damaged value is refused in words.
#[test]
fn window_state_roundtrip() {
let state =
WindowState { width: 1440, height: 960, x: Some(-20), y: Some(35), maximized: true };
let settings = voelin_core::settings::Settings::in_memory();
assert_eq!(settings.get(&UI_WINDOW), None, "none until a run left one");
settings.set(&UI_WINDOW, Some(state)).unwrap();
assert_eq!(settings.get(&UI_WINDOW), Some(state));
assert_eq!(
settings.get_json("ui.window"),
Some(
serde_json::json!({"width": 1440, "height": 960, "x": -20, "y": 35, "maximized": true})
)
);
// A platform that does not tell the position leaves it out.
let no_position = WindowState { x: None, y: None, maximized: false, ..state };
let json = serde_json::to_value(no_position).unwrap();
assert_eq!(json, serde_json::json!({"width": 1440, "height": 960, "maximized": false}));
assert_eq!(serde_json::from_value::<WindowState>(json).unwrap(), no_position);
let older: WindowState = serde_json::from_str(r#"{"width":800,"height":600}"#).unwrap();
assert_eq!(
older,
WindowState { width: 800, height: 600, x: None, y: None, maximized: false }
);
for damaged in [
WindowState { width: 0, ..state },
WindowState { height: 100_000, ..state },
WindowState { x: Some(1_000_000), ..state },
WindowState { y: None, ..state },
] {
assert!(!damaged.is_sane(), "{damaged:?}");
assert!(settings.set(&UI_WINDOW, Some(damaged)).is_err(), "{damaged:?}");
}
assert!(settings.set_json("ui.window", "big".into()).is_err());
assert_eq!(settings.get(&UI_WINDOW), Some(state), "a refused value changes nothing");
settings.set(&UI_WINDOW, None).unwrap();
assert_eq!(settings.get(&UI_WINDOW), None);
}
#[test]
fn ui_settings_defaults() {
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
+20 -5
View File
@@ -23,8 +23,9 @@ cases the foundation's review ran again on a quiet machine. The same day the
foundation of step 3 landed on `phase5/gpui-foundation` (items 1 to 4 and 6
of "What step 3's first slice must contain": Rust 1.95, ashpd on `async-io`,
the `voelin-gpui` crate with its root entity, the theme with Inter and Lucide,
the cost meter; item 5, the shell, is next): what exists, how to run it and
the slices that follow are in [docs/ui.md](../ui.md), "The GPUI front end".
the cost meter; item 5, the shell, followed the same day, below): what exists,
how to run it and the slices that follow are in [docs/ui.md](../ui.md), "The
GPUI front end".
The foundation was reviewed and gated the same day (a Sonnet review, then the
Opus gate: no blocker and no major, six minors), and the minors are closed in
the commits after it: the meter's `/proc` test waits for a CPU tick instead of
@@ -32,7 +33,17 @@ burning 60 ms, zbus runs on `async-io` alone in every binary (with a test for
the order of ashpd's callers), the lock figures and the Lucide 1.43 credit are
corrected, the slice list points at "Open choices for step 3", and the parity
test sees a second brush or string. The risks the review and the gate left to
the slices that meet them are in docs/ui.md, "For the next slices".
the slices that meet them are in docs/ui.md, "For the next slices". Item 5, the
desktop shell, is slice 1 of the step's list and landed on `phase5/gpui-shell`
(2026-10-27): the store at start (the client's database, the settings with the
UI's keys, the secrets, the default identity), the server rail, the sidebar,
the top bar and the main area as entities that draw when what they show
changed, the eleven callbacks of `bind/servers.rs` as actions through
`voelin-ui-vm`'s logic and the engine's commands, the window's size and
position kept in `ui.window`, the engine-event task in steps and a tick that
draws nothing. What it shows, what it costs idle and what it leaves to the
slices after it are in docs/ui.md, "The desktop shell"; the next slice is the
channel tree and the members.
| Spike | The plan's no-go | Seen (software rendering, see Setup) | Verdict |
|---|---|---|---|
@@ -637,8 +648,12 @@ set; the meter as `VOELIN_METER=1`. The crate is named `voelin-gpui` (binary
`voelin-gpui`), the choices below stayed as the report leaves them except
those named in docs/ui.md ("The GPUI front end"): the theme's second layer is
written as a `ThemeColor` mapping (a table there), and the client's Lucide set
is served under gpui-component's `icons/` paths. Item 5, the shell, is the
next task.
is served under gpui-component's `icons/` paths. Item 5, the shell, is done on
`phase5/gpui-shell` (the status paragraph above, docs/ui.md "The desktop
shell"): the screenshots are made the `docs/ui.md` way
(`scripts/gpui-shot.sh` under `headless.sh`), the form that adds a server is the
shell's own until the dialogs slice, and the open choices that remain (video,
emoji, links) are untouched by it.
### The risks of plan section 6, against what was seen
+265 -64
View File
@@ -50,8 +50,9 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit
bbcode.rs emoji.rs chat formatting; the Twemoji archive, text → runs of text and emoji
crates/voelin-gpui/ the GPUI front end, under construction (binary voelin-gpui; gpui-kit
pinned exactly); it uses voelin-ui-vm and the engine, not voelin-ui:
the root state, the theme, Inter and Lucide, the swatch page, the
cost meter ([The GPUI front end](#the-gpui-front-end))
the root state and the store, the desktop shell, the theme, Inter
and Lucide, the swatch page, the cost meter
([The GPUI front end](#the-gpui-front-end))
crates/voelin-ui/ the Slint front end
ui/
app.slint MainWindow: picks the shell, puts the page's screens in it, dialogs
@@ -967,58 +968,91 @@ conditions it settled, are in [design/gpui-spikes.md](design/gpui-spikes.md).
crates/voelin-gpui/
build.rs the client's 147 Lucide icons as a table of include_bytes!
src/
main.rs lib.rs `run()`: logging, the engine's runtime, the window; closing it
tells the engine to close the sessions, ends the app and, when
there were sessions, waits 500 ms for the engine to send the
main.rs lib.rs `run()`: logging, the engine's runtime, the store, the window (opened
where it was left); closing it keeps the window's place and the
settings, tells the engine to close the sessions, ends the app and,
when there were sessions, waits 500 ms for the engine to send the
closes before the runtime goes (as the Slint front end does)
engine.rs HostedEngine: Engine::start on a tokio runtime, its events
forwarded into a channel the window reads
app.rs AppState, the root Entity: the voelin-ui-vm state and Social,
the three loops (events, tick, Later), the one line of state
view.rs MainView: the status line, the shell's page (empty), the swatch
backend.rs the store at start: the client's database in the data directory,
the settings service on it with the UI's keys, the secrets, the
default identity; what the engine is handed (history, settings)
app.rs AppState, the root Entity: the voelin-ui-vm state and Social, the
backend, the three loops (events in batches, a quiet tick, Later)
and the callbacks of the Slint `bind/servers.rs` that the shell has
view.rs MainView, the window's root view: the shell or the swatch, the
handlers of the actions, the server form, the title, the window's place
shell/ the desktop shell (below): rail.rs, sidebar.rs, topbar.rs,
main_panel.rs, form.rs, toast.rs, actions.rs, widgets.rs
swatch.rs the swatch page (every token, widgets, icons)
theme/ VoelinTheme: tokens.rs, components.rs, slint_parity.rs (test)
fonts.rs Inter, from crates/voelin-ui/ui/assets/fonts
assets.rs icons/<name>.svg: the client's set before gpui-kit-assets'
assets.rs icons/<name>.svg: the client's set before gpui-kit-assets'; logo.svg
dev.rs the development switches
meter.rs the cost meter
```
- **The root state.** `AppState` (an `Entity`) holds `voelin_ui_vm::state::AppState<Vec<ChatLine>>`
and `Social`; `events::handle` is its one dispatch, as in the Slint front end,
and the `Update` it returns is carried out as far as this front end has the
parts: the engine's commands go out, the warnings are logged, the rest
(what to redraw, what to keep, the streams' capture and decoder) is for the
slices that have those parts. Three loops start with it and end when the
entity is released: **the engine's events** (a foreground task awaits the
tokio receiver, `this.update(cx, ...)`, `cx.notify()`; a tokio channel needs
no reactor, so GPUI's executor polls it); **the tick**, once a second, a loop
of `background_executor().timer`; and **`Later`**: GPUI's `AsyncApp` is not
`Send`, so a hotkey, camera or decoder thread holds a `Later` and calls
`later.run(|app, cx| ...)`, a queue a third foreground task drains with the
entity, as `later(|app| ...)` does in Slint. The window shows one line:
the version, the voice connections up, the engine events handled, the seconds
up; each part moves by one of the loops. The window's start shows no store:
the shell slice opens it with the settings and the bookmarks.
and `Social`, and the `Backend` (the store, the settings, the secrets);
`events::handle` is its one dispatch, as in the Slint front end, and the
`Update` it returns is carried out as far as this front end has the parts:
the engine's commands go out, the status line is set (the toast shows it),
what is to be kept goes to the store and the settings (a bookmark, the UI's
settings, the audio settings, the clients' volumes), a changed `ui.theme` or
`ui.font_scale` reaches the theme, the warnings are logged; the rest (what to
redraw, the notices, the pictures to decode, the streams' capture and
decoder) is for the slices that have those parts. Three loops start with it
and end when the entity is released: **the engine's events** (a foreground
task awaits the tokio receiver, takes what is queued, up to 64 events, in one
update with one `cx.notify()`, and yields to GPUI's executor before the next
step: a server's first sync neither starves the window nor draws it once per
event; a tokio channel needs no reactor, so GPUI's executor polls it); **the
tick**, once a second, a loop of `background_executor().timer`, which keeps
what is due (the window's place) and **notifies nobody**: nothing the shell
shows moves with the clock, so a window nobody touches is not drawn; and
**`Later`**: GPUI's `AsyncApp` is not `Send`, so a hotkey, camera or decoder
thread (or the gateway lookup on the engine's runtime) holds a `Later` and
calls `later.run(|app, cx| ...)`, a queue a third foreground task drains with
the entity, as `later(|app| ...)` does in Slint. The root notifies on every
batch and every move of the user's; the views compare what they would show
with what they showed and tell the window only when it differs
([The desktop shell](#the-desktop-shell)).
- **Tests**: the unit tests need no display (GPUI's test platform, `#[gpui::test]`, with
`gpui-pre`'s `test-support` as a dev-dependency beside gpui-kit's own pin: its
`test-support` feature would make Cargo lock the unused `gpui-fast` backend and
pin taffy 0.15.0): an injected engine event, a real engine's event, the tick
and a job from another thread reach the entity; the theme reaches
gpui-component, follows the window's appearance and the text size; the
Slint file's tokens equal the Rust ones (below); the icons and fonts load.
`tests/launch_failure.rs` starts the built binary where its window cannot
open (below): one of its two cases needs the test display of
`VOELIN_X11_TEST_DISPLAY` and is skipped without it, as the X11 tests of
the other crates are. `cargo test -p voelin-gpui`.
pin taffy 0.15.0): the root state (a burst of events is taken in steps, the tick
is quiet, a job from another thread reaches the entity, the store's servers are
the rail's, a server is saved, edited, removed and selected, a connect and the
other commands reach the engine's wire, the sample servers send nothing, the
window's place is kept and found again, the theme follows the settings and a
switch), the shell on a drawn window that the tests click (a server added is in
the rail, a click selects it and titles the window, an engine event updates the
rail and the cards, the form adds and removes, the toast goes, an idle window is
not told), a connect through a real engine that has no connector (it answers
that none serves the address, which reaches the status line), the store on a
directory of its own, the theme (it reaches gpui-component, follows the window's
appearance and the text size), the Slint file's tokens equal the Rust ones
(below), the icons and fonts load. `tests/launch_failure.rs` starts the built
binary where its window cannot open (below): one of its two cases needs the test
display of `VOELIN_X11_TEST_DISPLAY` and is skipped without it, as the X11 tests
of the other crates are. `cargo test -p voelin-gpui`.
### Running it
```sh
cargo run -p voelin-gpui --release # the window and its one line of state
cargo run -p voelin-gpui --release # the desktop shell, on the client's store
VOELIN_DEMO_UI=1 cargo run -p voelin-gpui --release # the sample servers, nothing kept
VOELIN_OPEN=swatch VOELIN_DEV_THEME=light cargo run -p voelin-gpui --release
```
The shell opens the client's database in the data directory (the platform's,
`~/.local/share/voelin` on Linux; `VOELIN_DATA_DIR` moves it) that the Slint
front end uses too, so the servers saved in one are the other's; **a run that
is not the user's own (a test, a screenshot, a measurement) sets
`VOELIN_DATA_DIR`** and, for the logs, the XDG directories (the headless
scripts below do).
GPUI draws through wgpu: it needs a Vulkan driver (Mesa's RADV, ANV or NVK,
NVIDIA's) or OpenGL at run time; in a virtual machine, a remote desktop or
CI, Mesa's lavapipe (`mesa-vulkan-drivers`) draws in software. The binary
@@ -1055,21 +1089,26 @@ anyway).
| Switch | Does |
|---|---|
| `VOELIN_OPEN=swatch` | the swatch page in place of the shell; the Slint front end's other pages are not here yet and are named in a warning |
| `VOELIN_DEV_THEME=dark\|light\|system` | the theme mode (the settings' `ui.theme` will give it) |
| `VOELIN_FONT_SCALE=1.25` | the text size factor (`ui.font_scale`) |
| `VOELIN_WINDOW_SIZE=1440x960` | the window's size |
| `VOELIN_METER=1` | the cost meter: once a second a log line (`voelin_gpui::meter`) with the process's CPU, the CPU of each group of threads (`llvmpipe` is the software renderer, work a GPU takes over; `voelin-gpui` is GPUI's thread), the resident memory, the app's own counters per second (engine events, ticks, renders, `Later` jobs) and the voice connections up |
| `VOELIN_DEMO_UI=1` | the Slint front end's sample servers (`voelin_ui_vm::dev::logic`) in place of the stored ones, through the app's own events (the first is connected, the second observed); nothing is sent to the engine or kept in the store, the window's place included, and the servers cannot be changed |
| `VOELIN_DEV_THEME=dark\|light\|system` | the theme mode, in place of the settings' `ui.theme` |
| `VOELIN_FONT_SCALE=1.25` | the text size factor, in place of the settings' `ui.font_scale` |
| `VOELIN_WINDOW_SIZE=1440x960` | the window's size, in place of the remembered one (`ui.window`), which it then leaves alone: the window's place is not kept while it is set |
| `VOELIN_METER=1` | the cost meter: once a second a log line (`voelin_gpui::meter`) with the process's CPU, the CPU of each group of threads (`llvmpipe` is the software renderer, work a GPU takes over; `voelin-gpui` is GPUI's thread), the resident memory, the app's own counters per second (engine events, ticks, renders: one render is one pass of the window's root view, a frame; `Later` jobs) and the voice connections up |
Screenshots are made headless, the way `scripts/shots.sh` makes the Slint
ones: `scripts/gpui-shot.sh out.png swatch 1440x960` runs the binary under
`xvfb-run`, takes the window with `xwd`, closes it with Alt+F4 when a window
manager is there (else TERM) and says how the app ended. On NixOS, with the
spikes' environment (a headless X display with openbox, lavapipe as the only
Vulkan driver, the XDG directories and the D-Bus bus private):
`xvfb-run`, takes the window with `xwd` (found by its title, "Voelin" and
"Voelin - <server>"), closes it with Alt+F4 when a window manager is there
(else TERM) and says how the app ended; `VOELIN_DEMO_UI=1` in its environment
puts a server on screen. On NixOS, with the spikes' environment (a headless X
display with openbox, lavapipe as the only Vulkan driver, the XDG directories
and the D-Bus bus private):
```sh
GPUI_SHOT_HEADLESS=1 DELAY=4 VOELIN_DEV_THEME=dark spikes/gpui/shell.sh \
spikes/gpui/headless.sh -- scripts/gpui-shot.sh docs/ui/gpui-swatch-dark.png swatch 1440x960
GPUI_SHOT_HEADLESS=1 DELAY=4 VOELIN_DEMO_UI=1 VOELIN_DEV_THEME=dark spikes/gpui/shell.sh \
spikes/gpui/headless.sh -- scripts/gpui-shot.sh docs/ui/gpui-shell-server-dark.png "" 1440x960
```
Wayland, the desktop's session bus and its portals are out of the environment,
@@ -1081,6 +1120,149 @@ colours would change the tokens' values).
![The swatch page, dark](ui/gpui-swatch-dark.png)
![The swatch page, light](ui/gpui-swatch-light.png)
### The desktop shell
Slice 1 of plan section 6 step 3: the frame of `ui/shells/desktop.slint` and
the server callbacks of the Slint `bind/servers.rs` (about 13 properties and 11
callbacks), on the client's store.
| Empty (no server) | A server on screen |
|---|---|
| ![the shell, no server, dark](ui/gpui-shell-empty-dark.png) | ![the shell with a server, dark](ui/gpui-shell-server-dark.png) |
| ![the shell, no server, light](ui/gpui-shell-empty-light.png) | ![the shell with a server, light](ui/gpui-shell-server-light.png) |
The pictures are the shell at 1440 by 960 under `scripts/gpui-shot.sh`; the
server on screen is the first of the sample servers (`VOELIN_DEMO_UI=1`),
connected, with its voice card and the user's card. `gpui-shell-form-dark.png`
is the server form.
![the server form, dark](ui/gpui-shell-form-dark.png)
What is on screen, each part an entity of `crates/voelin-gpui/src/shell/` that
observes the root state, makes its view of it (`voelin_ui_vm::servers::logic`:
`rail`, `toolbar`) and tells the window only when the view differs from the one
it showed: an engine event about a talker, a setting that is not the theme's or
a tick draws nothing (the `what_changes_nothing_shown_draws_nothing` test counts
the parts told).
- **The rail** (`rail.rs`): the app's mark, then the saved servers as 46 pixel
rounded squares (the server's icon from the engine's cache, else its initials
on its tint), a dot for the state (green: voice connected, blue: observed
invisibly, amber: connecting), the unread count, a red dot while someone
streams, the pill and the ring of the one on screen; a click selects, a second
click edits; the plus adds a server and the gear is the settings button.
- **The top bar** (`topbar.rs`): the page's title (the server on screen, else
"Voelin"), the search box and the settings button, which log that their
slices are to come (`OpenSearch`, `OpenSettings`).
- **The sidebar** (`sidebar.rs`): the server on screen (name, "9 online · 9
channels" once its presence is known, else its address), the place of the
channel tree (slice 2), the voice card while voice is connecting or connected
(the channel we are in, copy an invite, disconnect, and Hold to talk when the
transmit mode is push-to-talk) and the user's card (nickname, Online,
Observing or Offline, the microphone and sound buttons, which work with
voice).
- **The main area** (`main_panel.rs`): "No server selected" with an Add a server
button, or the server on screen (name, address, its state) with Connect or
Disconnect and Edit, until the pages of the next slices come.
- **The server form** (`form.rs`), in the place of the main area until the
dialogs slice: address (all a server needs), name (empty: the server's own),
nickname (the default identity's, else the system user's) and the server's
password (kept in the secrets, not in the database); Save, Save and connect,
Cancel, and for a saved server Remove, which asks twice. Enter saves.
- **The toast** (`toast.rs`): the status line ("Connecting to ts.example…", "A
server needs an address") for five seconds.
The window's title is "Voelin" and "Voelin - <server>" with one on screen. Its
minimum size is 640 by 480.
The eleven callbacks of `bind/servers.rs` that the shell has are GPUI actions
(`shell/actions.rs`); a click dispatches one with `Window::dispatch_action`,
`MainView` handles it, and the handler asks the root state for what the Slint
callback did, through `voelin-ui-vm`'s `servers::logic` and the engine's
commands:
| Slint callback | Action | What it does |
|---|---|---|
| `select_server` | `SelectServer { id }` | `logic::select_server`, then observes the server invisibly: through its gateway, else its own query login, else the gateway is looked up on the engine's runtime first (`logic::observe_plan`, `discover_wanted`, `gateway_found`) |
| `connect_voice` | `ConnectVoice` | `Command::ConnectVoice` with the bookmark's address, nickname and default channel, its identity, its password from the secrets |
| `disconnect_voice` | `DisconnectVoice` | `Command::DisconnectVoice` |
| `set_input_muted`, `set_output_muted` | `SetInputMuted { muted }`, `SetOutputMuted { muted }` | the same commands |
| `push_to_talk` | `PushToTalk { on }` | `Command::SetTransmitting`: on at the button's press, off at its release, on or off the button |
| `edit_bookmark` | `EditServer { id }` | opens the form with `servers::form` |
| `save_bookmark` | `SaveServer` | `logic::bookmark_from_form`, the store, the secrets; shows the server |
| `save_and_connect` | `SaveAndConnect` | saves, then connects into the form's channel or the default one (`servers::connect_to`) |
| `delete_bookmark` | `DeleteServer { id }` | `CloseSession`, the secrets and the store, `logic::forget_server` |
| `invite` | `Invite` | `logic::invite_link`, the link on the clipboard, the status line's note |
The others of that file are the next slices': `search_members`,
`show_voice_view`, `join_channel`, `join_with_password`, `toggle_collapse`,
`open_client` and `client_audio_changed` (the channel tree, the members, the
voice page), and `copied`, which the Slint toast of a copy needs and `Invite`
does for itself. `AddServer`, `CancelServerForm`, `OpenSearch` and
`OpenSettings` are the shell's own.
**The store at start** (`backend.rs`) is `run()` of the Slint front end through
`voelin-ui-vm`: the client's database at `<data dir>/client.db` (bookmarks,
identities, chat read marks), the settings service on it with the UI's keys
(and `config.toml` and the `VOELIN_SETTING_*` variables below the stored
values), the secrets (the OS keyring, memory where it refuses, memory alone
with the sample servers), the default identity (made and kept when there is
none), and the engine handed the chat history and the settings. The theme mode
and the text size come from the settings (`ui.theme`, `ui.font_scale`), a
development switch winning, and follow them when the engine reports a change.
Left out against the Slint front end, for later slices: importing the
identities of the official TeamSpeak clients at start (it reads the user's own
files: it comes with the identities page), the crash reports, `--set` on the
command line, `stream_peer` of a connect (what this front end can decode is for
the stream viewer's slice) and the stream effects of an update.
**The window's place** is the setting `ui.window` (`voelin_ui_vm::settings::
WindowState`: size, position where the platform tells one, maximized; none until
a run has left one; a value out of any screen's reach is refused in words). The
window reports where it is when it moves or changes size, the root state keeps
it at the next tick and at close, and the next run opens there: the size always,
the position when a screen still shows its corner and the window manager lets a
window choose (GPUI asks X11 for the place, and openbox, like most window
managers, places new windows itself; Wayland tells no position at all, so none
is kept there), maximized if it was. A development switch that sets the size or
the sample data leaves it alone.
**What the shell costs idle** (`VOELIN_METER=1`, release build of the shell
commit `6b4341a`, the later ones change nothing that runs while idle; 1440 by
960 on Mesa 26.2.5's lavapipe through Vulkan on Xvfb `:97`
with openbox, the machine's other jobs at a load average of 10 to 27; the
first 15 seconds of 75 left out, 60 samples of one second; CPU in percent of
one core, whose resolution is the 1 % of a clock tick):
| | CPU, mean (max) | Resident memory | Renders per second | Ticks per second |
|---|---|---|---|---|
| The empty shell (no server) | 0.3 % (2 %) | 191.7 MiB | 0.0 | 1.0 |
| The sample servers, the first connected (`VOELIN_DEMO_UI=1`) | 0.5 % (2 %) | 192.7 MiB | 0.0 | 1.0 |
A window nobody touches is not drawn (a render is one pass of `MainView`, so
one frame of the window): the foundation's tick told the root once a second,
which drew the window once a second by construction (not measured on that
commit). The software renderer's threads (`llvmpipe`) show nowhere in the
lines: they had no work. What the shell costs while it is used (the events of a
connect, a click, the form's typing) is not measured here: a frame takes a
frame's work on the GPU and, on this machine's software device, the CPU
(docs/design/gpui-spikes.md has the per-frame figures of the spikes).
**Seen against a server** (the TeamSpeak 3 development server of
`dev/docker-compose.yml`, 3.13.8, release build, the same headless display and
no sound card or sound server: `ALSA_CONFIG_PATH` empty, the XDG runtime
directory private): the server added through the form with Save and connect
shows its client (`clientlist -voice` over ServerQuery), the window's title and
the rail take the server's own name ("TeamSpeak ]I[ Server"), the voice card
says "Voice Connected"; the user card's buttons mute the microphone and the
sound, which the server sees (`client_input_muted=1`, `client_output_muted=1`);
the voice card's disconnect leaves the server (no client), the main area's
Connect joins again, and closing the window with Alt+F4 while connected ends
the app with exit status 0 and leaves **no ghost client** on the server after
two seconds. (The close found a panic in the foundation's wait for the engine's
closes, which no run had reached; it is fixed and a test calls the wait from
the GPUI thread.)
### The theme
Two layers (docs/design/gpui-spikes.md, "The theme against Theme tokens"):
@@ -1139,10 +1321,15 @@ draws the icons the client draws and the rest of the catalogue still answers.
The slices of plan section 6 step 3, in order, with what each takes from the
Slint `Bridge` (`ui/bridge.slint:801-1206`; properties / callbacks):
1. the **desktop shell**: the server rail, the sidebar, the top bar, the empty
main area, window state (about 13 / 11, `bind/servers.rs`), the store and the
settings opened as in Slint's `run()`;
2. the channel tree and the members (about 13 / 6);
1. the **desktop shell** (done, [above](#the-desktop-shell)): the server rail,
the sidebar, the top bar, the empty main area, window state (about 13 / 11,
`bind/servers.rs`), the store and the settings opened as in Slint's `run()`;
2. **next: the channel tree and the members** (about 13 / 6): the sidebar's
placeholder becomes `logic::tree_view`'s rows (`TreeItem`, `MemberItem`), the
callbacks `join_channel`, `join_with_password`, `toggle_collapse`,
`search_members`, `show_voice_view`, `open_client` and `client_audio_changed`
become actions beside the shell's, and the password prompt the transitions ask
for (`Update::password`, which the root state only logs today) gets its dialog;
3. the voice page and the call bar (6 / 6);
4. chat, the composer and emoji (about 19 / 18, and the `Emoji` global 3 / 3):
first the two open choices of the report that it touches
@@ -1171,17 +1358,21 @@ entries); the in-window keys as GPUI key bindings and the global ones through
What the foundation's review and the Opus gate (2026-10-27) found and left to
the slices that meet it; none of it is a defect of what exists today.
- **The engine-event task drains its channel without yielding** (`app.rs`,
`while let Some(event) = events.recv().await`): a burst of events (a server's
first sync) keeps the receiver ready, so the loop handles them back to back
without returning to GPUI's executor (a tokio receiver is cooperative only
inside a tokio runtime), and the window waits for the whole burst. The shell
slice takes what is queued in one go (`try_recv` after the first event, one
`update`, one `cx.notify()`) or yields between events.
- **The tick notifies the root every second** (`AppState::tick`), which draws
the window once a second whether or not anything changed. Notify only on a
change once the shell shows more than the uptime (the line of state moves
with it today, and it is how the loop is seen to run).
- **Settled by the shell slice: the engine-event task and the tick.** The task
takes what is queued (64 events at most) in one `update` with one
`cx.notify()` and yields between steps, and the tick notifies nobody (the
shell shows nothing that moves with the clock: the line of state with the
seconds is gone, and the meter's `ticks` counter is how the loop is seen to
run). A slice that shows something that moves with time (a clock, a speaking
indicator that fades) makes its own view notify, not the tick.
- **A view that handles actions sits under the window's focus.** GPUI
dispatches an action from the focused element up, and with nothing focused
from the window's root node, which is the root view's wrapper, not its
element. `MainView` keeps a focus handle on its root element, focuses it at
start and takes the focus back when the element that had it is gone
(`on_focus_lost`: the form closed, a button replaced by another). A later
window (the Stream Studio's) does the same, and a new page's buttons dispatch
actions the root handles rather than listeners of their own.
- **The hotkey portal calls `tokio::spawn`** (`voelin-platform`,
`hotkey/portal.rs`, `PortalBackend::new`): it panics where no tokio runtime
is current, and a GPUI foreground task has none. The GPUI front end starts
@@ -1204,7 +1395,19 @@ the slices that meet it; none of it is a defect of what exists today.
- **System mode's first frame is Light** until the colour-scheme portal answers
(`cx.window_appearance()` before the window exists; `set_system_appearance`
follows the answer): a dark desktop sees a light frame at start. The shell
slice, which reads the settings, can start from the last resolved mode.
reads `ui.theme`, whose default is dark (as in Slint), so only a user who chose
`system` sees it; starting from the last resolved mode needs a place to keep
it, which nothing has yet.
- **The window's position is the window manager's to give back.** GPUI asks X11
for the place saved in `ui.window` and sets no position hint, so openbox (and
most window managers) places the window itself; the size is restored, the
position is not, and on Wayland there is none to tell. A window manager that
honours the request, or a hint GPUI does not set, would make the saved
position count; the setting keeps it either way.
- **The identity import and the crash reports are not started**
(`backend.rs` says so): the import reads the official TeamSpeak clients' files
and belongs with the identities page, the crash hook with the settings pages.
A connection uses the store's default identity (made at the first start).
- **The gate's deviations from the mapping table** of the report ("The theme
against Theme tokens"): `bg-rail` is not mapped (the report has it with
`surface` on `sidebar.background`; the sidebar takes `surface` and the shell
@@ -1213,13 +1416,11 @@ the slices that meet it; none of it is a defect of what exists today.
`overlay` gets `scrim`), and gpui-base's non-colour tokens (radii, spacing,
type, shadows, motion) are not written: gpui-base 0.8.1 has no storage to
write them to, so those live in `VoelinTheme::metrics` only.
- **The close grace is not seen end to end** until a slice opens sessions:
`run()` waits `CLOSE_GRACE` (500 ms) for the engine to send the closes only
when the window's close found sessions to close, and the binary opens none
yet (the unit test counts the closes `shutdown` sends, and the engine ignores
a close for a session it never opened). The first slice that opens a session
checks against a server that no ghost client stays behind after the window is
closed.
- **The close grace is seen end to end now** (the shell opens sessions): a
connected window closed with Alt+F4 leaves no ghost client on the TeamSpeak 3
development server and exits with status 0 ([The desktop
shell](#the-desktop-shell)). `run()` waits `CLOSE_GRACE` (500 ms) for the engine
to send the closes only when the window's close found sessions to close.
## Limits
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 156 KiB

+4 -2
View File
@@ -25,7 +25,8 @@
#
# VOELIN_BIN: the binary (default target/release/voelin-gpui, else
# target/debug); DELAY: seconds the window is shown before the picture
# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE and the other switches of
# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE, VOELIN_DEMO_UI (the sample
# servers: a picture of the shell with one on screen) and the other switches of
# `src/dev.rs` are passed on as set.
set -eu
out=${1:?usage: gpui-shot.sh <out.png> [<VOELIN_OPEN> [<width>x<height>]]}
@@ -70,7 +71,8 @@ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u XDG_SESSION_TYPE -u DBUS_SESSION_BUS
"$bin" >"$work/app.log" 2>&1 &
pid=$!
i=0
until win=$(xdotool search --name '^Voelin$' 2>/dev/null | head -1) && [ -n "$win" ]; do
# The title is the app's name, and ` - <server>` once a server is on screen.
until win=$(xdotool search --name '^Voelin( - |$)' 2>/dev/null | head -1) && [ -n "$win" ]; do
i=$((i + 1))
kill -0 "$pid" 2>/dev/null || { echo "gpui-shot.sh: the app ended before its window:" >&2; tail -20 "$work/app.log" >&2; exit 1; }
[ $i -lt 300 ] || { echo "gpui-shot.sh: no window after 30 s:" >&2; tail -20 "$work/app.log" >&2; exit 1; }