Files
VoelinClient/crates/voelin-gpui/src/lib.rs
T
faumarayandClaude Sonnet 5.5 d0bcf1f5b2 voelin-gpui: pictures keyed by the file and its stamp, Update.reloaded honoured
GPUI's img(path) keeps what it decoded under the path alone, so a
picture the engine writes again into the same cache file (an avatar or
a server icon that changed) stayed stale on screen. Pictures are now
drawn through a loader keyed by PictureKey, the path and the Stamp the
reference carries (voelin-ui-vm's ImageSource::File): a reference made
after the file changed is another picture, decoded anew, and the lists
that show it compare unequal and draw the row again. perform hands the
paths of Update.reloaded to pictures::forget_stale, which drops the
copies decoded under a stamp the file no longer has and the textures the
atlas made of them. The Avatar widget uses it.

Tests: the key follows the file; a picture rewritten into the same file
is decoded again and the old copy is dropped from the asset cache.

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

269 lines
10 KiB
Rust

//! The GPUI front end of the desktop app, under construction (plan section 6
//! of the migration from Slint; docs/ui.md, "The GPUI front end"). The Slint
//! front end (`voelin-ui`, the `voelin` binary) stays the app until this one
//! reaches parity; both run on the same engine.
#![warn(missing_docs)]
pub mod app;
pub mod assets;
pub mod backend;
pub mod dev;
pub mod engine;
pub mod fonts;
pub mod meter;
pub mod pictures;
pub mod shell;
pub mod signals;
pub mod swatch;
pub mod theme;
pub mod view;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;
use anyhow::{Context as _, Result};
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, 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::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.
const CLOSE_GRACE: Duration = Duration::from_millis(500);
/// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every
/// crate, this front end's information, and what GPUI says about the display
/// and the GPU adapter it picked (which device a run used). Two warnings are
/// left out because they are harmless: zbus's, as in the Slint front end (it
/// warns when a desktop portal's request object is gone before it reads its
/// properties), and GPUI's "failed to load font .SystemUIFont" (gpui-component
/// asks for the platform's UI font, which Linux has no name for, before the
/// theme names Inter; the text system falls back).
const LOG_FILTER: &str =
"warn,zbus=error,gpui::text_system=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info";
/// Log to the terminal: `VOELIN_LOG`, else `RUST_LOG`, else [`LOG_FILTER`].
/// GPUI logs through the `log` crate; the subscriber carries those records.
pub fn init_logging() {
let filter = EnvFilter::try_from_env("VOELIN_LOG")
.or_else(|_| EnvFilter::try_from_default_env())
.unwrap_or_else(|_| EnvFilter::new(LOG_FILTER));
let _ = tracing_subscriber::registry()
.with(fmt::layer().with_writer(std::io::stderr).with_filter(filter))
.try_init();
}
/// 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. A window left maximized is asked for as maximized here, and
/// again by [`MainView`] once it is shown (an X11 window manager loses this
/// request: it manages a window only from its map).
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(title.into()), ..Default::default() }),
app_id: Some(voelin_platform::APP_ID.to_owned()),
window_min_size: Some(size(px(MIN_SIZE.0), px(MIN_SIZE.1))),
window_bounds: Some(window_bounds(switches, remembered, cx)),
..Default::default()
}
}
/// Open the main window on the root state; closing it leaves the servers and
/// ends the app. `closed_sessions` is set to how many sessions the close told
/// the engine to close, which [`run`] needs after GPUI's loop has ended.
fn open_main_window(
cx: &mut App,
switches: &Switches,
engine: HostedEngine,
backend: Backend,
counters: Counters,
closed_sessions: Rc<Cell<usize>>,
) -> Result<()> {
// Without a display server GPUI falls back to a headless platform, which
// opens windows that draw nothing and runs until it is stopped.
if cx.compositor_name() == "headless" {
return Err(anyhow::anyhow!(
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server"
))
.context("cannot open the main window");
}
let HostedEngine { engine, events, .. } = engine;
let app = cx.new({
let setup = Setup {
engine: Some(engine),
events,
counters: counters.clone(),
backend,
switches: switches.clone(),
};
move |cx| AppState::new(setup, 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();
move |window, cx| {
// The window's own appearance, which may differ from the system's before
// the window exists.
VoelinTheme::set_system_appearance(cx, window.appearance());
window.on_window_should_close(cx, {
let app = app.clone();
move |_, cx| {
closed_sessions.set(app.update(cx, |app, cx| app.shutdown(cx)));
cx.quit();
true
}
});
cx.new(|cx| MainView::new(app, page, counters, window, cx))
}
})
.context("cannot open the 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();
let switches = Switches::from_env();
tracing::info!(
version = env!("CARGO_PKG_VERSION"),
os = std::env::consts::OS,
"Voelin (GPUI) starting"
);
let counters = Counters::default();
if switches.meter {
meter::start(counters.clone());
}
// The engine runs on tokio threads of its own; the window is GPUI's.
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.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({
let failure = failure.clone();
let closed_sessions = closed_sessions.clone();
move |cx| {
gpui_kit::init(cx);
fonts::load(cx);
// 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
// asked for earlier (calloop clears its stop signal when it
// starts), so the process would stay with no window and no
// message. A task runs inside the loop.
cx.spawn(async move |cx| cx.update(|cx| cx.quit())).detach();
}
}
});
// The close told the engine to close the sessions; give its tasks time to
// send that before the runtime drops them (`shutdown_timeout` waits for
// blocking tasks only), as the Slint front end does, or ghost clients stay
// 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 {
give_the_engine_time(&runtime, CLOSE_GRACE);
}
runtime.shutdown_timeout(Duration::from_secs(2));
match failure.take() {
Some(e) => Err(e),
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));
}
}