diff --git a/CHANGELOG.md b/CHANGELOG.md index 05cb225..85065d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,11 +9,13 @@ 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 that opens and closes (`cargo run -p voelin-gpui - --release`). The Slint app (`voelin`) is unchanged and stays the app; both run - on the same 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. + 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 + (`cargo run -p voelin-gpui --release`). The Slint app (`voelin`) is unchanged + and 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. - Log files: each run logs to `/voelin/logs/voelin.log`, the previous four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced opens the folder. diff --git a/Cargo.lock b/Cargo.lock index 874d62b..8622a05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -751,6 +751,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -1818,6 +1824,15 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "convert_case" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -2129,6 +2144,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -2488,7 +2512,7 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ - "convert_case", + "convert_case 0.10.0", "proc-macro2", "quote", "rustc_version", @@ -3461,6 +3485,19 @@ dependencies = [ "futures-sink", ] +[[package]] +name = "futures-concurrency" +version = "7.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6" +dependencies = [ + "fixedbitset", + "futures-core", + "futures-lite", + "pin-project", + "smallvec", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -3993,6 +4030,7 @@ dependencies = [ "embed-resource", "etagere", "futures", + "futures-concurrency", "getrandom 0.3.4", "gpui-pre-collections", "gpui-pre-http-client", @@ -4015,8 +4053,10 @@ dependencies = [ "parking", "parking_lot", "pin-project", - "pollster", + "pollster 0.4.0", + "postage", "profiling", + "proptest", "rand 0.9.5", "raw-window-handle", "regex", @@ -4036,6 +4076,7 @@ dependencies = [ "usvg 0.46.0", "uuid", "waker-fn", + "web-time", "windows 0.62.2", "zed-scap", ] @@ -5492,7 +5533,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" dependencies = [ "byteorder-lite", - "quick-error", + "quick-error 2.0.1", ] [[package]] @@ -8221,6 +8262,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "pollster" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" + [[package]] name = "pollster" version = "0.4.0" @@ -8277,6 +8324,21 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "postage" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" +dependencies = [ + "atomic", + "crossbeam-queue", + "parking_lot", + "pin-project", + "pollster 0.2.5", + "static_assertions", + "thiserror 1.0.69", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -8418,6 +8480,39 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set 0.11.1", + "bit-vec 0.10.1", + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "proptest-macro", + "rand 0.10.3", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "proptest-macro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e99782ea31698c2206c6887c1220d2f594b291c26cb9ec5b6d7cf175320bc212" +dependencies = [ + "convert_case 0.11.0", + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "prost" version = "0.14.4" @@ -8490,6 +8585,12 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick-error" version = "2.0.1" @@ -8711,6 +8812,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -8767,7 +8877,7 @@ dependencies = [ "avif-serialize", "imgref", "loop9", - "quick-error", + "quick-error 2.0.1", "rav1e", "rayon", "rgb", @@ -9596,6 +9706,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + [[package]] name = "rustybuzz" version = "0.20.1" @@ -11162,7 +11284,7 @@ dependencies = [ "fax", "flate2", "half", - "quick-error", + "quick-error 2.0.1", "weezl", "zune-jpeg 0.5.15", ] @@ -12048,6 +12170,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicase" version = "2.9.0" @@ -12455,7 +12583,14 @@ version = "0.0.1-alpha" dependencies = [ "anyhow", "gpui-kit", + "gpui-pre", + "tokio", + "tracing", + "tracing-subscriber", + "voelin-core", "voelin-platform", + "voelin-store", + "voelin-ui-vm", ] [[package]] @@ -12736,6 +12871,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "waker-fn" version = "1.2.0" diff --git a/crates/voelin-gpui/Cargo.toml b/crates/voelin-gpui/Cargo.toml index 76956ed..def0740 100644 --- a/crates/voelin-gpui/Cargo.toml +++ b/crates/voelin-gpui/Cargo.toml @@ -20,8 +20,30 @@ path = "src/main.rs" anyhow = "1.0.104" # GPUI, gpui-component and gpui-kit-assets behind one pinned dependency. gpui-kit = { workspace = true } -# The app's name and id (the window's title and its desktop file). -voelin-platform = { path = "../voelin-platform", default-features = false } +# The engine's runtime and the channel of its events (a tokio receiver needs no +# reactor, so GPUI's executor can await it). +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 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 view models and the state, shared with the Slint front end. +voelin-ui-vm = { path = "../voelin-ui-vm" } + +[dev-dependencies] +# GPUI's test platform (`#[gpui::test]`, `TestAppContext`): the front end's tests +# need no display. gpui-kit's own `test-support` feature is not used: it names +# the optional `gpui-fast` backend in weak features, which puts gpui-fast and +# its tree into Cargo.lock and pins taffy to 0.15.0 for every build. gpui-kit +# pins `gpui-pre` exactly, so this line moves with its `=` pin (a mismatch does +# not resolve). +gpui = { package = "gpui-pre", version = "=0.3.10", features = ["test-support"] } [lints] workspace = true diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs new file mode 100644 index 0000000..829eb60 --- /dev/null +++ b/crates/voelin-gpui/src/app.rs @@ -0,0 +1,380 @@ +//! The root state of the window, `Entity`: everything the client +//! knows (the toolkit-free [`voelin_ui_vm`] state and the friends and pokes +//! beside it) and the three loops that keep it current on GPUI's thread: +//! +//! - the **engine's events**: a foreground task awaits the receiver of +//! [`crate::engine::HostedEngine`] (a tokio channel needs no reactor, so +//! GPUI's executor can poll it), hands every event to +//! [`events::handle`] and tells the entity to redraw (`cx.notify()`), the +//! pattern of spike 3's hotkey task; +//! - the **tick**, once a second, a loop of `background_executor().timer` +//! (the Slint front end's `slint::Timer` calling `App::tick`); +//! - **later**: other threads (a hotkey, a camera, a decoder) cannot touch the +//! entity, and GPUI's `AsyncApp` is not `Send`, so they hold a [`Later`], a +//! channel of jobs a third foreground task runs on GPUI's thread, as +//! `later(|app| ...)` does in the Slint front end. +//! +//! What a transition asks for besides the state (`Update`: which parts to +//! draw again, what to keep, the streams' capture and decoder) belongs to +//! the slices that have those parts; today only the engine commands go out +//! and the warnings are logged. + +use std::time::{Duration, Instant}; + +use gpui_kit::Context; +use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; +use voelin_core::{AudioSettings, Command, Engine, Event, VoiceState}; +use voelin_store::{ChatRead, ChatTarget as StoredTarget}; +use voelin_ui_vm::bridge::ChatLine; +use voelin_ui_vm::events; +use voelin_ui_vm::host::{Host, Update}; +use voelin_ui_vm::settings::UiSettings; +use voelin_ui_vm::social::logic::Social; + +/// The toolkit-free state of the client, with the chat lines of a tab as plain +/// rows (what a front end that draws again from the list needs). +pub type VmState = voelin_ui_vm::state::AppState>; + +/// A job for GPUI's thread, from any thread. +type Job = Box) + Send>; + +/// How other threads reach the root state: `later.run(|app, cx| ...)` runs +/// the closure on GPUI's thread with the entity (the Slint front end's +/// `later`). Cloneable and `Send`; the closure must be `Send` too. +#[derive(Clone)] +pub struct Later(UnboundedSender); + +impl Later { + /// Run `job` on GPUI's thread soon; `false` when the window is gone. + pub fn run( + &self, + job: impl FnOnce(&mut AppState, &mut Context) + Send + 'static, + ) -> bool { + self.0.send(Box::new(job)).is_ok() + } +} + +/// What the transitions of the state ask of this front end while they run. +/// There is no store yet (the shell slice opens it): nothing was read, and +/// nothing is kept. +#[derive(Debug, Default)] +struct ShellHost; + +impl Host for ShellHost { + fn demo_ui(&self) -> bool { + false + } + + fn chat_shown(&self) -> bool { + false + } + + fn watching(&self) -> bool { + false + } + + fn autowatch(&self) -> bool { + false + } + + fn studio_streams_to(&self, _session: i64) -> bool { + false + } + + fn preview_limit(&self) -> u64 { + 0 + } + + fn fetch_images(&self) -> bool { + false + } + + fn dm_shown(&self, _session: i64, _uid: &str) -> bool { + false + } + + fn chat_reads(&self, _server_uid: &str) -> Result, String> { + Ok(Vec::new()) + } + + fn set_chat_read( + &self, + _server_uid: &str, + _target: &StoredTarget, + _read: &ChatRead, + ) -> Result<(), String> { + Ok(()) + } +} + +/// The root entity. +pub struct AppState { + /// What the client knows apart from the window. + pub vm: VmState, + /// The friends, pokes and notices the social screens keep. + pub social: Social<()>, + /// Engine events handled since the window opened. + pub events_handled: u64, + /// One-second ticks since the window opened. + pub ticks: u64, + engine: Option, + host: ShellHost, + started: Instant, + later: Later, +} + +impl AppState { + /// The state at start, with its three loops running: the engine's + /// `events` (the engine is `None` in tests that need none), the tick and + /// the jobs of [`Later`]. They end when the entity is released. + pub fn new( + engine: Option, + events: UnboundedReceiver, + cx: &mut Context, + ) -> Self { + let (later, mut jobs) = mpsc::unbounded_channel::(); + + cx.spawn(async move |this, cx| { + let mut events = events; + while let Some(event) = events.recv().await { + if this.update(cx, |state, cx| state.handle_event(event, cx)).is_err() { + break; + } + } + }) + .detach(); + + cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(Duration::from_secs(1)).await; + if this.update(cx, |state, cx| state.tick(cx)).is_err() { + break; + } + } + }) + .detach(); + + cx.spawn(async move |this, cx| { + while let Some(job) = jobs.recv().await { + if this + .update(cx, |state, cx| { + job(state, cx); + cx.notify(); + }) + .is_err() + { + break; + } + } + }) + .detach(); + + Self { + vm: VmState::new( + Vec::new(), + UiSettings::default(), + AudioSettings::default(), + Default::default(), + ), + social: Social::default(), + events_handled: 0, + ticks: 0, + engine, + host: ShellHost, + started: Instant::now(), + later: Later(later), + } + } + + /// The handle other threads use to run something on GPUI's thread. + pub fn later(&self) -> Later { + self.later.clone() + } + + /// What an engine event does to the state ([`events::handle`], the one + /// dispatch of both front ends), and what comes of it for the engine. + pub fn handle_event(&mut self, event: Event, cx: &mut Context) { + self.events_handled += 1; + let update = events::handle(&mut self.vm, &mut self.social, &self.host, event); + self.perform(update); + cx.notify(); + } + + /// Do what an update asks that this front end has the parts for: the + /// engine's commands go out, the warnings are logged. + fn perform(&mut self, update: Update) { + if let Some(engine) = &self.engine { + for command in update.commands { + engine.send(command); + } + } + for warning in update.warnings { + tracing::warn!("{warning}"); + } + } + + /// The once-a-second work: what the Slint front end's `App::tick` will be + /// here (stream statistics, stored settings); today it counts. + pub fn tick(&mut self, cx: &mut Context) { + self.ticks += 1; + cx.notify(); + } + + /// Voice connections that are up. + pub fn connections(&self) -> usize { + self.vm.sessions.values().filter(|view| view.state.voice == VoiceState::Connected).count() + } + + /// Seconds since the window opened. + pub fn uptime(&self) -> Duration { + self.started.elapsed() + } + + /// The one line of state the window shows: the version, how many voice + /// connections are up, how many engine events came and how long the + /// window has run. Each part moves by a loop above, so a line that + /// changes shows that the loop runs. + pub fn state_line(&self) -> String { + let connections = self.connections(); + format!( + "{} {} · {} connection{} · {} engine event{} · {} s up", + voelin_platform::APP_NAME, + env!("CARGO_PKG_VERSION"), + connections, + if connections == 1 { "" } else { "s" }, + self.events_handled, + if self.events_handled == 1 { "" } else { "s" }, + self.ticks, + ) + } + + /// Leave the servers properly, so no ghost client stays behind until it + /// times out (the window is closing). + pub fn shutdown(&self) { + let Some(engine) = &self.engine else { return }; + for id in self.vm.sessions.keys() { + engine.send(Command::CloseSession { session: *id as u64 }); + } + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use gpui::TestAppContext; + use gpui_kit::AppContext as _; + use voelin_core::{Command, Event, SessionState, VoiceState}; + + use super::*; + use crate::engine::HostedEngine; + + fn voice(voice: VoiceState) -> Event { + Event::State { session: 1, state: SessionState { voice, ..Default::default() } } + } + + /// The entity of a test with no engine behind it: `tx` stands in for the + /// engine's events. + fn entity(cx: &mut TestAppContext) -> (gpui_kit::Entity, UnboundedSender) { + let (tx, rx) = mpsc::unbounded_channel(); + let app = cx.new(move |cx| AppState::new(None, rx, cx)); + (app, tx) + } + + #[gpui::test] + fn an_injected_engine_event_reaches_the_entity(cx: &mut TestAppContext) { + let (app, tx) = entity(cx); + app.read_with(cx, |app, _| { + assert_eq!(app.connections(), 0); + assert!(app.state_line().contains("0 connections · 0 engine events")); + }); + + tx.send(voice(VoiceState::Connected)).unwrap(); + cx.run_until_parked(); + app.read_with(cx, |app, _| { + assert_eq!(app.events_handled, 1); + assert_eq!(app.connections(), 1); + assert_eq!(app.vm.status, "Connected", "the transition's status line"); + assert!( + app.state_line().contains("1 connection · 1 engine event"), + "{}", + app.state_line() + ); + }); + + tx.send(voice(VoiceState::Disconnected)).unwrap(); + cx.run_until_parked(); + app.read_with(cx, |app, _| { + assert_eq!((app.events_handled, app.connections()), (2, 0)); + }); + } + + #[gpui::test] + fn the_entity_redraws_on_an_event(cx: &mut TestAppContext) { + let (app, tx) = entity(cx); + let notified = std::rc::Rc::new(std::cell::Cell::new(0)); + let _subscription = cx.update(|cx| { + let notified = notified.clone(); + cx.observe(&app, move |_, _| notified.set(notified.get() + 1)) + }); + tx.send(voice(VoiceState::Connecting)).unwrap(); + cx.run_until_parked(); + assert_eq!(notified.get(), 1); + } + + #[gpui::test] + fn the_tick_runs_once_a_second(cx: &mut TestAppContext) { + let (app, _tx) = entity(cx); + cx.run_until_parked(); + assert_eq!(app.read_with(cx, |app, _| app.ticks), 0); + for second in 1..=3 { + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + assert_eq!(app.read_with(cx, |app, _| app.ticks), second); + } + } + + #[gpui::test] + fn another_thread_runs_a_job_on_the_entity_through_later(cx: &mut TestAppContext) { + let (app, _tx) = entity(cx); + let later = app.read_with(cx, |app, _| app.later()); + let sent = std::thread::spawn(move || { + later.run(|app, _| app.vm.status = "from another thread".into()) + }) + .join() + .unwrap(); + assert!(sent); + cx.run_until_parked(); + assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "from another thread"); + } + + /// The whole path with a real engine: a command makes the engine report a + /// setting change, which its forwarder hands to the window's channel and + /// the foreground task to the entity. The engine's tasks run on tokio + /// threads, so the test looks again until the event is in (no bound on + /// how long the loaded machine takes, a generous one on the whole wait); + /// the test scheduler is told that other threads wake it + /// (`allow_parking`), which it otherwise reports as a test that is not + /// deterministic. + #[gpui::test] + fn a_real_engine_event_reaches_the_entity(cx: &mut TestAppContext) { + cx.executor().allow_parking(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let hosted = HostedEngine::start(&runtime); + let engine = hosted.engine.clone(); + let app = cx.new(|cx| AppState::new(Some(engine.clone()), hosted.events, cx)); + engine.send(Command::SetSetting { key: "stream.fps".into(), value: 144.into() }); + let deadline = Instant::now() + Duration::from_secs(120); + while app.read_with(cx, |app, _| app.events_handled) == 0 { + assert!(Instant::now() < deadline, "the engine's event never arrived"); + cx.run_until_parked(); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(app.read_with(cx, |app, _| app.events_handled) >= 1); + runtime.shutdown_timeout(Duration::from_secs(2)); + } +} diff --git a/crates/voelin-gpui/src/dev.rs b/crates/voelin-gpui/src/dev.rs new file mode 100644 index 0000000..704519a --- /dev/null +++ b/crates/voelin-gpui/src/dev.rs @@ -0,0 +1,63 @@ +//! The development switches of the GPUI front end, read from the +//! environment. They are the Slint front end's (docs/ui.md, "Development +//! switches and screenshots") where the GPUI one has the same thing to +//! switch, so that one recipe serves both. +//! +//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size. + +/// What the environment switched. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Switches { + /// The window's size in pixels, when the switch names one. + pub window: Option<(f32, f32)>, +} + +impl Switches { + /// The switches of this process's environment. + pub fn from_env() -> Self { + Self::parse(|name| std::env::var(name).ok()) + } + + /// The switches `get` answers for; what it does not understand is logged + /// and left out. + pub fn parse(get: impl Fn(&str) -> Option) -> Self { + let mut switches = Self::default(); + if let Some(text) = get("VOELIN_WINDOW_SIZE") { + match parse_size(&text) { + Some(size) => switches.window = Some(size), + None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"), + } + } + switches + } +} + +/// `WIDTHxHEIGHT` in pixels, at least 320 by 240 and at most 16384 each way. +fn parse_size(text: &str) -> Option<(f32, f32)> { + let (w, h) = text.trim().split_once('x')?; + let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?); + ((320..=16384).contains(&w) && (240..=16384).contains(&h)).then_some((w as f32, h as f32)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn size_of(text: &str) -> Switches { + let text = text.to_owned(); + Switches::parse(|name| (name == "VOELIN_WINDOW_SIZE").then(|| text.clone())) + } + + #[test] + fn the_window_size_is_read() { + assert_eq!(size_of("1440x960").window, Some((1440.0, 960.0))); + assert_eq!(Switches::parse(|_| None), Switches::default()); + } + + #[test] + fn what_makes_no_sense_is_left_out() { + for text in ["10x10", "1440", "axb", "99999x99999", ""] { + assert_eq!(size_of(text), Switches::default(), "{text:?}"); + } + } +} diff --git a/crates/voelin-gpui/src/engine.rs b/crates/voelin-gpui/src/engine.rs new file mode 100644 index 0000000..9646555 --- /dev/null +++ b/crates/voelin-gpui/src/engine.rs @@ -0,0 +1,45 @@ +//! The engine this front end runs on, the same one the Slint front end +//! hosts (`voelin_ui::HostedEngine`, `crates/voelin-ui/src/app.rs`): started +//! on a tokio runtime, its events forwarded into a channel the window reads. +//! The Slint crate cannot be a dependency here (it brings Slint in), so the +//! few lines are repeated; both go into `voelin-ui-vm` when the Slint front +//! end is retired. + +use tokio::runtime::{Handle, Runtime}; +use tokio::sync::{broadcast, mpsc}; +use voelin_core::{Engine, Event}; + +/// An engine owned by the caller of [`crate::run`]. +pub struct HostedEngine { + /// The handle: commands go in through it. + pub engine: Engine, + /// The runtime the engine runs on; the window's helpers run there too. + pub runtime: Handle, + /// The engine's events for the window: first those that rebuild the + /// current state of every session, then new ones. Reading them needs no + /// reactor, so the window's foreground executor can await it. + pub events: mpsc::UnboundedReceiver, +} + +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() }); + let (tx, events) = mpsc::unbounded_channel(); + let mut rx = engine.subscribe(); + runtime.spawn(async move { + loop { + match rx.recv().await { + Ok(event) => { + if tx.send(event).is_err() { + break; + } + } + Err(broadcast::error::RecvError::Lagged(_)) => continue, + Err(_) => break, + } + } + }); + Self { engine, runtime: runtime.handle().clone(), events } + } +} diff --git a/crates/voelin-gpui/src/lib.rs b/crates/voelin-gpui/src/lib.rs index 9354b7d..a826c62 100644 --- a/crates/voelin-gpui/src/lib.rs +++ b/crates/voelin-gpui/src/lib.rs @@ -5,63 +5,109 @@ #![warn(missing_docs)] +pub mod app; +pub mod dev; +pub mod engine; +pub mod view; + use std::cell::RefCell; use std::rc::Rc; +use std::time::Duration; use anyhow::{Context as _, Result}; -use gpui_kit::{ - App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, - TitlebarOptions, Window, WindowOptions, div, px, -}; +use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size}; +use tracing_subscriber::{EnvFilter, fmt, prelude::*}; -/// The window's first content: nothing yet. -struct Blank; +use crate::app::AppState; +use crate::dev::Switches; +use crate::engine::HostedEngine; +use crate::view::MainView; -impl Render for Blank { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { - div().size_full().child("") - } +/// 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). zbus's warnings +/// are left out, as in the Slint front end: it warns when a desktop portal's +/// request object is gone before it reads its properties, which is harmless. +const LOG_FILTER: &str = "warn,zbus=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(); } -/// The main window's options: titled with the app's name, grouped by its id. -fn window_options() -> WindowOptions { +/// 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)); WindowOptions { titlebar: Some(TitlebarOptions { title: Some(voelin_platform::APP_NAME.into()), ..Default::default() }), app_id: Some(voelin_platform::APP_ID.to_owned()), - window_min_size: Some(gpui_kit::size(px(640.0), px(480.0))), + window_min_size: Some(size(px(640.0), px(480.0))), + window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)), ..Default::default() } } -/// Open the main window; closing it ends the app. -fn open_main_window(cx: &mut App) -> Result> { - let (_, blank) = gpui_kit::open_window(window_options(), cx, |window, cx| { - window.on_window_should_close(cx, |_, cx| { - cx.quit(); - true - }); - cx.new(|_| Blank) +/// Open the main window on the root state; closing it leaves the servers and +/// ends the app. +fn open_main_window(cx: &mut App, switches: &Switches, engine: HostedEngine) -> Result<()> { + let HostedEngine { engine, events, .. } = engine; + let app = cx.new(move |cx| AppState::new(Some(engine), events, cx)); + let options = window_options(switches, cx); + gpui_kit::open_window(options, cx, { + let app = app.clone(); + move |window, cx| { + window.on_window_should_close(cx, { + let app = app.clone(); + move |_, cx| { + app.read(cx).shutdown(); + cx.quit(); + true + } + }); + cx.new(|cx| MainView::new(app, cx)) + } }) .context("cannot open the main window")?; - Ok(blank) + Ok(()) } /// 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" + ); + // 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); let failure: Rc>> = Rc::default(); gpui_kit::application().run({ let failure = failure.clone(); move |cx| { gpui_kit::init(cx); - if let Err(e) = open_main_window(cx) { + if let Err(e) = open_main_window(cx, &switches, hosted) { *failure.borrow_mut() = Some(e); cx.quit(); } } }); + runtime.shutdown_timeout(Duration::from_secs(2)); match failure.take() { Some(e) => Err(e), None => Ok(()), diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs new file mode 100644 index 0000000..d3611c6 --- /dev/null +++ b/crates/voelin-gpui/src/view.rs @@ -0,0 +1,39 @@ +//! The window's content. Today the shell is not built (slice 1 of the +//! migration): the window shows the one line of the root state that proves +//! the loops run. + +use gpui_kit::component::ActiveTheme as _; +use gpui_kit::{ + Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px, +}; + +use crate::app::AppState; + +/// What the main window draws, from the root state. +pub struct MainView { + app: Entity, +} + +impl MainView { + /// A view of `app` that draws again whenever it changes. + pub fn new(app: Entity, cx: &mut Context) -> Self { + cx.observe(&app, |_, _, cx| cx.notify()).detach(); + Self { app } + } +} + +impl Render for MainView { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let line = self.app.read(cx).state_line(); + let theme = cx.theme(); + div() + .size_full() + .flex() + .items_center() + .justify_center() + .bg(theme.background) + .text_color(theme.foreground) + .text_size(px(14.0)) + .child(line) + } +}