//! 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::settings::Settings; use voelin_core::{Backends, Engine, Event, History}; /// 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 { 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 { 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 } } }