From ec436cfc02861da2f2ca1122afcd6ab787ec2880 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 19:03:26 -0700 Subject: [PATCH] feat(gui): a tab owns its threads; kept state belongs to its books; one dock layout An independent review of the tab work found that closing a tab did not end what the tab started, that what the viewer keeps was filed under the book id alone, and a few smaller things. All of it is the viewer's own state: nothing here writes the books. Threads: every thread a tab starts (loader, receipts' workers, export, owner job, the dock's start and its agent's reaper) is counted in one per-view registry (jobs.rs). Dropping the view tells them to stop and the registry says, on a condition, when the last has ended. An owner job that changes something (restore, format upgrade, new books, connect, close the books, check for updates, update) is never abandoned: its tab's close control is off with a hover text saying what runs, App::close refuses, and the window's close request is cancelled with a dialog that offers only to wait. Read-only jobs (an export, a backup, the restore's check) stop with the tab: an export checks at its phase boundaries and saves nothing (the save is one atomic write of a new file; one the stop reaches too late is removed). The dock's agent is hung up on and, if it ignores that for two seconds, killed and reaped; the window's drop waits for that. Release on close: the loader checks "gone" before every retry and between the phases of a load, its retry wait is woken by the drop, and the viewer presence is let go in the drop itself, not when a refresh in flight ends. A thumbnail for a closed tab is not written. Kept state: filed under a hash of the data root's canonical path and the id (books outside any root: under their folder), with the books' identity, the SHA-256 of the journal's first line, taken once they load. A stored state whose identity differs from the loaded books' is discarded with the remembered name. Old unkeyed keys are read without error and not used. A start that names a company never writes the list of open companies. The dock's height is the app's one layout in every tab (said in the spec block and tested); the sidebar, rail and top bar panels now take ids made from their view's, since egui keys a panel's size by the id as given. Every new test was seen to fail with its fix switched off. The four sidenav tests keep their BAR_H: at the owner's 519 they fail by 15 points (sidebar) and 11 (rail) without it. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/ledger-gui/Cargo.toml | 5 + crates/ledger-gui/src/app.rs | 243 +++++- crates/ledger-gui/src/company.rs | 183 ++++- crates/ledger-gui/src/data.rs | 131 +++- crates/ledger-gui/src/dock.rs | 137 +++- crates/ledger-gui/src/jobs.rs | 322 ++++++++ crates/ledger-gui/src/lib.rs | 1 + crates/ledger-gui/src/menu.rs | 76 +- crates/ledger-gui/src/owner.rs | 177 ++++- crates/ledger-gui/src/receipts.rs | 92 ++- crates/ledger-gui/src/tabs.rs | 29 +- crates/ledger-gui/tests/exports.rs | 39 + crates/ledger-gui/tests/format_upgrade.rs | 145 +++- crates/ledger-gui/tests/live.rs | 83 ++ crates/ledger-gui/tests/tabs.rs | 878 +++++++++++++++++++++- 16 files changed, 2388 insertions(+), 154 deletions(-) create mode 100644 crates/ledger-gui/src/jobs.rs diff --git a/Cargo.lock b/Cargo.lock index 7a9df178..07f0fcfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3973,6 +3973,7 @@ dependencies = [ "ledger-package", "ledger-store", "ledger-vault", + "libc", "notify", "proptest", "rust_decimal", diff --git a/crates/ledger-gui/Cargo.toml b/crates/ledger-gui/Cargo.toml index 22102bbd..3040b7a9 100644 --- a/crates/ledger-gui/Cargo.toml +++ b/crates/ledger-gui/Cargo.toml @@ -40,6 +40,11 @@ zeroize = "1" # The dock: a terminal emulator over a PTY (ConPTY on Windows), P11b alacritty_terminal = "0.26" +[target.'cfg(unix)'.dependencies] +# The dock ends a dropped session's child that ignores the hang-up (dock.rs +# INVARIANT 8): a SIGKILL to the pid this crate's own PTY started. +libc = "0.2" + [dev-dependencies] chrono = "0.4" egui_kittest = { version = "0.36", features = ["wgpu", "snapshot", "eframe"] } diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 8dadec98..8737e322 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -19,15 +19,37 @@ //! otherwise the companies open when the app last closed, in their //! order, the same one in front; a company that is gone is skipped //! without a word, and when none remains the data root's first opens. -//! 4. What is kept for next time: the open companies (`open_companies`, +//! A session started with a company named never writes the list of +//! open companies, whatever it opens or closes: a plain start's list +//! is not replaced by a one-tab session's. (Each company's own page +//! and period are kept in both.) +//! 4. What is kept for next time is kept for a company of a data root, +//! by the root and the id: the open companies (`open_companies.`, //! the ids of their books, comma separated) and the one in front -//! (`active_company`); for each company its page, its report's -//! period, columns and comparison and its name as last known -//! (`company..…`); and, as -//! before and under the same keys, the scheme and its filter -//! (`scheme`, `scheme_filter`, `dark`) and the dock (`dock_open`, -//! `dock_agent`, the front tab's). +//! (`active_company.`), `R` being a hash of the root's canonical +//! path (`company::path_hash`); for each company its page, its +//! report's period, columns and comparison, its name as last known +//! and the identity of its books (`company...…`; books in a +//! folder outside any root: `company.dir..…`); +//! and, under their own keys, the scheme and its filter (`scheme`, +//! `scheme_filter`, `dark`) and the dock's preferences (`dock_open`, +//! `dock_agent`, the front tab's: the app's). Another root holding a +//! company of the same id, or the same id made again, is not this +//! company: a stored state is used only for the books it was kept +//! for, which each company's identity says once it loads +//! (company.rs INVARIANT 5): a stored identity that is not the +//! loaded books' discards the stored state and the remembered name, +//! and they are kept anew for these books. Files written before the +//! keys carried a root (`open_companies`, `company..…`) are +//! read without error and not used. //! 5. The window's title names the company in front. +//! 7. While a job that changes the books runs in any tab (an owner's +//! restore or format upgrade: owner.rs INVARIANT 6), the window is +//! not closed and that tab's close control is off, saying what is +//! running; a request to close the window is cancelled and a dialog +//! says what is running and offers only to wait; it goes when the +//! job ends, and its result is shown in the tab. A read-only job +//! (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. //! ``` @@ -43,12 +65,34 @@ use std::collections::HashMap; use std::path::PathBuf; pub use crate::company::{COMPACT_BELOW, PageState, Shell}; +use crate::company::{kept_scope_of, path_hash}; /// Where the viewer keeps the companies that were open (the ids of their -/// books, comma separated), and the one in front. +/// books, comma separated), and the one in front: under these names, then +/// the data root (`open_key`, `active_key`; INVARIANT 4). pub const OPEN_KEY: &str = "open_companies"; pub const ACTIVE_KEY: &str = "active_company"; +/// The key the open companies of the data root at `root` are kept under. +pub fn open_key(root: &std::path::Path) -> String { + format!("{OPEN_KEY}.{}", path_hash(root)) +} + +/// The key the company in front, of the data root at `root`, is kept under. +pub fn active_key(root: &std::path::Path) -> String { + format!("{ACTIVE_KEY}.{}", path_hash(root)) +} + +/// The key `thing` ("page", "range", "columns", "compare", "identity", +/// "name") of the company whose books are in `data_dir` is kept under. +pub fn company_key(data_dir: &std::path::Path, thing: &str) -> String { + stored(&kept_scope_of(data_dir), thing) +} + +fn stored(scope: &str, thing: &str) -> String { + format!("company.{scope}.{thing}") +} + /// How the app starts. pub enum Start { /// This company alone: the one named on the command line, or the demo. @@ -88,6 +132,12 @@ pub struct App { /// What a first run opens its books with: the data root named, and /// "today". first_run_source: (Option, Option), + /// The window was asked to close while a job that changes the books + /// ran, and the dialog that says so is up (INVARIANT 7). + close_dialog: bool, + /// 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, } /// What a window is called when no company is in front. @@ -116,9 +166,11 @@ impl App { match start { Start::Only(source) => { app.today = source.today; + app.writes_open_list = false; app.root = ledger_store::root::root_of_book_dir(&source.data_dir) .map(std::path::Path::to_path_buf); app.remember_all(get); + app.remember_scope(get, &kept_scope_of(&source.data_dir)); app.open(ctx, source); } Start::Restore { root, fallback } => { @@ -126,7 +178,7 @@ impl App { app.root = Some(root.clone()); app.remember_all(get); let there = list_books(&root); - let wanted: Vec = get(OPEN_KEY) + let wanted: Vec = get(&open_key(&root)) .map(|v| v.split(',').map(str::to_string).collect()) .unwrap_or_default(); let mut opened = Vec::new(); @@ -152,7 +204,7 @@ impl App { app.open(ctx, fallback); } else { // The one in front last time, else the first. - app.active = get(ACTIVE_KEY) + app.active = get(&active_key(&root)) .and_then(|front| opened.iter().position(|id| *id == front)) .unwrap_or(0); // The dock left open was the front tab's. @@ -233,6 +285,8 @@ impl App { title: TITLE.to_string(), welcome: None, first_run_source: (None, None), + close_dialog: false, + writes_open_list: true, } } @@ -272,6 +326,54 @@ impl App { } } + /// The jobs that change the books, running now in any tab, as the + /// window is held open for them: each tab's name and what runs there + /// (INVARIANT 7). + pub fn holding(&self) -> Vec<(String, String)> { + self.views + .iter() + .filter_map(|v| Some((self.title_of(v), v.closing_is_held()?))) + .collect() + } + + /// Whether the dialog that says the window is held open is up (tests). + pub fn close_dialog_is_up(&self) -> bool { + self.close_dialog + } + + /// A request to close the window while a job that changes the books + /// runs is cancelled and the dialog that says why is put up; the + /// dialog goes when the job ends (INVARIANT 7). + fn guard_close(&mut self, ctx: &egui::Context) { + let held = self.holding(); + if held.is_empty() { + self.close_dialog = false; + return; + } + if ctx.input(|i| i.viewport().close_requested()) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.close_dialog = true; + } + if !self.close_dialog { + return; + } + egui::Modal::new(egui::Id::new("wanderbooks-close-held")).show(ctx, |ui| { + ui.set_max_width(460.0); + ui.heading("The books are being changed"); + ui.add_space(4.0); + ui.label( + "The window stays open until this is done, so that nothing is cut off half way:", + ); + for (company, what) in &held { + ui.label(format!("{company}: {what}")); + } + ui.add_space(6.0); + if ui.button("Wait for it to finish").clicked() { + self.close_dialog = false; + } + }); + } + /// The window's title now. pub fn window_title(&self) -> String { match self.active_view() { @@ -293,8 +395,8 @@ impl App { // What was kept for it (last run's, or from when it was closed // earlier in this one) comes back. let mut view = view; - if let Some(id) = view.book_id() { - view.restore(&|k| self.kept.get(&format!("company.{id}.{k}")).cloned()); + if let Some(scope) = view.kept_scope() { + view.restore(&|k| self.kept.get(&stored(&scope, k)).cloned()); } self.views.push(view); self.active = at; @@ -320,14 +422,20 @@ impl App { /// Close tab `i`: its view is dropped (INVARIANT 2). The tab after it, /// else the one before, comes to the front when it was the front one. + /// A tab with a job that changes the books under way is not closed + /// (INVARIANT 7). pub fn close(&mut self, i: usize) { if i >= self.views.len() { return; } + // A job that changes the books is never abandoned: its tab stays. + if self.views[i].closing_is_held().is_some() { + return; + } let view = self.views.remove(i); - if let Some(id) = view.book_id() { + if let Some(scope) = view.kept_scope() { view.keep(&mut |k, v| { - self.kept.insert(format!("company.{id}.{k}"), v); + self.kept.insert(stored(&scope, k), v); }); } drop(view); @@ -361,15 +469,22 @@ impl App { let Some(root) = self.root.clone() else { return; }; + let root_hash = path_hash(&root); for id in list_books(&root) { - if let Some(name) = get(&format!("company.{id}.name")) { + if let Some(name) = get(&stored(&format!("{root_hash}.{id}"), "name")) { self.names.insert(id.clone(), name); } - for k in crate::company::KEPT_KEYS { - let key = format!("company.{id}.{k}"); - if let Some(v) = get(&key) { - self.kept.insert(key, v); - } + self.remember_scope(get, &format!("{root_hash}.{id}")); + } + } + + /// What was kept under `scope` (a company's), for the view that opens + /// for it. + fn remember_scope(&mut self, get: &dyn Fn(&str) -> Option, scope: &str) { + for k in crate::company::KEPT_KEYS { + let key = stored(scope, k); + if let Some(v) = get(&key) { + self.kept.insert(key, v); } } } @@ -412,6 +527,28 @@ impl App { } } + /// Books that are not the books a company's kept state was kept for + /// (their identity differs: made again under the id, or restored over + /// it): the kept state and the remembered name are dropped, to be + /// kept anew for these books (company.rs INVARIANT 5). + fn check_identities(&mut self) { + let mut stale = Vec::new(); + for v in &mut self.views { + if v.check_identity() { + stale.push((v.kept_scope(), v.book_id())); + } + } + for (scope, id) in stale { + if let Some(scope) = scope { + let prefix = format!("company.{scope}."); + self.kept.retain(|k, _| !k.starts_with(&prefix)); + } + if let Some(id) = id { + self.names.remove(&id); + } + } + } + /// Note the name of every company whose books are loaded. fn learn_names(&mut self) { for v in &self.views { @@ -581,6 +718,21 @@ fn list_books(root: &std::path::Path) -> Vec { .unwrap_or_default() } +impl Drop for App { + /// The window is closing: every tab's threads are told to stop and + /// waited for, so a dock's agent that ignored its hang-up is killed and + /// reaped before the process ends and not left to outlive it. Bounded: + /// the agent's grace and a little more. + fn drop(&mut self) { + let watches: Vec<_> = self.views.iter().map(CompanyView::jobs_watch).collect(); + self.views.clear(); + let limit = crate::dock::AGENT_GRACE + std::time::Duration::from_secs(3); + for w in watches { + w.wait_ended(limit); + } + } +} + impl eframe::App for App { fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) { // A first run: the page that sets the books up, until there are some. @@ -605,6 +757,8 @@ impl eframe::App for App { for (i, v) in self.views.iter_mut().enumerate() { v.pump(&ctx, i == self.active); } + self.guard_close(&ctx); + self.check_identities(); self.learn_names(); let tabs: Vec = self .views @@ -612,6 +766,7 @@ impl eframe::App for App { .map(|v| { let title = self.title_of(v); Tab { + held: v.closing_is_held(), detail: match v.book_id() { Some(id) if id != title => format!("{title}\n{id}"), _ => title.clone(), @@ -657,34 +812,42 @@ impl eframe::App for App { } } } - // The companies open, in order, and the one in front. - let open: Vec<(String, usize)> = self - .views - .iter() - .enumerate() - .filter_map(|(i, v)| Some((v.book_id()?, i))) - .collect(); - storage.set_string( - OPEN_KEY, - open.iter() - .map(|(id, _)| id.as_str()) - .collect::>() - .join(","), - ); - if let Some((id, _)) = open.iter().find(|(_, i)| *i == self.active) { - storage.set_string(ACTIVE_KEY, id.clone()); + // The companies open, in order, and the one in front: not after a + // start that named a company (INVARIANT 3). + if self.writes_open_list + && let Some(root) = self.root.clone() + { + let open: Vec<(String, usize)> = self + .views + .iter() + .enumerate() + .filter_map(|(i, v)| Some((v.book_id()?, i))) + .collect(); + storage.set_string( + &open_key(&root), + open.iter() + .map(|(id, _)| id.as_str()) + .collect::>() + .join(","), + ); + if let Some((id, _)) = open.iter().find(|(_, i)| *i == self.active) { + storage.set_string(&active_key(&root), id.clone()); + } } // What was kept for the companies closed, then for those open // (their own, as they are now). for (k, v) in &self.kept { storage.set_string(k, v.clone()); } - for (id, name) in &self.names { - storage.set_string(&format!("company.{id}.name"), name.clone()); + if let Some(root) = &self.root { + let root_hash = path_hash(root); + for (id, name) in &self.names { + storage.set_string(&stored(&format!("{root_hash}.{id}"), "name"), name.clone()); + } } for v in &self.views { - if let Some(id) = v.book_id() { - v.keep(&mut |k, val| storage.set_string(&format!("company.{id}.{k}"), val)); + if let Some(scope) = v.kept_scope() { + v.keep(&mut |k, val| storage.set_string(&stored(&scope, k), val)); } } } diff --git a/crates/ledger-gui/src/company.rs b/crates/ledger-gui/src/company.rs index 300c172d..9220ebd6 100644 --- a/crates/ledger-gui/src/company.rs +++ b/crates/ledger-gui/src/company.rs @@ -16,17 +16,38 @@ //! 2. Every egui id a view makes is scoped by the view's own id (the app //! draws a view inside `push_id`), so egui's memory (scroll offsets, //! collapsed headers, focus, remembered widths) never carries from -//! one company's tab into another's. +//! one company's tab into another's. A panel's id is not scoped by +//! `push_id` (egui keys a panel's size by the id it is given), so +//! the view's panels (sidebar, rail, top bar) are given ids made from +//! the view's own. What is not scoped is the app's, on purpose, and +//! says so: the assistant dock's panel (one height, one layout in +//! every tab: dock.rs INVARIANT 9), the tab bar's panel, the colour +//! scheme's palette (one scheme for the window), and the footer and +//! link rects published at fixed ids for the tests, which nothing +//! reads back (`tests/tabs.rs` says each). //! 3. A view that is not shown still follows its journal and takes the //! agent's `books.show` (its own page moves, nothing else does), so //! showing it later is current at once. //! 4. Dropping a view ends everything it started: its loader and its -//! watcher and viewer presence, its receipts' workers, and its -//! dock's agent process. +//! watcher and viewer presence, its receipts' workers, an export, +//! the dock's start and its agent's process. They are all counted in +//! one registry of the view (jobs.rs), which the drop tells to stop +//! and which says when the last has ended (`jobs_watch`); the +//! viewer's presence on the books is let go at the drop, not when a +//! refresh in flight is over. One exception, by decision: a job that +//! changes the books (an owner's restore or format upgrade, owner.rs +//! INVARIANT 6) is never abandoned: while one runs the view cannot +//! be closed (`closing_is_held`), nor the window (app.rs). +//! 5. What the view keeps for next time is filed under the data root +//! and the books' id (`kept_scope`), with the books' identity (the +//! SHA-256 of the journal's first line, which no other books share) +//! once they load; a stored state whose identity is not the loaded +//! books' is another set of books' and is discarded (`check_identity`). //! ``` use crate::books::Books; use crate::data::{Loader, Source, Update}; +use crate::jobs::Jobs; use crate::nav::{Nav, Route, Section}; use crate::owner::Owner; use crate::pages; @@ -98,6 +119,25 @@ pub struct CompanyView { /// Books arrived while the view wasn't shown: their receipts are /// prefetched when it is. prefetch_due: bool, + /// Every thread this view started (INVARIANT 4): the loader, the + /// receipts' workers, an export, an owner's job, the dock's start and + /// its agent's reaper. Told to stop when the view drops (`Drop`). + jobs: Jobs, + /// What identifies these books, taken from the books themselves once + /// they load, as it was kept (until then) or is now (INVARIANT 5). + identity: Option, + /// The identity of the books as last loaded (None while there is no + /// journal line to take it from). + loaded_identity: Option, +} + +impl Drop for CompanyView { + /// The tab is closing: every thread it started is told to stop before + /// anything else of the view goes (an export that hasn't saved yet + /// saves nothing; a thumbnail not written is not written). + fn drop(&mut self) { + self.jobs.stop(); + } } /// The key that tells a company's views apart: its books' folder, as the @@ -112,6 +152,8 @@ pub(crate) fn key_of(data_dir: &std::path::Path) -> String { impl CompanyView { fn bare(key: String, data_dir: Option, ctx: &egui::Context) -> Self { let id = egui::Id::new(("company", &key)); + let jobs = Jobs::new(); + let spawner = jobs.spawner(); Self { key, id, @@ -120,16 +162,19 @@ impl CompanyView { books: None, error: None, nav: Nav::new(Route::Overview), - receipts: Receipts::new(ctx), + receipts: Receipts::new(ctx, &spawner), state: PageState::default(), palette: crate::palette::Palette::scoped(id), updated_at: -1e9, live_label: false, - menu: Default::default(), - owner_menu: crate::owner::OwnerMenu::scoped(id), + menu: crate::menu::Menu::in_tab(spawner.clone()), + owner_menu: crate::owner::OwnerMenu::scoped(id, spawner), dock: Default::default(), owner: crate::owner::current(), prefetch_due: false, + jobs, + identity: None, + loaded_identity: None, } } @@ -138,7 +183,7 @@ impl CompanyView { pub fn open(ctx: &egui::Context, source: Source) -> Self { let mut view = Self::bare(key_of(&source.data_dir), Some(source.data_dir.clone()), ctx); view.receipts.thumb_dir = crate::receipts::thumb_dir(); - view.loader = Some(Loader::spawn(source, ctx.clone())); + view.loader = Some(Loader::spawn_in(source, ctx.clone(), &view.jobs.spawner())); view } @@ -146,6 +191,7 @@ impl CompanyView { pub fn with_books(ctx: &egui::Context, books: Books, start: Route) -> Self { let mut view = Self::bare(key_of(&books.data_dir), Some(books.data_dir.clone()), ctx); view.receipts.prefetch(&books); + view.loaded_identity = identity_of(&books); view.books = Some(Arc::new(books)); view.nav = Nav::new(start); view @@ -274,6 +320,38 @@ impl CompanyView { self.loader.as_ref().map(Loader::watch) } + /// A handle that says when every thread this view started has ended, + /// which outlives the view: its loader, its receipts' workers, its + /// exports and owner's jobs, the dock's start and its agent's reaper + /// (INVARIANT 4; tests). + pub fn jobs_watch(&self) -> crate::jobs::Watch { + self.jobs.watch() + } + + /// What this view's threads hold its tab open for, if a job that + /// changes the books runs (INVARIANT 4): the words the tab's close + /// control shows. + pub fn closing_is_held(&self) -> Option { + self.jobs.holding() + } + + /// Tell this view's threads to stop, as its close does; the signal a + /// thread of it was given (tests). + pub fn stop_signal(&self) -> crate::jobs::Stop { + self.jobs.spawner().stop_signal() + } + + /// Start `work` as this view's export job would be started (tests: a + /// job whose steps the test controls). + pub fn start_export_for_tests( + &mut self, + ctx: &egui::Context, + what: &str, + work: Box crate::menu::Done + Send>, + ) { + self.menu.start_with(ctx, what.to_string(), work); + } + /// The agent dock (tests). pub fn dock_mut(&mut self) -> &mut crate::dock::Dock { &mut self.dock @@ -348,6 +426,7 @@ impl CompanyView { } else { self.prefetch_due = true; } + self.loaded_identity = identity_of(&b); self.books = Some(b); self.error = None; } @@ -375,7 +454,7 @@ impl CompanyView { return; }; if let Some(book) = crate::owner::book_id(&books) { - self.dock.show(ui, &owner, &book); + self.dock.show(ui, &owner, &book, &self.jobs.spawner()); } } @@ -623,7 +702,7 @@ impl CompanyView { let p = pal(ui.ctx()); let books = self.books.clone(); let head = self.card_head(ui.ctx()); - egui::Panel::left("sidebar") + egui::Panel::left(ui.id().with("sidebar")) .exact_size(224.0) .resizable(false) .frame( @@ -745,7 +824,7 @@ impl CompanyView { let p = pal(ui.ctx()); let books = self.books.clone(); let head = self.card_head(ui.ctx()); - egui::Panel::left("rail") + egui::Panel::left(ui.id().with("rail")) .exact_size(RAIL_W) .resizable(false) .frame( @@ -877,7 +956,7 @@ impl CompanyView { /// nothing ever overlaps. fn topbar(&mut self, ui: &mut Ui) { let p = pal(ui.ctx()); - egui::Panel::top("topbar") + egui::Panel::top(ui.id().with("topbar")) .exact_size(52.0) .frame( Frame::new() @@ -1000,10 +1079,84 @@ impl CompanyView { } } -/// The keys a view keeps its things under (after `company..`). -pub(crate) const KEPT_KEYS: [&str; 4] = ["page", "range", "columns", "compare"]; +/// The keys a view keeps its things under (after `company..`; the +/// company's name is kept by the app beside them, under `name`). +pub(crate) const KEPT_KEYS: [&str; 5] = ["page", "range", "columns", "compare", "identity"]; + +/// A short, stable name for a place on disk: FNV-1a (64 bits) of its +/// canonical path's bytes, in twelve hex digits. Stable across runs and +/// versions (it is a key in a file); not a secret. +pub fn path_hash(path: &std::path::Path) -> String { + let real = ledger_store::root::canonical(path).unwrap_or_else(|_| path.to_path_buf()); + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in real.as_os_str().as_encoded_bytes() { + h ^= u64::from(*b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{:012x}", h & 0xffff_ffff_ffff) +} + +/// What a company's kept things are filed under: for books in a data +/// root, the root (a hash of its canonical path) and the books' id, +/// `.`; for books in a folder outside any root, that +/// folder (`dir.`). Two roots' companies of +/// one id are two companies. +pub fn kept_scope_of(data_dir: &std::path::Path) -> String { + match ( + ledger_store::root::root_of_book_dir(data_dir), + data_dir.file_name().and_then(|n| n.to_str()), + ) { + (Some(root), Some(id)) => format!("{}.{id}", path_hash(root)), + _ => format!("dir.{}", path_hash(data_dir)), + } +} + +/// What identifies a set of books, from the books themselves: the SHA-256 +/// of the journal's first line (its canonical bytes: the very value the +/// second line's `prev` repeats). Every set of books has its own first +/// line (its timestamp, its first event); books made again under an old +/// id, or restored over it from another set, do not share it. None until +/// the journal has a line. +pub fn identity_of(books: &Books) -> Option { + books + .journal + .first() + .map(|l| ledger_store::journal::sha256_hex(l.to_canonical().as_bytes())) +} impl CompanyView { + /// What this company's kept things are filed under ([`kept_scope_of`]), + /// when its books are read from a folder. + pub fn kept_scope(&self) -> Option { + self.data_dir.as_deref().map(kept_scope_of) + } + + /// The books' identity as kept, or as last loaded ([`identity_of`]). + pub fn identity(&self) -> Option<&str> { + self.identity.as_deref() + } + + /// Compare the identity kept with the loaded books' (INVARIANT 5). + /// First load with nothing kept: the books' identity is taken and + /// nothing changes. Kept, and the same: nothing changes. Kept, and + /// not the same: these are other books than the kept state was of + /// (made again under the id, or restored over it), so the state kept + /// is dropped, this view starts as for new books, and true is + /// returned: the caller drops what else it kept for them (their + /// name). + pub fn check_identity(&mut self) -> bool { + let Some(now) = self.loaded_identity.clone() else { + return false; + }; + let changed = self.identity.as_ref().is_some_and(|kept| *kept != now); + if changed { + self.nav = Nav::new(Route::Overview); + self.state.reports = Default::default(); + } + self.identity = Some(now); + changed + } + /// What a person expects to come back to: the page and the report's /// period, columns and comparison. (A detail page comes back as its /// list: the entry or the party may not be there any more.) @@ -1043,12 +1196,16 @@ impl CompanyView { } .to_string(), ); + if let Some(identity) = &self.identity { + set("identity", identity.clone()); + } } /// Take back what [`Self::keep`] kept (`get` reads a key; what isn't /// there, or isn't understood, is left as it is). pub fn restore(&mut self, get: &dyn Fn(&str) -> Option) { use crate::pages::reports::{Columns, Compare, Range}; + self.identity = get("identity"); if let Some(route) = get("page").and_then(|k| route_from_key(&k)) { self.nav = Nav::new(route); } diff --git a/crates/ledger-gui/src/data.rs b/crates/ledger-gui/src/data.rs index 744a3a7c..81b63f37 100644 --- a/crates/ledger-gui/src/data.rs +++ b/crates/ledger-gui/src/data.rs @@ -34,23 +34,55 @@ pub enum Update { Show(ledger_store::ops::ViewerTarget), } +/// The viewer's presence on the books (`ledger_store::ops::Presence`), held +/// by the loader's thread and let go by whichever comes first: the thread's +/// end, or the loader's drop (so a tab's close releases it at once, not +/// when a refresh in flight is over). +type PresenceSlot = Arc>>; + +/// What a loader's thread says of itself, for tests. +#[derive(Default)] +pub struct Probe { + attempts: std::sync::atomic::AtomicUsize, + /// Set while the thread waits to try the books again. + waiting: std::sync::atomic::AtomicBool, +} + pub struct Loader { rx: Receiver, /// Set when this is dropped: the loader's thread then ends, letting go /// of the books (and the viewer's presence on them). gone: Arc, + /// The viewer's presence, shared with the thread (INVARIANT: let go in + /// `drop`, taken by the thread only while `gone` is not set). + presence: PresenceSlot, /// Wakes the thread at once when this is dropped, so it ends now and /// not at its next look. wake: Sender<()>, /// Set by the thread as it ends. ended: Arc, + /// Counted by the thread at every full load it tries. + attempts: Arc, } /// Says whether a loader's thread has ended, after the loader is gone. #[derive(Clone)] -pub struct LoaderWatch(Arc); +pub struct LoaderWatch(Arc, Arc); impl LoaderWatch { + /// How many times the thread tried to load the books in full + /// (`Snapshot::load`), the first included (tests: a dropped loader + /// tries no more). + pub fn load_attempts(&self) -> usize { + self.1.attempts.load(std::sync::atomic::Ordering::SeqCst) + } + + /// Whether the thread is waiting to try the books again, after one + /// that failed (tests: drop the loader then, with certainty). + pub fn waiting(&self) -> bool { + self.1.waiting.load(std::sync::atomic::Ordering::SeqCst) + } + /// Whether the thread has ended: its watcher, its hold on the books /// and its viewer presence are released. pub fn ended(&self) -> bool { @@ -70,31 +102,66 @@ impl Drop for Ends { impl Drop for Loader { fn drop(&mut self) { self.gone.store(true, std::sync::atomic::Ordering::SeqCst); + // The viewer's presence goes now: the thread may be inside a + // refresh that takes a while, and the books are no longer looked + // at. The thread takes a presence only while `gone` is unset, + // under this lock, so none is taken after this. + drop( + self.presence + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take(), + ); let _ = self.wake.send(()); } } impl Loader { + /// A loader that no tab owns (tests, one-shot tools). pub fn spawn(source: Source, ctx: egui::Context) -> Loader { + Self::spawn_in(source, ctx, &crate::jobs::Spawner::default()) + } + + /// A loader whose thread is one of a tab's: counted in `jobs` until it + /// has ended (jobs.rs INVARIANT 1). + pub fn spawn_in(source: Source, ctx: egui::Context, jobs: &crate::jobs::Spawner) -> Loader { + let ticket = jobs.ticket("books-loader", crate::jobs::Hold::Free); + let presence: PresenceSlot = Arc::default(); + let thread_presence = presence.clone(); let (tx, rx) = channel(); let (wake, events) = channel(); let gone = Arc::new(std::sync::atomic::AtomicBool::new(false)); let ended = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let attempts = Arc::new(Probe::default()); + let thread_attempts = attempts.clone(); let stop = gone.clone(); let ends = Ends(ended.clone()); let wake_to_watcher = wake.clone(); std::thread::Builder::new() .name("books-loader".into()) .spawn(move || { + // Dropped last: the thread has let go of everything. + let _ticket = ticket; let _ends = ends; - run(source, ctx, tx, &stop, wake_to_watcher, events) + run( + source, + ctx, + tx, + &stop, + &thread_presence, + &thread_attempts, + wake_to_watcher, + events, + ) }) .expect("spawn loader"); Loader { rx, gone, + presence, wake, ended, + attempts, } } @@ -116,7 +183,7 @@ impl Loader { /// A handle that outlives the loader and says when its thread ended. pub fn watch(&self) -> LoaderWatch { - LoaderWatch(self.ended.clone()) + LoaderWatch(self.ended.clone(), self.attempts.clone()) } } @@ -167,11 +234,14 @@ pub fn settings(snap: &Snapshot) -> BooksSettings { ) } +#[allow(clippy::too_many_arguments)] fn run( source: Source, ctx: egui::Context, tx: Sender, gone: &std::sync::atomic::AtomicBool, + presence: &PresenceSlot, + attempts: &Probe, ev_tx: Sender<()>, ev_rx: Receiver<()>, ) { @@ -180,20 +250,40 @@ fn run( let _ = tx.send(u); ctx.request_repaint(); }; + // Gone is looked at before every try and between the phases of a load + // (the load itself, the picture built from it, the send): a tab closed + // while the books can't be read costs no further load. let mut snap = loop { + if gone() { + return; + } + attempts + .attempts + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); match Snapshot::load(&source.data_dir) { Ok(s) => break s, Err(e) => { - send(Update::Error(problem(&e, || { - format!("Can't read the books in {}", source.data_dir.display()) - }))); if gone() { return; } - std::thread::sleep(Duration::from_secs(2)); + send(Update::Error(problem(&e, || { + format!("Can't read the books in {}", source.data_dir.display()) + }))); + // Woken at once by the loader's drop, not at the next try. + attempts + .waiting + .store(true, std::sync::atomic::Ordering::SeqCst); + let _ = ev_rx.recv_timeout(Duration::from_secs(2)); + attempts + .waiting + .store(false, std::sync::atomic::Ordering::SeqCst); + while ev_rx.try_recv().is_ok() {} } } }; + if gone() { + return; + } let mut verified: HashSet = HashSet::new(); // Build the picture; also return the database check it was built with. let mut build = |snap: &Snapshot, prev: Option| -> (Update, ledger_store::DiskCheck) { @@ -209,6 +299,9 @@ fn run( }; let (first, disk) = build(&snap, None); let mut last_disk = Some(disk); + if gone() { + return; + } send(first); // Requests to show something: apply new ones, and on start one made in @@ -245,7 +338,6 @@ fn run( // held there while it runs (ledger_store::ops INVARIANT 3). let ops = ledger_store::ops::ops_dir(&source.data_dir); let mut ops_watched = false; - let mut presence: Option = None; let mut look_at_ops = |watcher: &mut Option| { if !ops_watched && ops.is_dir() @@ -253,10 +345,17 @@ fn run( { ops_watched = w.watch(&ops, RecursiveMode::NonRecursive).is_ok(); } - if presence.is_none() { - presence = ledger_store::ops::Presence::hold(&source.data_dir); + // Taken under the slot's lock and only while not gone: the + // loader's drop sets `gone` and then empties the slot, so a + // presence is never taken after a tab closed. + let mut held = presence.lock().unwrap_or_else(|e| e.into_inner()); + if held.is_none() && !gone() { + *held = ledger_store::ops::Presence::hold(&source.data_dir); } }; + if gone() { + return; + } look_at_ops(&mut watcher); let day_now = |snap: &Snapshot| today(&source, &settings(snap)); let mut day = day_now(&snap); @@ -272,6 +371,9 @@ fn run( } Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => { + if gone() { + return; + } std::thread::sleep(Duration::from_secs(3)); } } @@ -289,6 +391,9 @@ fn run( continue; } }; + if gone() { + return; + } look_at_ops(&mut watcher); let new_day = day_now(&snap); // The writer journals first and updates its database right after: @@ -302,8 +407,14 @@ fn run( day = new_day; let (update, disk) = build(&snap, grew.then_some(before)); last_disk = Some(disk); + if gone() { + return; + } send(update); } + if gone() { + return; + } check_show(&send); } } diff --git a/crates/ledger-gui/src/dock.rs b/crates/ledger-gui/src/dock.rs index ee02a715..1fa7600b 100644 --- a/crates/ledger-gui/src/dock.rs +++ b/crates/ledger-gui/src/dock.rs @@ -30,6 +30,23 @@ //! 7. Offered only where it has been checked to work (Linux and macOS): //! a ConPTY agent on Windows must pass the four checks (it starts, //! `/login` works, resize redraws, Ctrl-C reaches it) before it is. +//! 8. The agent belongs to its tab. The start (finding the agent and +//! making its books home, off the UI thread) is one of the tab's +//! threads (jobs.rs) and is told to stop with it; the child process +//! is started only by a tab that is shown, on the UI thread, once +//! the start's answer is in, so a tab closed mid-start starts none. +//! A session dropped (its tab closed, the agent restarted) is shut +//! down, its child hung up on (SIGHUP) and reaped, its terminal +//! closed; one that has not gone [`AGENT_GRACE`] later is killed +//! (SIGKILL, that pid alone, which this dock started) and reaped. +//! The reaping is a thread of the tab's, so the tab can say when +//! nothing of its agent is left (`CompanyView::jobs_watch`). +//! 9. The panel's height, and whether the dock is open by default, are +//! the app's, not a tab's: one layout for the assistant dock in +//! every tab. egui keys a panel's size by its id as given, `push_id` +//! scoping notwithstanding, so the panel's raw ids ("dock-open", +//! "dock-closed") are the one place the tabs share; that is the +//! rule, said and tested (`tests/tabs.rs`). //! ``` use crate::owner::{Agent, AgentStart, Installer, Owner}; @@ -133,8 +150,65 @@ pub struct Session { cells: Cells, exited: Arc, title: Arc>, + /// The child's process id (this session started it). + pid: u32, + /// Waits for the event loop's thread to end and drops what it returns, + /// the PTY with it (which hangs up on the child and reaps it). + end: Option>, + /// The session's count in its tab's threads, until it is reaped. + ticket: Option, } +/// How long a dropped session's child has to end after the hang-up before +/// it is killed (INVARIANT 8). +pub const AGENT_GRACE: std::time::Duration = std::time::Duration::from_secs(2); + +/// End a dropped session's child: wait for its hang-up to be answered, +/// kill it if it is not within [`AGENT_GRACE`], and reap it (INVARIANT 8). +fn reap(end: Box, pid: u32, ticket: Option) { + let work = move || { + let _ticket = ticket; + let (done_tx, done_rx) = std::sync::mpsc::channel::<()>(); + // The hang-up and the wait for the child are the PTY's drop: it + // blocks for as long as the child does not end. + let dropper = std::thread::Builder::new() + .name("dock-pty-drop".into()) + .spawn(move || { + end(); + let _ = done_tx.send(()); + }); + let Ok(dropper) = dropper else { + return; + }; + if done_rx.recv_timeout(AGENT_GRACE).is_err() { + kill(pid); + } + let _ = dropper.join(); + }; + // Without a thread to do it on, it is not done at all (the process is + // ending, or the system is out of threads): the PTY's own drop at + // thread end still hangs up. + let _ = std::thread::Builder::new() + .name("dock-reaper".into()) + .spawn(work); +} + +/// SIGKILL the child this dock started and has hung up on. +#[cfg(unix)] +fn kill(pid: u32) { + if let Ok(pid) = libc::pid_t::try_from(pid) { + // SAFETY: a plain signal to the pid of a child this process + // started and has not yet reaped (its PTY's drop is still + // waiting for it). + unsafe { + libc::kill(pid, libc::SIGKILL); + } + } +} + +#[cfg(not(unix))] +fn kill(_pid: u32) {} + impl Session { /// Run `program args` in `dir` with `env` added, on a terminal of `cells`; /// `wake` is called when there is something new to draw. @@ -145,6 +219,7 @@ impl Session { env: &[(String, String)], cells: Cells, wake: Arc, + jobs: &crate::jobs::Spawner, ) -> Result { let window = WindowSize { num_lines: cells.rows, @@ -163,7 +238,9 @@ impl Session { #[cfg(windows)] escape_args: true, }; + let ticket = jobs.ticket("dock agent", crate::jobs::Hold::Free); let pty = tty::new(&options, window, 0).map_err(|e| e.to_string())?; + let pid = pty.child().id(); let exited = Arc::new(AtomicBool::new(false)); let to_pty = Arc::new(Mutex::new(None)); let size = Arc::new(Mutex::new(window)); @@ -184,8 +261,9 @@ impl Session { EventLoop::new(term.clone(), proxy, pty, true, false).map_err(|e| e.to_string())?; let sender = event_loop.channel(); *to_pty.lock().unwrap_or_else(|e| e.into_inner()) = Some(sender.clone()); - // Its thread ends on Shutdown, and its terminal's child with it. - drop(event_loop.spawn()); + // Its thread ends on Shutdown, and its terminal's child with it + // (its drop, reaped by `reap`). + let handle = event_loop.spawn(); Ok(Session { term, to_pty: sender, @@ -193,6 +271,9 @@ impl Session { cells, exited, title, + pid, + end: Some(Box::new(move || drop(handle.join()))), + ticket: Some(ticket), }) } @@ -254,6 +335,9 @@ impl Session { impl Drop for Session { fn drop(&mut self) { let _ = self.to_pty.send(Msg::Shutdown); + if let Some(end) = self.end.take() { + reap(end, self.pid, self.ticket.take()); + } } } @@ -522,19 +606,43 @@ impl Dock { /// Start (or restart) the agent for `book`: found and its books home /// made off the UI thread, then run. - fn start(&mut self, ctx: &egui::Context, owner: &Arc, book: &str) { + fn start( + &mut self, + ctx: &egui::Context, + owner: &Arc, + book: &str, + jobs: &crate::jobs::Spawner, + ) { let (tx, rx) = channel(); let (o, agent, b, ctx) = (owner.clone(), self.agent, book.to_string(), ctx.clone()); - std::thread::spawn(move || { - let _ = tx.send(o.agent_start(agent, &b)); + let started = jobs.spawn("agent start", crate::jobs::Hold::Free, move |stop| { + if stop.requested() { + return; + } + let answer = o.agent_start(agent, &b); + // Its tab closed meanwhile: the answer is nobody's. + if stop.requested() { + return; + } + let _ = tx.send(answer); ctx.request_repaint(); }); - self.state = State::Starting(rx); + self.state = if started { + State::Starting(rx) + } else { + State::Failed("the system gave no thread to start it".into()) + }; self.book = Some(book.to_string()); } /// The panel along the bottom of the window, for `book`'s agent. - pub fn show(&mut self, ui: &mut Ui, owner: &Arc, book: &str) { + pub fn show( + &mut self, + ui: &mut Ui, + owner: &Arc, + book: &str, + jobs: &crate::jobs::Spawner, + ) { let p = crate::theme::pal(ui.ctx()); // Another book is shown: its own agent, not the last one's. if self.book.as_deref().is_some_and(|b| b != book) { @@ -565,6 +673,7 @@ impl Dock { rows: 24, }, wake, + jobs, ) { Ok(s) => { self.focused = true; @@ -578,7 +687,7 @@ impl Dock { }; } if self.open && matches!(self.state, State::Idle) { - self.start(ui.ctx(), owner, book); + self.start(ui.ctx(), owner, book, jobs); } let header = 34.0; let panel = // Its own id open and closed: a size is remembered for each. @@ -600,7 +709,7 @@ impl Dock { if self.open { ui.set_min_height(ui.available_height()); } - self.header(ui, owner, book); + self.header(ui, owner, book, jobs); if !self.open { return; } @@ -609,7 +718,13 @@ impl Dock { }); } - fn header(&mut self, ui: &mut Ui, owner: &Arc, book: &str) { + fn header( + &mut self, + ui: &mut Ui, + owner: &Arc, + book: &str, + jobs: &crate::jobs::Spawner, + ) { let p = crate::theme::pal(ui.ctx()); let mut restart = false; ui.horizontal(|ui| { @@ -682,7 +797,7 @@ impl Dock { }); if restart { self.state = State::Idle; - self.start(ui.ctx(), owner, book); + self.start(ui.ctx(), owner, book, jobs); } } diff --git a/crates/ledger-gui/src/jobs.rs b/crates/ledger-gui/src/jobs.rs new file mode 100644 index 00000000..0ab26449 --- /dev/null +++ b/crates/ledger-gui/src/jobs.rs @@ -0,0 +1,322 @@ +//! One owner for every background thread a tab starts. +//! +//! ```text +//! GOAL: a tab's threads (its loader, its receipts' workers, an export, an +//! owner's job, the dock's start and its agent's reaper) have one +//! owner that can tell them all to stop when the tab closes, and say +//! when every one of them has ended; and a job that must not be cut +//! off (an owner's change to the books) holds the tab and the window +//! open until it is done. +//! SOURCE: plan/p15-app-and-relay.md 3.2 (closing a tab ends what the tab +//! started); WB-GUI-2 (the viewer never abandons a change to the +//! books). +//! INVARIANTS: +//! 1. Every thread started through a [`Spawner`] is counted from before +//! it starts until it has ended, however it ends (a panic too): the +//! count is its [`Ticket`], dropped last. +//! 2. [`Jobs`] is dropped (or [`Jobs::stop`]ped) with its tab: every +//! [`Stop`] it handed out then says so, for good. A thread checks it +//! at its phase boundaries and between files, and stops there. +//! 3. A [`Watch`] outlives the tab and says, on a condition and not by +//! looking now and then, when no thread of the tab is left +//! ([`Watch::wait_ended`]). +//! 4. A thread started with [`Hold::Keep`] is one the tab's close +//! control and the window's close are held for: [`Jobs::holding`] +//! says what is running, in the words the close control shows. +//! ``` + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +/// Whether a running thread may be cut off. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Hold { + /// It may: it is told to stop when its tab closes. + Free, + /// It may not: the tab and the window stay open until it ends. The + /// words say what is running ("Restoring these books: wait for it + /// to finish"). + Keep(String), +} + +struct Live { + id: u64, + name: String, + hold: Hold, +} + +#[derive(Default)] +struct Table { + next: u64, + live: Vec, +} + +struct Shared { + stop: AtomicBool, + table: Mutex, + ended: Condvar, +} + +impl Shared { + fn new() -> Arc { + Arc::new(Shared { + stop: AtomicBool::new(false), + table: Mutex::new(Table::default()), + ended: Condvar::new(), + }) + } + + fn table(&self) -> MutexGuard<'_, Table> { + self.table.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// A tab's threads, and the means to stop them. Dropping it tells every +/// thread to stop (INVARIANT 2). +pub struct Jobs(Spawner); + +/// A handle for starting threads in a tab's [`Jobs`] (cloneable; it does +/// not stop anything when dropped). +#[derive(Clone)] +pub struct Spawner(Arc); + +/// Tells a thread to stop (INVARIANT 2). +#[derive(Clone)] +pub struct Stop(Arc, Option>); + +/// The count of one thread: held from before it starts to after it ends. +pub struct Ticket { + shared: Arc, + id: u64, +} + +/// Says when a tab's threads have ended, after the tab is gone. +#[derive(Clone)] +pub struct Watch(Arc); + +impl Default for Jobs { + fn default() -> Self { + Self::new() + } +} + +impl Jobs { + pub fn new() -> Jobs { + Jobs(Spawner(Shared::new())) + } + + /// A handle to start threads with. + pub fn spawner(&self) -> Spawner { + self.0.clone() + } + + /// Tell every thread to stop, now and for good. + pub fn stop(&self) { + self.0.0.stop.store(true, Ordering::SeqCst); + } + + /// A handle that outlives the tab and says when its threads ended. + pub fn watch(&self) -> Watch { + Watch(self.0.0.clone()) + } + + /// The names of the threads running now. + pub fn running(&self) -> Vec { + self.watch().running() + } + + /// What the tab is held open for, if a [`Hold::Keep`] thread runs + /// (INVARIANT 4): its words. + pub fn holding(&self) -> Option { + self.0.holding() + } +} + +impl Drop for Jobs { + fn drop(&mut self) { + self.stop(); + } +} + +impl Default for Spawner { + /// A handle to a registry of its own that nothing owns: nothing ever + /// tells its threads to stop (a menu made outside a tab, in tests). + fn default() -> Self { + Spawner(Shared::new()) + } +} + +impl Spawner { + /// The stop signal of this registry. + pub fn stop_signal(&self) -> Stop { + Stop(self.0.clone(), None) + } + + /// Count a thread to be started; the count ends when the ticket is + /// dropped. + pub fn ticket(&self, name: &str, hold: Hold) -> Ticket { + let mut table = self.0.table(); + let id = table.next; + table.next += 1; + table.live.push(Live { + id, + name: name.to_string(), + hold, + }); + Ticket { + shared: self.0.clone(), + id, + } + } + + /// Run `work` on a thread of its own, counted (INVARIANT 1). It is + /// handed the stop signal to check at its phase boundaries. False when + /// the system refused the thread (nothing runs, nothing is counted). + pub fn spawn(&self, name: &str, hold: Hold, work: impl FnOnce(&Stop) + Send + 'static) -> bool { + let ticket = self.ticket(name, hold); + let stop = self.stop_signal(); + std::thread::Builder::new() + .name(name.to_string()) + .spawn(move || { + // Dropped last, whatever happens in `work`. + let _ticket = ticket; + work(&stop); + }) + .is_ok() + } + + /// What is held open for, if a [`Hold::Keep`] thread runs. + pub fn holding(&self) -> Option { + self.0.table().live.iter().find_map(|l| match &l.hold { + Hold::Keep(words) => Some(words.clone()), + Hold::Free => None, + }) + } +} + +impl Stop { + /// Whether the tab asked for its threads to stop. + pub fn requested(&self) -> bool { + if self.0.stop.load(Ordering::SeqCst) { + return true; + } + // A signal that trips after so many looks (tests). + self.1.as_ref().is_some_and(|left| { + left.try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) + .is_err() + }) + } + + /// A signal that is not given until it has been looked at `looks` + /// times, and is given at the next (tests: a job's every phase + /// boundary, one after another). + pub fn given_after(looks: usize) -> Stop { + Stop( + Shared::new(), + Some(Arc::new(std::sync::atomic::AtomicUsize::new(looks))), + ) + } + + /// A signal already given (tests of what a thread does once told to + /// stop). + pub fn given() -> Stop { + let shared = Shared::new(); + shared.stop.store(true, Ordering::SeqCst); + Stop(shared, None) + } + + /// A signal never given (what runs outside a tab). + pub fn never() -> Stop { + Stop(Shared::new(), None) + } +} + +impl Drop for Ticket { + fn drop(&mut self) { + let mut table = self.shared.table(); + table.live.retain(|l| l.id != self.id); + drop(table); + self.shared.ended.notify_all(); + } +} + +impl Watch { + /// The names of the threads running now. + pub fn running(&self) -> Vec { + self.0.table().live.iter().map(|l| l.name.clone()).collect() + } + + /// Whether every thread has ended. + pub fn ended(&self) -> bool { + self.0.table().live.is_empty() + } + + /// Wait until every thread has ended, for at most `limit` (a failure + /// guard, never a stand-in for the other side getting there): whether + /// they have. + pub fn wait_ended(&self, limit: Duration) -> bool { + let end = Instant::now() + limit; + let mut table = self.0.table(); + while !table.live.is_empty() { + let Some(left) = end.checked_duration_since(Instant::now()) else { + return false; + }; + table = self + .0 + .ended + .wait_timeout(table, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_thread_is_counted_until_it_has_ended_and_stop_reaches_it() { + let jobs = Jobs::new(); + let watch = jobs.watch(); + let (go_tx, go_rx) = std::sync::mpsc::channel::<()>(); + let (seen_tx, seen_rx) = std::sync::mpsc::channel::(); + assert!(jobs.spawner().spawn("w", Hold::Free, move |stop| { + let _ = go_rx.recv(); + let _ = seen_tx.send(stop.requested()); + })); + assert_eq!(watch.running(), ["w"]); + assert!(!watch.ended()); + drop(jobs); + go_tx.send(()).unwrap(); + assert!(seen_rx.recv().unwrap(), "dropping the jobs says stop"); + assert!(watch.wait_ended(Duration::from_secs(30))); + assert!(watch.running().is_empty()); + } + + #[test] + fn a_kept_thread_is_what_the_tab_is_held_for() { + let jobs = Jobs::new(); + let free = jobs.spawner().ticket("free", Hold::Free); + assert_eq!(jobs.holding(), None); + let keep = jobs + .spawner() + .ticket("restore", Hold::Keep("Restoring".into())); + assert_eq!(jobs.holding().as_deref(), Some("Restoring")); + drop(keep); + assert_eq!(jobs.holding(), None); + drop(free); + assert!(jobs.watch().ended()); + } + + #[test] + fn a_panic_still_ends_the_count() { + let jobs = Jobs::new(); + let watch = jobs.watch(); + jobs.spawner() + .spawn("boom", Hold::Free, |_| panic!("on purpose")); + assert!(watch.wait_ended(Duration::from_secs(30))); + } +} diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index 1ae01eb4..3851f100 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -13,6 +13,7 @@ pub mod demo; pub mod dock; pub mod export; pub mod fmt; +pub mod jobs; pub mod menu; pub mod nav; pub mod owner; diff --git a/crates/ledger-gui/src/menu.rs b/crates/ledger-gui/src/menu.rs index df799971..f97b4213 100644 --- a/crates/ledger-gui/src/menu.rs +++ b/crates/ledger-gui/src/menu.rs @@ -17,6 +17,16 @@ //! missing TIN never stops the file: the package lists the gaps. //! 3. The file is saved as a new file in Downloads (export::save), never //! over one, off the UI thread; what came of it is shown. +//! 4. An export belongs to its tab: closing the tab, with no question, +//! tells the job to stop (jobs.rs). It checks at its phase +//! boundaries (before and after the books are read, after the file +//! is built, and just before it is saved) and stops there, saving +//! nothing: the save is one atomic write of a new file +//! (`ledger_store::saving`: written aside whole and linked in), so a +//! file is whole or is not there, and one that a stop reaches +//! too late to prevent (it came after the last check) is removed +//! again, being the job's own new file. What the builder +//! (`ledger_package`) does inside one call is not interrupted. //! ``` use crate::books::Books; @@ -35,9 +45,19 @@ pub type Done = Result<(PathBuf, Option), String>; pub struct Menu { job: Option<(String, Receiver)>, done: Option<(String, Done)>, + /// The tab's threads: the job is one of them (INVARIANT 4). + jobs: crate::jobs::Spawner, } impl Menu { + /// A menu whose jobs are threads of a tab. + pub fn in_tab(jobs: crate::jobs::Spawner) -> Self { + Self { + jobs, + ..Default::default() + } + } + /// The menu button, its items, and a note of the last job's outcome. pub fn ui(&mut self, ui: &mut Ui, books: &Arc, compact: bool) { let p = crate::theme::pal(ui.ctx()); @@ -117,13 +137,30 @@ impl Menu { } fn start(&mut self, ctx: &egui::Context, books: Arc, job: Job) { - let (tx, rx) = channel(); let what = job.label(); + self.start_with(ctx, what, Box::new(move |stop| job.run_until(&books, stop))); + } + + /// Run `work` as an export job: off the UI thread, one of the tab's + /// threads, told to stop with the tab (INVARIANT 4). + pub fn start_with( + &mut self, + ctx: &egui::Context, + what: String, + work: Box Done + Send>, + ) { + let (tx, rx) = channel(); let ctx = ctx.clone(); - std::thread::spawn(move || { - let _ = tx.send(job.run(&books)); - ctx.request_repaint(); - }); + let started = self + .jobs + .spawn("export", crate::jobs::Hold::Free, move |stop| { + let _ = tx.send(work(stop)); + ctx.request_repaint(); + }); + if !started { + self.done = Some((what, Err("the system gave no thread for it".into()))); + return; + } self.job = Some((what, rx)); self.done = None; } @@ -148,7 +185,20 @@ impl Job { /// Make the file and save it (INVARIANTS 1-3). pub fn run(self, books: &Books) -> Done { + self.run_until(books, &crate::jobs::Stop::never()) + } + + /// [`Self::run`], stopping at its phase boundaries when `stop` is + /// given, saving nothing (INVARIANT 4). + pub fn run_until(self, books: &Books, stop: &crate::jobs::Stop) -> Done { + let stopped = || -> Done { Err("stopped: its tab was closed".into()) }; + if stop.requested() { + return stopped(); + } let snap = ledger_store::Snapshot::load(&books.data_dir).map_err(|e| e.to_string())?; + if stop.requested() { + return stopped(); + } let ledger = snap.ledger(); // The settings the rest of the viewer shows, read as the server // reads them (data::settings). @@ -176,8 +226,17 @@ impl Job { tins: Some(&tin), }, )?; + if stop.requested() { + return stopped(); + } let (stem, ext) = crate::export::split_name(&p.file_name); let path = crate::export::save(stem, ext, &p.zip)?; + if stop.requested() { + // Reached too late to stop the write: the new file it + // made is the job's own, and goes. + let _ = std::fs::remove_file(&path); + return stopped(); + } let mut notes = Vec::new(); if !p.tin_gaps.is_empty() { notes.push(format!( @@ -205,8 +264,15 @@ impl Job { )?; let csv = ledger_package::vendor_1099_csv(&w, true); let name = ledger_package::vendor_1099_csv_name(year, true); + if stop.requested() { + return stopped(); + } let (stem, ext) = crate::export::split_name(&name); let path = crate::export::save(stem, ext, csv.as_bytes())?; + if stop.requested() { + let _ = std::fs::remove_file(&path); + return stopped(); + } let gaps = w .lines .iter() diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 518614dc..b5b45019 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -29,6 +29,17 @@ //! owner's `upgrade_format` (the server checks it; nothing here //! does). "Not now" changes nothing; a refusal (a wrong passphrase) //! is said in the dialog, which stays. +//! 6. An action that changes or replaces the books, their format or +//! what the owner holds (restore, the format upgrade, new books, +//! connect, close the books, check for updates, update) is never +//! abandoned: while one runs, its tab's close control is off, with +//! the words of what is running ("Restoring these books: wait for it +//! to finish"), and the window's close is held (app.rs); its result +//! is shown in that tab when it ends. A read-only one (back up now, +//! the restore's check of a backup) is stopped with the tab: it does +//! not start once the tab has closed, and what it sends after is +//! dropped (a request the books server already has it finishes: the +//! viewer only reads its answer). //! ``` use crate::books::Books; @@ -231,6 +242,31 @@ pub fn book_id(books: &Books) -> Option { type Outcome = Result, String>; +/// What a job does to the books (INVARIANT 6). +#[derive(Clone, Copy)] +enum Effect { + /// It only reads: stopped with its tab. + Reads, + /// It changes something and is never abandoned; the words say what is + /// running ("Restoring these books"). + Changes(&'static str), +} + +impl Effect { + fn hold(self) -> crate::jobs::Hold { + match self { + Effect::Reads => crate::jobs::Hold::Free, + Effect::Changes(what) => { + crate::jobs::Hold::Keep(format!("{what}: wait for it to finish")) + } + } + } +} + +/// A job to run off the UI thread: what it is called, what it does to the +/// books, and the work. +type Start = (String, Effect, Box Outcome + Send>); + /// A dialog open over the viewer. #[derive(Default)] enum Dialog { @@ -323,16 +359,20 @@ pub struct OwnerMenu { /// The update waiting, as last read, and when (re-read every few /// seconds and after any job). update: Option<(std::time::Instant, Option)>, + /// The tab's threads: every job is one of them (INVARIANT 6). + jobs: crate::jobs::Spawner, } /// How long a reading of the waiting update is kept. const UPDATE_LOOK: std::time::Duration = std::time::Duration::from_secs(5); impl OwnerMenu { - /// A menu whose ids belong to the view `scope`. - pub fn scoped(scope: egui::Id) -> Self { + /// A menu whose ids belong to the view `scope`, and whose jobs are + /// threads of that view (`jobs`). + pub fn scoped(scope: egui::Id, jobs: crate::jobs::Spawner) -> Self { Self { scope: Some(scope), + jobs, ..Default::default() } } @@ -411,7 +451,14 @@ impl OwnerMenu { }); }); if let Some(work) = start { - self.start(ui.ctx(), "Update".into(), work); + self.start( + ui.ctx(), + ( + "Update".into(), + Effect::Changes("Updating wanderbooks"), + work, + ), + ); } } let Some(upgrade) = books.format_upgrade.clone() else { @@ -500,7 +547,7 @@ impl OwnerMenu { } let busy = self.job.is_some(); let waiting = self.update_waiting(ui.ctx(), &owner); - let mut start: Option<(String, Box Outcome + Send>)> = None; + let mut start: Option = None; let response = ui .add_enabled_ui(!busy, |ui| { egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| { @@ -511,7 +558,11 @@ impl OwnerMenu { .clicked() { let (o, b) = (owner.clone(), book.clone()); - start = Some(("Back up now".into(), Box::new(move || o.back_up_now(&b)))); + start = Some(( + "Back up now".into(), + Effect::Reads, + Box::new(move || o.back_up_now(&b)), + )); } if ui .button(format!("{} Restore…", icon::CLOCK_COUNTER_CLOCKWISE)) @@ -543,6 +594,10 @@ impl OwnerMenu { let (o, b) = (owner.clone(), book.clone()); start = Some(( format!("Connect {}", agent.label()), + Effect::Changes(match agent { + Agent::Claude => "Connecting Claude Code to these books", + Agent::Codex => "Connecting Codex to these books", + }), Box::new(move || o.connect(agent, &b)), )); } @@ -564,7 +619,11 @@ impl OwnerMenu { .clicked() { let o = owner.clone(); - start = Some(("Check for updates".into(), Box::new(move || o.check_for_updates()))); + start = Some(( + "Check for updates".into(), + Effect::Changes("Checking for updates"), + Box::new(move || o.check_for_updates()), + )); } if let Some(u) = &waiting && ui @@ -573,7 +632,11 @@ impl OwnerMenu { .clicked() { let o = owner.clone(); - start = Some(("Update".into(), Box::new(move || o.apply_update()))); + start = Some(( + "Update".into(), + Effect::Changes("Updating wanderbooks"), + Box::new(move || o.apply_update()), + )); } ui.separator(); if ui @@ -586,8 +649,8 @@ impl OwnerMenu { }) }) .inner; - if let Some((what, work)) = start { - self.start(ui.ctx(), what, work); + if let Some(start) = start { + self.start(ui.ctx(), start); } self.dialogs(ui.ctx(), &owner, &book); let said = if self.job.is_some() { @@ -609,18 +672,21 @@ impl OwnerMenu { } } - fn start( - &mut self, - ctx: &egui::Context, - what: String, - work: Box Outcome + Send>, - ) { + fn start(&mut self, ctx: &egui::Context, (what, effect, work): Start) { let (tx, rx) = channel(); let ctx = ctx.clone(); - std::thread::spawn(move || { + let started = self.jobs.spawn(&what.clone(), effect.hold(), move |stop| { + // A read-only job of a tab that has closed is not begun. + if matches!(effect, Effect::Reads) && stop.requested() { + return; + } let _ = tx.send(work()); ctx.request_repaint(); }); + if !started { + self.done = Some((what, Err("the system gave no thread for it".into()))); + return; + } self.job = Some((what, rx)); self.done = None; } @@ -628,7 +694,8 @@ impl OwnerMenu { /// The open dialog, if any, for the books `book`. fn dialogs(&mut self, ctx: &egui::Context, owner: &Arc, book: &str) { let mut close = false; - let mut run: Option<(String, Box Outcome + Send>)> = None; + let mut run: Option = None; + let jobs = self.jobs.clone(); match &mut self.dialog { Dialog::None => {} Dialog::Upgrade(form) => { @@ -660,6 +727,7 @@ impl OwnerMenu { form, owner, book, + &jobs, &mut close, ); } @@ -671,7 +739,11 @@ impl OwnerMenu { ui.horizontal(|ui| { if ui.button("Close the books").clicked() { let o = owner.clone(); - run = Some(("Close the books".into(), Box::new(move || o.close_books().map(|l| vec![l])))); + run = Some(( + "Close the books".into(), + Effect::Changes("Closing the books"), + Box::new(move || o.close_books().map(|l| vec![l])), + )); close = true; } if ui.button("Cancel").clicked() { @@ -697,6 +769,7 @@ impl OwnerMenu { let (o, i, c) = (owner.clone(), id.clone(), currency.clone()); run = Some(( "New books".into(), + Effect::Changes("Making new books"), Box::new(move || o.new_books(&i, &c).map(|l| vec![l])), )); close = true; @@ -780,13 +853,27 @@ impl OwnerMenu { let (o, s, r) = (owner.clone(), form.source.clone(), form.replace); let id = Some(form.id.trim().to_string()).filter(|i| !i.is_empty()); let ctx = ui.ctx().clone(); - std::thread::spawn(move || { - let _ = tx.send(o.plan_restore(&s, id, r)); - ctx.request_repaint(); - }); - let asked = (form.source.clone(), form.id.clone(), form.replace); - form.planning = Some((rx, asked)); - form.problem = None; + // Only reads the backup: stopped with its tab. + let started = jobs.spawn( + "restore check", + crate::jobs::Hold::Free, + move |stop| { + if stop.requested() { + return; + } + let _ = tx.send(o.plan_restore(&s, id, r)); + ctx.request_repaint(); + }, + ); + if started { + let asked = + (form.source.clone(), form.id.clone(), form.replace); + form.planning = Some((rx, asked)); + form.problem = None; + } else { + form.problem = + Some("the system gave no thread for it".into()); + } } if planning { ui.label("Checking the backup…"); @@ -795,7 +882,11 @@ impl OwnerMenu { Some(plan) => { if ui.button("Restore it").clicked() { let (o, plan) = (owner.clone(), plan.clone()); - run = Some(("Restore".into(), Box::new(move || o.restore(&plan)))); + run = Some(( + "Restore".into(), + Effect::Changes("Restoring these books"), + Box::new(move || o.restore(&plan)), + )); close = true; } } @@ -810,8 +901,8 @@ impl OwnerMenu { if close { self.dialog = Dialog::None; } - if let Some((what, work)) = run { - self.start(ctx, what, work); + if let Some(run) = run { + self.start(ctx, run); } } } @@ -824,6 +915,7 @@ fn upgrade_dialog( form: &mut UpgradeForm, owner: &Arc, book: &str, + jobs: &crate::jobs::Spawner, close: &mut bool, ) { let p = crate::theme::pal(ctx); @@ -864,15 +956,26 @@ fn upgrade_dialog( let (o, b) = (owner.clone(), book.to_string()); let (tx, rx) = channel(); let ctx = ui.ctx().clone(); - std::thread::spawn(move || { - // The window is woken however this ends (a panic - // too), once the answer, or its absence, can be seen. - let _wake = Wake(ctx); - let (tx, passphrase) = (tx, passphrase); - let _ = tx.send(o.upgrade_format(&b, &passphrase)); - }); - form.working = Some(rx); - form.problem = None; + // Changes the books' format: never abandoned (INVARIANT 6). + let started = jobs.spawn( + "format upgrade", + crate::jobs::Hold::Keep( + "Upgrading these books' format: wait for it to finish".into(), + ), + move |_| { + // The window is woken however this ends (a panic + // too), once the answer, or its absence, can be seen. + let _wake = Wake(ctx); + let (tx, passphrase) = (tx, passphrase); + let _ = tx.send(o.upgrade_format(&b, &passphrase)); + }, + ); + if started { + form.working = Some(rx); + form.problem = None; + } else { + form.problem = Some("the system gave no thread for it".into()); + } } if ui .add_enabled(!working, egui::Button::new("Not now")) diff --git a/crates/ledger-gui/src/receipts.rs b/crates/ledger-gui/src/receipts.rs index 7bf1631c..16d08af5 100644 --- a/crates/ledger-gui/src/receipts.rs +++ b/crates/ledger-gui/src/receipts.rs @@ -112,11 +112,14 @@ pub struct Receipts { } impl Receipts { - pub fn new(ctx: &Context) -> Self { + /// Receipts whose workers are threads of a tab: counted in `spawner` + /// until they have ended, which they do when this is dropped (their + /// queues' senders go) or the tab says stop (jobs.rs). + pub fn new(ctx: &Context, spawner: &crate::jobs::Spawner) -> Self { let (done_tx, done) = channel(); let workers = std::thread::available_parallelism().map_or(2, |n| n.get().clamp(2, 4)); - let jobs = workers_for(ctx, &done_tx, "receipt-render", workers); - let thumb_jobs = workers_for(ctx, &done_tx, "thumb-render", 2); + let jobs = workers_for(ctx, spawner, &done_tx, "receipt-render", workers); + let thumb_jobs = workers_for(ctx, spawner, &done_tx, "thumb-render", 2); Self { cache: HashMap::new(), thumbs: HashMap::new(), @@ -246,16 +249,23 @@ impl Receipts { /// Workers taking jobs from one queue, sending what they render to /// `done`; the queue's sender. -fn workers_for(ctx: &Context, done_tx: &Sender, name: &str, n: usize) -> Sender { +fn workers_for( + ctx: &Context, + spawner: &crate::jobs::Spawner, + done_tx: &Sender, + name: &str, + n: usize, +) -> Sender { let (jobs, job_rx) = channel::(); let job_rx = std::sync::Arc::new(std::sync::Mutex::new(job_rx)); for i in 0..n { let ctx = ctx.clone(); let job_rx = job_rx.clone(); let done_tx = done_tx.clone(); - std::thread::Builder::new() - .name(format!("{name}-{i}")) - .spawn(move || { + spawner.spawn( + &format!("{name}-{i}"), + crate::jobs::Hold::Free, + move |stop| { loop { let job = match job_rx.lock() { Ok(rx) => rx.recv(), @@ -264,13 +274,17 @@ fn workers_for(ctx: &Context, done_tx: &Sender, name: &str, n: usize) -> S let Ok(job) = job else { return; }; + // The tab is gone: what is still queued isn't rendered. + if stop.requested() { + return; + } // A file that crashes its renderer is that file's // error, not the end of the worker (and every file // queued after it). let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { match &job.thumb { - Some(dir) => render_thumb(&job, dir.as_deref()), + Some(dir) => render_thumb(&job, dir.as_deref(), stop), None => render(&job), } })) @@ -283,8 +297,8 @@ fn workers_for(ctx: &Context, done_tx: &Sender, name: &str, n: usize) -> S }); ctx.request_repaint(); } - }) - .expect("spawn renderer"); + }, + ); } jobs } @@ -297,7 +311,11 @@ fn workers_for(ctx: &Context, done_tx: &Sender, name: &str, n: usize) -> S /// A text file's thumbnail is the start of its text, kept nowhere: it is /// cheaper to read than a picture. A thumbnail that can't be kept is /// still shown. -fn render_thumb(job: &Job, dir: Option<&std::path::Path>) -> Result { +fn render_thumb( + job: &Job, + dir: Option<&std::path::Path>, + stop: &crate::jobs::Stop, +) -> Result { let bytes = BlobStore::open_read_only(&job.root) .get(&job.sha) .map_err(|e| e.to_string())?; @@ -348,7 +366,9 @@ fn render_thumb(job: &Job, dir: Option<&std::path::Path>) -> Result ColorImage { let size = [img.width() as usize, img.height() as usize]; ColorImage::from_rgba_unmultiplied(size, img.as_raw()) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::jobs::Stop; + + /// A picture in a blob store, and a thumbnail job for it. + fn picture_job(blobs: &std::path::Path, cache: &std::path::Path) -> Job { + let mut png = Vec::new(); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 40, + 30, + image::Rgba([200, 30, 30, 255]), + )) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let (sha, _) = BlobStore::open(blobs).unwrap().put(&png).unwrap(); + Job { + sha, + mime: "image/png".into(), + root: blobs.to_path_buf(), + thumb: Some(Some(cache.to_path_buf())), + generation: 0, + } + } + + /// A thumbnail is kept in the cache for a tab that is open, and not + /// written for one that has closed (the cache is shared by every tab + /// and every viewer). + #[test] + fn a_thumbnail_is_not_written_for_a_tab_that_has_closed() { + let dir = tempfile::tempdir().unwrap(); + let cache = dir.path().join("cache"); + let job = picture_job(&dir.path().join("blobs"), &cache); + let named = cache.join(format!("{}.png", job.sha)); + + // Closed: it is still drawn (the render is whole) but never kept. + let gone = render_thumb(&job, Some(&cache), &Stop::given()); + assert!(matches!(gone, Ok(Rendered::Pages(_)))); + assert!(!named.exists(), "a closed tab wrote into the shared cache"); + assert!(!cache.exists(), "a closed tab made the shared cache folder"); + + // Open: kept, as before. + let open = render_thumb(&job, Some(&cache), &Stop::never()); + assert!(matches!(open, Ok(Rendered::Pages(_)))); + assert!(named.is_file(), "an open tab's thumbnail is kept"); + } +} diff --git a/crates/ledger-gui/src/tabs.rs b/crates/ledger-gui/src/tabs.rs index 73d2335e..a3b2ce4c 100644 --- a/crates/ledger-gui/src/tabs.rs +++ b/crates/ledger-gui/src/tabs.rs @@ -46,6 +46,10 @@ //! for a state mark (drawn by a later unit, nothing now). //! 6. This only says what was asked (show, close, open); the app does //! it. +//! 7. A tab whose company has a job under way that changes its books +//! (`Tab::held`) has its close control off: disabled to assistive +//! technology, drawn faint, no click and no middle click closes it, +//! and its hover text says what is running. //! ``` use crate::theme::{self, pal}; @@ -92,6 +96,10 @@ pub struct Tab { /// What its badge's hue is chosen from: the id of its books /// ([`hue_of`]). pub hue_key: String, + /// Why the tab can't be closed now: a job that changes its books is + /// running ("Restoring these books: wait for it to finish"). Its close + /// control is off, and says so on hover. + pub held: Option, } /// The badge hue of the company whose books have id `book_id`, light or @@ -428,7 +436,7 @@ fn one_tab( close.widget_info(|| { egui::WidgetInfo::labeled( egui::WidgetType::Button, - true, + tab.held.is_none(), format!("Close {}", tab.title), ) }); @@ -507,7 +515,7 @@ fn one_tab( galley, p.text, ); - if close.hovered() { + if close.hovered() && tab.held.is_none() { painter.rect_filled(close_rect, CornerRadius::same(5), p.selected); } painter.text( @@ -515,7 +523,9 @@ fn one_tab( egui::Align2::CENTER_CENTER, icon::X, egui::FontId::proportional(12.0), - if close.hovered() || here { + if tab.held.is_some() { + p.faint + } else if close.hovered() || here { p.text } else { p.muted @@ -525,12 +535,15 @@ fn one_tab( let resp = resp.on_hover_text(&tab.detail); // The close control sits over the tab and is the one under the pointer // there: a click on it is its own, never the tab's. - if close - .on_hover_text(format!("Close {}", tab.title)) - .clicked() - || resp.middle_clicked() - { + let close_tip = match &tab.held { + Some(why) => why.clone(), + None => format!("Close {}", tab.title), + }; + let closes = close.on_hover_text(close_tip).clicked() || resp.middle_clicked(); + if closes && tab.held.is_none() { *action = Some(TabAction::Close(i)); + } else if closes { + // Held open: the click is the close control's, and does nothing. } else if resp.clicked() { *action = Some(TabAction::Show(i)); } diff --git a/crates/ledger-gui/tests/exports.rs b/crates/ledger-gui/tests/exports.rs index c536067a..684f1e02 100644 --- a/crates/ledger-gui/tests/exports.rs +++ b/crates/ledger-gui/tests/exports.rs @@ -554,3 +554,42 @@ fn the_menus_worksheet_says_which_payees_lack_a_tin() { "{note}" ); } + +/// menu.rs INVARIANT 4: an export whose tab has closed is told to stop and +/// saves nothing, at any of its phase boundaries: told before it starts, +/// after the books are read, after the file is built, or too late to stop +/// the write (the file it just made is removed). Told at none, it saves. +#[test] +fn a_stopped_export_leaves_no_file_whenever_it_is_told() { + use ledger_gui::jobs::Stop; + downloads(); + let f = root_book(); + let b = load(&f.book); + // A year of its own (the other tests save 2026's): no other test's file has its name. + let mine = || -> Vec { + saved_files() + .into_iter() + .filter(|n| n.contains("2025")) + .collect() + }; + let mut told = 0; + for looks in 0..20 { + match Job::Worksheet(2025).run_until(&b, &Stop::given_after(looks)) { + Err(why) => { + assert!(why.starts_with("stopped"), "{why}"); + assert_eq!( + mine(), + Vec::::new(), + "told after {looks} looks, the export left a file" + ); + told += 1; + } + Ok((path, _)) => { + assert_eq!(mine().len(), 1, "told too late: it saves"); + std::fs::remove_file(path).unwrap(); + break; + } + } + } + assert!(told >= 4, "its boundaries: only {told} told it to stop"); +} diff --git a/crates/ledger-gui/tests/format_upgrade.rs b/crates/ledger-gui/tests/format_upgrade.rs index ce0eb14e..2ed43663 100644 --- a/crates/ledger-gui/tests/format_upgrade.rs +++ b/crates/ledger-gui/tests/format_upgrade.rs @@ -8,7 +8,7 @@ use chrono::NaiveDate; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use ledger_core::Currency; use ledger_gui::App; use ledger_gui::books::Books; @@ -23,6 +23,55 @@ use std::sync::{Arc, Mutex, OnceLock}; const PASS: &str = "correct horse battery"; /// The passphrase on which the fake owner's worker dies, answering nothing. const DIES: &str = "the worker dies on this one"; +/// The passphrase on which the fake owner's upgrade waits for the test to +/// let it go. +const HOLDS: &str = "the upgrade waits on this one"; + +/// A latch: opened once, it stays open. +struct Latch { + open: Mutex, + changed: std::sync::Condvar, +} + +impl Latch { + const fn new() -> Latch { + Latch { + open: Mutex::new(false), + changed: std::sync::Condvar::new(), + } + } + + fn open(&self) { + *self.open.lock().unwrap_or_else(|e| e.into_inner()) = true; + self.changed.notify_all(); + } + + fn is_open(&self) -> bool { + *self.open.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Wait for it to open (the limit is a failure guard). + fn wait(&self) -> bool { + let end = std::time::Instant::now() + std::time::Duration::from_secs(120); + let mut open = self.open.lock().unwrap_or_else(|e| e.into_inner()); + while !*open { + let Some(left) = end.checked_duration_since(std::time::Instant::now()) else { + return false; + }; + open = self + .changed + .wait_timeout(open, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + true + } +} + +/// Said by the owner when the held upgrade has begun; opened by the test +/// to let it end. +static HELD_BEGUN: Latch = Latch::new(); +static HELD_LET_GO: Latch = Latch::new(); /// An owner that says what it was asked, and takes only PASS. #[derive(Default)] @@ -55,6 +104,11 @@ impl Owner for Fake { Err("not in these tests".into()) } fn upgrade_format(&self, book: &str, passphrase: &str) -> Result, String> { + if passphrase == HOLDS { + HELD_BEGUN.open(); + assert!(HELD_LET_GO.wait(), "the test never let the upgrade go"); + return Ok(vec![format!("Upgraded the books \"{book}\".")]); + } // Slow enough to be seen at work. std::thread::sleep(std::time::Duration::from_millis(300)); // A worker that dies on the way: no answer comes back. @@ -394,3 +448,92 @@ fn screenshots() { settle(&mut h, &f, n + 1); shot(&mut h, "upgrade-done"); } + +/// owner.rs INVARIANT 6: the upgrade changes the books' format, so it is +/// never abandoned: while it runs its tab's close control is off, saying +/// so, and the window's close is cancelled with a dialog that offers only +/// to wait; when it ends the dialog goes and the result shows in the tab. +#[test] +fn an_upgrade_under_way_holds_its_tab_and_the_window_open() { + let _alone = alone(); + let _ = fake(); + let (_dir, _book, b) = books(true, true); + let mut h = harness(b); + // Nothing runs: the window's close goes through. + assert!(!close_is_cancelled(&mut h)); + type_passphrase(&mut h, HOLDS); + h.get_by_label("Upgrade").click(); + for _ in 0..600 { + h.run_steps(2); + if HELD_BEGUN.is_open() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(HELD_BEGUN.is_open(), "the owner was never asked"); + h.run_steps(3); + let words = "Upgrading these books' format: wait for it to finish"; + assert_eq!( + h.state().holding(), + [("Unnamed company".to_string(), words.to_string())] + ); + assert!( + h.get_by_role_and_label(egui::accesskit::Role::Button, "Close Unnamed company") + .accesskit_node() + .is_disabled(), + "the tab can be closed while its books' format is being upgraded" + ); + assert!( + close_is_cancelled(&mut h), + "the window's close went through" + ); + h.run_steps(3); + assert!(h.state().close_dialog_is_up()); + assert!( + h.query_by_label_contains("The books are being changed") + .is_some() + ); + assert!( + h.query_by_label_contains(&format!("Unnamed company: {words}")) + .is_some() + ); + HELD_LET_GO.open(); + for _ in 0..600 { + h.run_steps(2); + if h.state().holding().is_empty() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.run_steps(6); + assert!(h.state().holding().is_empty()); + assert!(!h.state().close_dialog_is_up()); + assert!( + h.query_by_label_contains("The books are being changed") + .is_none() + ); + assert!( + h.query_by_label_contains("Format upgrade: Upgraded the books") + .is_some(), + "the result isn't shown in the tab" + ); +} + +/// Whether the window's close, asked for now, was cancelled by the app. +fn close_is_cancelled(h: &mut Harness<'static, App>) -> bool { + h.input_mut() + .viewports + .entry(egui::ViewportId::ROOT) + .or_default() + .events + .push(egui::ViewportEvent::Close); + h.run_steps(1); + h.output() + .viewport_output + .get(&egui::ViewportId::ROOT) + .is_some_and(|v| { + v.commands + .iter() + .any(|c| matches!(c, egui::ViewportCommand::CancelClose)) + }) +} diff --git a/crates/ledger-gui/tests/live.rs b/crates/ledger-gui/tests/live.rs index dd61eab9..718e5a73 100644 --- a/crates/ledger-gui/tests/live.rs +++ b/crates/ledger-gui/tests/live.rs @@ -173,3 +173,86 @@ fn a_setting_changed_while_it_runs_is_followed() { } } } + +/// A loader whose books can't be read is told to go (its tab closed): it +/// tries no further load, however long it was to wait before the next, and +/// it ends at once (the registry says when). +#[test] +fn a_loader_whose_books_cant_be_read_tries_no_more_once_it_is_dropped() { + let dir = std::env::temp_dir().join(format!("ledger-gui-live-gone-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let _cleanup = TestDir(dir.clone()); + std::fs::create_dir_all(&dir).unwrap(); + // Books that are not there: every try fails. + let data = dir.join("not-there"); + let jobs = ledger_gui::jobs::Jobs::new(); + let loader = Loader::spawn_in( + Source { + data_dir: data, + today: NaiveDate::from_ymd_opt(2026, 10, 12), + }, + egui::Context::default(), + &jobs.spawner(), + ); + let watch = loader.watch(); + match loader.wait(Duration::from_secs(30)) { + Some(Update::Error(_)) => {} + _ => panic!("the books that aren't there didn't say so"), + } + // Dropped while it waits for its next try: waited for until it does. + let end = Instant::now() + Duration::from_secs(30); + while !watch.waiting() { + assert!(Instant::now() < end, "it never waited to try again"); + std::thread::yield_now(); + } + let tried = watch.load_attempts(); + assert_eq!(tried, 1); + drop(loader); + assert!( + jobs.watch().wait_ended(Duration::from_secs(60)), + "the loader's thread runs on: {:?}", + jobs.running() + ); + assert!(watch.ended()); + assert_eq!( + watch.load_attempts(), + tried, + "a dropped loader tried to load the books again" + ); +} + +/// The viewer's presence is let go when the loader is dropped, not when its +/// thread gets to end: nothing waits on the thread. +#[test] +fn a_dropped_loader_lets_go_of_its_presence_at_once() { + let dir = std::env::temp_dir().join(format!("ledger-gui-live-presence-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let _cleanup = TestDir(dir.clone()); + let data = dir.join("books-data"); + drop(Store::create(&data, Currency::USD).unwrap()); + ledger_store::ops::prepare(&data).unwrap(); + let loader = Loader::spawn( + Source { + data_dir: data.clone(), + today: NaiveDate::from_ymd_opt(2026, 10, 12), + }, + egui::Context::default(), + ); + assert!(matches!( + loader.wait(Duration::from_secs(30)), + Some(Update::Books(_)) + )); + let deadline = Instant::now() + Duration::from_secs(30); + while !ledger_store::ops::viewer_open(&data) { + assert!( + Instant::now() < deadline, + "the viewer never held its presence" + ); + std::thread::sleep(Duration::from_millis(5)); + } + drop(loader); + assert!( + !ledger_store::ops::viewer_open(&data), + "a dropped loader still holds the books' presence" + ); +} diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs index 626fb73e..040a20a6 100644 --- a/crates/ledger-gui/tests/tabs.rs +++ b/crates/ledger-gui/tests/tabs.rs @@ -144,6 +144,45 @@ impl World { co } + /// The key the open companies are kept under for this world's root. + fn open_key(&self) -> String { + ledger_gui::app::open_key(&self.root) + } + + fn active_key(&self) -> String { + ledger_gui::app::active_key(&self.root) + } + + /// The key `thing` of company `id` of this world is kept under. + fn kept_key(&self, id: &str, thing: &str) -> String { + ledger_gui::app::company_key(&self.root.join("books").join(id), thing) + } + + /// Preferences written with the plain names tests give them + /// (`open_companies`, `active_company`, `company..`), filed + /// as the app files them: under this world's root (app.rs INVARIANT 4). + fn filed(&self, plain: Prefs) -> Prefs { + Prefs( + plain + .0 + .into_iter() + .map(|(k, v)| { + let key = match k.as_str() { + "open_companies" => self.open_key(), + "active_company" => self.active_key(), + _ => match k.strip_prefix("company.").and_then(|r| r.split_once('.')) { + // Plain: `company..`; one already + // filed has a root before its id. + Some((id, thing)) if !thing.contains('.') => self.kept_key(id, thing), + _ => k, + }, + }; + (key, v) + }) + .collect(), + ) + } + fn source(&self, id: &str) -> Source { Source { data_dir: self @@ -195,6 +234,11 @@ fn prefs(pairs: &[(&str, &str)]) -> Prefs { /// The app as it starts from `kept`, over `world`'s data root, its first /// company the fallback. fn start(world: &World, kept: Prefs, size: egui::Vec2) -> Harness<'static, App> { + start_as_is(world, world.filed(kept), size) +} + +/// [`start`] with the preferences exactly as given (filed or not). +fn start_as_is(world: &World, kept: Prefs, size: egui::Vec2) -> Harness<'static, App> { let root = world.root.clone(); let fallback = world.source("alpha"); let mut h = Harness::builder().with_size(size).build_eframe(move |cc| { @@ -623,18 +667,34 @@ fn closing_a_tab_releases_its_lock_its_threads_and_its_agent() { assert!(alive(pid), "the agent runs"); assert_eq!(*owner.asked.lock().unwrap(), ["beta"], "beta's own owner"); - // Closed: its viewer lock is released, its loader's thread ends, its - // agent's process is gone; alpha's are as they were. + // Every thread of beta's tab is one of its registry's: the loader, the + // receipts' workers, the dock's agent (jobs.rs). + let beta_threads = h.state().views()[1].jobs_watch(); + let running = beta_threads.running(); + for name in [ + "books-loader", + "receipt-render-0", + "thumb-render-0", + "dock agent", + ] { + assert!( + running.iter().any(|n| n == name), + "{name} isn't counted among beta's threads: {running:?}" + ); + } + + // Closed: every thread of the tab ends (waited for on that condition; + // the limit is only a failure guard), and with them its viewer lock is + // released, its loader's thread has ended, its agent's process is gone; + // alpha's are as they were. close_tab(&mut h, "Beta Co"); assert_eq!(titles(&h), ["Alpha Co"]); assert_eq!(h.state().active(), Some(0)); - let end = Instant::now() + Duration::from_secs(20); - while (ledger_store::ops::viewer_open(&b.data) || !beta_loader.ended() || alive(pid)) - && Instant::now() < end - { - h.run_steps(1); - std::thread::sleep(Duration::from_millis(25)); - } + assert!( + beta_threads.wait_ended(Duration::from_secs(120)), + "a closed tab's threads run on: {:?}", + beta_threads.running() + ); assert!( !ledger_store::ops::viewer_open(&b.data), "a closed tab still holds its books' viewer lock" @@ -758,8 +818,8 @@ fn the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back() { h.run_steps(2); let mut kept = Prefs::default(); eframe::App::save(h.state_mut(), &mut kept); - assert_eq!(kept.0["open_companies"], "alpha,beta,gamma"); - assert_eq!(kept.0["active_company"], "gamma"); + assert_eq!(kept.0[&w.open_key()], "alpha,beta,gamma"); + assert_eq!(kept.0[&w.active_key()], "gamma"); // The per-app keys are as they always were. for key in ["scheme", "scheme_filter", "dark", "dock_open", "dock_agent"] { assert!( @@ -806,8 +866,8 @@ fn the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back() { )); let mut again = Prefs::default(); eframe::App::save(h.state_mut(), &mut again); - assert_eq!(again.0["open_companies"], "beta,gamma,alpha"); - assert_eq!(again.0["active_company"], "alpha"); + assert_eq!(again.0[&w.open_key()], "beta,gamma,alpha"); + assert_eq!(again.0[&w.active_key()], "alpha"); // Closing the last tab keeps a list with nothing in it, and the next // start opens the data root's first. for _ in 0..3 { @@ -817,7 +877,7 @@ fn the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back() { assert!(h.state().views().is_empty()); let mut none = Prefs::default(); eframe::App::save(h.state_mut(), &mut none); - assert_eq!(none.0["open_companies"], ""); + assert_eq!(none.0[&w.open_key()], ""); drop(h); let h = start(&w, none, egui::vec2(1280.0, 800.0)); assert_eq!(h.state().views().len(), 1); @@ -1026,14 +1086,14 @@ fn a_name_is_remembered_and_shown_in_the_plus_list_and_on_a_loading_tab() { let mut kept = Prefs::default(); eframe::App::save(h.state_mut(), &mut kept); assert_eq!( - kept.0.get("company.beta.name").map(String::as_str), + kept.0.get(&w.kept_key("beta", "name")).map(String::as_str), Some("Beta Co") ); // ...and a window started from it titles a tab whose books are not // loaded yet by name; a company with no name known by its id. let ctx = egui::Context::default(); - kept.0.remove("company.alpha.name"); - kept.0.insert("open_companies".into(), "alpha,beta".into()); + kept.0.remove(&w.kept_key("alpha", "name")); + kept.0.insert(w.open_key(), "alpha,beta".into()); let root = w.root.clone(); let fallback = w.source("alpha"); let app = App::start_with( @@ -1786,3 +1846,787 @@ fn pictures() { save(&mut h, &format!("smallest-window-two-tabs-{mode}")); } } + +// ---- 14: threads, held jobs and the window's close --------------------------- + +/// A latch: opened once, it stays open; waiters block until then. +#[derive(Default)] +struct Latch { + open: Mutex, + changed: std::sync::Condvar, +} + +impl Latch { + fn open(&self) { + *self.open.lock().unwrap() = true; + self.changed.notify_all(); + } + + fn is_open(&self) -> bool { + *self.open.lock().unwrap() + } + + /// Wait for it to open; the limit is a failure guard, never what the + /// test relies on. + fn wait(&self) -> bool { + let end = Instant::now() + Duration::from_secs(120); + let mut open = self.open.lock().unwrap(); + while !*open { + let Some(left) = end.checked_duration_since(Instant::now()) else { + return false; + }; + open = self.changed.wait_timeout(open, left).unwrap().0; + } + true + } +} + +/// An owner whose changing calls (restore, close the books), its backup +/// and its agent's start each say they were entered and then wait to be +/// let go: the test decides when they end. +struct Gated { + entered: Latch, + release: Latch, + start: Mutex>, +} + +impl Gated { + fn new() -> Arc { + Arc::new(Gated { + entered: Latch::default(), + release: Latch::default(), + start: Mutex::new(None), + }) + } + + fn block(&self) { + self.entered.open(); + assert!(self.release.wait(), "the test never let the call go"); + } +} + +impl Owner for Gated { + fn close_books(&self) -> Result { + self.block(); + Ok("The books are closing.".into()) + } + fn new_books(&self, _: &str, _: &str) -> Result { + Err("not here".into()) + } + fn back_up_now(&self, _: &str) -> Result, String> { + self.block(); + Ok(vec!["Backed up.".into()]) + } + fn plan_restore( + &self, + source: &str, + id: Option, + replace: bool, + ) -> Result { + Ok(RestorePlan { + source: source.to_string(), + id: id.unwrap_or_else(|| "alpha".into()), + replace, + head: (7, "ab".repeat(32)), + lines: vec!["The backup is whole: through event 7.".into()], + }) + } + fn restore(&self, plan: &RestorePlan) -> Result, String> { + self.block(); + Ok(vec![format!("Restored as \"{}\".", plan.id)]) + } + fn connect(&self, _: Agent, _: &str) -> Result, String> { + Err("not here".into()) + } + fn upgrade_format(&self, _: &str, _: &str) -> Result, String> { + Err("not here".into()) + } + fn agent_start(&self, _: Agent, _: &str) -> Result { + self.block(); + self.start + .lock() + .unwrap() + .clone() + .ok_or_else(|| "no agent set".to_string()) + } +} + +/// Whether the window's close, asked for now, was cancelled by the app. +fn window_close_is_cancelled(h: &mut Harness<'static, App>) -> bool { + h.input_mut() + .viewports + .entry(egui::ViewportId::ROOT) + .or_default() + .events + .push(egui::ViewportEvent::Close); + h.run_steps(1); + h.output() + .viewport_output + .get(&egui::ViewportId::ROOT) + .is_some_and(|v| { + v.commands + .iter() + .any(|c| matches!(c, egui::ViewportCommand::CancelClose)) + }) +} + +/// Whether the close control of the tab named `name` is disabled for +/// assistive technology. +fn close_is_off(h: &Harness<'_, App>, name: &str) -> bool { + h.get_by_role_and_label(Role::Button, &format!("Close {name}")) + .accesskit_node() + .is_disabled() +} + +/// Through the front tab's Books menu to a restore that has been checked +/// and is asked for: `Restore it` clicked. +fn ask_for_a_restore(h: &mut Harness<'static, App>) { + let page_fields = h.query_all_by_role(Role::TextInput).count(); + h.get_by_label_contains(" Books").click(); + h.run_steps(3); + h.get_by_label_contains("Restore…").click(); + h.run_steps(3); + h.get_all_by_role(Role::TextInput) + .nth(page_fields) + .unwrap() + .focus(); + h.run_steps(2); + h.get_all_by_role(Role::TextInput) + .nth(page_fields) + .unwrap() + .type_text("/media/disk/alpha.git"); + h.run_steps(2); + h.get_by_label("Check it").click(); + let end = Instant::now() + Duration::from_secs(60); + while h.query_by_label("Restore it").is_none() { + assert!(Instant::now() < end, "the backup was never checked"); + h.run_steps(2); + std::thread::sleep(Duration::from_millis(10)); + } + h.run_steps(3); + h.get_by_label("Restore it").click(); + h.run_steps(2); +} + +#[test] +fn a_restore_under_way_holds_its_tab_and_the_window_open() { + let (w, _, _, _) = three(); + let owner = Gated::new(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + h.state_mut() + .view_mut(0) + .unwrap() + .set_owner(owner.clone() as Arc); + // Nothing runs: the tab closes freely, the window's close goes through. + assert!(!close_is_off(&h, "Alpha Co")); + assert!( + !window_close_is_cancelled(&mut h), + "nothing holds the window" + ); + assert!(h.state().holding().is_empty()); + + ask_for_a_restore(&mut h); + until(&mut h, "the owner is asked to restore", |_| { + owner.entered.is_open() + }); + h.run_steps(3); + let words = "Restoring these books: wait for it to finish".to_string(); + assert_eq!( + h.state().holding(), + [("Alpha Co".to_string(), words.clone())] + ); + // The tab: its close control is off, and a click on it closes nothing. + assert!(close_is_off(&h, "Alpha Co")); + assert!(!close_is_off(&h, "Beta Co"), "beta's own is not held"); + close_tab(&mut h, "Alpha Co"); + assert_eq!(titles(&h), ["Alpha Co", "Beta Co"], "alpha stayed"); + h.state_mut().close(0); + assert_eq!( + titles(&h), + ["Alpha Co", "Beta Co"], + "not even asked in code" + ); + // The window: the close is cancelled and the dialog says why, and + // offers only to wait. + assert!( + window_close_is_cancelled(&mut h), + "the window's close went through with a restore running" + ); + h.run_steps(3); + assert!(h.state().close_dialog_is_up()); + assert!(shows(&h, "The books are being changed"), "{:?}", texts(&h)); + assert!(shows(&h, &format!("Alpha Co: {words}")), "{:?}", texts(&h)); + assert!(h.query_by_label("Wait for it to finish").is_some()); + + // Let go: the dialog goes, the result is shown in that tab, and the + // tab closes as any other. + owner.release.open(); + until(&mut h, "the restore ends", |a| a.holding().is_empty()); + h.run_steps(4); + assert!(!h.state().close_dialog_is_up()); + assert!(!shows(&h, "The books are being changed")); + assert!( + shows(&h, "Restore: Restored as"), + "its result isn't in the tab: {:?}", + texts(&h) + ); + assert!(!close_is_off(&h, "Alpha Co")); + close_tab(&mut h, "Alpha Co"); + assert_eq!(titles(&h), ["Beta Co"]); +} + +#[test] +fn a_backup_only_reads_so_its_tab_closes_and_its_thread_ends() { + let (w, _, _, _) = three(); + let owner = Gated::new(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + h.state_mut() + .view_mut(0) + .unwrap() + .set_owner(owner.clone() as Arc); + h.run_steps(3); + h.get_by_label_contains(" Books").click(); + h.run_steps(3); + h.get_by_label_contains("Back up now").click(); + until(&mut h, "the owner is asked to back up", |_| { + owner.entered.is_open() + }); + let watch = h.state().views()[0].jobs_watch(); + assert!( + watch.running().iter().any(|n| n == "Back up now"), + "the backup isn't one of the tab's threads: {:?}", + watch.running() + ); + // It changes nothing of the books: nothing holds the tab or the window. + assert!(h.state().holding().is_empty()); + assert!(!close_is_off(&h, "Alpha Co")); + close_tab(&mut h, "Alpha Co"); + assert_eq!(titles(&h), ["Beta Co"]); + // Its thread ends when the owner's call does, and says nothing. + owner.release.open(); + assert!( + watch.wait_ended(Duration::from_secs(60)), + "{:?}", + watch.running() + ); +} + +#[test] +fn an_export_is_stopped_when_its_tab_closes() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + // A job that waits to be told, then says whether it was told to stop. + let go = Arc::new(Latch::default()); + let told = Arc::new(Mutex::new(None::)); + let (go2, told2) = (go.clone(), told.clone()); + let ctx = h.ctx.clone(); + h.state_mut().view_mut(1).unwrap().start_export_for_tests( + &ctx, + "A file", + Box::new(move |stop| { + assert!(go2.wait()); + *told2.lock().unwrap() = Some(stop.requested()); + Err("stopped".into()) + }), + ); + let watch = h.state().views()[1].jobs_watch(); + assert!(watch.running().iter().any(|n| n == "export")); + // Closing the tab asks nothing: it stops the job. + assert!(h.state().holding().is_empty()); + close_tab(&mut h, "Beta Co"); + go.open(); + assert!( + watch.wait_ended(Duration::from_secs(60)), + "{:?}", + watch.running() + ); + assert_eq!(*told.lock().unwrap(), Some(true), "the export wasn't told"); +} + +// ---- 14b: the dock's agent and its tab --------------------------------------- + +#[cfg(unix)] +fn agent_script(pidfile: &Path, body: &str) -> AgentStart { + AgentStart::Ready { + label: "Claude Code".into(), + program: PathBuf::from("/bin/sh"), + args: vec![ + "-c".into(), + format!( + "{body} echo $$ > '{}'; {}", + pidfile.display(), + "while true; do sleep 1; done" + ), + ], + dir: pidfile.parent().unwrap().to_path_buf(), + env: vec![("TERM".into(), "xterm-256color".into())], + } +} + +#[cfg(unix)] +#[test] +fn a_tab_closed_while_its_agent_is_starting_leaves_no_child_and_no_thread() { + let (w, _, _, _) = three(); + let work = tempfile::tempdir().unwrap(); + let pidfile = work.path().join("agent.pid"); + let owner = Gated::new(); + *owner.start.lock().unwrap() = Some(agent_script(&pidfile, "")); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + h.state_mut() + .view_mut(1) + .unwrap() + .set_owner(owner.clone() as Arc); + show_tab(&mut h, "Beta Co"); + h.state_mut().dock_mut().open = true; + // Starting: the owner is looking for the agent and holds its answer. + until(&mut h, "the owner is asked to start the agent", |_| { + owner.entered.is_open() + }); + let watch = h.state().views()[1].jobs_watch(); + assert!( + watch.running().iter().any(|n| n == "agent start"), + "the start isn't one of the tab's threads: {:?}", + watch.running() + ); + close_tab(&mut h, "Beta Co"); + // The answer comes after the tab is gone. + owner.release.open(); + assert!( + watch.wait_ended(Duration::from_secs(60)), + "{:?}", + watch.running() + ); + h.run_steps(6); + assert!( + !pidfile.exists(), + "a child was started for a tab that had closed" + ); +} + +#[cfg(unix)] +#[test] +fn a_tab_closed_with_its_agent_running_ends_the_child_even_if_it_ignores_the_hangup() { + let (w, _, _, _) = three(); + let work = tempfile::tempdir().unwrap(); + let pidfile = work.path().join("agent.pid"); + let owner = Gated::new(); + owner.release.open(); + // An agent that ignores the hang-up a closed terminal sends. + *owner.start.lock().unwrap() = Some(agent_script(&pidfile, "trap '' HUP;")); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + h.state_mut() + .view_mut(1) + .unwrap() + .set_owner(owner.clone() as Arc); + show_tab(&mut h, "Beta Co"); + h.state_mut().dock_mut().open = true; + let pid = { + let end = Instant::now() + Duration::from_secs(60); + loop { + h.run_steps(2); + if let Ok(text) = std::fs::read_to_string(&pidfile) + && let Ok(pid) = text.trim().parse::() + { + break pid; + } + assert!(Instant::now() < end, "the agent never started"); + std::thread::sleep(Duration::from_millis(20)); + } + }; + assert!(alive(pid)); + let watch = h.state().views()[1].jobs_watch(); + assert!( + watch.running().iter().any(|n| n == "dock agent"), + "{:?}", + watch.running() + ); + close_tab(&mut h, "Beta Co"); + // Every thread of the tab, the one that reaps its agent included, ends; + // and with them the child, hung up on, killed and reaped. + assert!( + watch.wait_ended(Duration::from_secs(120)), + "{:?}", + watch.running() + ); + assert!(!alive(pid), "a closed tab's agent survived it"); +} + +// ---- 15: what is kept belongs to the books it was kept for ------------------- + +/// Wait for the clock's next second. A set of books' identity is the hash +/// of its journal's first line, which says when the books were made to the +/// second: books made again in the same second as the old would have the +/// old ones' identity, so a test that makes other books under an id waits +/// for the clock first (a condition, not a guess at a duration). +fn next_second() { + let now = chrono::Utc::now().timestamp(); + while chrono::Utc::now().timestamp() == now { + std::thread::yield_now(); + } +} + +/// Save the app's preferences into `into`. +fn saved(h: &mut Harness<'static, App>, mut into: Prefs) -> Prefs { + eframe::App::save(h.state_mut(), &mut into); + into +} + +#[test] +fn another_data_root_with_a_company_of_the_same_id_inherits_nothing() { + // Root A: alpha and beta, open, alpha on a report in a custom period. + let a = World::new(); + a.company("alpha", "Alpha One", 1_000_000, 100); + a.company("beta", "Beta One", 500_000, 100); + let mut h = start_with_prefs(&a, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + { + use ledger_gui::pages::reports::Range; + let v = h.state_mut().view_mut(0).unwrap(); + v.goto(Route::Reports(ReportKind::BalanceSheet)); + v.state_mut().reports.range = Range::Custom(d(2026, 1, 1), d(2026, 6, 30)); + } + h.run_steps(2); + let kept = saved(&mut h, Prefs::default()); + drop(h); + + // Root B: another alpha (other books under the same id), and a beta. + next_second(); + let b = World::new(); + b.company("alpha", "Alpha Two", 2_000_000, 100); + b.company("beta", "Beta Two", 700_000, 100); + // Before anything loads: B's alpha is not named for A's, and A's list + // of open companies is not B's. + let ctx = egui::Context::default(); + let app = App::start_with( + &ctx, + &|k| kept.0.get(k).cloned(), + Start::Restore { + root: b.root.clone(), + fallback: b.source("alpha"), + }, + ); + assert_eq!(app.views().len(), 1, "opened from another root's list"); + assert_eq!(app.tab_title(0).as_deref(), Some("alpha"), "A's name kept"); + assert_eq!(app.remembered_name("alpha"), None); + drop(app); + // Loaded: its own page and period, its own name. + let mut h = start_as_is(&b, kept.clone(), egui::vec2(1280.0, 800.0)); + loaded(&mut h); + assert_eq!(titles(&h), ["Alpha Two"]); + assert!(matches!(h.state().views()[0].route(), Route::Overview)); + assert_eq!( + h.state().views()[0].state().reports.range, + ledger_gui::pages::reports::Range::YearToDate + ); + // And A's, kept in the same file, are still A's. + let both = saved(&mut h, kept.clone()); + assert_eq!(both.0[&a.open_key()], "alpha,beta"); + assert_eq!(both.0[&a.kept_key("alpha", "name")], "Alpha One"); + assert_eq!(both.0[&b.kept_key("alpha", "name")], "Alpha Two"); + assert_ne!(a.kept_key("alpha", "page"), b.kept_key("alpha", "page")); +} + +#[test] +fn books_made_again_under_an_id_start_fresh_and_a_restart_of_the_same_books_does_not() { + let w = World::new(); + w.company("alpha", "Alpha One", 1_000_000, 100); + w.company("beta", "Beta One", 500_000, 100); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + { + use ledger_gui::pages::reports::Range; + let v = h.state_mut().view_mut(0).unwrap(); + v.goto(Route::Reports(ReportKind::BalanceSheet)); + v.state_mut().reports.range = Range::Custom(d(2026, 1, 1), d(2026, 6, 30)); + } + h.run_steps(2); + let kept = saved(&mut h, Prefs::default()); + let identity = kept.0[&w.kept_key("alpha", "identity")].clone(); + assert_eq!(identity.len(), 64, "the journal's first line's SHA-256"); + drop(h); + + // The same books, restarted: the state comes back, the identity is the + // same. + let mut h = start_as_is(&w, kept.clone(), egui::vec2(1280.0, 800.0)); + loaded(&mut h); + assert!(matches!( + h.state().views()[0].route(), + Route::Reports(ReportKind::BalanceSheet) + )); + let again = saved(&mut h, kept.clone()); + assert_eq!(again.0[&w.kept_key("alpha", "identity")], identity); + drop(h); + + // Alpha deleted and made again, as other books. + std::fs::remove_dir_all(w.root.join("books").join("alpha")).unwrap(); + next_second(); + w.company("alpha", "Alpha Two", 2_000_000, 100); + let mut h = start_as_is(&w, kept.clone(), egui::vec2(1280.0, 800.0)); + loaded(&mut h); + assert_eq!(titles(&h), ["Alpha Two", "Beta One"]); + assert!( + matches!(h.state().views()[0].route(), Route::Overview), + "the old books' page was kept for the new books" + ); + assert_eq!( + h.state().views()[0].state().reports.range, + ledger_gui::pages::reports::Range::YearToDate, + "the old books' period was kept for the new books" + ); + assert_eq!(h.state().remembered_name("alpha"), Some("Alpha Two")); + // Beta, untouched, kept its own. + assert_eq!(h.state().remembered_name("beta"), Some("Beta One")); + let fresh = saved(&mut h, kept.clone()); + assert_ne!(fresh.0[&w.kept_key("alpha", "identity")], identity); + assert_eq!(fresh.0[&w.kept_key("alpha", "name")], "Alpha Two"); + assert_eq!(fresh.0[&w.kept_key("alpha", "page")], "overview"); +} + +#[test] +fn books_outside_any_data_root_are_kept_under_their_folder() { + let make = |tag: &str| { + let dir = tempfile::Builder::new() + .prefix(&format!("wb-gui-folder-{tag}-")) + .tempdir() + .unwrap(); + let book = dir.path().join("books-data"); + let mut s = Store::create(&book, Currency::USD).unwrap(); + s.add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + drop(s); + (dir, book) + }; + let open = |book: &Path, kept: Prefs| { + let src = Source { + data_dir: book.to_path_buf(), + today: Some(today()), + }; + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .build_eframe(move |cc| { + App::start_with(&cc.egui_ctx, &|k| kept.0.get(k).cloned(), Start::Only(src)) + }); + loaded(&mut h); + h + }; + let (_one, one) = make("one"); + let mut h = open(&one, Prefs::default()); + h.state_mut() + .view_mut(0) + .unwrap() + .goto(Route::Reports(ReportKind::CashFlow)); + let kept = saved(&mut h, Prefs::default()); + let key = ledger_gui::app::company_key(&one, "page"); + assert!(key.starts_with("company.dir."), "{key}"); + assert_eq!(kept.0[&key], "reports:cash-flow"); + drop(h); + // The same folder comes back to its page... + let h = open(&one, kept.clone()); + assert!(matches!( + h.state().views()[0].route(), + Route::Reports(ReportKind::CashFlow) + )); + drop(h); + // ...another folder, though it is also `books-data`, does not. + let (_two, two) = make("two"); + let h = open(&two, kept); + assert!(matches!(h.state().views()[0].route(), Route::Overview)); +} + +#[test] +fn preferences_written_before_the_keys_had_a_root_are_read_and_not_used() { + let (w, _, _, _) = three(); + let old = prefs(&[ + ("open_companies", "beta,gamma"), + ("active_company", "gamma"), + ("company.beta.page", "transactions"), + ("company.beta.name", "Old Beta"), + ("company.alpha.page", "accounts"), + ("scheme", "Wanderland/Light"), + ]); + let mut h = start_as_is(&w, old, egui::vec2(1280.0, 800.0)); + loaded(&mut h); + // The data root's first, alone, on its overview: nothing was matched. + assert_eq!(titles(&h), ["Alpha Co"]); + assert!(matches!(h.state().views()[0].route(), Route::Overview)); + assert_eq!(h.state().remembered_name("beta"), None); +} + +// ---- 16: a start that names a company leaves the open list alone ------------- + +#[test] +fn a_start_with_a_named_company_never_writes_the_list_of_open_companies() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta,gamma")]); + loaded(&mut h); + h.state_mut().activate(2); + h.run_steps(2); + let kept = saved(&mut h, Prefs::default()); + let (list, front) = ( + kept.0[&w.open_key()].clone(), + kept.0[&w.active_key()].clone(), + ); + assert_eq!(list, "alpha,beta,gamma"); + drop(h); + + // `wanderbooks gui beta`: one tab; another opened and beta closed. + let src = w.source("beta"); + let from = kept.clone(); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .build_eframe(move |cc| { + App::start_with(&cc.egui_ctx, &|k| from.0.get(k).cloned(), Start::Only(src)) + }); + loaded(&mut h); + assert_eq!(titles(&h), ["Beta Co"]); + h.state_mut().view_mut(0).unwrap().goto(Route::Transactions); + let ctx = h.ctx.clone(); + h.state_mut().open(&ctx, w.source("alpha")); + loaded(&mut h); + close_tab(&mut h, "Beta Co"); + assert_eq!(titles(&h), ["Alpha Co"]); + let after = saved(&mut h, kept.clone()); + // The list and the front tab are the plain start's, as they were. + assert_eq!(after.0[&w.open_key()], list); + assert_eq!(after.0[&w.active_key()], front); + // Each company's own page is still kept. + assert_eq!(after.0[&w.kept_key("beta", "page")], "transactions"); + assert_eq!(after.0[&w.kept_key("alpha", "page")], "overview"); +} + +// ---- 17: what the tabs share on purpose -------------------------------------- + +#[cfg(unix)] +#[test] +fn the_docks_height_and_layout_are_the_apps_one_for_every_tab() { + let (w, _, _, _) = three(); + let owner = Gated::new(); + owner.release.open(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + for i in 0..2 { + h.state_mut() + .view_mut(i) + .unwrap() + .set_owner(owner.clone() as Arc); + h.state_mut().view_mut(i).unwrap().dock_mut().open = true; + } + h.run_steps(4); + let top = |h: &Harness<'_, App>| h.get_by_label_contains(" Agent").rect().top(); + let before = top(&h); + // Resized in alpha: dragged up by a hundred points. + let x = h.get_by_label_contains(" Agent").rect().left() + 300.0; + let panel_top = egui::containers::panel::PanelState::load(&h.ctx, egui::Id::new("dock-open")) + .expect("the dock's panel") + .outer_rect + .top(); + let edge = egui::pos2(x, panel_top); + let to = egui::pos2(x, panel_top - 100.0); + h.hover_at(edge); + h.run_steps(2); + h.drag_at(edge); + h.run_steps(2); + h.hover_at(to); + h.run_steps(3); + h.drop_at(to); + h.run_steps(4); + let grown = top(&h); + assert!( + grown < before - 50.0, + "the dock didn't grow: header at {before} then {grown}" + ); + // Beta's dock has the same height: one layout for the assistant dock + // everywhere. + show_tab(&mut h, "Beta Co"); + h.run_steps(3); + assert!( + (top(&h) - grown).abs() < 0.5, + "beta's dock is {} from the top, alpha's {grown}", + top(&h) + ); + // And so it is in the egui memory: the panel is the app's, its id the + // raw one, the one id of a panel that is not scoped by its tab. + use egui::containers::panel::PanelState; + let ctx = h.ctx.clone(); + assert!(PanelState::load(&ctx, egui::Id::new("dock-open")).is_some()); +} + +#[test] +fn no_panel_but_the_apps_own_is_keyed_by_an_id_every_tab_shares() { + use egui::containers::panel::PanelState; + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + let ctx = h.ctx.clone(); + let raw = |name: &str| PanelState::load(&ctx, egui::Id::new(name)); + // Drawn in both tabs, and in the narrow window's rail too. + for name in ["Alpha Co", "Beta Co"] { + show_tab(&mut h, name); + h.run_steps(3); + } + h.set_size(egui::vec2(800.0, 800.0)); + h.run_steps(4); + // A company's panels (the sidebar, the rail, the top bar) are keyed by + // ids made from its own, never by a name every tab shares. + for shared in ["sidebar", "rail", "topbar"] { + assert!( + raw(shared).is_none(), + "a company's {shared} panel is keyed by an id every tab shares" + ); + } + // The ones that are the app's, and say so: the tab bar's. + assert!(raw("company_tabs").is_some()); +} + +#[test] +fn the_color_scheme_is_the_windows_one_for_every_tab() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + // The sidebar's own fill: the largest rectangle in its column below the + // bar. + let sidebar = |h: &Harness<'_, App>| -> egui::Color32 { + fn walk(s: &egui::Shape, out: &mut Vec<(f32, egui::Color32)>) { + match s { + egui::Shape::Rect(r) if in_sidebar(r.rect) && r.fill.a() > 0 => { + out.push((r.rect.area(), r.fill)) + } + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut all = Vec::new(); + for c in &h.output().shapes { + walk(&c.shape, &mut all); + } + all.into_iter() + .max_by(|a, b| a.0.total_cmp(&b.0)) + .expect("the sidebar's fill") + .1 + }; + let ctx = h.ctx.clone(); + let key = h.state().scheme_key(); + let other = if key.ends_with("/Dark") { + "Wanderbooks/Light" + } else { + "Wanderbooks/Dark" + }; + let was = sidebar(&h); + h.state_mut().set_scheme(&ctx, other); + h.run_steps(3); + let in_alpha = sidebar(&h); + assert_ne!(in_alpha, was, "the scheme didn't change what is drawn"); + show_tab(&mut h, "Beta Co"); + h.run_steps(3); + assert_eq!( + sidebar(&h), + in_alpha, + "beta wears another scheme than alpha" + ); + assert_eq!(h.state().scheme_key(), other); +}