voelin-gpui: the store at start, the shell's actions on the root state, quiet loops

The window opens the client's store as the Slint front end's run() does
(backend.rs): the database in the platform's data directory (VOELIN_DATA_DIR
moves it), the settings service on it with the UI's keys, the secrets (the OS
keyring, memory when it refuses), the default identity (made and kept when the
store has none), the chat history and the settings handed to the engine. The
state starts from the store's bookmarks, the settings' theme and text size
(a development switch still wins), and the sample servers of VOELIN_DEMO_UI
through the app's own events with nothing sent to the engine or kept.

AppState gains the callbacks of bind/servers.rs that the shell has: select a
server (and observe it through its gateway or query login, the gateway looked
up on the engine's runtime and handed back through Later), connect and
disconnect voice, mute the microphone and the sound, hold to talk, copy an
invite, and add, edit, save-and-connect and remove a bookmark, all through
voelin-ui-vm's logic; perform() carries out an Update as far as this front end
has the parts (commands, status, what to keep, the theme settings). It keeps
the window's place in ui.window at the tick and at close, and opens the window
where it was left if a screen still shows its corner.

The engine-event task takes what is queued (BATCH, 64) in one update with one
notification and yields to GPUI's executor between steps; the tick counts and
notifies nobody, since nothing the shell shows moves with the clock.

Tests: one per behaviour on GPUI's test platform (the store's servers, select,
save, edit, remove, connect, the other commands, observe, the sample servers,
the theme settings, the window's place, the burst and the quiet tick), and a
connect through a real engine with no connector, which answers that none
serves the address.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-27 16:34:14 +03:00
1 parent bc390f433c
commit e66238847d
7 files changed
+1723 -147

No files matched your search

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
+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 {
+81 -26
View File
@@ -7,6 +7,7 @@
pub mod app;
pub mod assets;
pub mod backend;
pub mod dev;
pub mod engine;
pub mod fonts;
@@ -20,17 +21,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 +69,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 +122,7 @@ fn open_main_window(
cx: &mut App,
switches: &Switches,
engine: HostedEngine,
backend: Backend,
counters: Counters,
closed_sessions: Rc<Cell<usize>>,
) -> Result<()> {
@@ -94,10 +136,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 +159,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
}
@@ -139,6 +190,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 +205,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