From f476c95a642a836092dbc2dc204187208010a8af Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 08:58:51 -0700 Subject: [PATCH] feat(gui): a tab is a company open in the app's books server; closing the window closes it in view The window starts the server with the companies it restores, a tab opened or closed opens or closes that company in it (one queue per company, so one company's backup at close delays no other), failures and incomplete backups are notices under the tab bar, and asked to close the window waits, saying so, for the server's bounded close (WB-app-2, WB-app-4). The viewer no longer starts a detached host. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 115 ++++++++--- crates/ledger-gui/src/app.rs | 156 +++++++++++++- crates/ledger-gui/src/lib.rs | 1 + crates/ledger-gui/src/owner.rs | 43 +++- crates/ledger-gui/src/serving.rs | 341 +++++++++++++++++++++++++++++++ 5 files changed, 625 insertions(+), 31 deletions(-) create mode 100644 crates/ledger-gui/src/serving.rs diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 42aab5b1..3bc716a3 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -70,20 +70,86 @@ fn gui_args(args: Vec) -> Vec { /// The viewer's owner (ledger-gui owner.rs): its Books menu, done as the /// command line does it (the books server, the agents' own commands). #[cfg(feature = "gui")] -struct ViewerOwner(ledger_host::commands::Common); +struct ViewerOwner { + common: ledger_host::commands::Common, + /// The books server this window runs, a child process of it (plan P15 + /// 3.1): started with the window, closed with it. + server: std::sync::Mutex>>, +} + +#[cfg(feature = "gui")] +impl ViewerOwner { + fn new(common: ledger_host::commands::Common) -> Self { + Self { + common, + server: std::sync::Mutex::new(None), + } + } + + /// The running server, or why there is none. + fn running(&self) -> Result, String> { + self.server + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .ok_or_else(|| "the books server isn't running".to_string()) + } +} #[cfg(feature = "gui")] impl ledger_gui::owner::Owner for ViewerOwner { + fn serves(&self) -> bool { + true + } + + fn serve_start(&self, open: &[String]) -> Result<(), String> { + use ledger_host::app_server::{AppServer, READY_WAIT}; + // Started before it is waited for, and kept at once: a window + // closed meanwhile closes this one too. + let server = std::sync::Arc::new(AppServer::start(self.common.root.as_deref(), open)?); + *self.server.lock().unwrap_or_else(|e| e.into_inner()) = Some(server.clone()); + server.wait_ready(READY_WAIT) + } + + fn serve_open(&self, book: &str) -> Result, String> { + self.running()?.open_book(book) + } + + fn serve_close(&self, book: &str) -> Result, String> { + self.running()?.close_book(book) + } + + fn serve_stop(&self) -> Result, String> { + use ledger_host::app_server::{STOP_WAIT, Stopped}; + let Some(server) = self.server.lock().unwrap_or_else(|e| e.into_inner()).take() else { + return Ok(None); + }; + Ok(match server.stop(STOP_WAIT) { + Stopped::Closed => None, + Stopped::StillClosing => Some( + "The books are still closing in the background (most likely a last backup): Wanderbooks finishes it on its own. Start it again once it has.".into(), + ), + }) + } + + fn serve_exited(&self) -> Option { + self.server + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref()? + .exited() + } + fn close_books(&self) -> Result { - ledger_host::commands::close_books(&self.0) + ledger_host::commands::close_books(&self.common) } fn new_books(&self, id: &str, currency: &str) -> Result { - ledger_host::commands::new_books_and_home(&self.0, id, currency) + ledger_host::commands::new_books_and_home(&self.common, id, currency) } fn back_up_now(&self, book: &str) -> Result, String> { - ledger_host::commands::back_up_now(&self.0, book, false) + ledger_host::commands::back_up_now(&self.common, book, false) } fn plan_restore( @@ -92,7 +158,7 @@ impl ledger_gui::owner::Owner for ViewerOwner { id: Option, replace: bool, ) -> Result { - let p = ledger_host::commands::plan_restore(&self.0, source, id, replace, false)?; + let p = ledger_host::commands::plan_restore(&self.common, source, id, replace, false)?; Ok(ledger_gui::owner::RestorePlan { source: p.source, id: p.id, @@ -104,7 +170,7 @@ impl ledger_gui::owner::Owner for ViewerOwner { fn restore(&self, plan: &ledger_gui::owner::RestorePlan) -> Result, String> { ledger_host::commands::carry_out_restore( - &self.0, + &self.common, &ledger_host::commands::RestorePlan { source: plan.source.clone(), id: plan.id.clone(), @@ -121,11 +187,11 @@ impl ledger_gui::owner::Owner for ViewerOwner { ledger_gui::owner::Agent::Claude => "claude", ledger_gui::owner::Agent::Codex => "codex", }; - ledger_host::commands::connect_and_home(&self.0, agent, book) + ledger_host::commands::connect_and_home(&self.common, agent, book) } fn first_run(&self) -> ledger_gui::owner::FirstRun { - let s = ledger_host::commands::first_run_state(&self.0); + let s = ledger_host::commands::first_run_state(&self.common); ledger_gui::owner::FirstRun { root: s.root, books: s.books, @@ -134,16 +200,16 @@ impl ledger_gui::owner::Owner for ViewerOwner { } fn set_up(&self) -> Result, String> { - ledger_host::commands::set_up_root(&self.0) + ledger_host::commands::set_up_root(&self.common) } fn set_passphrase(&self, new: &str) -> Result<(), String> { - ledger_host::commands::set_first_passphrase(&self.0, new) + ledger_host::commands::set_first_passphrase(&self.common, new) } - fn hold(&self, book: &str) { - ledger_host::commands::hold_for_viewer(&self.0, Some(book.to_string())); - } + /// Nothing: the window's server holds the books for as long as the + /// window runs, a company at a time (`serve_open`), and no host does. + fn hold(&self, _book: &str) {} fn agent_start( &self, @@ -178,22 +244,24 @@ impl ledger_gui::owner::Owner for ViewerOwner { } fn upgrade_format(&self, book: &str, passphrase: &str) -> Result, String> { - ledger_host::commands::upgrade_format(&self.0, book, passphrase) + ledger_host::commands::upgrade_format(&self.common, book, passphrase) } fn update_waiting(&self) -> Option { - ledger_host::commands::update_waiting(&self.0).map(|u| ledger_gui::owner::UpdateWaiting { - version: u.version, - staged_at: u.staged_at, + ledger_host::commands::update_waiting(&self.common).map(|u| { + ledger_gui::owner::UpdateWaiting { + version: u.version, + staged_at: u.staged_at, + } }) } fn check_for_updates(&self) -> Result, String> { - ledger_host::commands::check_for_updates(&self.0).map(|l| vec![l]) + ledger_host::commands::check_for_updates(&self.common).map(|l| vec![l]) } fn apply_update(&self) -> Result, String> { - ledger_host::commands::apply_update(&self.0).map(|l| vec![l]) + ledger_host::commands::apply_update(&self.common).map(|l| vec![l]) } } @@ -222,7 +290,6 @@ fn run_gui(args: Vec) -> i32 { } } let root = value("--root").map(PathBuf::from); - let book = value("--book"); if known { // The viewer asks about a format upgrade in its own window, makes // the first books when there are none, and starts the agent in @@ -231,10 +298,10 @@ fn run_gui(args: Vec) -> i32 { root: root.clone(), ..Default::default() }; - ledger_gui::owner::set_owner(std::sync::Arc::new(ViewerOwner(common.clone()))); - if ledger_gui::book_in_root(root.as_deref(), book.as_deref()).is_ok() { - ledger_host::commands::hold_for_viewer(&common, book); - } + // The window runs the books server itself, as a child process + // (plan P15 3.1), once it knows which companies it opens: no + // host is started for it. + ledger_gui::owner::set_owner(std::sync::Arc::new(ViewerOwner::new(common))); } } match ledger_gui::run("wanderbooks gui", args) { diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 8737e322..368cff8b 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -7,7 +7,8 @@ //! (the color scheme, the dock's preferences) is kept once. //! SOURCE: plan/p15-app-and-relay.md 3.2 (tabs: `App` holds the per-app //! state and a `CompanyView` per tab); D-78 (one top-level tab per -//! open company). +//! open company); 3.1 (a tab is a company open in the books +//! server the app runs); WB-app-2, WB-app-4. //! INVARIANTS: //! 1. One view per open company, no company twice: opening one that is //! open shows its tab instead, and start-up opens each company of the @@ -52,12 +53,25 @@ //! (an export, a backup) is stopped with its tab, with no question. //! 6. The viewer stays read-only: a tab not in front reads what a tab //! in front reads, and writes nothing either. +//! 8. A tab is a company open in the books server the program runs for +//! the window, when it runs one (serving.rs, WB-app-2): the +//! companies restored at the start are opened with the server, a +//! company opened later when its tab opens, and closed when its tab +//! closes. What fails, and a server that stops on its own, is a +//! notice under the tab bar, in words, until dismissed. Where the +//! session list and the connection states will go (A4) is +//! `Self::connection_slot`. +//! 9. Asked to close, a window with a server stays up, saying it is +//! closing the books, until the server has exited or its bounded +//! close has run out (and then says what is left); a close is never +//! begun while a job that changes the books runs (7) (WB-app-4). //! ``` use crate::company::CompanyView; use crate::data::Source; use crate::nav::Route; use crate::scheme_menu::SchemeMenu; +use crate::serving::Serving; use crate::tabs::{Listed, Tab, TabAction, TabBar}; use crate::theme::{self, pal}; use egui::{Frame, RichText, Ui}; @@ -138,6 +152,14 @@ pub struct App { /// Whether the list of open companies is written when the app saves /// (INVARIANT 3: not after a start that named a company). writes_open_list: bool, + /// The window asked to close and the server's close is being waited + /// for: the window closes when it is done (INVARIANT 9). + closing_window: bool, + /// The books server the program runs for the window, if it runs one: + /// a tab is a company open in it (INVARIANT 8). + serving: Serving, + /// What the server work has said that the person has not dismissed. + notices: Vec, } /// What a window is called when no company is in front. @@ -161,6 +183,18 @@ impl App { ctx: &egui::Context, get: &dyn Fn(&str) -> Option, start: Start, + ) -> Self { + Self::start_with_owner(ctx, get, start, crate::owner::current()) + } + + /// [`Self::start_with`], with the program's owner given (tests give + /// one that hosts a server of its own): the server it hosts starts + /// with the companies this start opens (INVARIANT 8). + pub fn start_with_owner( + ctx: &egui::Context, + get: &dyn Fn(&str) -> Option, + start: Start, + owner: Option>, ) -> Self { let mut app = Self::without_books(ctx, get); match start { @@ -171,6 +205,9 @@ impl App { .map(std::path::Path::to_path_buf); app.remember_all(get); app.remember_scope(get, &kept_scope_of(&source.data_dir)); + // A company of a data root is served; the demo's is not. + let id = crate::owner::book_id_of_dir(&source.data_dir); + app.serving = Serving::start(owner, id.into_iter().collect()); app.open(ctx, source); } Start::Restore { root, fallback } => { @@ -181,7 +218,10 @@ impl App { let wanted: Vec = get(&open_key(&root)) .map(|v| v.split(',').map(str::to_string).collect()) .unwrap_or_default(); + // The companies this start opens, in order (INVARIANT 3): + // the server starts with exactly these open. let mut opened = Vec::new(); + let mut sources = Vec::new(); for id in wanted { // Gone, or listed twice: skipped, with no word. if !there.contains(&id) || opened.contains(&id) { @@ -193,13 +233,16 @@ impl App { let Ok(r) = ledger_store::root::Root::find(Some(&root)) else { break; }; - let source = Source { + sources.push(Source { data_dir: r.book_dir(&book), today: app.today, - }; - app.open(ctx, source); + }); opened.push(id); } + app.serving = Serving::start(owner, opened.clone()); + for source in sources { + app.open(ctx, source); + } if app.views.is_empty() { app.open(ctx, fallback); } else { @@ -287,6 +330,9 @@ impl App { first_run_source: (None, None), close_dialog: false, writes_open_list: true, + closing_window: false, + serving: Serving::off(), + notices: Vec::new(), } } @@ -374,6 +420,88 @@ impl App { }); } + /// Asked to close, a window with a server stays up, saying it is + /// closing the books, until the server has exited or its bounded + /// close has run out (INVARIANT 9). A job that changes the books holds + /// the window first (`guard_close`), and no close begins meanwhile. + fn guard_server_close(&mut self, ctx: &egui::Context) { + if !self.serving.is_on() || !self.holding().is_empty() { + return; + } + let asked = ctx.input(|i| i.viewport().close_requested()); + if asked && !self.serving.is_closed() { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.serving.begin_stop(); + self.closing_window = true; + } + if !self.closing_window { + return; + } + if self.serving.is_closed() { + self.closing_window = false; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + return; + } + egui::Modal::new(egui::Id::new("wanderbooks-closing-books")).show(ctx, |ui| { + ui.set_max_width(460.0); + ui.heading("Closing your books"); + ui.add_space(4.0); + ui.label( + "Finishing what is running and making each company's last backup. \ + This can take a minute; the window closes by itself.", + ); + ui.add_space(6.0); + ui.spinner(); + }); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + + /// The notices from the server work, shown under the tab bar until + /// dismissed (INVARIANT 8). + fn show_notices(&mut self, ui: &mut Ui) { + self.notices.extend(self.serving.take_notices()); + if self.notices.is_empty() { + return; + } + let p = pal(ui.ctx()); + let mut dismiss = None; + egui::Panel::top("server_notices") + .resizable(false) + .frame( + Frame::new() + .fill(p.warning_soft) + .inner_margin(egui::Margin::symmetric(12, 6)), + ) + .show(ui, |ui| { + for (i, words) in self.notices.iter().enumerate() { + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(words).color(p.text)); + if ui.button("Dismiss").clicked() { + dismiss = Some(i); + } + }); + } + }); + if let Some(i) = dismiss { + self.notices.remove(i); + } + } + + /// What the server work has said that has not been dismissed (tests). + pub fn notices(&mut self) -> &[String] { + self.notices.extend(self.serving.take_notices()); + &self.notices + } + + /// The server work of the window (tests). + pub fn serving(&self) -> &Serving { + &self.serving + } + + /// Where the connection states and the list of who is connected will + /// be shown (plan 3.3, unit A4); nothing is drawn yet. + fn connection_slot(&mut self, _ui: &mut Ui) {} + /// The window's title now. pub fn window_title(&self) -> String { match self.active_view() { @@ -417,7 +545,13 @@ impl App { return i; } let view = CompanyView::open(ctx, source).with_dock(self.new_dock()); - self.add_view(view) + let at = self.add_view(view); + // A tab is a company open in the server (INVARIANT 8): one this + // start opened is open in it already. + if let Some(id) = self.views[at].book_id() { + self.serving.open(&id); + } + at } /// Close tab `i`: its view is dropped (INVARIANT 2). The tab after it, @@ -438,6 +572,10 @@ impl App { self.kept.insert(stored(&scope, k), v); }); } + // The company is closed in the server with its tab (INVARIANT 8). + if let Some(id) = view.book_id() { + self.serving.close(&id); + } drop(view); if i < self.active || self.active >= self.views.len() { self.active = self.active.saturating_sub(1); @@ -496,6 +634,11 @@ impl App { match crate::book_in_root(root.as_deref(), Some(id)) { Ok(data_dir) => { self.today = today; + // The first company of a first run: the server starts with + // it (INVARIANT 8), if the program runs one. + if !self.serving.is_on() { + self.serving = Serving::start(crate::owner::current(), vec![id.to_string()]); + } self.open(ctx, Source { data_dir, today }); self.welcome = None; } @@ -758,6 +901,7 @@ impl eframe::App for App { v.pump(&ctx, i == self.active); } self.guard_close(&ctx); + self.guard_server_close(&ctx); self.check_identities(); self.learn_names(); let tabs: Vec = self @@ -781,6 +925,8 @@ impl eframe::App for App { // The bar goes across the whole window, above everything of the // company in front: a tab is the top level (D-78). let action = self.tabs.show(ui, &tabs, shown, &others); + self.show_notices(ui); + self.connection_slot(ui); let active = self.active; match self.views.get_mut(active) { Some(v) => v.ui(ui, &mut self.schemes), diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index 80daf6ab..75d17ce0 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -23,6 +23,7 @@ mod prefs; mod receipts; mod scheme_menu; mod schemes; +pub mod serving; pub mod tabs; #[cfg(test)] mod test_support; diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index b5b45019..638dd572 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -157,6 +157,40 @@ pub struct UpdateWaiting { /// over the books server and the agents' own commands). Each blocks: the /// menu calls it off the UI thread. pub trait Owner: Send + Sync { + /// Whether this program hosts the books' server for the window (plan + /// P15 3.1: the app starts it, as a child process, and closes it): when + /// it does not, the window asks nothing of a server (`serve_*`). + fn serves(&self) -> bool { + false + } + /// Start the books server with the companies `open` (their ids) open, + /// and return when it is ready, or why it is not. Blocks. + fn serve_start(&self, _open: &[String]) -> Result<(), String> { + Ok(()) + } + /// Open the company `book` in the server (a tab opened): `Ok(None)` + /// when it is open now. Blocks. + fn serve_open(&self, _book: &str) -> Result, String> { + Ok(None) + } + /// Close the company `book` in the server (a tab closed): `Ok(None)` + /// when it is closed, `Ok(Some(words))` when it is closed but its last + /// backup wasn't whole, `Err` when it could not be asked or refused. + /// Blocks (a backup is made first). + fn serve_close(&self, _book: &str) -> Result, String> { + Ok(None) + } + /// Close the server (the window closed): its input is closed and the + /// exit waited for, for a bounded time. `Ok(Some(words))` when it is + /// still finishing by itself after that. Blocks. + fn serve_stop(&self) -> Result, String> { + Ok(None) + } + /// Why the server is gone, if it has exited on its own. Cheap: asked + /// on every frame. + fn serve_exited(&self) -> Option { + None + } /// Close the books: everything holding them lets go. fn close_books(&self) -> Result; /// New, empty books `id` in `currency`. @@ -235,8 +269,13 @@ pub fn current() -> Option> { /// The id of books of the data root (their folder's name), or None for /// books outside one, the demo's (INVARIANT 4). pub fn book_id(books: &Books) -> Option { - ledger_store::root::inside_a_root(&books.data_dir) - .then(|| books.data_dir.file_name()?.to_str().map(str::to_string)) + book_id_of_dir(&books.data_dir) +} + +/// [`book_id`] of the books in `dir`. +pub fn book_id_of_dir(dir: &std::path::Path) -> Option { + ledger_store::root::inside_a_root(dir) + .then(|| dir.file_name()?.to_str().map(str::to_string)) .flatten() } diff --git a/crates/ledger-gui/src/serving.rs b/crates/ledger-gui/src/serving.rs new file mode 100644 index 00000000..24cb619f --- /dev/null +++ b/crates/ledger-gui/src/serving.rs @@ -0,0 +1,341 @@ +//! The window's line to the books server (plan P15 3.1; D-77, D-78). +//! +//! ```text +//! GOAL: a tab is a company open in the books server, and the server is +//! the app's child: it starts with the companies the window +//! restored, a tab opened or closed opens or closes that company in +//! it, and closing the window closes it, in view and in bounded +//! time. What fails is said to the person, never swallowed. +//! SOURCE: plan/p15-app-and-relay.md 3.1 (the app starts the server and +//! closes it by closing its input; opening or closing a tab is +//! the server opening or closing that book), 3.2, D-77, D-78, +//! WB-app-2, WB-app-4. +//! INVARIANTS: +//! 1. Nothing here touches the UI thread's time: every request to the +//! server runs on a thread of its own, and the window only reads +//! the notices those threads leave. +//! 2. A company's requests are one queue, in the order they were made +//! (a tab closed and opened again is a close, then an open); no +//! company's request waits for another company's, so closing one +//! company's tab, which makes its last backup, delays no other. +//! 3. No request is made before the server has started, and none after +//! a start that failed (the person was told why, once). +//! 4. A company the window opened at the start is not opened again; a +//! company whose open failed is asked for again the next time its +//! tab opens. +//! 5. A failed request, a close whose last backup wasn't whole, and a +//! server that has exited on its own are each a notice, in words, +//! once; the window shows them until they are dismissed. +//! 6. The server is closed once: by `begin_stop` (the window asked to +//! close, with the wait in view), else when this is dropped. Neither +//! returns before the owner's bounded close has, and neither kills +//! anything. +//! 7. Without an owner that hosts a server (the viewer on its own, the +//! demo, tests) it does nothing at all. +//! ``` + +use crate::owner::Owner; +use std::collections::{BTreeSet, HashMap}; +use std::sync::mpsc::{Sender, channel}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; + +/// Where the server's start stands (INVARIANT 3). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Gate { + Starting, + Up, + Down, +} + +/// Where the server's close stands (INVARIANT 6). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Closing { + Not, + Running, + Done, +} + +enum Cmd { + Open, + Close, +} + +#[derive(Default)] +struct State { + /// The companies the server has open, or is being asked to have. + wanted: BTreeSet, + /// What the person has not been told yet. + notices: Vec, + /// One queue per company (INVARIANT 2). + lanes: HashMap>, + /// The server's exit has been said. + exit_said: bool, +} + +struct Inner { + owner: Arc, + gate: Mutex, + gate_changed: Condvar, + closing: Mutex, + closing_changed: Condvar, + state: Mutex, +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl Inner { + fn note(&self, words: String) { + lock(&self.state).notices.push(words); + } + + /// Wait for the start to have come out: whether the server is up. + fn up(&self) -> bool { + let mut gate = lock(&self.gate); + while *gate == Gate::Starting { + gate = self + .gate_changed + .wait(gate) + .unwrap_or_else(|e| e.into_inner()); + } + *gate == Gate::Up + } + + /// Close the server, once; the others wait for that one to be done. + fn close_server(&self) { + { + let mut closing = lock(&self.closing); + if *closing != Closing::Not { + while *closing != Closing::Done { + closing = self + .closing_changed + .wait(closing) + .unwrap_or_else(|e| e.into_inner()); + } + return; + } + *closing = Closing::Running; + } + match self.owner.serve_stop() { + Ok(None) => {} + Ok(Some(words)) => { + // The window may be gone before anyone reads a notice. + eprintln!("wanderbooks: {words}"); + self.note(words); + } + Err(why) => self.note(format!( + "The books server could not be closed cleanly: {why}" + )), + } + *lock(&self.closing) = Closing::Done; + self.closing_changed.notify_all(); + } +} + +/// The window's line to the server; one per window. +pub struct Serving { + inner: Option>, +} + +impl Serving { + /// No server: nothing is asked of any (INVARIANT 7). + pub fn off() -> Self { + Self { inner: None } + } + + /// Start the server with the companies `open` open, if `owner` hosts + /// one; the start runs on a thread of its own (INVARIANT 1). + pub fn start(owner: Option>, open: Vec) -> Self { + let Some(owner) = owner.filter(|o| o.serves()) else { + return Self::off(); + }; + let inner = Arc::new(Inner { + owner, + gate: Mutex::new(Gate::Starting), + gate_changed: Condvar::new(), + closing: Mutex::new(Closing::Not), + closing_changed: Condvar::new(), + state: Mutex::new(State { + wanted: open.iter().cloned().collect(), + ..State::default() + }), + }); + let starting = inner.clone(); + let spawned = std::thread::Builder::new() + .name("serving-start".into()) + .spawn(move || { + let came = match starting.owner.serve_start(&open) { + Ok(()) => Gate::Up, + Err(why) => { + starting.note(format!("Assistants can't reach your companies: {why}")); + Gate::Down + } + }; + *lock(&starting.gate) = came; + starting.gate_changed.notify_all(); + }); + if spawned.is_err() { + inner.note( + "Assistants can't reach your companies: the books server could not be started." + .into(), + ); + *lock(&inner.gate) = Gate::Down; + } + Self { inner: Some(inner) } + } + + /// Whether a server is being hosted for this window. + pub fn is_on(&self) -> bool { + self.inner.is_some() + } + + /// A tab for the company `id` opened: ask the server to open it, unless + /// it has it (INVARIANT 4). + pub fn open(&self, id: &str) { + let Some(inner) = &self.inner else { return }; + let fresh = lock(&inner.state).wanted.insert(id.to_string()); + if fresh { + Self::send(inner, id, Cmd::Open); + } + } + + /// The tab of the company `id` closed: ask the server to close it. + pub fn close(&self, id: &str) { + let Some(inner) = &self.inner else { return }; + let had = lock(&inner.state).wanted.remove(id); + if had { + Self::send(inner, id, Cmd::Close); + } + } + + /// Whether the server has, or is being asked to have, `id` open + /// (tests). + pub fn wants(&self, id: &str) -> bool { + self.inner + .as_ref() + .is_some_and(|i| lock(&i.state).wanted.contains(id)) + } + + /// Queue `cmd` for the company `id` on its own thread, made the first + /// time (INVARIANT 2). + fn send(inner: &Arc, id: &str, cmd: Cmd) { + let mut state = lock(&inner.state); + let mut cmd = cmd; + if let Some(lane) = state.lanes.get(id) { + match lane.send(cmd) { + Ok(()) => return, + // Its thread is gone: the command comes back, for a new one. + Err(back) => cmd = back.0, + } + } + let (tx, rx) = channel::(); + let worker = inner.clone(); + let book = id.to_string(); + let started = std::thread::Builder::new() + .name(format!("serving-{id}")) + .spawn(move || { + for cmd in rx { + // INVARIANT 3. + if !worker.up() { + continue; + } + match cmd { + Cmd::Open => match worker.owner.serve_open(&book) { + Ok(None) => {} + Ok(Some(words)) => worker.note(words), + Err(why) => { + lock(&worker.state).wanted.remove(&book); + worker.note(why); + } + }, + Cmd::Close => match worker.owner.serve_close(&book) { + Ok(None) => {} + Ok(Some(words)) => worker.note(words), + Err(why) => worker.note(format!( + "{book} could not be closed to your assistants: {why}" + )), + }, + } + } + }); + match started { + Ok(_) => { + let _ = tx.send(cmd); + state.lanes.insert(id.to_string(), tx); + } + Err(_) => { + drop(state); + inner.note(format!( + "Assistants may not be able to reach {id}: a thread could not be started." + )); + } + } + } + + /// What the person has not been told yet (INVARIANT 5), and, once, + /// that the server exited on its own. + pub fn take_notices(&self) -> Vec { + let Some(inner) = &self.inner else { + return Vec::new(); + }; + let closing = *lock(&inner.closing) != Closing::Not; + let mut state = lock(&inner.state); + if !state.exit_said + && !closing + && let Some(why) = inner.owner.serve_exited() + { + state.exit_said = true; + state.notices.push(format!( + "{why}. Assistants can't reach your companies until Wanderbooks is started again." + )); + } + std::mem::take(&mut state.notices) + } + + /// The window was asked to close: close the server on a thread of its + /// own, so the window can say so while it does (INVARIANT 6). + pub fn begin_stop(&self) { + let Some(inner) = &self.inner else { return }; + if *lock(&inner.closing) != Closing::Not { + return; + } + let inner = inner.clone(); + let spawned = std::thread::Builder::new() + .name("serving-stop".into()) + .spawn({ + let inner = inner.clone(); + move || inner.close_server() + }); + if spawned.is_err() { + inner.close_server(); + } + } + + /// Whether the close has begun. + pub fn is_closing(&self) -> bool { + self.inner + .as_ref() + .is_some_and(|i| *lock(&i.closing) != Closing::Not) + } + + /// Whether the close is done (or there is no server to close). + pub fn is_closed(&self) -> bool { + self.inner + .as_ref() + .is_none_or(|i| *lock(&i.closing) == Closing::Done) + } +} + +impl Drop for Serving { + /// The window is gone without having been asked to close first (a + /// signal, a test): the server is closed here, in bounded time, with + /// a line on stderr (INVARIANT 6). + fn drop(&mut self) { + let Some(inner) = &self.inner else { return }; + if *lock(&inner.closing) == Closing::Not { + eprintln!("wanderbooks: closing the books before it exits"); + } + inner.close_server(); + } +}