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 7da35dea..8737e322 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -1,170 +1,222 @@ -//! The window: sidebar, top bar, and the current page. +//! The window: a tab bar with one tab per open company, and the company +//! in front (company.rs). +//! +//! ```text +//! GOAL: one window, a tab for each company that is open, each tab a +//! window on that company alone; what the app keeps of its own +//! (the color scheme, the dock's preferences) is kept once. +//! SOURCE: plan/p15-app-and-relay.md 3.2 (tabs: `App` holds the per-app +//! state and a `CompanyView` per tab); D-78 (one top-level tab per +//! open company). +//! INVARIANTS: +//! 1. One view per open company, no company twice: opening one that is +//! open shows its tab instead, and start-up opens each company of the +//! kept list once. +//! 2. Closing a tab drops its view, and with it its loader (its +//! watcher and its viewer presence), its receipts' workers and its +//! dock's agent; the other tabs are as they were. +//! 3. Start: a company named on the command line is the only tab; +//! 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. +//! 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.`), `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. +//! ``` -use crate::books::Books; -use crate::data::{Loader, Source, Update}; -use crate::nav::{Nav, Route, Section}; -use crate::pages; -use crate::receipts::Receipts; -use crate::schemes::{self, Filter, Scheme}; +use crate::company::CompanyView; +use crate::data::Source; +use crate::nav::Route; +use crate::scheme_menu::SchemeMenu; +use crate::tabs::{Listed, Tab, TabAction, TabBar}; use crate::theme::{self, pal}; -use egui::{Align, CornerRadius, Frame, Key, Layout, Margin, RichText, Sense, Stroke, Ui, vec2}; -use egui_phosphor::regular as icon; -use std::sync::Arc; +use egui::{Frame, RichText, Ui}; +use std::collections::HashMap; +use std::path::PathBuf; -/// Window widths below this get the icon rail instead of the sidebar. -pub const COMPACT_BELOW: f32 = 1000.0; +pub use crate::company::{COMPACT_BELOW, PageState, Shell}; +use crate::company::{kept_scope_of, path_hash}; -/// Per-page state that survives navigation. -#[derive(Default)] -pub struct PageState { - pub transactions: pages::transactions::State, - pub reports: pages::reports::State, - pub accounts: pages::accounts::State, - pub assets: pages::assets::State, - pub parties: pages::parties::State, - pub projects: pages::projects::State, - pub documents: pages::documents::State, - pub invoices: pages::invoices::State, - pub journal: pages::journal::State, +/// Where the viewer keeps the companies that were open (the ids of their +/// 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)) } -/// What a page can ask of the shell. -pub struct Shell<'a> { - pub receipts: &'a mut Receipts, - pub state: &'a mut PageState, - pub go: Option, - /// Seconds since the last live update arrived (for "new" highlights). - pub since_update: f64, +/// 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)) } -impl Shell<'_> { - pub fn go(&mut self, r: Route) { - self.go = Some(r); - } +/// 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) } -/// The height of a family's row in the color scheme menu, for laying the -/// families out in columns. -const FAMILY_ROW: f32 = 34.0; - -/// How long the pointer rests on a scheme's row (or off every row) before -/// that scheme (or the one in force) is worn, seconds. -const PREVIEW_AFTER: f64 = 0.05; - -/// The width of a variant's row in a family's flyout: room for its colors -/// and the longest name. -const SCHEME_ROW_WIDTH: f32 = 200.0; - -/// Where the viewer keeps its color scheme ("Family/Variant"). -const SCHEME_KEY: &str = "scheme"; -/// Where it keeps its scheme menu's filter. -const FILTER_KEY: &str = "scheme_filter"; - -/// One variant in the color scheme menu: a strip of its colors and its -/// name, the whole row one button, selected when it is the one in force. -fn scheme_row(ui: &mut Ui, scheme: &Scheme, current: bool) -> egui::Response { - let p = pal(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(SCHEME_ROW_WIDTH, 28.0), Sense::click()); - response.widget_info(|| { - egui::WidgetInfo::selected( - egui::WidgetType::SelectableLabel, - true, - current, - scheme.name, - ) - }); - if ui.is_rect_visible(rect) { - let painter = ui.painter(); - let fill = if current { - Some(p.selected) - } else if response.hovered() { - Some(p.hover) - } else { - None - }; - if let Some(fill) = fill { - painter.rect_filled(rect, CornerRadius::same(6), fill); - } - let strip = egui::Rect::from_min_size( - egui::pos2(rect.left() + 8.0, rect.center().y - 7.0), - vec2(50.0, 14.0), - ); - let w = strip.width() / 5.0; - for (i, c) in scheme.swatch().into_iter().enumerate() { - let r = egui::Rect::from_min_size( - strip.min + vec2(w * i as f32, 0.0), - vec2(w, strip.height()), - ); - painter.rect_filled(r, 0.0, c); - } - painter.rect_stroke( - strip, - 3.0, - Stroke::new(1.0, p.border), - egui::StrokeKind::Outside, - ); - painter.text( - egui::pos2(strip.right() + 10.0, rect.center().y), - egui::Align2::LEFT_CENTER, - scheme.name, - theme::regular(14.0), - p.text, - ); - } - response +fn stored(scope: &str, thing: &str) -> String { + format!("company.{scope}.{thing}") } -/// The scheme and menu filter kept from last time (`get` reads the -/// viewer's preferences): the scheme kept; before schemes, the light or -/// dark choice kept as "dark"; else the viewer's own for the system's -/// mode (schemes INVARIANT 4). -fn restored(get: impl Fn(&str) -> Option, system_dark: bool) -> (&'static Scheme, Filter) { - let dark = get("dark").map_or(system_dark, |v| v == "true"); - let scheme = get(SCHEME_KEY).map_or_else(|| schemes::own(dark), |k| Scheme::from_key(&k, dark)); - let filter = get(FILTER_KEY) - .and_then(|f| Filter::from_name(&f)) - .unwrap_or_default(); - (scheme, filter) +/// How the app starts. +pub enum Start { + /// This company alone: the one named on the command line, or the demo. + Only(Source), + /// The companies kept from last time, of the data root `root`; if none + /// of them is there any more, `fallback` (the root's first). + Restore { root: PathBuf, fallback: Source }, } pub struct App { - loader: Option, - books: Option>, - error: Option, - nav: Nav, - receipts: Receipts, - /// The color scheme in force (schemes.rs). - scheme: &'static Scheme, - /// The scheme being worn: the one in force, or one previewed while - /// its row in the menu is hovered. - shown: &'static Scheme, - /// The scheme the pointer asks for, and since when: worn once it has - /// asked for PREVIEW_AFTER. - wanted: Option<(&'static Scheme, f64)>, - /// Which schemes its menu shows. - filter: Filter, - state: PageState, - palette: crate::palette::Palette, - updated_at: f64, - live_label: bool, - /// The export menu (menu.rs). - menu: crate::menu::Menu, - /// The owner's Books menu (owner.rs). - owner_menu: crate::owner::OwnerMenu, - /// The agent dock along the bottom (dock.rs). - dock: crate::dock::Dock, + /// The color scheme and its menu: the app's, whatever tab is shown. + schemes: SchemeMenu, + /// One view per open company, in the order of the tabs. + views: Vec, + /// The tab in front, an index of `views` (0 when there are none). + active: usize, + /// The tab bar's memory. + tabs: TabBar, + /// The data root the companies are in: "+" lists its companies. + root: Option, + /// "Today", fixed (tests, screenshots) or not. + today: Option, + /// What was kept for companies not open now (and for those that are, + /// as they were last closed), by key. + kept: HashMap, + /// Each company's name as last known, by the id of its books: kept for + /// the tab's title before the books load and for the "+" list, which + /// doesn't read every company's journal for it. + names: HashMap, + /// The dock's preferences as they were kept, for a dock made while no + /// tab has one. + dock_prefs: (Option, Option), + /// The title last given the window. + title: String, /// The first-run page, while there are no books to show (welcome.rs). welcome: Option, /// What a first run opens its books with: the data root named, and /// "today". - first_run_source: (Option, Option), + 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. +const TITLE: &str = "wanderbooks"; + impl App { - /// The live app over a books directory. + /// The live app over one company's books directory. pub fn new(cc: &eframe::CreationContext<'_>, source: Source) -> Self { - let mut app = Self::new_without_books(cc); - app.loader = Some(Loader::spawn(source, cc.egui_ctx.clone())); + Self::start(cc, Start::Only(source)) + } + + /// The live app, started as `start` says (INVARIANT 3). + pub fn start(cc: &eframe::CreationContext<'_>, start: Start) -> Self { + let get = |key: &str| cc.storage.and_then(|s| s.get_string(key)); + Self::start_with(&cc.egui_ctx, &get, start) + } + + /// [`Self::start`], with the viewer's kept preferences read by `get` + /// (tests give them without a window). + pub fn start_with( + ctx: &egui::Context, + get: &dyn Fn(&str) -> Option, + start: Start, + ) -> Self { + let mut app = Self::without_books(ctx, get); + 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 } => { + app.today = fallback.today; + app.root = Some(root.clone()); + app.remember_all(get); + let there = list_books(&root); + let wanted: Vec = get(&open_key(&root)) + .map(|v| v.split(',').map(str::to_string).collect()) + .unwrap_or_default(); + let mut opened = Vec::new(); + for id in wanted { + // Gone, or listed twice: skipped, with no word. + if !there.contains(&id) || opened.contains(&id) { + continue; + } + let Ok(book) = ledger_store::root::BookId::parse(&id) else { + continue; + }; + let Ok(r) = ledger_store::root::Root::find(Some(&root)) else { + break; + }; + let source = Source { + data_dir: r.book_dir(&book), + today: app.today, + }; + app.open(ctx, source); + opened.push(id); + } + if app.views.is_empty() { + app.open(ctx, fallback); + } else { + // The one in front last time, else the first. + 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. + let front = app.active; + for (i, v) in app.views.iter_mut().enumerate() { + if i != front { + v.dock_mut().open = false; + } + } + } + } + } app } @@ -173,7 +225,7 @@ impl App { /// root named on the command line, if any. pub fn first_run( cc: &eframe::CreationContext<'_>, - root: Option, + root: Option, today: Option, state: crate::owner::FirstRun, ) -> Self { @@ -183,18 +235,18 @@ impl App { app } - /// An app with no books and no loader yet: the scheme kept from last - /// time (before schemes, a light/dark choice; else the system's mode: - /// schemes INVARIANT 4) and the dock as it was left. + /// An app with no company open: the scheme kept from last time (before + /// schemes, a light/dark choice; else the system's mode: schemes + /// INVARIANT 4) and the dock as it was left. pub fn new_without_books(cc: &eframe::CreationContext<'_>) -> Self { - let (scheme, filter) = restored( - |key| cc.storage.and_then(|s| s.get_string(key)), - cc.egui_ctx.global_style().visuals.dark_mode, - ); - let mut app = Self::bare(&cc.egui_ctx, scheme); - app.filter = filter; - app.dock = crate::dock::Dock::restored(|key| cc.storage.and_then(|s| s.get_string(key))); - app.receipts.thumb_dir = crate::receipts::thumb_dir(); + let get = |key: &str| cc.storage.and_then(|s| s.get_string(key)); + Self::without_books(&cc.egui_ctx, &get) + } + + fn without_books(ctx: &egui::Context, get: &dyn Fn(&str) -> Option) -> Self { + let schemes = SchemeMenu::restored(get, ctx.global_style().visuals.dark_mode); + let mut app = Self::bare(ctx, schemes); + app.dock_prefs = (get("dock_open"), get("dock_agent")); app } @@ -203,13 +255,248 @@ impl App { self.welcome.as_ref() } + /// An app showing fixed books (tests and screenshots): one tab. + pub fn with_books( + ctx: &egui::Context, + books: crate::books::Books, + dark: bool, + start: Route, + ) -> Self { + let mut app = Self::bare(ctx, SchemeMenu::new(crate::schemes::own(dark))); + app.add_view(CompanyView::with_books(ctx, books, start)); + app + } + + /// An app with no company open, wearing `schemes`. + fn bare(ctx: &egui::Context, schemes: SchemeMenu) -> Self { + theme::install_fonts(ctx); + theme::apply_scheme(ctx, schemes.in_force()); + egui_extras::install_image_loaders(ctx); + Self { + schemes, + views: Vec::new(), + active: 0, + tabs: TabBar::default(), + root: None, + today: None, + kept: HashMap::new(), + names: HashMap::new(), + dock_prefs: (None, None), + title: TITLE.to_string(), + welcome: None, + first_run_source: (None, None), + close_dialog: false, + writes_open_list: true, + } + } + + // ---- the tabs -------------------------------------------------------- + + /// The views, in the order of the tabs. + pub fn views(&self) -> &[CompanyView] { + &self.views + } + + /// Tab `i`'s view (tests). + pub fn view_mut(&mut self, i: usize) -> Option<&mut CompanyView> { + self.views.get_mut(i) + } + + /// The tab in front, if any is open. + pub fn active(&self) -> Option { + (!self.views.is_empty()).then_some(self.active) + } + + /// The view in front, if any is open. + pub fn active_view(&self) -> Option<&CompanyView> { + self.views.get(self.active) + } + + /// The view in front, if any is open. + pub fn active_view_mut(&mut self) -> Option<&mut CompanyView> { + self.views.get_mut(self.active) + } + + /// Bring tab `i` to the front; an index that isn't a tab changes + /// nothing. + pub fn activate(&mut self, i: usize) { + if i < self.views.len() && i != self.active { + self.active = i; + self.tabs.reveal(); + } + } + + /// 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() { + Some(v) => format!("{} · {TITLE}", self.title_of(v)), + None => TITLE.to_string(), + } + } + + /// Put `view` in the tabs and bring it to the front; the index of its + /// tab. A company already open isn't opened twice (INVARIANT 1): its + /// own tab comes to the front and `view` is dropped, ending what it + /// started. + pub fn add_view(&mut self, view: CompanyView) -> usize { + if let Some(i) = self.views.iter().position(|v| v.key() == view.key()) { + self.activate(i); + return i; + } + let at = self.views.len(); + // 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(scope) = view.kept_scope() { + view.restore(&|k| self.kept.get(&stored(&scope, k)).cloned()); + } + self.views.push(view); + self.active = at; + self.tabs.reveal(); + at + } + + /// Open the company of `source` in a tab (or show its tab, if it is + /// open): the index of its tab. + pub fn open(&mut self, ctx: &egui::Context, source: Source) -> usize { + if self.root.is_none() { + self.root = ledger_store::root::root_of_book_dir(&source.data_dir) + .map(std::path::Path::to_path_buf); + } + let key = crate::company::key_of(&source.data_dir); + if let Some(i) = self.views.iter().position(|v| v.key() == key) { + self.activate(i); + return i; + } + let view = CompanyView::open(ctx, source).with_dock(self.new_dock()); + self.add_view(view) + } + + /// 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(scope) = view.kept_scope() { + view.keep(&mut |k, v| { + self.kept.insert(stored(&scope, k), v); + }); + } + drop(view); + if i < self.active || self.active >= self.views.len() { + self.active = self.active.saturating_sub(1); + } + self.tabs.reveal(); + } + + /// A dock for a view just made: the front tab's agent and closed, else + /// as kept (the first view of the app takes the dock as it was left). + fn new_dock(&self) -> crate::dock::Dock { + match self.active_view() { + // The agent chosen, but closed: opening a company must not + // start an agent in it that nobody asked for. + Some(v) => crate::dock::Dock::closed_with(v.dock_ref().agent), + None => { + let (open, agent) = self.dock_prefs.clone(); + crate::dock::Dock::restored(|key| match key { + "dock_open" => open.clone(), + "dock_agent" => agent.clone(), + _ => None, + }) + } + } + } + + /// Everything kept for the companies of the data root, so a company + /// opened later comes back as it was. + fn remember_all(&mut self, get: &dyn Fn(&str) -> Option) { + 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(&stored(&format!("{root_hash}.{id}"), "name")) { + self.names.insert(id.clone(), name); + } + 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); + } + } + } + /// Open the books `id` of the data root named, as the first-run page /// was asked to: the books come in as the loader reads them. fn open_first_books(&mut self, ctx: &egui::Context, id: &str) { let (root, today) = self.first_run_source.clone(); match crate::book_in_root(root.as_deref(), Some(id)) { Ok(data_dir) => { - self.loader = Some(Loader::spawn(Source { data_dir, today }, ctx.clone())); + self.today = today; + self.open(ctx, Source { data_dir, today }); self.welcome = None; } Err(why) => { @@ -220,1501 +507,236 @@ impl App { } } - /// An app showing fixed books (tests and screenshots). - pub fn with_books(ctx: &egui::Context, books: Books, dark: bool, start: Route) -> Self { - let mut app = Self::bare(ctx, schemes::own(dark)); - app.receipts.prefetch(&books); - app.books = Some(Arc::new(books)); - app.nav = Nav::new(start); - app - } - - fn bare(ctx: &egui::Context, scheme: &'static Scheme) -> Self { - theme::install_fonts(ctx); - theme::apply_scheme(ctx, scheme); - egui_extras::install_image_loaders(ctx); - Self { - loader: None, - books: None, - error: None, - nav: Nav::new(Route::Overview), - receipts: Receipts::new(ctx), - scheme, - shown: scheme, - wanted: None, - filter: Filter::default(), - state: PageState::default(), - palette: Default::default(), - updated_at: -1e9, - live_label: false, - menu: Default::default(), - owner_menu: Default::default(), - dock: Default::default(), - welcome: None, - first_run_source: (None, None), + /// The data root's companies that aren't open, with the names last + /// known (reading the ids is all it does). + fn not_open(&self) -> impl Fn() -> Vec + use<> { + let root = self.root.clone(); + let open: Vec = self.views.iter().filter_map(CompanyView::book_id).collect(); + let names = self.names.clone(); + move || { + root.as_deref() + .map(list_books) + .unwrap_or_default() + .into_iter() + .filter(|id| !open.contains(id)) + .map(|id| Listed { + name: names.get(&id).cloned(), + id, + }) + .collect() } } - /// The agent dock (tests). + /// 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 { + if let (Some(id), Some(name)) = (v.book_id(), v.name()) + && self.names.get(&id) != Some(&name) + { + self.names.insert(id, name); + } + } + } + + /// The name last known for the company with books `id` (tests). + pub fn remembered_name(&self, id: &str) -> Option<&str> { + self.names.get(id).map(String::as_str) + } + + /// A view's tab title: the name its books carry, else the name last + /// known, else the id. + fn title_of(&self, v: &CompanyView) -> String { + v.name() + .or_else(|| self.names.get(&v.book_id()?).cloned()) + .unwrap_or_else(|| v.title()) + } + + /// Tab `i`'s title as the bar shows it (tests). + pub fn tab_title(&self, i: usize) -> Option { + self.views.get(i).map(|v| self.title_of(v)) + } + + /// Do what the tab bar was asked. + fn act(&mut self, ctx: &egui::Context, action: TabAction) { + match action { + TabAction::Show(i) => self.activate(i), + TabAction::Close(i) => self.close(i), + TabAction::Open(id) => { + let Some(root) = self.root.clone() else { + return; + }; + let Ok(book) = ledger_store::root::BookId::parse(&id) else { + return; + }; + let Ok(r) = ledger_store::root::Root::find(Some(&root)) else { + return; + }; + let source = Source { + data_dir: r.book_dir(&book), + today: self.today, + }; + self.open(ctx, source); + } + } + } + + // ---- the front tab, for tests and screenshots ------------------------- + + /// The agent dock of the front tab (tests). + /// + /// # Panics + /// With no tab open. pub fn dock_mut(&mut self) -> &mut crate::dock::Dock { - &mut self.dock + self.views[self.active].dock_mut() } - /// The dock along the bottom, for books of a data root with an owner - /// to start the agent (dock.rs). - fn dock(&mut self, ui: &mut Ui) { - if !crate::dock::offered() { - return; - } - let (Some(owner), Some(books)) = (crate::owner::current(), self.books.clone()) else { - return; - }; - if let Some(book) = crate::owner::book_id(&books) { - self.dock.show(ui, &owner, &book); - } - } - - /// Navigate (tests). + /// Navigate the front tab (tests). pub fn goto(&mut self, r: Route) { - self.nav.go(r); + if let Some(v) = self.active_view_mut() { + v.goto(r); + } } /// Wear the color scheme kept as `key` ("Family/Variant"; tests). pub fn set_scheme(&mut self, ctx: &egui::Context, key: &str) { - self.choose(ctx, Scheme::from_key(key, self.scheme.dark)); + self.schemes.set_scheme(ctx, key); } /// The color scheme in force, as kept ("Family/Variant"). pub fn scheme_key(&self) -> String { - self.scheme.key() + self.schemes.scheme_key() } /// The scheme being worn ("Family/Variant"): a previewed one while /// its row is hovered (tests). pub fn shown_scheme_key(&self) -> String { - self.shown.key() + self.schemes.shown_scheme_key() } - fn choose(&mut self, ctx: &egui::Context, scheme: &'static Scheme) { - self.scheme = scheme; - self.wear(ctx, scheme); - } - - /// Wear `scheme`, in force or previewed. - fn wear(&mut self, ctx: &egui::Context, scheme: &'static Scheme) { - self.shown = scheme; - self.wanted = None; - theme::apply_scheme(ctx, scheme); - } - - /// The preview (owner, 2026-10-19: "when we hover over a scheme for - /// some time switch to it live; when we switch out of it go to either - /// the new thing we're hovering or back to the current one"). While - /// the menu is open, the scheme whose row is hovered, else the one in - /// force, is worn once the pointer has asked for it PREVIEW_AFTER - /// without change; the menu closed, the one in force is worn at once. - /// A preview is never kept: only a click chooses. - fn preview(&mut self, ctx: &egui::Context, open: bool, hovered: Option<&'static Scheme>) { - let want = match (open, hovered) { - (true, Some(s)) => s, - _ => self.scheme, - }; - if std::ptr::eq(want, self.shown) { - self.wanted = None; - return; - } - if !open { - self.wear(ctx, want); - return; - } - let now = ctx.input(|i| i.time); - match self.wanted { - Some((s, since)) if std::ptr::eq(s, want) => { - let waited = now - since; - if waited >= PREVIEW_AFTER { - self.wear(ctx, want); - } else { - ctx.request_repaint_after(std::time::Duration::from_secs_f64( - PREVIEW_AFTER - waited, - )); - } - } - _ => { - self.wanted = Some((want, now)); - ctx.request_repaint_after(std::time::Duration::from_secs_f64(PREVIEW_AFTER)); - } + /// Keep thumbnails on disk in `dir` for the front tab (tests). + pub fn keep_thumbs_in(&mut self, dir: PathBuf) { + if let Some(v) = self.active_view_mut() { + v.keep_thumbs_in(dir); } } - /// The color scheme button and its menu: a filter (all, light, dark), - /// then each family with a flyout of its variants. `compact`: the - /// narrow rail's icon alone. - fn scheme_menu(&mut self, ui: &mut Ui, compact: bool) { - let p = pal(ui.ctx()); - let text = if compact { - RichText::new(icon::PALETTE).size(16.0).color(p.muted) - } else { - RichText::new(format!("{} {}", icon::PALETTE, self.scheme.label())) - .font(theme::regular(12.5)) - .color(p.muted) - }; - let mut button = egui::Button::new(text).frame(false); - if compact { - button = button.min_size(vec2(32.0, ui.spacing().interact_size.y + 4.0)); - } - // Open while the filter changes; closed when a scheme is chosen. - let config = egui::containers::menu::MenuConfig::new() - .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); - let mut chosen = None; - let mut hovered = None; - let (response, open) = egui::containers::menu::MenuButton::from_button(button) - .config(config) - .ui(ui, |ui| { - ui.set_min_width(200.0); - ui.horizontal(|ui| { - for f in [Filter::All, Filter::Light, Filter::Dark] { - ui.selectable_value(&mut self.filter, f, f.name()); - } - }); - ui.separator(); - // Every family on screen at once, in as many columns as - // the window's height needs: nothing hides below a scroll. - let families = schemes::families(self.filter); - let rows = (((ui.ctx().content_rect().height() - 160.0) / FAMILY_ROW).floor() - as usize) - .clamp(6, families.len().max(6)); - let font = theme::regular(14.0); - let check = ui - .painter() - .layout_no_wrap(icon::CHECK.into(), font.clone(), p.accent) - .size() - .x; - ui.horizontal_top(|ui| { - for column in families.chunks(rows) { - // Each family's button as wide as its column, its - // flyout opening beside the column. - ui.allocate_ui_with_layout( - vec2(170.0, 0.0), - Layout::top_down_justified(Align::LEFT), - |ui| { - ui.set_width(170.0); - for (family, variants) in column { - let here = *family == self.scheme.family - && self.filter.shows(self.scheme); - // Only the family in force is checked; the - // others are indented by the check's width, - // so names line up and a screen reader hears - // the check only where it is. - let mut label = egui::text::LayoutJob::default(); - if here { - label.append( - icon::CHECK, - 0.0, - egui::TextFormat::simple(font.clone(), p.accent), - ); - } - let indent = if here { 8.0 } else { check + 8.0 }; - label.append( - family, - indent, - egui::TextFormat::simple(font.clone(), p.text), - ); - ui.menu_button(label, |ui| { - for v in variants { - let row = - scheme_row(ui, v, std::ptr::eq(*v, self.scheme)); - if row.hovered() { - hovered = Some(*v); - } - if row.clicked() { - chosen = Some(*v); - ui.close(); - } - } - }); - } - }, - ); - } - }); - }); - response.on_hover_text(format!("Color scheme: {}", self.scheme.label())); - match chosen { - Some(v) => self.choose(ui.ctx(), v), - None => self.preview(ui.ctx(), open.is_some(), hovered), - } - } - - /// Keep thumbnails on disk in `dir` (the live viewer keeps them in - /// the user's cache directory, `wanderbooks/thumbs`); tests point it - /// at their own. - pub fn keep_thumbs_in(&mut self, dir: std::path::PathBuf) { - self.receipts.thumb_dir = Some(dir); - self.receipts.forget_thumbs(); - if let Some(b) = self.books.clone() { - self.receipts.prefetch(&b); - } - } - - /// The size in pixels of a file's thumbnail, once drawn (tests). + /// The size in pixels of a file's thumbnail in the front tab, once + /// drawn (tests). pub fn thumb_size(&self, sha: &str) -> Option<[usize; 2]> { - self.receipts.thumb_size(sha) + self.active_view().and_then(|v| v.thumb_size(sha)) } - /// Block until every receipt on screen has rendered (screenshots). + /// Block until every receipt on screen in the front tab has rendered + /// (screenshots). pub fn settle(&mut self, ctx: &egui::Context) { - self.receipts.settle(ctx); + if let Some(v) = self.active_view_mut() { + v.settle(ctx); + } } - /// Go where the agent asked (`books.show`). - /// - /// ```text - /// GOAL: the viewer shows what the agent was told it shows. - /// SOURCE: BS-period-3 (one default period; a start after the end is - /// refused, never swapped); plan/served.md P3 defect 15. - /// INVARIANTS: - /// 1. A target's dates are taken as the server resolved them, an - /// omitted one (an earlier writer's) by the same rule - /// (Books::periods), never swapped, clamped or guessed. - /// 2. A target the viewer can't honour (an unknown page, report, - /// split or comparison; text that isn't a date; a start after - /// the end; an account, asset or party not in the books) is - /// ignored whole: the page, range and split stay as they were. - /// ``` + /// Go where the agent asked, in the front tab (`books.show`; tests). pub fn show(&mut self, target: ledger_store::ops::ViewerTarget) { - use crate::nav::ReportKind; - use ledger_store::ops::ViewerTarget as T; - let Some(b) = self.books.clone() else { - return; - }; - // Some(None): omitted; None: text that isn't a date. - let date = |s: &Option| match s.as_deref() { - None => Some(None), - Some(d) => d.parse::().ok().map(Some), - }; - let dates = |start: &Option, end: &Option| { - b.periods().statement(date(start)?, date(end)?).ok() - }; - let route = match target { - T::Page { page } => match page.as_str() { - "overview" => Route::Overview, - "cash" => Route::Cash, - "profit" => Route::Profit, - "transactions" => Route::Transactions, - "reports" => Route::Reports(ReportKind::ProfitAndLoss), - "accounts" => Route::Accounts, - "assets" => Route::Assets, - "parties" => Route::Parties, - "projects" => Route::Projects, - "documents" => Route::Documents, - "company" => Route::Company, - "journal" => Route::Journal, - _ => return, - }, - T::Entry { entry_id } => Route::Entry(entry_id), - T::Account { code, start, end } => { - use crate::pages::accounts::RegisterRange; - let Some(a) = b.ledger.chart().find_by_code(&code) else { - return; - }; - let Some((s, e)) = dates(&start, &end) else { - return; - }; - self.state.accounts.range = if start.is_none() && end.is_none() { - RegisterRange::Default - } else { - RegisterRange::Dates(s, e) - }; - Route::Account(a.id) - } - T::Report { - report, - start, - end, - columns, - compare, - } => { - use crate::pages::reports::{Columns, Compare, Range}; - let columns = match columns.as_deref() { - None | Some("total") => Columns::Total, - Some("month") => Columns::Month, - Some("quarter") => Columns::Quarter, - Some("year") => Columns::Year, - Some(_) => return, - }; - let compare = match compare.as_deref() { - None => Compare::None, - Some("prior_period") => Compare::PriorPeriod, - Some("prior_year") => Compare::PriorYear, - Some(_) => return, - }; - let Some((s, e)) = dates(&start, &end) else { - return; - }; - let kind = match report.as_str() { - "profit_and_loss" => ReportKind::ProfitAndLoss, - "balance_sheet" => ReportKind::BalanceSheet, - "cash_flow" => ReportKind::CashFlow, - "members_equity" => ReportKind::MembersEquity, - "trial_balance" => ReportKind::TrialBalance, - "general_ledger" => ReportKind::GeneralLedger, - "tax_summary" => ReportKind::TaxSummary, - "vendor_1099" => ReportKind::Vendor1099, - "ar_aging" => ReportKind::ArAging, - "ap_aging" => ReportKind::ApAging, - "fixed_asset_register" => ReportKind::FixedAssetRegister, - _ => return, - }; - self.state.reports.columns = columns; - self.state.reports.compare = compare; - // The dates as sent, by a preset's name when they are one - // (the default first: "Year to date"), else Custom. - self.state.reports.range = std::iter::once(Range::default()) - .chain(Range::PRESETS) - .find(|r| r.dates(&b) == (s, e)) - .unwrap_or(Range::Custom(s, e)); - Route::Reports(kind) - } - T::Document { attachment_id } => Route::Document(attachment_id), - T::Asset { asset_id } => { - if b.ledger.get_asset(asset_id).is_none() { - return; - } - Route::Asset(asset_id) - } - T::Party { party_id } => { - if b.ledger.get_party(party_id).is_none() { - return; - } - Route::Party(party_id) - } - T::Project { class_id } => { - if b.ledger.get_class(class_id).is_none() { - return; - } - Route::Project(class_id) - } - T::Reconciliation { id } => { - // Its own page: statement, balance, the lines it cleared. - if b.reconciliation(id).is_none() { - return; - } - Route::Reconciliation(id) - } - T::Search { query } => { - let st = &mut self.state.transactions; - st.query = query; - st.filter = Default::default(); - st.account = None; - Route::Transactions - } - }; - self.nav.go(route); + if let Some(v) = self.active_view_mut() { + v.show(target); + } } - /// Where the app is (tests). + /// Where the front tab is (tests). pub fn route(&self) -> &Route { - &self.nav.current + match self.active_view() { + Some(v) => v.route(), + None => &Route::Overview, + } } - /// Page state (tests). - /// Label a fixed-books app "Live", as it reads when following a - /// journal (screenshots of what a running app looks like). + /// Label the front tab "Live", as it reads when following a journal + /// (screenshots of what a running app looks like). pub fn show_live_label(&mut self) { - self.live_label = true; + if let Some(v) = self.active_view_mut() { + v.show_live_label(); + } } + /// The front tab's page state (tests). + /// + /// # Panics + /// With no tab open. pub fn state_mut(&mut self) -> &mut PageState { - &mut self.state + self.views[self.active].state_mut() } - fn handle_keys(&mut self, ui: &Ui) { - // The agent in the dock has the keyboard while it is clicked on. - if self.dock.has_keyboard() { - return; - } - let (back, fwd, palette) = ui.input(|i| { - ( - (i.modifiers.alt && i.key_pressed(Key::ArrowLeft)) - || i.pointer.button_pressed(egui::PointerButton::Extra1), - (i.modifiers.alt && i.key_pressed(Key::ArrowRight)) - || i.pointer.button_pressed(egui::PointerButton::Extra2), - i.modifiers.command && i.key_pressed(Key::K), - ) - }); - if back { - self.nav.back(); - } - if fwd { - self.nav.forward(); - } - if palette { - self.palette.open(); - } - } - - /// The sidebar: full below [`COMPACT_BELOW`] window widths, an icon - /// rail (names in tooltips) when the window is narrower. - fn sidebar(&mut self, ui: &mut Ui, compact: bool) { - if compact { - return self.rail(ui); - } + /// The window with no company in it. + fn empty(&self, ui: &mut Ui) { let p = pal(ui.ctx()); - let books = self.books.clone(); - egui::Panel::left("sidebar") - .exact_size(224.0) - .resizable(false) - .frame( - Frame::new() - .fill(p.sidebar) - .inner_margin(Margin::symmetric(12, 16)), - ) + egui::CentralPanel::no_frame() + .frame(Frame::new().fill(p.bg)) .show(ui, |ui| { - ui.horizontal(|ui| { - let (r, _) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::hover()); - ui.painter().rect_filled(r, CornerRadius::same(8), p.accent); - let initial = books - .as_ref() - .and_then(|b| b.company_name().chars().next()) - .unwrap_or('W'); - ui.painter().text( - r.center(), - egui::Align2::CENTER_CENTER, - initial, - theme::bold(15.0), - schemes::on(p.accent), - ); - ui.vertical(|ui| { - ui.spacing_mut().item_spacing.y = 0.0; - let name = books - .as_ref() - .map(|b| b.company_name().to_string()) - .unwrap_or_else(|| "wanderbooks".into()); - ui.add( - egui::Label::new(RichText::new(name).font(theme::semibold(13.5))) - .truncate(), - ); + ui.centered_and_justified(|ui| { + ui.vertical_centered(|ui| { + ui.add_space((ui.available_height() / 2.0 - 40.0).max(0.0)); + ui.label(RichText::new("No company is open").font(theme::semibold(18.0))); + ui.add_space(6.0); ui.label( - RichText::new("Books") - .font(theme::regular(11.5)) + RichText::new("Open a company with the + at the top of the window.") + .font(theme::regular(14.0)) .color(p.muted), ); }); }); - let current = self.nav.current.section(); - let attention = books.as_ref().map(|b| b.attention.len()).unwrap_or(0); - // Short windows give way in steps (Fit): the status card - // folds, then the rows tighten, then the links scroll. - // The footer's heights are the ones it was drawn at. - let fold = 3.0 - * (ui.ctx().fonts_mut(|f| f.row_height(&theme::regular(11.5))) - + ui.spacing().item_spacing.y); - let memo = FooterMemo::load(ui, "sidebar"); - let heights = memo.heights(SIDEBAR_FOOTER, fold, SIDEBAR_TIGHTEN); - let fit = fit(ui.available_height(), heights, &SIDEBAR_ROWS, slack(ui)); - ui.add_space(if fit.tight { - HEAD_GAP_TIGHT - } else { - SIDEBAR_ROWS.head_gap - }); - let footer_h = heights[fit.form()]; - // At least one link always shows; below that the footer - // gives way (footer_layout). - let links_h = (ui.available_height() - footer_h - FOOTER_GAP).max(fit.row); - let nav = &mut self.nav; - links(ui, "sidebar", fit, links_h, current, |ui, s| { - let on = s == current; - let (rect, resp) = - ui.allocate_exact_size(vec2(ui.available_width(), fit.row), Sense::click()); - // Named for assistive tech (and the tests). - resp.widget_info(|| { - egui::WidgetInfo::labeled(egui::WidgetType::Button, true, s.title()) - }); - if on { - ui.painter() - .rect_filled(rect, CornerRadius::same(8), p.surface); - ui.painter().rect_stroke( - rect, - CornerRadius::same(8), - Stroke::new(1.0, p.border), - egui::StrokeKind::Inside, - ); - } else if resp.hovered() { - ui.painter() - .rect_filled(rect, CornerRadius::same(8), p.hover); - } - let color = if on { p.text } else { p.muted }; - ui.painter().text( - rect.left_center() + vec2(10.0, 0.0), - egui::Align2::LEFT_CENTER, - s.icon(), - egui::FontId::proportional(16.0), - if on { p.accent } else { p.muted }, - ); - ui.painter().text( - rect.left_center() + vec2(36.0, 0.0), - egui::Align2::LEFT_CENTER, - s.title(), - if on { - theme::semibold(13.5) - } else { - theme::regular(13.5) - }, - color, - ); - if s == Section::Overview && attention > 0 { - let badge = egui::Rect::from_center_size( - rect.right_center() - vec2(18.0, 0.0), - vec2(22.0, 18.0), - ); - ui.painter() - .rect_filled(badge, CornerRadius::same(9), p.warning_soft); - ui.painter().text( - badge.center(), - egui::Align2::CENTER_CENTER, - attention.to_string(), - theme::semibold(11.0), - p.warning, - ); - } - if resp.clicked() { - nav.go(s.home()); - } - resp - }); - let footer = footer_layout(ui, footer_h, Align::Min, |ui| { - if fit.tight { - tighten(ui); - } - self.scheme_menu(ui, false); - if let Some(b) = &books { - ui.add_space(2.0); - self.menu.ui(ui, b, false); - self.owner_menu.ui(ui, b, false); - } - ui.add_space(6.0); - if let Some(b) = &books { - live_status( - ui, - b, - ui.input(|i| i.time) - self.updated_at, - self.loader.is_some() || self.live_label, - fit.folded, - ); - } - }); - memo.measured(ui, "sidebar", fit.form(), footer.response.rect); - }); - } - - /// The sidebar as a narrow rail of icons, for narrow windows. - fn rail(&mut self, ui: &mut Ui) { - let p = pal(ui.ctx()); - let books = self.books.clone(); - egui::Panel::left("rail") - .exact_size(RAIL_W) - .resizable(false) - .frame( - Frame::new() - .fill(p.sidebar) - .inner_margin(Margin::symmetric(10, 16)), - ) - .show(ui, |ui| { - let name = books - .as_ref() - .map(|b| b.company_name().to_string()) - .unwrap_or_else(|| "wanderbooks".into()); - let (r, _) = - ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover()); - let logo = egui::Rect::from_center_size(r.center(), vec2(28.0, 28.0)); - ui.painter() - .rect_filled(logo, CornerRadius::same(8), p.accent); - ui.painter().text( - logo.center(), - egui::Align2::CENTER_CENTER, - name.chars().next().unwrap_or('W'), - theme::bold(15.0), - schemes::on(p.accent), - ); - ui.interact(r, ui.id().with("logo"), Sense::hover()) - .on_hover_text(format!("{name} · Books")); - let current = self.nav.current.section(); - let attention = books.as_ref().map(|b| b.attention.len()).unwrap_or(0); - // As the sidebar's, with no card to fold. - let memo = FooterMemo::load(ui, "rail"); - let heights = memo.heights(RAIL_FOOTER, 0.0, RAIL_TIGHTEN); - let fit = fit(ui.available_height(), heights, &RAIL_ROWS, slack(ui)); - ui.add_space(if fit.tight { - HEAD_GAP_TIGHT - } else { - RAIL_ROWS.head_gap - }); - let footer_h = heights[fit.form()]; - let links_h = (ui.available_height() - footer_h - FOOTER_GAP).max(fit.row); - let nav = &mut self.nav; - links(ui, "rail", fit, links_h, current, |ui, s| { - let on = s == current; - let (rect, resp) = - ui.allocate_exact_size(vec2(ui.available_width(), fit.row), Sense::click()); - resp.widget_info(|| { - egui::WidgetInfo::labeled(egui::WidgetType::Button, true, s.title()) - }); - if on { - ui.painter() - .rect_filled(rect, CornerRadius::same(8), p.surface); - ui.painter().rect_stroke( - rect, - CornerRadius::same(8), - Stroke::new(1.0, p.border), - egui::StrokeKind::Inside, - ); - } else if resp.hovered() { - ui.painter() - .rect_filled(rect, CornerRadius::same(8), p.hover); - } - ui.painter().text( - rect.center(), - egui::Align2::CENTER_CENTER, - s.icon(), - egui::FontId::proportional(18.0), - if on { p.accent } else { p.muted }, - ); - let tip = if s == Section::Overview && attention > 0 { - ui.painter() - .circle_filled(rect.center() + vec2(9.0, -8.0), 4.0, p.warning); - format!("{} · {attention} need attention", s.title()) - } else { - s.title().to_string() - }; - let resp = resp.on_hover_text(tip); - if resp.clicked() { - nav.go(s.home()); - } - resp - }); - let footer = footer_layout(ui, footer_h, Align::Center, |ui| { - if fit.tight { - tighten(ui); - } - self.scheme_menu(ui, true); - if let Some(b) = &books { - self.menu.ui(ui, b, true); - self.owner_menu.ui(ui, b, true); - } - ui.add_space(6.0); - if let Some(b) = &books { - let live = self.loader.is_some() || self.live_label; - let checks = checks(b); - let ok = checks.iter().all(|c| c.0); - let (r, resp) = ui.allocate_exact_size( - vec2(32.0, ui.spacing().interact_size.y + 4.0), - Sense::hover(), - ); - if ok { - let pulse = (ui.input(|i| i.time) - self.updated_at < 2.0) as u8 as f32; - ui.painter().circle_filled( - r.center(), - 4.0 + pulse, - if live { p.positive } else { p.faint }, - ); - } else { - ui.painter().text( - r.center(), - egui::Align2::CENTER_CENTER, - icon::WARNING_CIRCLE, - egui::FontId::proportional(18.0), - p.negative, - ); - } - let mut tip = format!( - "{} · event {}", - if live { "Live" } else { "Snapshot" }, - b.seq() - ); - for (ok, text, _) in &checks { - tip.push_str(&format!( - "\n{} {text}", - if *ok { - icon::SEAL_CHECK - } else { - icon::WARNING_CIRCLE - } - )); - } - resp.on_hover_text(tip); - } - }); - memo.measured(ui, "rail", fit.form(), footer.response.rect); - }); - } - - /// Back, forward, where you are, today, and search. Squeezed, the - /// search shrinks to its icon, the date goes, and the crumb truncates: - /// nothing ever overlaps. - fn topbar(&mut self, ui: &mut Ui) { - let p = pal(ui.ctx()); - egui::Panel::top("topbar") - .exact_size(52.0) - .frame( - Frame::new() - .fill(p.bg) - .inner_margin(Margin::symmetric(16, 10)) - .stroke(Stroke::new(1.0, p.border)), - ) - .show(ui, |ui| { - let width = ui.available_width(); - ui.horizontal_centered(|ui| { - let nav_btn = |ui: &mut Ui, glyph: &str, enabled: bool, tip: &str| { - ui.add_enabled( - enabled, - egui::Button::new(RichText::new(glyph).size(16.0)) - .frame(false) - .min_size(vec2(28.0, 28.0)), - ) - .on_hover_text(tip) - .clicked() - }; - if nav_btn(ui, icon::ARROW_LEFT, self.nav.can_back(), "Back (Alt+←)") { - self.nav.back(); - } - if nav_btn( - ui, - icon::ARROW_RIGHT, - self.nav.can_forward(), - "Forward (Alt+→)", - ) { - self.nav.forward(); - } - ui.add_space(6.0); - // Right side first, so the crumb gets only what's left. - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let (text, min_w) = if width >= 640.0 { - ( - format!( - "{} Search everything… Ctrl K", - icon::MAGNIFYING_GLASS - ), - 260.0, - ) - } else if width >= 420.0 { - (format!("{} Search", icon::MAGNIFYING_GLASS), 0.0) - } else { - (icon::MAGNIFYING_GLASS.to_string(), 30.0) - }; - let search = egui::Button::new( - RichText::new(text) - .font(theme::regular(13.0)) - .color(p.faint), - ) - .fill(p.surface) - .stroke(Stroke::new(1.0, p.border)) - .corner_radius(CornerRadius::same(8)) - .min_size(vec2(min_w, 30.0)); - if ui - .add(search) - .on_hover_text("Search everything (Ctrl K)") - .clicked() - { - self.palette.open(); - } - if let Some(b) = &self.books - && width >= 860.0 - { - ui.label( - RichText::new(format!("Today {}", crate::fmt::date(b.today))) - .font(theme::regular(12.5)) - .color(p.muted), - ); - } - ui.add_space(8.0); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - let crumbs = - crate::palette::crumbs(self.books.as_deref(), &self.nav.current); - // Narrow, the last crumb alone says where you are. - let skip = if ui.available_width() >= 260.0 { - 0 - } else { - crumbs.len() - 1 - }; - let last = crumbs.len() - 1; - let mut go = None; - for (i, (text, to)) in crumbs.iter().enumerate().skip(skip) { - if i > skip && ui.available_width() >= 260.0 - 80.0 { - ui.label(RichText::new(icon::CARET_RIGHT).color(p.faint)); - } - let rich = if i == last && i > 0 { - RichText::new(text).font(theme::semibold(13.5)) - } else { - RichText::new(text) - .font(theme::regular(13.5)) - .color(p.muted) - }; - let label = egui::Label::new(rich).truncate(); - match to { - Some(to) => { - let r = ui.add(label.sense(egui::Sense::click())); - if r.hovered() { - ui.ctx() - .set_cursor_icon(egui::CursorIcon::PointingHand); - } - if r.on_hover_text(format!("Go to {text}")).clicked() { - go = Some(to.clone()); - } - } - None => { - ui.add(label); - } - } - } - if let Some(to) = go { - self.nav.go(to); - } - }); - }); - }); }); } } -/// Width of the icon rail. -const RAIL_W: f32 = 60.0; -/// The footer's height (the status box and the menus under the sidebar's -/// links; the rail's equivalent) before it is first measured. After the -/// first frame its drawn heights are used ([`FooterMemo`]). -const SIDEBAR_FOOTER: f32 = 172.0; -const RAIL_FOOTER: f32 = 84.0; -/// How much shorter the footer is tightened ([`tighten`]), before it is -/// measured so. -const SIDEBAR_TIGHTEN: f32 = 36.0; -const RAIL_TIGHTEN: f32 = 36.0; - -/// Space kept between the last link and the footer. -const FOOTER_GAP: f32 = 8.0; - -/// Tightened: the space between links, and under the header. -const GAP_MIN: f32 = 2.0; -const HEAD_GAP_TIGHT: f32 = 8.0; - -/// A panel's links: how many, their height and spacing, the least height -/// they tighten to, the gap above them, and whether its status card folds. -struct Rows { - n: usize, - row: f32, - gap: f32, - row_min: f32, - head_gap: f32, - foldable: bool, +/// The ids of the books in the data root at `root`, in order; none when +/// it can't be read. +fn list_books(root: &std::path::Path) -> Vec { + ledger_store::root::Root::find(Some(root)) + .and_then(|r| r.list_books()) + .map(|ids| ids.iter().map(|i| i.as_str().to_string()).collect()) + .unwrap_or_default() } -impl Rows { - fn height(&self, row: f32, gap: f32) -> f32 { - let n = self.n as f32; - n * row + (n - 1.0) * gap - } -} - -const SIDEBAR_ROWS: Rows = Rows { - n: Section::ALL.len(), - row: 32.0, - gap: 6.0, - // 22, not 24, since Invoices & Bills made 13 links (2026-10-24): so - // they still fit the owner's 1479x519 window unscrolled. - row_min: 22.0, - head_gap: 18.0, - foldable: true, -}; - -const RAIL_ROWS: Rows = Rows { - n: Section::ALL.len(), - row: 36.0, - gap: 6.0, - // As low as the sidebar's: at 28 the rail scrolled in the owner's - // window (review, 2026-10-22), and at 24 once there were 13 links. - row_min: 22.0, - head_gap: 18.0, - foldable: false, -}; - -/// How a panel's links and footer share the window's height (owner, -/// 2026-10-22: at 1479x519 half the links hid behind the status box). -/// Each step is taken only when the one before isn't enough, so where -/// everything fits nothing changes. -#[derive(Clone, Copy, Debug, PartialEq)] -struct Fit { - /// 1. The status card folded to its summary line. - folded: bool, - /// 2. The rows tightened: the footer's menus, the gap under the - /// header, and the links' spacing, then their height. - tight: bool, - row: f32, - gap: f32, - /// 3. Even tight they don't fit: the links scroll. - scroll: bool, -} - -impl Fit { - /// Which of the footer's three forms it draws: full, folded, tight. - fn form(&self) -> usize { - if self.tight { - 2 - } else if self.folded { - 1 - } else { - 0 +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); } } } -/// The fit for `avail` points under the header, the footer being -/// `footer` high in each form ([`Fit::form`]), overrunning by `slack` -/// points ([`slack`]) taken as fitting. -fn fit(avail: f32, footer: [f32; 3], g: &Rows, slack: f32) -> Fit { - let full = g.height(g.row, g.gap); - let at_ease = Fit { - folded: false, - tight: false, - row: g.row, - gap: g.gap, - scroll: false, - }; - // The links fit when what they overrun is under half a pixel - // (`slack`, points), which no one sees: at 1.25 the rows' sum runs a - // hair over whole points, and without it the card folded where main - // drew everything (review, 2026-10-22). - let fits = |footer: f32| avail - g.head_gap - FOOTER_GAP - footer + slack >= full; - if fits(footer[0]) { - return at_ease; - } - if g.foldable && fits(footer[1]) { - return Fit { - folded: true, - ..at_ease - }; - } - let tight = Fit { - folded: g.foldable, - tight: true, - ..at_ease - }; - let room = avail - HEAD_GAP_TIGHT - FOOTER_GAP - footer[2]; - let n = g.n as f32; - // The space between the links gives first, then the links. - let gap = ((room - n * g.row) / (n - 1.0)).floor(); - if gap >= GAP_MIN { - return Fit { - gap: gap.min(g.gap), - ..tight - }; - } - let row = ((room - (n - 1.0) * GAP_MIN) / n).floor(); - if row >= g.row_min { - return Fit { - row: row.min(g.row), - gap: GAP_MIN, - ..tight - }; - } - Fit { - row: g.row_min, - gap: GAP_MIN, - scroll: true, - ..tight - } -} - -/// Half a pixel, in points: links overrunning their room by less are -/// drawn whole, with no cue. -fn slack(ui: &Ui) -> f32 { - 0.5 / ui.ctx().pixels_per_point() -} - -/// The footer's height in each form, as last drawn; a form not drawn yet -/// is estimated from one that was. -#[derive(Clone, Copy, Debug, Default)] -struct FooterMemo([Option; 3]); - -impl FooterMemo { - fn id(key: &str) -> egui::Id { - egui::Id::new((key, "footer_memo")) - } - - fn load(ui: &Ui, key: &str) -> FooterMemo { - ui.ctx() - .data(|d| d.get_temp(Self::id(key))) - .unwrap_or_default() - } - - /// Each form's height: `guess` full before anything was drawn, a - /// form not drawn `fold` (the card's checks) and `tighten` shorter - /// than the one before it. - fn heights(&self, guess: f32, fold: f32, tighten: f32) -> [f32; 3] { - let off = [0.0, -fold, -fold - tighten]; - let anchor = (0..3) - .find_map(|i| self.0[i].map(|h| h - off[i])) - .unwrap_or(guess); - std::array::from_fn(|i| self.0[i].unwrap_or(anchor + off[i])) - } - - /// Keep form `form`'s drawn height for the next frame (the footer's - /// content changing moves every form alike), the footer's rect for - /// the tests, and draw again at once when it changed. - fn measured(mut self, ui: &Ui, key: &str, form: usize, rect: egui::Rect) { - let h = rect.height(); - let changed = match self.0[form] { - Some(old) if (old - h).abs() <= 0.5 => false, - Some(old) => { - for v in self.0.iter_mut().flatten() { - *v += h - old; - } - true - } - None => { - self.0[form] = Some(h); - true - } - }; - ui.ctx().data_mut(|d| { - d.insert_temp(Self::id(key), self); - d.insert_temp(egui::Id::new(format!("{key}_footer_rect")), rect); - d.insert_temp(egui::Id::new(format!("{key}_footer_h")), h); - }); - if changed { - ui.ctx().request_repaint(); - } - } -} - -/// The footer's menus tightened, as the links are. -fn tighten(ui: &mut Ui) { - let s = ui.spacing_mut(); - s.item_spacing.y = GAP_MIN; - s.interact_size.y = 22.0; - s.button_padding.y = 2.0; -} - -/// Height of the fade over a clipped edge of the links. -const FADE: f32 = 28.0; - -/// A panel's links, `row` draws one: at most `max_h` high, scrolling -/// when they don't fit, then with a fade and a chevron at each clipped -/// edge, and the current page's link scrolled into view whenever the -/// page changes. What it drew is kept for the tests -/// (`{key}_links_view`, `{key}_links_scroll`). -fn links( - ui: &mut Ui, - key: &str, - fit: Fit, - max_h: f32, - current: Section, - mut row: impl FnMut(&mut Ui, Section) -> egui::Response, -) { - // Last frame's page, viewport height and scrolling: the current link - // is scrolled into view when they change while the links scroll. - let shown_id = egui::Id::new((key, "links_shown")); - let shown = ui - .ctx() - .data(|d| d.get_temp::<(Section, i32, bool)>(shown_id)); - let now = (current, max_h.round() as i32); - let reveal = fit.scroll && shown != Some((now.0, now.1, true)); - let out = egui::ScrollArea::vertical() - .id_salt(format!("{key}_links")) - .max_height(max_h) - .show(ui, |ui| { - ui.spacing_mut().item_spacing.y = fit.gap; - for s in Section::ALL { - let resp = row(ui, s); - if reveal && s == current { - resp.scroll_to_me(Some(Align::Center)); - } - } - }); - let view = out.inner_rect; - let content = out.content_size.y; - let offset = out.state.offset.y; - let scrolls = content > view.height() + slack(ui); - ui.ctx().data_mut(|d| { - d.insert_temp(shown_id, (now.0, now.1, scrolls)); - d.insert_temp(egui::Id::new(format!("{key}_links_view")), view); - d.insert_temp(egui::Id::new(format!("{key}_links_scroll")), scrolls); - }); - if !scrolls { - return; - } - let p = pal(ui.ctx()); - let painter = ui.painter().with_clip_rect(view); - let above = offset > 0.5; - let below = offset + view.height() < content - 0.5; - for (clipped, down) in [(above, false), (below, true)] { - if !clipped { - continue; - } - let h = FADE.min(view.height() / 2.0); - let (band, edge_y) = if down { - ( - egui::Rect::from_min_max(egui::pos2(view.left(), view.bottom() - h), view.max), - view.bottom() - 8.0, - ) - } else { - ( - egui::Rect::from_min_max(view.min, egui::pos2(view.right(), view.top() + h)), - view.top() + 8.0, - ) - }; - let (top, bottom) = if down { - (egui::Color32::TRANSPARENT, p.sidebar) - } else { - (p.sidebar, egui::Color32::TRANSPARENT) - }; - let mut mesh = egui::Mesh::default(); - mesh.colored_vertex(band.left_top(), top); - mesh.colored_vertex(band.right_top(), top); - mesh.colored_vertex(band.left_bottom(), bottom); - mesh.colored_vertex(band.right_bottom(), bottom); - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(1, 3, 2); - painter.add(egui::Shape::mesh(mesh)); - // The sidebar's at the edge's right end, clear of the links' - // names. The rail's has no room beside its icons (there it read - // as a caret on one): centred on the edge, on a pill of its own - // that covers the faded icon under it. - let narrow = view.width() < 80.0; - let chevron = if narrow { - egui::Rect::from_center_size( - egui::pos2( - view.center().x, - if down { - view.bottom() - 7.0 - } else { - view.top() + 7.0 - }, - ), - vec2(26.0, 14.0), - ) - } else { - egui::Rect::from_center_size(egui::pos2(view.right() - 14.0, edge_y), vec2(24.0, 16.0)) - }; - let label = if down { - "More links below" - } else { - "More links above" - }; - let resp = ui - .interact(chevron, ui.id().with((key, down)), Sense::click()) - .on_hover_text(label); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); - if narrow { - painter.rect( - chevron, - CornerRadius::same(7), - if resp.hovered() { p.hover } else { p.sidebar }, - Stroke::new(1.0, p.border), - egui::StrokeKind::Inside, - ); - } - painter.text( - chevron.center(), - egui::Align2::CENTER_CENTER, - if down { - icon::CARET_DOWN - } else { - icon::CARET_UP - }, - egui::FontId::proportional(if narrow { 11.0 } else { 14.0 }), - if resp.hovered() { p.text } else { p.muted }, - ); - if resp.clicked() { - // A page of links on, keeping one link of the last in view. - let step = (view.height() - fit.row - fit.gap).max(fit.row); - let mut state = out.state; - state.offset.y = (offset + if down { step } else { -step }) - .clamp(0.0, (content - view.height()).max(0.0)); - state.store(ui.ctx(), out.id); - ui.ctx().request_repaint(); - } - } -} - -/// The sidebar's footer, bottom up: on the panel's floor when it fits -/// under the links, else right under them, running off the bottom of the -/// window, so it gives way and never draws over a link. -fn footer_layout( - ui: &mut Ui, - footer_h: f32, - align: Align, - add: impl FnOnce(&mut Ui) -> R, -) -> egui::InnerResponse { - if ui.available_height() >= footer_h { - ui.with_layout(Layout::bottom_up(align), add) - } else { - let w = ui.available_width(); - ui.allocate_ui_with_layout(vec2(w, footer_h), Layout::bottom_up(align), add) - } -} - -/// The status card: whether the books are live, their newest event, and -/// the integrity checks. Folded (a short window), one line, the checks -/// in its tooltip. -fn live_status(ui: &mut Ui, b: &Books, since_update: f64, live: bool, folded: bool) { - if folded { - return folded_status(ui, b, since_update, live); - } - let p = pal(ui.ctx()); - Frame::new() - .fill(p.surface) - .stroke(Stroke::new(1.0, p.border)) - .corner_radius(CornerRadius::same(8)) - .inner_margin(Margin::same(10)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - let (r, _) = ui.allocate_exact_size(vec2(8.0, 8.0), Sense::hover()); - let pulse = (since_update < 2.0) as u8 as f32; - let color = if live { p.positive } else { p.faint }; - ui.painter().circle_filled(r.center(), 4.0 + pulse, color); - ui.label( - RichText::new(if live { "Live" } else { "Snapshot" }) - .font(theme::semibold(12.0)), - ); - ui.label( - RichText::new(format!("· event {}", b.seq())) - .font(theme::regular(12.0)) - .color(p.muted), - ); - }); - for (ok, text, tip) in checks(b) { - let (glyph, color) = if ok { - (icon::SEAL_CHECK, p.muted) - } else { - (icon::WARNING_CIRCLE, p.negative) - }; - let r = ui - .label( - RichText::new(format!("{glyph} {text}")) - .font(theme::regular(11.5)) - .color(color), - ) - .on_hover_text(tip); - if text == "Journal chain verified" { - r.context_menu(|ui| { - crate::widgets::copy_item(ui, "Copy journal head", &b.head); - crate::widgets::copy_item( - ui, - "Copy data folder", - &b.data_dir.display().to_string(), - ); - }); - } - } - }); -} - -/// The status card folded to its summary line ("● Live · event 559 · -/// ✓ verified", or the check that failed), the three checks on hover -/// and the card's copy menu on a right click. The line is the fullest -/// of [`summaries`] that fits the card, so it is never cut off: a failed -/// check's name outranks the event and the word "Live" (review, -/// 2026-10-22: cut to "⊘ Datab…" it hid what failed). -fn folded_status(ui: &mut Ui, b: &Books, since_update: f64, live: bool) { - let p = pal(ui.ctx()); - let checks = checks(b); - let failed: Vec<&str> = checks - .iter() - .filter(|c| !c.0) - .map(|c| c.1.as_str()) - .collect(); - let status = if live { "Live" } else { "Snapshot" }; - let event = format!("· event {}", b.seq()); - // The card's inner width: the panel's less the frame's margins. - let room = ui.available_width() - 2.0 * 10.0 - 2.0; - let gap = 5.0; - let width = |s: &Summary| { - let w = |text: &str, font: egui::FontId| { - ui.fonts_mut(|f| f.layout_no_wrap(text.to_string(), font, p.text).size().x) - }; - let mut x = 8.0 + gap + w(s.verdict(), theme::regular(12.0)); - if s.status { - x += gap + w(status, theme::semibold(12.0)); - } - if s.event { - x += gap + w(&event, theme::regular(12.0)); - } - x - }; - let all = summaries(&failed); - let line = all - .iter() - .find(|s| width(s) <= room) - .unwrap_or_else(|| all.last().expect("a summary")); - let color = if failed.is_empty() { - p.muted - } else { - p.negative - }; - let card = Frame::new() - .fill(p.surface) - .stroke(Stroke::new(1.0, p.border)) - .corner_radius(CornerRadius::same(8)) - .inner_margin(Margin::same(10)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = gap; - let (r, _) = ui.allocate_exact_size(vec2(8.0, 8.0), Sense::hover()); - let pulse = (since_update < 2.0) as u8 as f32; - let dot = if live { p.positive } else { p.faint }; - ui.painter().circle_filled(r.center(), 4.0 + pulse, dot); - if line.status { - ui.label(RichText::new(status).font(theme::semibold(12.0))); - } - if line.event { - ui.label( - RichText::new(&event) - .font(theme::regular(12.0)) - .color(p.muted), - ); - } - ui.label( - RichText::new(line.verdict()) - .font(theme::regular(12.0)) - .color(color), - ); - }); - }); - let resp = ui.interact( - card.response.rect, - ui.id().with("folded_status"), - Sense::click(), - ); - resp.on_hover_ui(|ui| { - if !(line.status && line.event) { - ui.label( - RichText::new(format!("{status} {event}")) - .font(theme::regular(11.5)) - .color(p.muted), - ); - } - for (ok, text, _) in &checks { - let (glyph, color) = if *ok { - (icon::SEAL_CHECK, p.muted) - } else { - (icon::WARNING_CIRCLE, p.negative) - }; - ui.label( - RichText::new(format!("{glyph} {text}")) - .font(theme::regular(11.5)) - .color(color), - ); - } - }) - .context_menu(|ui| { - crate::widgets::copy_item(ui, "Copy journal head", &b.head); - crate::widgets::copy_item(ui, "Copy data folder", &b.data_dir.display().to_string()); - }); -} - -/// One way to say the folded card's line: whether it names the status -/// ("Live") and the event, and its verdict. -#[derive(Clone, Debug, PartialEq)] -struct Summary { - status: bool, - event: bool, - verdict: String, -} - -impl Summary { - /// The verdict as drawn: right after the dot it needs no "·". - fn verdict(&self) -> &str { - if self.status { - &self.verdict - } else { - self.verdict.trim_start_matches("· ") - } - } -} - -/// The folded card's lines, fullest first, given the checks that -/// `failed`. All passing, the event outranks the word "verified" (the -/// seal says it). A failure is named before anything else is kept: the -/// event goes first, then "Live" (the dot's colour says it), and only -/// then is the name shortened to a count. Whatever the line leaves out -/// its tooltip says. -fn summaries(failed: &[&str]) -> Vec { - let s = |status, event, verdict: String| Summary { - status, - event, - verdict, - }; - match failed { - [] => { - let full = format!("· {} verified", icon::SEAL_CHECK); - let seal = format!("· {}", icon::SEAL_CHECK); - vec![ - s(true, true, full.clone()), - s(true, true, seal.clone()), - s(true, false, full), - s(true, false, seal.clone()), - s(false, false, seal), - ] - } - names => { - let named = format!("· {} {}", icon::WARNING_CIRCLE, names.join(", ")); - let counted = match names.len() { - 1 => format!("· {} check failed", icon::WARNING_CIRCLE), - n => format!("· {} {n} checks failed", icon::WARNING_CIRCLE), - }; - let short = match names.len() { - 1 => format!("· {} failed", icon::WARNING_CIRCLE), - n => format!("· {} {n} failed", icon::WARNING_CIRCLE), - }; - vec![ - s(true, true, named.clone()), - s(true, false, named.clone()), - s(false, false, named), - s(true, false, counted.clone()), - s(false, false, counted), - s(false, false, short), - ] - } - } -} - -/// The integrity checks the sidebar shows: (ok, label, explanation). -fn checks(b: &Books) -> Vec<(bool, String, String)> { - use ledger_store::DiskCheck; - let mut out = vec![( - true, - "Journal chain verified".to_string(), - format!( - "Every journal event's hash chains to the one before it.\nHead: {}\nData: {}", - b.head, - b.data_dir.display() - ), - )]; - out.push(match &b.integrity.disk { - DiskCheck::Matches => (true, "Database matches journal".to_string(), "The server's SQLite database matches a fresh projection of the journal, every table, row for row.".to_string()), - DiskCheck::Behind { applied, journal } => (true, "Database catching up".to_string(), format!("The database has applied {applied} of {journal} journal events; the server applies the rest right after writing them.")), - DiskCheck::Ahead { .. } => (true, "Viewer catching up".to_string(), "The server has written journal events this view hasn't read yet; it reads them on its next refresh.".to_string()), - DiskCheck::Missing => (true, "Read-only copy".to_string(), "No server database here: a copy of the books (a CPA's, say), or the server hasn't run yet. The journal and every file are verified either way.".to_string()), - DiskCheck::Differs(why) => (false, "Database differs".to_string(), format!("{why}. The server rebuilds it from the journal (books.verify, or on its next start).")), - DiskCheck::Unreadable(why) => (false, "Database unreadable".to_string(), why.clone()), - }); - let bad = b.integrity.file_failures.len(); - out.push(( - bad == 0, - if bad == 0 { - format!("{} files verified", b.integrity.files_ok) - } else { - format!("{bad} files damaged") - }, - "Every stored receipt and document re-hashed against its recorded SHA-256.".into(), - )); - out -} - 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. - if self.welcome.is_some() && self.books.is_none() { + if self.welcome.is_some() && self.views.is_empty() { let p = pal(ui.ctx()); let owner = crate::owner::current(); let mut open = None; @@ -1729,259 +751,104 @@ impl eframe::App for App { } return; } - let updates = self.loader.as_ref().map(|l| l.poll()).unwrap_or_default(); - for u in updates { - match u { - Update::Books(b) => { - if self.books.is_some() { - self.updated_at = ui.input(|i| i.time); - } - self.receipts.prefetch(&b); - self.books = Some(b); - self.error = None; - } - Update::Error(e) => self.error = Some(e), - Update::Show(target) => self.show(target), - } + let ctx = ui.ctx().clone(); + // Every view takes what its loader has sent, the one in front + // and the others alike (views INVARIANT 3). + for (i, v) in self.views.iter_mut().enumerate() { + v.pump(&ctx, i == self.active); } - self.receipts.pump(ui.ctx()); - self.handle_keys(ui); - let compact = ui.available_width() < COMPACT_BELOW; - self.sidebar(ui, compact); - self.topbar(ui); - self.dock(ui); - let p = pal(ui.ctx()); - let since_update = ui.input(|i| i.time) - self.updated_at; - if since_update < 6.0 { - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(250)); + self.guard_close(&ctx); + self.check_identities(); + self.learn_names(); + let tabs: Vec = self + .views + .iter() + .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(), + }, + title, + hue_key: v.hue_key(), + } + }) + .collect(); + let shown = self.active(); + let others = self.not_open(); + // The bar goes across the whole window, above everything of the + // company in front: a tab is the top level (D-78). + let action = self.tabs.show(ui, &tabs, shown, &others); + let active = self.active; + match self.views.get_mut(active) { + Some(v) => v.ui(ui, &mut self.schemes), + None => self.empty(ui), + } + if let Some(action) = action { + self.act(&ctx, action); + } + // The title names the company in front. + let title = self.window_title(); + if title != self.title { + ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone())); + self.title = title; } - egui::CentralPanel::no_frame() - .frame(Frame::new().fill(p.bg)) - .show(ui, |ui| { - if let Some(err) = &self.error { - Frame::new() - .fill(p.negative_soft) - .inner_margin(Margin::symmetric(20, 8)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label( - RichText::new(format!("{} {err}", icon::WARNING)).color(p.negative), - ); - }); - } - let Some(books) = self.books.clone() else { - ui.centered_and_justified(|ui| { - ui.label(RichText::new("Opening the books…").color(p.muted)); - }); - return; - }; - // Books waiting for a format upgrade: said above every page - // until it is done (owner.rs INVARIANT 5). - self.owner_menu.notice(ui, &books); - let mut shell = Shell { - receipts: &mut self.receipts, - state: &mut self.state, - go: None, - since_update, - }; - let route = self.nav.current.clone(); - pages::show(ui, &books, &route, &mut shell); - if let Some(to) = shell.go.take() { - self.nav.go(to); - } - if let Some(to) = self.palette.show(ui.ctx(), &books) { - self.nav.go(to); - } - }); } fn save(&mut self, storage: &mut dyn eframe::Storage) { - storage.set_string(SCHEME_KEY, self.scheme.key()); - storage.set_string(FILTER_KEY, self.filter.name().to_string()); - storage.set_string("dark", self.scheme.dark.to_string()); - self.dock.keep(&mut |k, v| storage.set_string(k, v)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - - fn kept(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { - let map: HashMap = pairs - .iter() - .map(|(k, v)| (k.to_string(), v.to_string())) - .collect(); - move |k| map.get(k).cloned() - } - - /// The footer's heights in the owner's window (measured 2026-10-22). - const FOOTER: [f32; 3] = [219.0, 147.0, 112.0]; - - #[test] - fn a_window_that_fits_everything_changes_nothing() { - let f = fit(900.0, FOOTER, &SIDEBAR_ROWS, 0.5); - assert_eq!( - (f.folded, f.tight, f.row, f.gap, f.scroll), - (false, false, 32.0, 6.0, false) - ); - } - - #[test] - fn the_sidebar_gives_way_in_order() { - // The links' height at a row and gap, however many sections there - // are (12 until 2026-10-24, when Invoices & Bills made 13). - let links = |row: f32, gap: f32| SIDEBAR_ROWS.height(row, gap); - // Card folds first. - let f = fit( - 18.0 + links(32.0, 6.0) + 8.0 + 147.0, - FOOTER, - &SIDEBAR_ROWS, - 0.5, - ); - assert!(f.folded && !f.tight && f.row == 32.0 && f.gap == 6.0); - // Then the spacing goes, before the rows. - let f = fit( - 8.0 + links(32.0, 4.0) + 8.0 + 112.0, - FOOTER, - &SIDEBAR_ROWS, - 0.5, - ); - assert!(f.folded && f.tight && f.row == 32.0 && f.gap < 6.0 && f.gap >= GAP_MIN); - // Then the rows, down to their least. - let f = fit( - 8.0 + links(28.0, GAP_MIN) + 8.0 + 112.0, - FOOTER, - &SIDEBAR_ROWS, - 0.5, - ); - assert!(f.tight && !f.scroll && f.gap == GAP_MIN && f.row < 32.0 && f.row >= 22.0); - // Then they scroll. - let f = fit(300.0, FOOTER, &SIDEBAR_ROWS, 0.5); - assert!(f.scroll && f.row == 22.0 && f.gap == GAP_MIN); - } - - #[test] - fn whatever_fit_is_chosen_the_links_fit_unless_they_scroll() { - for g in [&SIDEBAR_ROWS, &RAIL_ROWS] { - let foot = if g.foldable { - FOOTER - } else { - [150.0, 150.0, 120.0] - }; - let mut last = (0, f32::INFINITY); - for tenths in (1000..12000).rev() { - let avail = tenths as f32 / 10.0; - let f = fit(avail, foot, g, 0.5); - let head = if f.tight { HEAD_GAP_TIGHT } else { g.head_gap }; - let need = head + g.height(f.row, f.gap) + FOOTER_GAP + foot[f.form()]; - // Within the scroll area's rounding (fit). - assert!(f.scroll || need <= avail + 0.5, "{avail}: {f:?}"); - assert!(f.row >= g.row_min && f.row <= g.row && f.gap >= GAP_MIN); - // Shorter windows never step back. - let step = (f.form() + f.scroll as usize, f.row + f.gap); - assert!(step.0 >= last.0, "{avail}: {f:?}"); - assert!(step.0 > last.0 || step.1 <= last.1, "{avail}: {f:?}"); - last = step; + self.schemes.keep(&mut |k, v| storage.set_string(k, v)); + // The dock, as the front tab has it, else as it was kept. + match self.active_view() { + Some(v) => v.dock_ref().keep(&mut |k, v| storage.set_string(k, v)), + None => { + let (open, agent) = self.dock_prefs.clone(); + if let Some(v) = open { + storage.set_string("dock_open", v); + } + if let Some(v) = agent { + storage.set_string("dock_agent", v); + } } } - } - - #[test] - fn a_folded_card_names_a_failure_before_keeping_anything_else() { - let lines = summaries(&["Database differs"]); - // Every line says it failed; the name goes only after the event - // and the word "Live" have. - assert!( - lines + // 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() - .all(|l| l.verdict.contains(icon::WARNING_CIRCLE)) - ); - let named = lines - .iter() - .take_while(|l| l.verdict.contains("Database differs")) - .count(); - assert_eq!(named, 3); - assert!(!lines[named - 1].status && !lines[named - 1].event); - assert!(lines[named..].iter().all(|l| l.verdict.contains("failed"))); - // Passing, the line is never a failure's and keeps its seal. - let ok = summaries(&[]); - assert!( - ok.iter().all(|l| l.verdict.contains(icon::SEAL_CHECK) - && !l.verdict.contains(icon::WARNING_CIRCLE)) - ); - assert_eq!( - ok[0], - Summary { - status: true, - event: true, - verdict: format!("· {} verified", icon::SEAL_CHECK), + .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()); + } + 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(scope) = v.kept_scope() { + v.keep(&mut |k, val| storage.set_string(&stored(&scope, k), val)); } - ); - assert!( - summaries(&["a", "b"]) - .last() - .unwrap() - .verdict - .contains("2 failed") - ); - } - - #[test] - fn an_unmeasured_footer_form_is_reckoned_from_a_measured_one() { - let m = FooterMemo([None, Some(150.0), None]); - assert_eq!(m.heights(172.0, 70.0, 36.0), [220.0, 150.0, 114.0]); - assert_eq!( - FooterMemo::default().heights(172.0, 70.0, 36.0), - [172.0, 102.0, 66.0] - ); - } - - #[test] - fn the_kept_scheme_and_filter_come_back() { - let (s, f) = restored( - kept(&[ - ("scheme", "Ayu/Mirage"), - ("scheme_filter", "Dark"), - ("dark", "false"), - ]), - false, - ); - assert_eq!(s.key(), "Ayu/Mirage", "the scheme wins over the old choice"); - assert_eq!(f, Filter::Dark); - } - - #[test] - fn before_schemes_the_light_or_dark_choice_is_kept() { - let (s, f) = restored(kept(&[("dark", "true")]), false); - assert!(std::ptr::eq(s, schemes::own(true))); - assert_eq!(f, Filter::All); - let (s, _) = restored(kept(&[("dark", "false")]), true); - assert!(std::ptr::eq(s, schemes::own(false))); - } - - #[test] - fn with_nothing_kept_the_systems_mode_decides() { - for dark in [false, true] { - let (s, f) = restored(kept(&[]), dark); - assert!(std::ptr::eq(s, schemes::own(dark))); - assert_eq!(f, Filter::All); } } - - #[test] - fn a_lost_scheme_or_filter_falls_back() { - let (s, f) = restored( - kept(&[ - ("scheme", "Gone/Away"), - ("scheme_filter", "Sepia"), - ("dark", "true"), - ]), - false, - ); - assert!(std::ptr::eq(s, schemes::own(true))); - assert_eq!(f, Filter::All); - } } diff --git a/crates/ledger-gui/src/company.rs b/crates/ledger-gui/src/company.rs new file mode 100644 index 00000000..798efdf4 --- /dev/null +++ b/crates/ledger-gui/src/company.rs @@ -0,0 +1,2254 @@ +//! One company's window: its sidebar, top bar and current page, with +//! everything that belongs to it alone (its loader, its books, where it +//! is, its dock). The app holds one per open tab (`app.rs`). +//! +//! ```text +//! GOAL: a company's tab holds all of that company's viewer state and +//! none of another's: tabs are independent windows on their books. +//! SOURCE: plan/p15-app-and-relay.md 3.2 (a `CompanyView` per tab: loader, +//! books, nav, page state, receipts, export menu, owner menu, +//! dock); D-78 (one top-level tab per open company). +//! INVARIANTS: +//! 1. Everything a company's page remembers (navigation, filters, +//! periods, the open receipt, the dock, the export and owner menus, +//! its loader and its owner handle) is a field of its view; no two +//! views share a loader, a dock, a menu or a path-keyed handle. +//! 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. 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, 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; +use crate::receipts::Receipts; +use crate::scheme_menu::SchemeMenu; +use crate::theme::{self, pal}; +use egui::{Align, CornerRadius, Frame, Key, Layout, Margin, RichText, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as icon; +use std::sync::Arc; + +/// Window widths below this get the icon rail instead of the sidebar. +pub const COMPACT_BELOW: f32 = 1000.0; + +/// Per-page state that survives navigation. +#[derive(Default)] +pub struct PageState { + pub transactions: pages::transactions::State, + pub reports: pages::reports::State, + pub accounts: pages::accounts::State, + pub assets: pages::assets::State, + pub parties: pages::parties::State, + pub projects: pages::projects::State, + pub documents: pages::documents::State, + pub invoices: pages::invoices::State, + pub journal: pages::journal::State, +} + +/// What a page can ask of the shell. +pub struct Shell<'a> { + pub receipts: &'a mut Receipts, + pub state: &'a mut PageState, + pub go: Option, + /// Seconds since the last live update arrived (for "new" highlights). + pub since_update: f64, +} + +impl Shell<'_> { + pub fn go(&mut self, r: Route) { + self.go = Some(r); + } +} + +/// Everything that belongs to one open company: the tab's whole state. +pub struct CompanyView { + /// What tells this company's views apart: where its books are, as a + /// real path where it can be told. Two views never have the same. + key: String, + /// The scope of every egui id this view makes (INVARIANT 2). + id: egui::Id, + /// The books' folder, if they are read from one. + data_dir: Option, + loader: Option, + books: Option>, + error: Option, + nav: Nav, + receipts: Receipts, + state: PageState, + palette: crate::palette::Palette, + updated_at: f64, + live_label: bool, + /// The export menu (menu.rs). + menu: crate::menu::Menu, + /// The owner's Books menu (owner.rs). + owner_menu: crate::owner::OwnerMenu, + /// The agent dock along the bottom (dock.rs). + dock: crate::dock::Dock, + /// What this view asks to do the owner's actions (INVARIANT 1). + owner: Option>, + /// 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 +/// system really has it. +pub(crate) fn key_of(data_dir: &std::path::Path) -> String { + ledger_store::root::canonical(data_dir) + .unwrap_or_else(|_| data_dir.to_path_buf()) + .display() + .to_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, + data_dir, + loader: None, + books: None, + error: None, + nav: Nav::new(Route::Overview), + receipts: Receipts::new(ctx, &spawner), + state: PageState::default(), + palette: crate::palette::Palette::scoped(id), + updated_at: -1e9, + live_label: false, + 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, + } + } + + /// The live view of the books in `source`: its own loader follows + /// their journal for as long as the view lives. + 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_in(source, ctx.clone(), &view.jobs.spawner())); + view + } + + /// A view of fixed books (tests and screenshots). + 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 + } + + /// This view asking `owner` for the owner's actions, whatever the + /// program gave the viewer (tests give each view its own). + pub fn with_owner(mut self, owner: Arc) -> Self { + self.owner = Some(owner); + self + } + + /// [`Self::with_owner`], for a view already in the tabs (tests). + pub fn set_owner(&mut self, owner: Arc) { + self.owner = Some(owner); + } + + /// The dock as it was last left (the app's preferences). + pub fn with_dock(mut self, dock: crate::dock::Dock) -> Self { + self.dock = dock; + self + } + + /// What tells this company's view apart from another's. + pub fn key(&self) -> &str { + &self.key + } + + /// The scope of this view's egui ids. + pub fn id(&self) -> egui::Id { + self.id + } + + /// The books' id in the data root (their folder's name), if they are + /// in one. + pub fn book_id(&self) -> Option { + let dir = self.data_dir.as_deref()?; + ledger_store::root::inside_a_root(dir) + .then(|| dir.file_name()?.to_str().map(str::to_string)) + .flatten() + } + + /// The name the books carry, once they are loaded (and it isn't + /// blank). + pub fn name(&self) -> Option { + self.books + .as_ref() + .map(|b| b.company_name().trim().to_string()) + .filter(|n| !n.is_empty()) + } + + /// The tab's title: the name the books carry, else the id of the + /// books, else the folder's name. + pub fn title(&self) -> String { + self.name() + .or_else(|| self.book_id()) + .or_else(|| self.folder_name()) + .unwrap_or_else(|| "Company".to_string()) + } + + /// The books' folder's name: a demo's or a copy's folder is + /// `books-data`, which its parent names. + fn folder_name(&self) -> Option { + let dir = self.data_dir.as_deref()?; + let name = dir.file_name()?.to_str()?; + let parent = dir.parent().and_then(|p| p.file_name()?.to_str()); + Some(match (name, parent) { + ("books-data", Some(p)) => p.to_string(), + _ => name.to_string(), + }) + } + + /// What this company's badge hue is chosen from: the id of its books + /// (theme.rs `hue_of`), else the name of their folder, which is that + /// id for books in a data root: a function of where the books are + /// kept and never of the name they carry, so renaming a company + /// leaves its colour. + pub fn hue_key(&self) -> String { + self.book_id() + .or_else(|| self.folder_name()) + .unwrap_or_default() + } + + /// The status card's heading: this company's badge and name. + fn card_head(&self, ctx: &egui::Context) -> CardHead { + CardHead { + initial: self.initial(), + title: self.title(), + hue: theme::badge_hue(ctx, &self.hue_key()), + } + } + + /// The letter on this company's badge: its title's first, upper case. + fn initial(&self) -> char { + self.title() + .chars() + .next() + .map(|c| c.to_uppercase().next().unwrap_or(c)) + .unwrap_or('W') + } + + /// The books as last loaded (tests). + pub fn books(&self) -> Option<&Arc> { + self.books.as_ref() + } + + /// Why the books couldn't be read, if they couldn't (tests). + pub fn error(&self) -> Option<&str> { + self.error.as_deref() + } + + /// Whether this view follows a journal on a loader of its own. + pub fn follows_journal(&self) -> bool { + self.loader.is_some() + } + + /// Whether its loader's thread has ended (tests; false while it runs + /// and for a view with no loader). + pub fn loader_finished(&self) -> bool { + self.loader.as_ref().is_some_and(Loader::finished) + } + + /// A handle that says when this view's loader's thread has ended, + /// which outlives the view (tests). + pub fn loader_watch(&self) -> Option { + 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 + } + + /// The agent dock (read). + pub fn dock_ref(&self) -> &crate::dock::Dock { + &self.dock + } + + /// Navigate (tests). + pub fn goto(&mut self, r: Route) { + self.nav.go(r); + } + + /// Where the view is. + pub fn route(&self) -> &Route { + &self.nav.current + } + + /// Label a fixed-books view "Live", as it reads when following a + /// journal (screenshots of what a running app looks like). + pub fn show_live_label(&mut self) { + self.live_label = true; + } + + /// Page state (tests). + pub fn state_mut(&mut self) -> &mut PageState { + &mut self.state + } + + /// Page state (read). + pub fn state(&self) -> &PageState { + &self.state + } + + /// Keep thumbnails on disk in `dir` (the live viewer keeps them in + /// the user's cache directory, `wanderbooks/thumbs`); tests point it + /// at their own. + pub fn keep_thumbs_in(&mut self, dir: std::path::PathBuf) { + self.receipts.thumb_dir = Some(dir); + self.receipts.forget_thumbs(); + if let Some(b) = self.books.clone() { + self.receipts.prefetch(&b); + } + } + + /// The size in pixels of a file's thumbnail, once drawn (tests). + pub fn thumb_size(&self, sha: &str) -> Option<[usize; 2]> { + self.receipts.thumb_size(sha) + } + + /// Block until every receipt on screen has rendered (screenshots). + pub fn settle(&mut self, ctx: &egui::Context) { + self.receipts.settle(ctx); + } + + /// Take what the loader has sent since the last frame (INVARIANT 3: + /// whether or not the view is shown). `shown`: its receipts are + /// worked on only then. + pub fn pump(&mut self, ctx: &egui::Context, shown: bool) { + let now = ctx.input(|i| i.time); + let updates = self.loader.as_ref().map(|l| l.poll()).unwrap_or_default(); + for u in updates { + match u { + Update::Books(b) => { + if self.books.is_some() { + self.updated_at = now; + } + if shown { + self.receipts.prefetch(&b); + } else { + self.prefetch_due = true; + } + self.loaded_identity = identity_of(&b); + self.books = Some(b); + self.error = None; + } + Update::Error(e) => self.error = Some(e), + Update::Show(target) => self.show(target), + } + } + if shown { + if std::mem::take(&mut self.prefetch_due) + && let Some(b) = self.books.clone() + { + self.receipts.prefetch(&b); + } + self.receipts.pump(ctx); + } + } + + /// The dock along the bottom, for books of a data root with an owner + /// to start the agent (dock.rs). + fn draw_dock(&mut self, ui: &mut Ui) { + if !crate::dock::offered() { + return; + } + let (Some(owner), Some(books)) = (self.owner.clone(), self.books.clone()) else { + return; + }; + if let Some(book) = crate::owner::book_id(&books) { + self.dock.show(ui, &owner, &book, &self.jobs.spawner()); + } + } + + /// The window: the sidebar, the top bar, the dock and the page, with + /// every id in them scoped to this view (INVARIANT 2). + /// + /// The app's tab bar is already across the top of `ui` (`tabs.rs`): + /// this window is what is below it, and the sidebar's height is the + /// window's less the bar's (`tests/sidenav.rs` adds the bar's height + /// to the windows it sizes). + pub fn ui(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu) { + let id = self.id; + ui.push_id(id, |ui| self.window(ui, schemes)); + } + + fn window(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu) { + self.handle_keys(ui); + let compact = ui.available_width() < COMPACT_BELOW; + self.sidebar(ui, schemes, compact); + self.topbar(ui); + self.draw_dock(ui); + let p = pal(ui.ctx()); + let since_update = ui.input(|i| i.time) - self.updated_at; + if since_update < 6.0 { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(250)); + } + egui::CentralPanel::no_frame() + .frame(Frame::new().fill(p.bg)) + .show(ui, |ui| { + if let Some(err) = &self.error { + Frame::new() + .fill(p.negative_soft) + .inner_margin(Margin::symmetric(20, 8)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label( + RichText::new(format!("{} {err}", icon::WARNING)).color(p.negative), + ); + }); + } + let Some(books) = self.books.clone() else { + ui.centered_and_justified(|ui| { + ui.label(RichText::new("Opening the books…").color(p.muted)); + }); + return; + }; + // Books waiting for a format upgrade: said above every page + // until it is done (owner.rs INVARIANT 5). + self.owner_menu.notice(ui, self.owner.clone(), &books); + let mut shell = Shell { + receipts: &mut self.receipts, + state: &mut self.state, + go: None, + since_update, + }; + let route = self.nav.current.clone(); + pages::show(ui, &books, &route, &mut shell); + if let Some(to) = shell.go.take() { + self.nav.go(to); + } + if let Some(to) = self.palette.show(ui.ctx(), &books) { + self.nav.go(to); + } + }); + } + + /// Go where the agent asked (`books.show`). + /// + /// ```text + /// GOAL: the viewer shows what the agent was told it shows. + /// SOURCE: BS-period-3 (one default period; a start after the end is + /// refused, never swapped); plan/served.md P3 defect 15. + /// INVARIANTS: + /// 1. A target's dates are taken as the server resolved them, an + /// omitted one (an earlier writer's) by the same rule + /// (Books::periods), never swapped, clamped or guessed. + /// 2. A target the viewer can't honour (an unknown page, report, + /// split or comparison; text that isn't a date; a start after + /// the end; an account, asset or party not in the books) is + /// ignored whole: the page, range and split stay as they were. + /// ``` + pub fn show(&mut self, target: ledger_store::ops::ViewerTarget) { + use crate::nav::ReportKind; + use ledger_store::ops::ViewerTarget as T; + let Some(b) = self.books.clone() else { + return; + }; + // Some(None): omitted; None: text that isn't a date. + let date = |s: &Option| match s.as_deref() { + None => Some(None), + Some(d) => d.parse::().ok().map(Some), + }; + let dates = |start: &Option, end: &Option| { + b.periods().statement(date(start)?, date(end)?).ok() + }; + let route = match target { + T::Page { page } => match page.as_str() { + "overview" => Route::Overview, + "cash" => Route::Cash, + "profit" => Route::Profit, + "transactions" => Route::Transactions, + "reports" => Route::Reports(ReportKind::ProfitAndLoss), + "accounts" => Route::Accounts, + "assets" => Route::Assets, + "parties" => Route::Parties, + "projects" => Route::Projects, + "documents" => Route::Documents, + "company" => Route::Company, + "journal" => Route::Journal, + _ => return, + }, + T::Entry { entry_id } => Route::Entry(entry_id), + T::Account { code, start, end } => { + use crate::pages::accounts::RegisterRange; + let Some(a) = b.ledger.chart().find_by_code(&code) else { + return; + }; + let Some((s, e)) = dates(&start, &end) else { + return; + }; + self.state.accounts.range = if start.is_none() && end.is_none() { + RegisterRange::Default + } else { + RegisterRange::Dates(s, e) + }; + Route::Account(a.id) + } + T::Report { + report, + start, + end, + columns, + compare, + } => { + use crate::pages::reports::{Columns, Compare, Range}; + let columns = match columns.as_deref() { + None | Some("total") => Columns::Total, + Some("month") => Columns::Month, + Some("quarter") => Columns::Quarter, + Some("year") => Columns::Year, + Some(_) => return, + }; + let compare = match compare.as_deref() { + None => Compare::None, + Some("prior_period") => Compare::PriorPeriod, + Some("prior_year") => Compare::PriorYear, + Some(_) => return, + }; + let Some((s, e)) = dates(&start, &end) else { + return; + }; + let kind = match report.as_str() { + "profit_and_loss" => ReportKind::ProfitAndLoss, + "balance_sheet" => ReportKind::BalanceSheet, + "cash_flow" => ReportKind::CashFlow, + "members_equity" => ReportKind::MembersEquity, + "trial_balance" => ReportKind::TrialBalance, + "general_ledger" => ReportKind::GeneralLedger, + "tax_summary" => ReportKind::TaxSummary, + "vendor_1099" => ReportKind::Vendor1099, + "ar_aging" => ReportKind::ArAging, + "ap_aging" => ReportKind::ApAging, + "fixed_asset_register" => ReportKind::FixedAssetRegister, + _ => return, + }; + self.state.reports.columns = columns; + self.state.reports.compare = compare; + // The dates as sent, by a preset's name when they are one + // (the default first: "Year to date"), else Custom. + self.state.reports.range = std::iter::once(Range::default()) + .chain(Range::PRESETS) + .find(|r| r.dates(&b) == (s, e)) + .unwrap_or(Range::Custom(s, e)); + Route::Reports(kind) + } + T::Document { attachment_id } => Route::Document(attachment_id), + T::Asset { asset_id } => { + if b.ledger.get_asset(asset_id).is_none() { + return; + } + Route::Asset(asset_id) + } + T::Party { party_id } => { + if b.ledger.get_party(party_id).is_none() { + return; + } + Route::Party(party_id) + } + T::Project { class_id } => { + if b.ledger.get_class(class_id).is_none() { + return; + } + Route::Project(class_id) + } + T::Reconciliation { id } => { + // Its own page: statement, balance, the lines it cleared. + if b.reconciliation(id).is_none() { + return; + } + Route::Reconciliation(id) + } + T::Search { query } => { + let st = &mut self.state.transactions; + st.query = query; + st.filter = Default::default(); + st.account = None; + Route::Transactions + } + }; + self.nav.go(route); + } + + fn handle_keys(&mut self, ui: &Ui) { + // The agent in the dock has the keyboard while it is clicked on. + if self.dock.has_keyboard() { + return; + } + let (back, fwd, palette) = ui.input(|i| { + ( + (i.modifiers.alt && i.key_pressed(Key::ArrowLeft)) + || i.pointer.button_pressed(egui::PointerButton::Extra1), + (i.modifiers.alt && i.key_pressed(Key::ArrowRight)) + || i.pointer.button_pressed(egui::PointerButton::Extra2), + i.modifiers.command && i.key_pressed(Key::K), + ) + }); + if back { + self.nav.back(); + } + if fwd { + self.nav.forward(); + } + if palette { + self.palette.open(); + } + } + + /// The sidebar: full below [`COMPACT_BELOW`] window widths, an icon + /// rail (names in tooltips) when the window is narrower. + fn sidebar(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu, compact: bool) { + if compact { + return self.rail(ui, schemes); + } + let p = pal(ui.ctx()); + let books = self.books.clone(); + let head = self.card_head(ui.ctx()); + egui::Panel::left(ui.id().with("sidebar")) + .exact_size(224.0) + .resizable(false) + .frame( + Frame::new() + .fill(p.sidebar) + .inner_margin(Margin::symmetric(12, 16)), + ) + .show(ui, |ui| { + top_slot(ui); + let current = self.nav.current.section(); + let attention = books.as_ref().map(|b| b.attention.len()).unwrap_or(0); + // Short windows give way in steps (Fit): the status card + // folds, then the rows tighten, then the links scroll. + // The footer's heights are the ones it was drawn at. + let fold = 3.0 + * (ui.ctx().fonts_mut(|f| f.row_height(&theme::regular(11.5))) + + ui.spacing().item_spacing.y); + let memo = FooterMemo::load(ui, "sidebar"); + let heights = memo.heights(SIDEBAR_FOOTER, fold, SIDEBAR_TIGHTEN); + let fit = fit(ui.available_height(), heights, &SIDEBAR_ROWS, slack(ui)); + ui.add_space(if fit.tight { + HEAD_GAP_TIGHT + } else { + SIDEBAR_ROWS.head_gap + }); + let footer_h = heights[fit.form()]; + // At least one link always shows; below that the footer + // gives way (footer_layout). + let links_h = (ui.available_height() - footer_h - FOOTER_GAP).max(fit.row); + let nav = &mut self.nav; + links(ui, "sidebar", fit, links_h, current, |ui, s| { + let on = s == current; + let (rect, resp) = + ui.allocate_exact_size(vec2(ui.available_width(), fit.row), Sense::click()); + // Named for assistive tech (and the tests). + resp.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, s.title()) + }); + if on { + ui.painter() + .rect_filled(rect, CornerRadius::same(8), p.surface); + ui.painter().rect_stroke( + rect, + CornerRadius::same(8), + Stroke::new(1.0, p.border), + egui::StrokeKind::Inside, + ); + } else if resp.hovered() { + ui.painter() + .rect_filled(rect, CornerRadius::same(8), p.hover); + } + let color = if on { p.text } else { p.muted }; + ui.painter().text( + rect.left_center() + vec2(10.0, 0.0), + egui::Align2::LEFT_CENTER, + s.icon(), + egui::FontId::proportional(16.0), + if on { p.accent } else { p.muted }, + ); + ui.painter().text( + rect.left_center() + vec2(36.0, 0.0), + egui::Align2::LEFT_CENTER, + s.title(), + if on { + theme::semibold(13.5) + } else { + theme::regular(13.5) + }, + color, + ); + if s == Section::Overview && attention > 0 { + let badge = egui::Rect::from_center_size( + rect.right_center() - vec2(18.0, 0.0), + vec2(22.0, 18.0), + ); + ui.painter() + .rect_filled(badge, CornerRadius::same(9), p.warning_soft); + ui.painter().text( + badge.center(), + egui::Align2::CENTER_CENTER, + attention.to_string(), + theme::semibold(11.0), + p.warning, + ); + } + if resp.clicked() { + nav.go(s.home()); + } + resp + }); + let footer = footer_layout(ui, footer_h, Align::Min, |ui| { + if fit.tight { + tighten(ui); + } + schemes.menu(ui, false); + if let Some(b) = &books { + ui.add_space(2.0); + self.menu.ui(ui, b, false); + self.owner_menu.ui(ui, self.owner.clone(), b, false); + } + ui.add_space(6.0); + if let Some(b) = &books { + live_status( + ui, + b, + ui.input(|i| i.time) - self.updated_at, + self.loader.is_some() || self.live_label, + fit.folded, + &head, + ); + } + }); + memo.measured(ui, "sidebar", fit.form(), footer.response.rect); + }); + } + + /// The sidebar as a narrow rail of icons, for narrow windows. + fn rail(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu) { + let p = pal(ui.ctx()); + let books = self.books.clone(); + let head = self.card_head(ui.ctx()); + egui::Panel::left(ui.id().with("rail")) + .exact_size(RAIL_W) + .resizable(false) + .frame( + Frame::new() + .fill(p.sidebar) + .inner_margin(Margin::symmetric(10, 16)), + ) + .show(ui, |ui| { + top_slot(ui); + let current = self.nav.current.section(); + let attention = books.as_ref().map(|b| b.attention.len()).unwrap_or(0); + // As the sidebar's, with no card to fold. + let memo = FooterMemo::load(ui, "rail"); + let heights = memo.heights(RAIL_FOOTER, 0.0, RAIL_TIGHTEN); + let fit = fit(ui.available_height(), heights, &RAIL_ROWS, slack(ui)); + ui.add_space(if fit.tight { + HEAD_GAP_TIGHT + } else { + RAIL_ROWS.head_gap + }); + let footer_h = heights[fit.form()]; + let links_h = (ui.available_height() - footer_h - FOOTER_GAP).max(fit.row); + let nav = &mut self.nav; + links(ui, "rail", fit, links_h, current, |ui, s| { + let on = s == current; + let (rect, resp) = + ui.allocate_exact_size(vec2(ui.available_width(), fit.row), Sense::click()); + resp.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, s.title()) + }); + if on { + ui.painter() + .rect_filled(rect, CornerRadius::same(8), p.surface); + ui.painter().rect_stroke( + rect, + CornerRadius::same(8), + Stroke::new(1.0, p.border), + egui::StrokeKind::Inside, + ); + } else if resp.hovered() { + ui.painter() + .rect_filled(rect, CornerRadius::same(8), p.hover); + } + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + s.icon(), + egui::FontId::proportional(18.0), + if on { p.accent } else { p.muted }, + ); + let tip = if s == Section::Overview && attention > 0 { + ui.painter() + .circle_filled(rect.center() + vec2(9.0, -8.0), 4.0, p.warning); + format!("{} · {attention} need attention", s.title()) + } else { + s.title().to_string() + }; + let resp = resp.on_hover_text(tip); + if resp.clicked() { + nav.go(s.home()); + } + resp + }); + let footer = footer_layout(ui, footer_h, Align::Center, |ui| { + if fit.tight { + tighten(ui); + } + schemes.menu(ui, true); + if let Some(b) = &books { + self.menu.ui(ui, b, true); + self.owner_menu.ui(ui, self.owner.clone(), b, true); + } + ui.add_space(6.0); + if let Some(b) = &books { + let live = self.loader.is_some() || self.live_label; + let checks = checks(b); + let ok = checks.iter().all(|c| c.0); + // The company's badge, its live dot on the badge's + // corner (a warning there when a check failed); its + // name, state, event and checks on hover. + let (r, resp) = + ui.allocate_exact_size(vec2(RAIL_BADGE, RAIL_BADGE), Sense::hover()); + head.paint(ui, r, 6); + let corner = r.right_bottom() - vec2(1.0, 1.0); + ui.painter().circle_filled(corner, 6.0, p.sidebar); + if ok { + let pulse = (ui.input(|i| i.time) - self.updated_at < 2.0) as u8 as f32; + ui.painter().circle_filled( + corner, + 4.0 + pulse, + if live { p.positive } else { p.faint }, + ); + } else { + ui.painter().text( + corner, + egui::Align2::CENTER_CENTER, + icon::WARNING_CIRCLE, + egui::FontId::proportional(13.0), + p.negative, + ); + } + let mut tip = format!( + "{}\n{} · event {}", + head.title, + if live { "Live" } else { "Snapshot" }, + b.seq() + ); + for (ok, text, _) in &checks { + tip.push_str(&format!( + "\n{} {text}", + if *ok { + icon::SEAL_CHECK + } else { + icon::WARNING_CIRCLE + } + )); + } + resp.on_hover_text(tip); + } + }); + memo.measured(ui, "rail", fit.form(), footer.response.rect); + }); + } + + /// Back, forward, where you are, today, and search. Squeezed, the + /// search shrinks to its icon, the date goes, and the crumb truncates: + /// nothing ever overlaps. + fn topbar(&mut self, ui: &mut Ui) { + let p = pal(ui.ctx()); + egui::Panel::top(ui.id().with("topbar")) + .exact_size(52.0) + .frame( + Frame::new() + .fill(p.bg) + .inner_margin(Margin::symmetric(16, 10)) + .stroke(Stroke::new(1.0, p.border)), + ) + .show(ui, |ui| { + let width = ui.available_width(); + ui.horizontal_centered(|ui| { + let nav_btn = |ui: &mut Ui, glyph: &str, enabled: bool, tip: &str| { + ui.add_enabled( + enabled, + egui::Button::new(RichText::new(glyph).size(16.0)) + .frame(false) + .min_size(vec2(28.0, 28.0)), + ) + .on_hover_text(tip) + .clicked() + }; + if nav_btn(ui, icon::ARROW_LEFT, self.nav.can_back(), "Back (Alt+←)") { + self.nav.back(); + } + if nav_btn( + ui, + icon::ARROW_RIGHT, + self.nav.can_forward(), + "Forward (Alt+→)", + ) { + self.nav.forward(); + } + ui.add_space(6.0); + // Right side first, so the crumb gets only what's left. + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let (text, min_w) = if width >= 640.0 { + ( + format!( + "{} Search everything… Ctrl K", + icon::MAGNIFYING_GLASS + ), + 260.0, + ) + } else if width >= 420.0 { + (format!("{} Search", icon::MAGNIFYING_GLASS), 0.0) + } else { + (icon::MAGNIFYING_GLASS.to_string(), 30.0) + }; + let search = egui::Button::new( + RichText::new(text) + .font(theme::regular(13.0)) + .color(p.faint), + ) + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .min_size(vec2(min_w, 30.0)); + if ui + .add(search) + .on_hover_text("Search everything (Ctrl K)") + .clicked() + { + self.palette.open(); + } + if let Some(b) = &self.books + && width >= 860.0 + { + ui.label( + RichText::new(format!("Today {}", crate::fmt::date(b.today))) + .font(theme::regular(12.5)) + .color(p.muted), + ); + } + ui.add_space(8.0); + ui.with_layout(Layout::left_to_right(Align::Center), |ui| { + let crumbs = + crate::palette::crumbs(self.books.as_deref(), &self.nav.current); + // Narrow, the last crumb alone says where you are. + let skip = if ui.available_width() >= 260.0 { + 0 + } else { + crumbs.len() - 1 + }; + let last = crumbs.len() - 1; + let mut go = None; + for (i, (text, to)) in crumbs.iter().enumerate().skip(skip) { + if i > skip && ui.available_width() >= 260.0 - 80.0 { + ui.label(RichText::new(icon::CARET_RIGHT).color(p.faint)); + } + let rich = if i == last && i > 0 { + RichText::new(text).font(theme::semibold(13.5)) + } else { + RichText::new(text) + .font(theme::regular(13.5)) + .color(p.muted) + }; + let label = egui::Label::new(rich).truncate(); + match to { + Some(to) => { + let r = ui.add(label.sense(egui::Sense::click())); + if r.hovered() { + ui.ctx() + .set_cursor_icon(egui::CursorIcon::PointingHand); + } + if r.on_hover_text(format!("Go to {text}")).clicked() { + go = Some(to.clone()); + } + } + None => { + ui.add(label); + } + } + } + if let Some(to) = go { + self.nav.go(to); + } + }); + }); + }); + }); + } +} + +/// 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.) + pub fn keep(&self, set: &mut dyn FnMut(&str, String)) { + use crate::pages::reports::{Columns, Compare, Range}; + set("page", route_key(&self.nav.current)); + let r = &self.state.reports; + set( + "range", + match r.range { + Range::ThisMonth => "this-month".to_string(), + Range::LastMonth => "last-month".to_string(), + Range::ThisQuarter => "this-quarter".to_string(), + Range::YearToDate => "year-to-date".to_string(), + Range::LastYear => "last-year".to_string(), + Range::Last12Months => "last-12-months".to_string(), + Range::AllTime => "all-time".to_string(), + Range::Custom(s, e) => format!("custom:{s}..{e}"), + }, + ); + set( + "columns", + match r.columns { + Columns::Total => "total", + Columns::Month => "month", + Columns::Quarter => "quarter", + Columns::Year => "year", + } + .to_string(), + ); + set( + "compare", + match r.compare { + Compare::None => "none", + Compare::PriorPeriod => "prior-period", + Compare::PriorYear => "prior-year", + } + .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); + } + let r = &mut self.state.reports; + if let Some(v) = get("range") { + let range = match v.as_str() { + "this-month" => Some(Range::ThisMonth), + "last-month" => Some(Range::LastMonth), + "this-quarter" => Some(Range::ThisQuarter), + "year-to-date" => Some(Range::YearToDate), + "last-year" => Some(Range::LastYear), + "last-12-months" => Some(Range::Last12Months), + "all-time" => Some(Range::AllTime), + other => other.strip_prefix("custom:").and_then(|d| { + let (s, e) = d.split_once("..")?; + let (s, e) = (s.parse().ok()?, e.parse().ok()?); + // A start after the end is never kept (BS-period-3). + (s <= e).then_some(Range::Custom(s, e)) + }), + }; + if let Some(range) = range { + r.range = range; + } + } + match get("columns").as_deref() { + Some("total") => r.columns = Columns::Total, + Some("month") => r.columns = Columns::Month, + Some("quarter") => r.columns = Columns::Quarter, + Some("year") => r.columns = Columns::Year, + _ => {} + } + match get("compare").as_deref() { + Some("none") => r.compare = Compare::None, + Some("prior-period") => r.compare = Compare::PriorPeriod, + Some("prior-year") => r.compare = Compare::PriorYear, + _ => {} + } + } +} + +/// The page, as kept: a list page by name, a report by its kind; a page +/// of one thing (an entry, a party) by the list it is in. +fn route_key(r: &Route) -> String { + match r { + Route::Reports(k) => format!("reports:{}", report_key(*k)), + other => section_key(other.section()).to_string(), + } +} + +fn route_from_key(key: &str) -> Option { + if let Some(kind) = key.strip_prefix("reports:") { + return crate::nav::ReportKind::ALL + .into_iter() + .find(|k| report_key(*k) == kind) + .map(Route::Reports); + } + Section::ALL + .into_iter() + .find(|s| section_key(*s) == key) + .map(Section::home) +} + +fn section_key(s: Section) -> &'static str { + match s { + Section::Overview => "overview", + Section::Cash => "cash", + Section::Profit => "profit", + Section::Transactions => "transactions", + Section::Reports => "reports", + Section::Accounts => "accounts", + Section::Assets => "assets", + Section::Parties => "parties", + Section::Projects => "projects", + Section::Invoices => "invoices", + Section::Documents => "documents", + Section::Company => "company", + Section::Journal => "journal", + } +} + +fn report_key(k: crate::nav::ReportKind) -> &'static str { + use crate::nav::ReportKind as K; + match k { + K::ProfitAndLoss => "profit-and-loss", + K::BalanceSheet => "balance-sheet", + K::CashFlow => "cash-flow", + K::TrialBalance => "trial-balance", + K::GeneralLedger => "general-ledger", + K::MembersEquity => "members-equity", + K::TaxSummary => "tax-summary", + K::ArAging => "ar-aging", + K::ApAging => "ap-aging", + K::Vendor1099 => "vendor-1099", + K::FixedAssetRegister => "fixed-asset-register", + } +} + +/// Width of the icon rail. +const RAIL_W: f32 = 60.0; +/// The footer's height (the status box and the menus under the sidebar's +/// links; the rail's equivalent) before it is first measured. After the +/// first frame its drawn heights are used ([`FooterMemo`]). +const SIDEBAR_FOOTER: f32 = 192.0; +const RAIL_FOOTER: f32 = 112.0; +/// How much shorter the footer is tightened ([`tighten`]), before it is +/// measured so. +const SIDEBAR_TIGHTEN: f32 = 36.0; +const RAIL_TIGHTEN: f32 = 36.0; + +/// Space kept between the last link and the footer. +const FOOTER_GAP: f32 = 8.0; + +/// Tightened: the space between links, and under the top slot. The slot +/// draws nothing (`top_slot`), and the panel's margin is the first link's +/// room under the tab bar, so both gaps are nothing today. +const GAP_MIN: f32 = 2.0; +const HEAD_GAP: f32 = 0.0; +const HEAD_GAP_TIGHT: f32 = 0.0; + +/// A panel's links: how many, their height and spacing, the least height +/// they tighten to, the gap above them, and whether its status card folds. +struct Rows { + n: usize, + row: f32, + gap: f32, + row_min: f32, + head_gap: f32, + foldable: bool, +} + +impl Rows { + fn height(&self, row: f32, gap: f32) -> f32 { + let n = self.n as f32; + n * row + (n - 1.0) * gap + } +} + +const SIDEBAR_ROWS: Rows = Rows { + n: Section::ALL.len(), + row: 32.0, + gap: 6.0, + // 22, not 24, since Invoices & Bills made 13 links (2026-10-24): so + // they still fit the owner's 1479x519 window unscrolled. + row_min: 22.0, + head_gap: HEAD_GAP, + foldable: true, +}; + +const RAIL_ROWS: Rows = Rows { + n: Section::ALL.len(), + row: 36.0, + gap: 6.0, + // As low as the sidebar's: at 28 the rail scrolled in the owner's + // window (review, 2026-10-22), and at 24 once there were 13 links. + row_min: 22.0, + head_gap: HEAD_GAP, + foldable: false, +}; + +/// How a panel's links and footer share the window's height (owner, +/// 2026-10-22: at 1479x519 half the links hid behind the status box). +/// Each step is taken only when the one before isn't enough, so where +/// everything fits nothing changes. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Fit { + /// 1. The status card folded to its summary line. + folded: bool, + /// 2. The rows tightened: the footer's menus, the gap under the + /// header, and the links' spacing, then their height. + tight: bool, + row: f32, + gap: f32, + /// 3. Even tight they don't fit: the links scroll. + scroll: bool, +} + +impl Fit { + /// Which of the footer's three forms it draws: full, folded, tight. + fn form(&self) -> usize { + if self.tight { + 2 + } else if self.folded { + 1 + } else { + 0 + } + } +} + +/// The fit for `avail` points under the header, the footer being +/// `footer` high in each form ([`Fit::form`]), overrunning by `slack` +/// points ([`slack`]) taken as fitting. +fn fit(avail: f32, footer: [f32; 3], g: &Rows, slack: f32) -> Fit { + let full = g.height(g.row, g.gap); + let at_ease = Fit { + folded: false, + tight: false, + row: g.row, + gap: g.gap, + scroll: false, + }; + // The links fit when what they overrun is under half a pixel + // (`slack`, points), which no one sees: at 1.25 the rows' sum runs a + // hair over whole points, and without it the card folded where main + // drew everything (review, 2026-10-22). + let fits = |footer: f32| avail - g.head_gap - FOOTER_GAP - footer + slack >= full; + if fits(footer[0]) { + return at_ease; + } + if g.foldable && fits(footer[1]) { + return Fit { + folded: true, + ..at_ease + }; + } + let tight = Fit { + folded: g.foldable, + tight: true, + ..at_ease + }; + let room = avail - HEAD_GAP_TIGHT - FOOTER_GAP - footer[2]; + let n = g.n as f32; + // The space between the links gives first, then the links. + let gap = ((room - n * g.row) / (n - 1.0)).floor(); + if gap >= GAP_MIN { + return Fit { + gap: gap.min(g.gap), + ..tight + }; + } + let row = ((room - (n - 1.0) * GAP_MIN) / n).floor(); + if row >= g.row_min { + return Fit { + row: row.min(g.row), + gap: GAP_MIN, + ..tight + }; + } + Fit { + row: g.row_min, + gap: GAP_MIN, + scroll: true, + ..tight + } +} + +/// Half a pixel, in points: links overrunning their room by less are +/// drawn whole, with no cue. +fn slack(ui: &Ui) -> f32 { + 0.5 / ui.ctx().pixels_per_point() +} + +/// The footer's height in each form, as last drawn; a form not drawn yet +/// is estimated from one that was. +#[derive(Clone, Copy, Debug, Default)] +struct FooterMemo([Option; 3]); + +impl FooterMemo { + /// Scoped by the panel it measures, which is the view's own + /// (INVARIANT 2 of the module). + fn id(ui: &Ui, key: &str) -> egui::Id { + ui.id().with((key, "footer_memo")) + } + + fn load(ui: &Ui, key: &str) -> FooterMemo { + ui.ctx() + .data(|d| d.get_temp(Self::id(ui, key))) + .unwrap_or_default() + } + + /// Each form's height: `guess` full before anything was drawn, a + /// form not drawn `fold` (the card's checks) and `tighten` shorter + /// than the one before it. + fn heights(&self, guess: f32, fold: f32, tighten: f32) -> [f32; 3] { + let off = [0.0, -fold, -fold - tighten]; + let anchor = (0..3) + .find_map(|i| self.0[i].map(|h| h - off[i])) + .unwrap_or(guess); + std::array::from_fn(|i| self.0[i].unwrap_or(anchor + off[i])) + } + + /// Keep form `form`'s drawn height for the next frame (the footer's + /// content changing moves every form alike), the footer's rect for + /// the tests, and draw again at once when it changed. + fn measured(mut self, ui: &Ui, key: &str, form: usize, rect: egui::Rect) { + let h = rect.height(); + let changed = match self.0[form] { + Some(old) if (old - h).abs() <= 0.5 => false, + Some(old) => { + for v in self.0.iter_mut().flatten() { + *v += h - old; + } + true + } + None => { + self.0[form] = Some(h); + true + } + }; + ui.ctx().data_mut(|d| { + d.insert_temp(Self::id(ui, key), self); + d.insert_temp(egui::Id::new(format!("{key}_footer_rect")), rect); + d.insert_temp(egui::Id::new(format!("{key}_footer_h")), h); + }); + if changed { + ui.ctx().request_repaint(); + } + } +} + +/// The footer's menus tightened, as the links are. +fn tighten(ui: &mut Ui) { + let s = ui.spacing_mut(); + s.item_spacing.y = GAP_MIN; + s.interact_size.y = 22.0; + s.button_padding.y = 2.0; +} + +/// Height of the fade over a clipped edge of the links. +const FADE: f32 = 28.0; + +/// A panel's links, `row` draws one: at most `max_h` high, scrolling +/// when they don't fit, then with a fade and a chevron at each clipped +/// edge, and the current page's link scrolled into view whenever the +/// page changes. What it drew is kept for the tests +/// (`{key}_links_view`, `{key}_links_scroll`). +fn links( + ui: &mut Ui, + key: &str, + fit: Fit, + max_h: f32, + current: Section, + mut row: impl FnMut(&mut Ui, Section) -> egui::Response, +) { + // Last frame's page, viewport height and scrolling: the current link + // is scrolled into view when they change while the links scroll. + let shown_id = ui.id().with((key, "links_shown")); + let shown = ui + .ctx() + .data(|d| d.get_temp::<(Section, i32, bool)>(shown_id)); + let now = (current, max_h.round() as i32); + let reveal = fit.scroll && shown != Some((now.0, now.1, true)); + let out = egui::ScrollArea::vertical() + .id_salt(format!("{key}_links")) + .max_height(max_h) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = fit.gap; + for s in Section::ALL { + let resp = row(ui, s); + if reveal && s == current { + resp.scroll_to_me(Some(Align::Center)); + } + } + }); + let view = out.inner_rect; + let content = out.content_size.y; + let offset = out.state.offset.y; + let scrolls = content > view.height() + slack(ui); + ui.ctx().data_mut(|d| { + d.insert_temp(shown_id, (now.0, now.1, scrolls)); + d.insert_temp(egui::Id::new(format!("{key}_links_view")), view); + d.insert_temp(egui::Id::new(format!("{key}_links_scroll")), scrolls); + }); + if !scrolls { + return; + } + let p = pal(ui.ctx()); + let painter = ui.painter().with_clip_rect(view); + let above = offset > 0.5; + let below = offset + view.height() < content - 0.5; + for (clipped, down) in [(above, false), (below, true)] { + if !clipped { + continue; + } + let h = FADE.min(view.height() / 2.0); + let (band, edge_y) = if down { + ( + egui::Rect::from_min_max(egui::pos2(view.left(), view.bottom() - h), view.max), + view.bottom() - 8.0, + ) + } else { + ( + egui::Rect::from_min_max(view.min, egui::pos2(view.right(), view.top() + h)), + view.top() + 8.0, + ) + }; + let (top, bottom) = if down { + (egui::Color32::TRANSPARENT, p.sidebar) + } else { + (p.sidebar, egui::Color32::TRANSPARENT) + }; + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(band.left_top(), top); + mesh.colored_vertex(band.right_top(), top); + mesh.colored_vertex(band.left_bottom(), bottom); + mesh.colored_vertex(band.right_bottom(), bottom); + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(1, 3, 2); + painter.add(egui::Shape::mesh(mesh)); + // The sidebar's at the edge's right end, clear of the links' + // names. The rail's has no room beside its icons (there it read + // as a caret on one): centred on the edge, on a pill of its own + // that covers the faded icon under it. + let narrow = view.width() < 80.0; + let chevron = if narrow { + egui::Rect::from_center_size( + egui::pos2( + view.center().x, + if down { + view.bottom() - 7.0 + } else { + view.top() + 7.0 + }, + ), + vec2(26.0, 14.0), + ) + } else { + egui::Rect::from_center_size(egui::pos2(view.right() - 14.0, edge_y), vec2(24.0, 16.0)) + }; + let label = if down { + "More links below" + } else { + "More links above" + }; + let resp = ui + .interact(chevron, ui.id().with((key, down)), Sense::click()) + .on_hover_text(label); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); + if narrow { + painter.rect( + chevron, + CornerRadius::same(7), + if resp.hovered() { p.hover } else { p.sidebar }, + Stroke::new(1.0, p.border), + egui::StrokeKind::Inside, + ); + } + painter.text( + chevron.center(), + egui::Align2::CENTER_CENTER, + if down { + icon::CARET_DOWN + } else { + icon::CARET_UP + }, + egui::FontId::proportional(if narrow { 11.0 } else { 14.0 }), + if resp.hovered() { p.text } else { p.muted }, + ); + if resp.clicked() { + // A page of links on, keeping one link of the last in view. + let step = (view.height() - fit.row - fit.gap).max(fit.row); + let mut state = out.state; + state.offset.y = (offset + if down { step } else { -step }) + .clamp(0.0, (content - view.height()).max(0.0)); + state.store(ui.ctx(), out.id); + ui.ctx().request_repaint(); + } + } +} + +/// The sidebar's footer, bottom up: on the panel's floor when it fits +/// under the links, else right under them, running off the bottom of the +/// window, so it gives way and never draws over a link. +fn footer_layout( + ui: &mut Ui, + footer_h: f32, + align: Align, + add: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse { + if ui.available_height() >= footer_h { + ui.with_layout(Layout::bottom_up(align), add) + } else { + let w = ui.available_width(); + ui.allocate_ui_with_layout(vec2(w, footer_h), Layout::bottom_up(align), add) + } +} + +/// The top of the sidebar (and of the rail): where the assistant's +/// connection state goes, in a later unit. It draws nothing today, so the +/// links begin at the panel's top margin, under the tab bar. A block put +/// here adds its own height and gap below it ([`HEAD_GAP`], +/// [`HEAD_GAP_TIGHT`] are what the fit leaves under it). +fn top_slot(_ui: &mut Ui) {} + +/// What the status card says of its company: the heading row's badge +/// (its hue, its letter) and name. +struct CardHead { + initial: char, + title: String, + hue: egui::Color32, +} + +/// The status card's badge, and the rail's. +const CARD_BADGE: f32 = 16.0; +/// The card's vertical padding (its sides' is 10): the footer is short. +const CARD_PAD_Y: i8 = 8; +const RAIL_BADGE: f32 = 24.0; + +impl CardHead { + fn paint(&self, ui: &Ui, rect: egui::Rect, radius: u8) { + let font = theme::bold(if rect.width() > 20.0 { 13.0 } else { 10.0 }); + theme::paint_badge(ui.painter(), rect, radius, self.initial, self.hue, font); + } + + /// The card's heading row, one line: the badge, small, and the name, + /// cut with an ellipsis to the room the live mark leaves; at the + /// card's right edge that mark, the dot and "Live" (or "Snapshot"), + /// pulsing for two seconds after an update. The name elides before + /// the mark is ever clipped. The mark's accessible label is "Live · + /// event N". `tip` is the row's hover text (none: the caller's own + /// covers the row). + fn row(&self, ui: &mut Ui, d: &CardView, tip: Option) { + let p = pal(ui.ctx()); + let status = d.status(); + let font = theme::semibold(12.0); + let word = ui.fonts_mut(|f| { + f.layout_no_wrap(status.to_string(), font.clone(), p.text) + .size() + .x + }); + let gap = MARK_GAP; + let dot = 8.0; + let mark = dot + gap + word; + let room = (ui.available_width() - CARD_BADGE - 2.0 * gap - mark - 1.0).max(0.0); + // As tall as its badge, not as a button: the card is short. + let row = ui.scope(|ui| { + ui.spacing_mut().interact_size.y = CARD_BADGE; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = gap; + let (r, _) = ui.allocate_exact_size(vec2(CARD_BADGE, CARD_BADGE), Sense::hover()); + self.paint(ui, r, 4); + // The name's room is all kept, so the mark is at the right. + ui.allocate_ui_with_layout( + vec2(room, CARD_BADGE), + Layout::left_to_right(Align::Center), + |ui| { + ui.set_min_width(room); + ui.add( + egui::Label::new( + RichText::new(&self.title).font(theme::semibold(12.5)), + ) + .truncate(), + ); + }, + ); + let (r, _) = ui.allocate_exact_size(vec2(dot, dot), Sense::hover()); + let pulse = (d.since_update < 2.0) as u8 as f32; + let color = if d.live { p.positive } else { p.faint }; + ui.painter().circle_filled(r.center(), 4.0 + pulse, color); + let label = format!("{status} · event {}", d.seq); + ui.add(egui::Label::new(RichText::new(status).font(font)).truncate()) + .widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Label, true, label.clone()) + }); + }) + }); + if let Some(tip) = tip { + ui.interact(row.response.rect, ui.id().with("card_head"), Sense::hover()) + .on_hover_text(tip); + } + } +} + +/// The least space between the heading's parts. +const MARK_GAP: f32 = 4.0; + +/// What the status card shows of its books: the newest event, the +/// journal's head and folder (the copy menu's), and the integrity +/// checks; and how it is drawn: live or a snapshot, how long since the +/// last update. +struct CardView { + seq: u64, + head: String, + data_dir: String, + checks: Vec<(bool, String, String)>, + since_update: f64, + live: bool, +} + +impl CardView { + fn new(b: &Books, since_update: f64, live: bool) -> Self { + CardView { + seq: b.seq(), + head: b.head.clone(), + data_dir: b.data_dir.display().to_string(), + checks: checks(b), + since_update, + live, + } + } + + fn status(&self) -> &'static str { + if self.live { "Live" } else { "Snapshot" } + } + + /// The hover text of the heading: the company, "Live · event N", + /// then each check, one fact a line. + fn tip(&self, head: &CardHead) -> String { + let mut tip = format!("{}\n{} · event {}", head.title, self.status(), self.seq); + for (ok, text, _) in &self.checks { + tip.push_str(&format!("\n{} {text}", check_glyph(*ok))); + } + tip + } + + fn copy_menu(&self, ui: &mut Ui) { + crate::widgets::copy_item(ui, "Copy journal head", &self.head); + crate::widgets::copy_item(ui, "Copy data folder", &self.data_dir); + } +} + +fn check_glyph(ok: bool) -> &'static str { + if ok { + icon::SEAL_CHECK + } else { + icon::WARNING_CIRCLE + } +} + +/// A check's line: its glyph and name, small, one line, elided. +fn check_line(ui: &mut Ui, ok: bool, text: &str) -> egui::Response { + let p = pal(ui.ctx()); + ui.add( + egui::Label::new( + RichText::new(format!("{} {text}", check_glyph(ok))) + .font(theme::regular(11.5)) + .color(if ok { p.muted } else { p.negative }), + ) + .truncate(), + ) +} + +/// The status card: the company and whether its books are live in the +/// heading, and the integrity checks. Every text is one line and elides; +/// the event is on the heading's hover and its live mark's label, not on +/// a row. Folded (a short window), the heading alone (and a failed +/// check's line), the checks on hover. +fn live_status( + ui: &mut Ui, + b: &Books, + since_update: f64, + live: bool, + folded: bool, + head: &CardHead, +) { + status_card(ui, &CardView::new(b, since_update, live), folded, head); +} + +fn status_card(ui: &mut Ui, d: &CardView, folded: bool, head: &CardHead) { + if folded { + return folded_status(ui, d, head); + } + let p = pal(ui.ctx()); + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(10, CARD_PAD_Y)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + for (i, (ok, text, tip)) in d.checks.iter().enumerate() { + let r = check_line(ui, *ok, text).on_hover_text(tip); + if i == 0 { + r.context_menu(|ui| d.copy_menu(ui)); + } + } + // The footer is laid out bottom up, so what is added last is + // the card's top: the heading, over what the card always said. + head.row(ui, d, Some(d.tip(head))); + }); +} + +/// The status card folded. Its heading alone: the badge, the name, and at +/// the right "● Live". A check failed, a line under the heading names it +/// ([`summaries`], the fullest that fits, so it is never cut to +/// "Datab…": review, 2026-10-22). The card is one target: hovered it +/// shows the name, "Live · event N" and the three checks, and a right +/// click copies the journal head or the data folder. +fn folded_status(ui: &mut Ui, d: &CardView, head: &CardHead) { + let p = pal(ui.ctx()); + let failed: Vec<&str> = d + .checks + .iter() + .filter(|c| !c.0) + .map(|c| c.1.as_str()) + .collect(); + // The card's inner width: the panel's less the frame's margins. + let room = ui.available_width() - 2.0 * 10.0 - 2.0; + let width = |s: &str| { + ui.fonts_mut(|f| { + f.layout_no_wrap(s.to_string(), theme::regular(12.0), p.text) + .size() + .x + }) + }; + let all = summaries(&failed); + let line = (!failed.is_empty()).then(|| { + all.iter() + .find(|s| width(s) <= room) + .unwrap_or_else(|| all.last().expect("a summary")) + }); + let card = Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(10, CARD_PAD_Y)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + if let Some(line) = line { + ui.add( + egui::Label::new( + RichText::new(line) + .font(theme::regular(12.0)) + .color(p.negative), + ) + .truncate(), + ); + } + // Bottom up, so last is the top: the heading. Its hover is the + // card's (below): the card is one target. + head.row(ui, d, None); + }); + let resp = ui.interact( + card.response.rect, + ui.id().with("folded_status"), + Sense::click(), + ); + resp.on_hover_ui(|ui| { + ui.label(RichText::new(&head.title).font(theme::semibold(12.0))); + ui.label( + RichText::new(format!("{} · event {}", d.status(), d.seq)) + .font(theme::regular(11.5)) + .color(p.muted), + ); + for (ok, text, _) in &d.checks { + check_line_hover(ui, *ok, text); + } + }) + .context_menu(|ui| d.copy_menu(ui)); +} + +/// A check's line in a tooltip (which has room to say it whole). +fn check_line_hover(ui: &mut Ui, ok: bool, text: &str) { + let p = pal(ui.ctx()); + ui.label( + RichText::new(format!("{} {text}", check_glyph(ok))) + .font(theme::regular(11.5)) + .color(if ok { p.muted } else { p.negative }), + ); +} + +/// The folded card's failure line, fullest first, given the checks that +/// `failed`: the names, then a count, then the shortest. A failure is +/// named before anything is shortened; "Live" is the heading's. +fn summaries(failed: &[&str]) -> Vec { + let named = format!("{} {}", icon::WARNING_CIRCLE, failed.join(", ")); + let counted = match failed.len() { + 1 => format!("{} check failed", icon::WARNING_CIRCLE), + n => format!("{} {n} checks failed", icon::WARNING_CIRCLE), + }; + let short = match failed.len() { + 1 => format!("{} failed", icon::WARNING_CIRCLE), + n => format!("{} {n} failed", icon::WARNING_CIRCLE), + }; + vec![named, counted, short] +} + +/// The integrity checks the sidebar shows: (ok, label, explanation). +fn checks(b: &Books) -> Vec<(bool, String, String)> { + use ledger_store::DiskCheck; + let mut out = vec![( + true, + "Journal chain verified".to_string(), + format!( + "Every journal event's hash chains to the one before it.\nHead: {}\nData: {}", + b.head, + b.data_dir.display() + ), + )]; + out.push(match &b.integrity.disk { + DiskCheck::Matches => (true, "Database matches journal".to_string(), "The server's SQLite database matches a fresh projection of the journal, every table, row for row.".to_string()), + DiskCheck::Behind { applied, journal } => (true, "Database catching up".to_string(), format!("The database has applied {applied} of {journal} journal events; the server applies the rest right after writing them.")), + DiskCheck::Ahead { .. } => (true, "Viewer catching up".to_string(), "The server has written journal events this view hasn't read yet; it reads them on its next refresh.".to_string()), + DiskCheck::Missing => (true, "Read-only copy".to_string(), "No server database here: a copy of the books (a CPA's, say), or the server hasn't run yet. The journal and every file are verified either way.".to_string()), + DiskCheck::Differs(why) => (false, "Database differs".to_string(), format!("{why}. The server rebuilds it from the journal (books.verify, or on its next start).")), + DiskCheck::Unreadable(why) => (false, "Database unreadable".to_string(), why.clone()), + }); + let bad = b.integrity.file_failures.len(); + out.push(( + bad == 0, + if bad == 0 { + format!("{} files verified", b.integrity.files_ok) + } else { + format!("{bad} files damaged") + }, + "Every stored receipt and document re-hashed against its recorded SHA-256.".into(), + )); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The footer's heights in the owner's window (measured 2026-10-22). + const FOOTER: [f32; 3] = [219.0, 147.0, 112.0]; + + #[test] + fn a_window_that_fits_everything_changes_nothing() { + let f = fit(900.0, FOOTER, &SIDEBAR_ROWS, 0.5); + assert_eq!( + (f.folded, f.tight, f.row, f.gap, f.scroll), + (false, false, 32.0, 6.0, false) + ); + } + + #[test] + fn the_sidebar_gives_way_in_order() { + // The links' height at a row and gap, however many sections there + // are (12 until 2026-10-24, when Invoices & Bills made 13). + let links = |row: f32, gap: f32| SIDEBAR_ROWS.height(row, gap); + // Card folds first. + let f = fit( + 18.0 + links(32.0, 6.0) + 8.0 + 147.0, + FOOTER, + &SIDEBAR_ROWS, + 0.5, + ); + assert!(f.folded && !f.tight && f.row == 32.0 && f.gap == 6.0); + // Then the spacing goes, before the rows. + let f = fit( + 8.0 + links(32.0, 4.0) + 8.0 + 112.0, + FOOTER, + &SIDEBAR_ROWS, + 0.5, + ); + assert!(f.folded && f.tight && f.row == 32.0 && f.gap < 6.0 && f.gap >= GAP_MIN); + // Then the rows, down to their least. + let f = fit( + 8.0 + links(28.0, GAP_MIN) + 8.0 + 112.0, + FOOTER, + &SIDEBAR_ROWS, + 0.5, + ); + assert!(f.tight && !f.scroll && f.gap == GAP_MIN && f.row < 32.0 && f.row >= 22.0); + // Then they scroll. + let f = fit(300.0, FOOTER, &SIDEBAR_ROWS, 0.5); + assert!(f.scroll && f.row == 22.0 && f.gap == GAP_MIN); + } + + #[test] + fn whatever_fit_is_chosen_the_links_fit_unless_they_scroll() { + for g in [&SIDEBAR_ROWS, &RAIL_ROWS] { + let foot = if g.foldable { + FOOTER + } else { + [150.0, 150.0, 120.0] + }; + let mut last = (0, f32::INFINITY); + for tenths in (1000..12000).rev() { + let avail = tenths as f32 / 10.0; + let f = fit(avail, foot, g, 0.5); + let head = if f.tight { HEAD_GAP_TIGHT } else { g.head_gap }; + let need = head + g.height(f.row, f.gap) + FOOTER_GAP + foot[f.form()]; + // Within the scroll area's rounding (fit). + assert!(f.scroll || need <= avail + 0.5, "{avail}: {f:?}"); + assert!(f.row >= g.row_min && f.row <= g.row && f.gap >= GAP_MIN); + // Shorter windows never step back. + let step = (f.form() + f.scroll as usize, f.row + f.gap); + assert!(step.0 >= last.0, "{avail}: {f:?}"); + assert!(step.0 > last.0 || step.1 <= last.1, "{avail}: {f:?}"); + last = step; + } + } + } + + #[test] + fn a_folded_card_names_a_failure_before_keeping_anything_else() { + let lines = summaries(&["Database differs"]); + // Every line says it failed; the name goes only after the full + // names have. + assert!(lines.iter().all(|l| l.contains(icon::WARNING_CIRCLE))); + let named = lines + .iter() + .take_while(|l| l.contains("Database differs")) + .count(); + assert_eq!(named, 1); + assert!(lines[named..].iter().all(|l| l.contains("failed"))); + // The event is the heading's hover, never on the line. + assert!(lines.iter().all(|l| !l.contains("event"))); + assert!(summaries(&["a", "b"]).last().unwrap().contains("2 failed")); + } + + /// The card at the sidebar's width (it is not resizable: 224 less the + /// panel's margins), with a very long company name and an event of + /// 1,234,567: every text a single line, so the card is exactly its + /// rows and its padding, in every state. + #[test] + fn the_status_card_never_wraps_in_any_state() { + use egui_kittest::Harness; + use std::cell::RefCell; + use std::rc::Rc; + let check = |ok: bool, t: &str| (ok, t.to_string(), String::new()); + let passing = [ + vec![ + check(true, "Journal chain verified"), + check(true, "Database matches journal"), + check(true, "12345 files verified"), + ], + vec![ + check(true, "Journal chain verified"), + check(true, "Database catching up"), + check(true, "12345 files verified"), + ], + vec![ + check(true, "Journal chain verified"), + check(true, "Viewer catching up"), + check(true, "12345 files verified"), + ], + vec![ + check(true, "Journal chain verified"), + check(true, "Read-only copy"), + check(true, "12345 files verified"), + ], + ]; + let failing = [ + vec![ + check(true, "Journal chain verified"), + check(false, "Database differs"), + check(true, "12345 files verified"), + ], + vec![ + check(true, "Journal chain verified"), + check(false, "Database unreadable"), + check(false, "12345 files damaged"), + ], + ]; + let long = "Wanderland Labs, the Very Long Named Limited Liability Company of Somewhere"; + for width in [224.0, 200.0] { + for folded in [false, true] { + for live in [true, false] { + for checks in passing.iter().chain(failing.iter()) { + let tag = format!("{width} folded {folded} live {live} {checks:?}"); + let got = Rc::new(RefCell::new(None)); + let out = got.clone(); + let ready = std::cell::Cell::new(false); + let view = CardView { + seq: 1_234_567, + head: "abc".into(), + data_dir: "/x".into(), + checks: checks.clone(), + since_update: 9.0, + live, + }; + let mut h = + Harness::builder() + .with_size(vec2(width, 400.0)) + .build_ui(move |ui| { + // The fonts are bound a frame after they are + // installed. + if !ready.replace(true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + let head = CardHead { + initial: 'W', + title: long.to_string(), + hue: egui::Color32::from_rgb(90, 120, 200), + }; + let inner = ui.available_width() - 24.0; + ui.add_space(12.0); + let mut rect = None; + ui.allocate_ui_with_layout( + vec2(inner, 300.0), + Layout::bottom_up(Align::Min), + |ui| { + let before = ui.cursor(); + status_card(ui, &view, folded, &head); + rect = Some((before, ui.min_rect())); + }, + ); + let y = ui.spacing().interact_size.y; + let row = ui.fonts_mut(|f| f.row_height(&theme::regular(11.5))); + let row12 = + ui.fonts_mut(|f| f.row_height(&theme::regular(12.0))); + let gap = ui.spacing().item_spacing.y; + *out.borrow_mut() = Some((rect, y, row, row12, gap)); + }); + h.run_steps(3); + let (_, interact, row, row12, gap) = got.borrow().unwrap(); + // Every text the card painted is one row, and none + // runs past the sidebar's inner width. + let mut texts = 0; + let mut lines = Vec::new(); + fn walk(s: &egui::Shape, out: &mut Vec<(f32, usize, f32)>) { + match s { + egui::Shape::Text(t) => out.push(( + t.galley.size().y, + t.galley.rows.len(), + t.pos.x + t.galley.size().x, + )), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + for cs in &h.output().shapes { + walk(&cs.shape, &mut lines); + } + for (height, rows, right) in &lines { + texts += 1; + assert_eq!(*rows, 1, "{tag}: a text wrapped"); + assert!(*height <= row12 + 1.0, "{tag}: a text {height} high"); + assert!(*right <= width - 12.0 + 0.5, "{tag}: a text runs out"); + } + assert!(texts >= 3, "{tag}: the card painted {texts} texts"); + // The card: its rows and its padding (10 and the + // stroke's 1 on each side). + let heading = CARD_BADGE; + let failed = checks.iter().any(|c| !c.0); + let body = if folded { + if failed { row12 + gap } else { 0.0 } + } else { + checks.len() as f32 * (row + gap) + }; + let want = body + heading + 2.0 * CARD_PAD_Y as f32 + 2.0; + let (rect, ..) = got.borrow().unwrap(); + let (_, used) = rect.unwrap(); + let have = used.height(); + assert!( + (have - want).abs() < 1.0, + "{tag}: the card is {have} high, its rows and padding {want} (heading {heading}, row {row}, gap {gap}, interact {interact}, used {used:?})" + ); + } + } + } + } + } + + #[test] + fn an_unmeasured_footer_form_is_reckoned_from_a_measured_one() { + let m = FooterMemo([None, Some(150.0), None]); + assert_eq!(m.heights(172.0, 70.0, 36.0), [220.0, 150.0, 114.0]); + assert_eq!( + FooterMemo::default().heights(172.0, 70.0, 36.0), + [172.0, 102.0, 66.0] + ); + } +} diff --git a/crates/ledger-gui/src/data.rs b/crates/ledger-gui/src/data.rs index b7794ff3..81b63f37 100644 --- a/crates/ledger-gui/src/data.rs +++ b/crates/ledger-gui/src/data.rs @@ -34,29 +34,135 @@ 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, 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 { + self.0.load(std::sync::atomic::Ordering::SeqCst) + } +} + +/// Sets the flag when the loader's thread ends, however it ends. +struct Ends(Arc); + +impl Drop for Ends { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::SeqCst); + } } 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 || run(source, ctx, tx, &stop)) + .spawn(move || { + // Dropped last: the thread has let go of everything. + let _ticket = ticket; + let _ends = ends; + run( + source, + ctx, + tx, + &stop, + &thread_presence, + &thread_attempts, + wake_to_watcher, + events, + ) + }) .expect("spawn loader"); - Loader { rx, gone } + Loader { + rx, + gone, + presence, + wake, + ended, + attempts, + } } /// Every update since the last call, in order (books before the @@ -69,6 +175,16 @@ impl Loader { pub fn wait(&self, timeout: Duration) -> Option { self.rx.recv_timeout(timeout).ok() } + + /// Whether the thread has ended (it ends once this is dropped). + pub fn finished(&self) -> bool { + self.ended.load(std::sync::atomic::Ordering::SeqCst) + } + + /// A handle that outlives the loader and says when its thread ended. + pub fn watch(&self) -> LoaderWatch { + LoaderWatch(self.ended.clone(), self.attempts.clone()) + } } /// Load once, synchronously (tests and one-shot tools). @@ -118,31 +234,56 @@ 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<()>, ) { let gone = || gone.load(std::sync::atomic::Ordering::SeqCst); let send = |u: Update| { 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) { @@ -158,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 @@ -180,7 +324,6 @@ fn run( }; check_show(&send); - let (ev_tx, ev_rx) = channel(); let mut watcher = notify::recommended_watcher(move |res: notify::Result| { if res.is_ok() { let _ = ev_tx.send(()); @@ -195,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() @@ -203,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); @@ -222,9 +371,16 @@ fn run( } Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => { + if gone() { + return; + } std::thread::sleep(Duration::from_secs(3)); } } + // Dropped meanwhile (the wake-up is the drop): end now. + if gone() { + return; + } let before = snap.journal_seq(); let grew = match snap.refresh() { Ok(n) => n > 0, @@ -235,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: @@ -248,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 68591d20..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()); + } } } @@ -466,6 +550,15 @@ impl Default for Dock { } impl Dock { + /// A closed dock with `agent` chosen: another company's tab opening + /// beside one whose dock is in use. + pub fn closed_with(agent: Agent) -> Dock { + Dock { + agent, + ..Default::default() + } + } + /// The dock as kept: the `agent` key and the `open` flag. pub fn restored(get: impl Fn(&str) -> Option) -> Dock { Dock { @@ -513,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) { @@ -556,6 +673,7 @@ impl Dock { rows: 24, }, wake, + jobs, ) { Ok(s) => { self.focused = true; @@ -569,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. @@ -591,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; } @@ -600,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| { @@ -673,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 3f40ffaa..80daf6ab 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -7,11 +7,13 @@ pub mod app; pub mod attention; pub mod books; pub mod charts; +pub mod company; pub mod data; pub mod demo; pub mod dock; pub mod export; pub mod fmt; +pub mod jobs; pub mod menu; pub mod nav; pub mod owner; @@ -19,14 +21,17 @@ pub mod pages; pub mod palette; mod prefs; mod receipts; +mod scheme_menu; mod schemes; +pub mod tabs; #[cfg(test)] mod test_support; mod theme; pub mod welcome; mod widgets; -pub use app::App; +pub use app::{App, Start}; +pub use company::CompanyView; pub use data::Source; use std::path::PathBuf; @@ -52,10 +57,12 @@ impl std::error::Error for Exit {} /// window closes. An unknown argument returns [`Exit`] (code 2). /// /// `ledger-gui [--root PATH] [--book ID] [--today YYYY-MM-DD] [--demo]`: -/// a book of the data root (plan 3.6), the only books it opens (D-44): +/// books of the data root (plan 3.6), the only books it opens (D-44): /// `--root`, else the root `wanderbooks setup` made, never the current -/// directory or a settings file; `--book` names one, else the root's only -/// one (or the first, by id). With no books yet, and an owner to set them +/// directory or a settings file; `--book` names one, which is then the +/// only tab; else the companies that were open when the window last +/// closed, each in a tab, in their order (the root's first, by id, if +/// none of them is there any more). With no books yet, and an owner to set them /// up (`wanderbooks gui`), it opens the first-run page (welcome.rs) instead /// of ending. `--demo` builds a demo company in a temp directory and opens /// that. @@ -100,11 +107,21 @@ pub fn run( } // The books to show, or a first run (no books yet, and the program gave // the viewer an owner to set them up: plan P11b), or the reason not. + // A company named (`--book`, the demo) is the only tab; otherwise the + // companies that were open last time come back (app.rs INVARIANT 3), + // the data root's first if none does. let mut first_run = None; - let data_dir = match data_dir { - Some(d) => Some(d), + let start = match data_dir { + Some(d) => Some(Start::Only(Source { data_dir: d, today })), None => match book_in_root(root.as_deref(), book.as_deref()) { - Ok(d) => Some(d), + Ok(d) if book.is_some() => Some(Start::Only(Source { data_dir: d, today })), + Ok(d) => match ledger_store::root::Root::find(root.as_deref()) { + Ok(r) => Some(Start::Restore { + root: r.path().to_path_buf(), + fallback: Source { data_dir: d, today }, + }), + Err(_) => Some(Start::Only(Source { data_dir: d, today })), + }, Err(why) => match owner::current() { // Named books that aren't there are a mistake, not a first run. Some(owner) if book.is_none() => { @@ -135,8 +152,8 @@ pub fn run( "wanderbooks", options, Box::new(move |cc| { - Ok(Box::new(match (data_dir, first_run) { - (Some(data_dir), _) => App::new(cc, Source { data_dir, today }), + Ok(Box::new(match (start, first_run) { + (Some(start), _) => App::start(cc, start), (None, state) => App::first_run(cc, root, today, state.unwrap_or_default()), })) }), 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 14af7717..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; @@ -204,6 +215,11 @@ pub trait Owner: Send + Sync { } } +/// The owner the program gave the viewer, for every company's view that +/// isn't given one of its own. It is the program's (one per process, as +/// the program is one), not a company's: each view takes a handle to it +/// when it is made, and holds that (`CompanyView::with_owner` gives a view +/// another). static OWNER: OnceLock> = OnceLock::new(); /// Give the viewer its owner (once, at start; INVARIANT 4). @@ -213,10 +229,6 @@ pub fn set_owner(owner: Arc) { /// The viewer's owner, if the program gave it one. pub fn current() -> Option> { - owner() -} - -fn owner() -> Option> { OWNER.get().cloned() } @@ -230,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 { @@ -307,6 +344,9 @@ struct RestoreForm { /// The menu's state: a dialog, the job under way, and the last outcome. #[derive(Default)] pub struct OwnerMenu { + /// The view that owns it: its dialogs' ids are scoped by it, so two + /// views' dialogs never share egui state. + scope: Option, /// The books last shown (by identity) and their id: found once for /// each load, not every frame. book: Option<(usize, Option)>, @@ -319,12 +359,24 @@ 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`, 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() + } + } + /// The id of the books shown, if they are books of a data root: found /// once for each load. fn book_of(&mut self, books: &Arc) -> Option { @@ -355,8 +407,8 @@ impl OwnerMenu { /// The standing notices above the page: an update waiting for the /// owner's accept, and a format upgrade the books wait for, whose /// go-ahead is asked for once each open (INVARIANT 5). - pub fn notice(&mut self, ui: &mut Ui, books: &Arc) { - let Some(owner) = owner() else { + pub fn notice(&mut self, ui: &mut Ui, owner: Option>, books: &Arc) { + let Some(owner) = owner else { return; }; let Some(book) = self.book_of(books) else { @@ -399,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 { @@ -447,8 +506,14 @@ impl OwnerMenu { } /// The menu button and a note of the last outcome; its dialogs. - pub fn ui(&mut self, ui: &mut Ui, books: &Arc, compact: bool) { - let Some(owner) = owner() else { + pub fn ui( + &mut self, + ui: &mut Ui, + owner: Option>, + books: &Arc, + compact: bool, + ) { + let Some(owner) = owner else { return; }; let Some(book) = self.book_of(books) else { @@ -482,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| { @@ -493,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)) @@ -525,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)), )); } @@ -546,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 @@ -555,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 @@ -568,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() { @@ -591,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; } @@ -610,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) => { @@ -636,17 +721,29 @@ impl OwnerMenu { } } if !close { - upgrade_dialog(ctx, form, owner, book, &mut close); + upgrade_dialog( + ctx, + self.scope.unwrap_or(egui::Id::NULL), + form, + owner, + book, + &jobs, + &mut close, + ); } } Dialog::Close => { - egui::Modal::new(egui::Id::new("owner-close")).show(ctx, |ui| { + egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-close")).show(ctx, |ui| { ui.heading("Close the books?"); ui.label("Agents' sessions and everything else holding them let go. They open again when something holds them."); 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() { @@ -656,30 +753,32 @@ impl OwnerMenu { }); } Dialog::NewBooks { id, currency } => { - egui::Modal::new(egui::Id::new("owner-new-books")).show(ctx, |ui| { - ui.heading("New books"); - ui.label("Their id: lowercase letters, digits and hyphens."); - ui.text_edit_singleline(id); - ui.label("Their base currency (fixed for good):"); - ui.text_edit_singleline(currency); - ui.horizontal(|ui| { - let ready = !id.trim().is_empty() && !currency.trim().is_empty(); - if ui - .add_enabled(ready, egui::Button::new("Make them")) - .clicked() - { - let (o, i, c) = (owner.clone(), id.clone(), currency.clone()); - run = Some(( - "New books".into(), - Box::new(move || o.new_books(&i, &c).map(|l| vec![l])), - )); - close = true; - } - if ui.button("Cancel").clicked() { - close = true; - } + egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-new-books")) + .show(ctx, |ui| { + ui.heading("New books"); + ui.label("Their id: lowercase letters, digits and hyphens."); + ui.text_edit_singleline(id); + ui.label("Their base currency (fixed for good):"); + ui.text_edit_singleline(currency); + ui.horizontal(|ui| { + let ready = !id.trim().is_empty() && !currency.trim().is_empty(); + if ui + .add_enabled(ready, egui::Button::new("Make them")) + .clicked() + { + 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; + } + if ui.button("Cancel").clicked() { + close = true; + } + }); }); - }); } Dialog::Restore(form) => { if let Some((rx, asked)) = &form.planning @@ -699,7 +798,7 @@ impl OwnerMenu { _ => {} } } - egui::Modal::new(egui::Id::new("owner-restore")).show(ctx, |ui| { + egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-restore")).show(ctx, |ui| { ui.set_max_width(520.0); ui.heading("Restore books"); ui.label("The backup: its repository's address, or its folder (the books' .git folder in your backup folder)."); @@ -754,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…"); @@ -769,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; } } @@ -784,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); } } } @@ -794,13 +911,15 @@ impl OwnerMenu { /// passphrase, and the go-ahead or not now. fn upgrade_dialog( ctx: &egui::Context, + scope: egui::Id, form: &mut UpgradeForm, owner: &Arc, book: &str, + jobs: &crate::jobs::Spawner, close: &mut bool, ) { let p = crate::theme::pal(ctx); - egui::Modal::new(egui::Id::new("owner-upgrade")).show(ctx, |ui| { + egui::Modal::new(scope.with("owner-upgrade")).show(ctx, |ui| { ui.set_max_width(520.0); ui.heading("Upgrade these books' format?"); ui.add_space(4.0); @@ -837,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/pages/mod.rs b/crates/ledger-gui/src/pages/mod.rs index 76f96013..52905e25 100644 --- a/crates/ledger-gui/src/pages/mod.rs +++ b/crates/ledger-gui/src/pages/mod.rs @@ -166,7 +166,9 @@ pub fn split( ui.allocate_rect(rect, egui::Sense::hover()); return; } - let key = egui::Id::new(("split", id)); + // Scoped by the page's ui, which is its company's: another company's + // tab keeps its own width. + let key = ui.id().with(("split", id)); let mut detail_w: f32 = ui .ctx() .data_mut(|d| d.get_persisted(key)) diff --git a/crates/ledger-gui/src/pages/overview.rs b/crates/ledger-gui/src/pages/overview.rs index a3f6f584..8a19b547 100644 --- a/crates/ledger-gui/src/pages/overview.rs +++ b/crates/ledger-gui/src/pages/overview.rs @@ -20,7 +20,7 @@ use rust_decimal::Decimal; pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { page(ui, "overview", |ui| { let k = &b.kpis; - widgets::page_header(ui, b.company_name(), &headline(b)); + widgets::page_lead(ui, &headline(b)); kpis(ui, b, shell); let _ = k; // What needs doing gets the page's full width, under the numbers: diff --git a/crates/ledger-gui/src/pages/projects.rs b/crates/ledger-gui/src/pages/projects.rs index b89ca138..84dad086 100644 --- a/crates/ledger-gui/src/pages/projects.rs +++ b/crates/ledger-gui/src/pages/projects.rs @@ -748,7 +748,9 @@ pub fn figures( fiscal: bool, ) -> std::sync::Arc { type Stamp = (chrono::DateTime, String, NaiveDate, bool); - let key = egui::Id::new(("project_figures", id)); + // Of these books: another company's project of the same number has + // its own figures. + let key = egui::Id::new(("project_figures", &b.data_dir, id)); let stamp: Stamp = (b.loaded_at, b.head.clone(), b.today, fiscal); if let Some((was, figs)) = ctx.data(|d| d.get_temp::<(Stamp, std::sync::Arc)>(key)) && was == stamp diff --git a/crates/ledger-gui/src/palette.rs b/crates/ledger-gui/src/palette.rs index bd7bfab8..e6ee07f3 100644 --- a/crates/ledger-gui/src/palette.rs +++ b/crates/ledger-gui/src/palette.rs @@ -13,6 +13,9 @@ use egui_phosphor::regular as icon; #[derive(Default)] pub struct Palette { + /// The view that owns it: its modal's id is scoped by it, so two + /// views' palettes never share egui state. + scope: Option, open: bool, query: String, selected: usize, @@ -29,6 +32,13 @@ pub struct Item { } impl Palette { + /// A palette whose ids belong to the view `scope`. + pub fn scoped(scope: egui::Id) -> Self { + Self { + scope: Some(scope), + ..Default::default() + } + } pub fn open(&mut self) { self.open = true; self.query.clear(); @@ -66,7 +76,7 @@ impl Palette { self.open = false; return Some(it.route.clone()); } - let modal = egui::Modal::new(egui::Id::new("palette")) + let modal = egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("palette")) .frame( egui::Frame::new() .fill(p.surface) 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/scheme_menu.rs b/crates/ledger-gui/src/scheme_menu.rs new file mode 100644 index 00000000..99f55e23 --- /dev/null +++ b/crates/ledger-gui/src/scheme_menu.rs @@ -0,0 +1,369 @@ +//! The color scheme button and its menu (app-wide: one scheme for the +//! whole window, whatever company's tab is shown). + +use crate::schemes::{self, Filter, Scheme}; +use crate::theme::{self, pal}; +use egui::{Align, CornerRadius, Layout, RichText, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as icon; + +/// The height of a family's row in the color scheme menu, for laying the +/// families out in columns. +const FAMILY_ROW: f32 = 34.0; + +/// How long the pointer rests on a scheme's row (or off every row) before +/// that scheme (or the one in force) is worn, seconds. +const PREVIEW_AFTER: f64 = 0.05; + +/// The width of a variant's row in a family's flyout: room for its colors +/// and the longest name. +const SCHEME_ROW_WIDTH: f32 = 200.0; + +/// Where the viewer keeps its color scheme ("Family/Variant"). +const SCHEME_KEY: &str = "scheme"; +/// Where it keeps its scheme menu's filter. +const FILTER_KEY: &str = "scheme_filter"; + +/// One variant in the color scheme menu: a strip of its colors and its +/// name, the whole row one button, selected when it is the one in force. +fn scheme_row(ui: &mut Ui, scheme: &Scheme, current: bool) -> egui::Response { + let p = pal(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(SCHEME_ROW_WIDTH, 28.0), Sense::click()); + response.widget_info(|| { + egui::WidgetInfo::selected( + egui::WidgetType::SelectableLabel, + true, + current, + scheme.name, + ) + }); + if ui.is_rect_visible(rect) { + let painter = ui.painter(); + let fill = if current { + Some(p.selected) + } else if response.hovered() { + Some(p.hover) + } else { + None + }; + if let Some(fill) = fill { + painter.rect_filled(rect, CornerRadius::same(6), fill); + } + let strip = egui::Rect::from_min_size( + egui::pos2(rect.left() + 8.0, rect.center().y - 7.0), + vec2(50.0, 14.0), + ); + let w = strip.width() / 5.0; + for (i, c) in scheme.swatch().into_iter().enumerate() { + let r = egui::Rect::from_min_size( + strip.min + vec2(w * i as f32, 0.0), + vec2(w, strip.height()), + ); + painter.rect_filled(r, 0.0, c); + } + painter.rect_stroke( + strip, + 3.0, + Stroke::new(1.0, p.border), + egui::StrokeKind::Outside, + ); + painter.text( + egui::pos2(strip.right() + 10.0, rect.center().y), + egui::Align2::LEFT_CENTER, + scheme.name, + theme::regular(14.0), + p.text, + ); + } + response +} + +/// The scheme and menu filter kept from last time (`get` reads the +/// viewer's preferences): the scheme kept; before schemes, the light or +/// dark choice kept as "dark"; else the viewer's own for the system's +/// mode (schemes INVARIANT 4). +fn restored(get: impl Fn(&str) -> Option, system_dark: bool) -> (&'static Scheme, Filter) { + let dark = get("dark").map_or(system_dark, |v| v == "true"); + let scheme = get(SCHEME_KEY).map_or_else(|| schemes::own(dark), |k| Scheme::from_key(&k, dark)); + let filter = get(FILTER_KEY) + .and_then(|f| Filter::from_name(&f)) + .unwrap_or_default(); + (scheme, filter) +} + +/// The color scheme in force, the one worn (a hovered one previewed), and +/// the menu's filter: the app's, shared by every tab. +pub struct SchemeMenu { + /// The color scheme in force (schemes.rs). + scheme: &'static Scheme, + /// The scheme being worn: the one in force, or one previewed while + /// its row in the menu is hovered. + shown: &'static Scheme, + /// The scheme the pointer asks for, and since when: worn once it has + /// asked for PREVIEW_AFTER. + wanted: Option<(&'static Scheme, f64)>, + /// Which schemes its menu shows. + filter: Filter, +} + +impl SchemeMenu { + pub fn new(scheme: &'static Scheme) -> Self { + Self { + scheme, + shown: scheme, + wanted: None, + filter: Filter::default(), + } + } + + /// The scheme and filter kept from last time (`get` reads the + /// viewer's preferences; the system's mode decides without them). + pub fn restored(get: impl Fn(&str) -> Option, system_dark: bool) -> Self { + let (scheme, filter) = restored(get, system_dark); + let mut me = Self::new(scheme); + me.filter = filter; + me + } + + /// Keep the preferences (the keys they have always had). + pub fn keep(&self, set: &mut dyn FnMut(&str, String)) { + set(SCHEME_KEY, self.scheme.key()); + set(FILTER_KEY, self.filter.name().to_string()); + set("dark", self.scheme.dark.to_string()); + } + + /// The scheme in force. + pub fn in_force(&self) -> &'static Scheme { + self.scheme + } + + /// Whether the scheme in force is a dark one. + pub fn dark(&self) -> bool { + self.scheme.dark + } + + /// Wear the color scheme kept as `key` ("Family/Variant"; tests). + pub fn set_scheme(&mut self, ctx: &egui::Context, key: &str) { + self.choose(ctx, Scheme::from_key(key, self.scheme.dark)); + } + + /// The color scheme in force, as kept ("Family/Variant"). + pub fn scheme_key(&self) -> String { + self.scheme.key() + } + + /// The scheme being worn ("Family/Variant"): a previewed one while + /// its row is hovered (tests). + pub fn shown_scheme_key(&self) -> String { + self.shown.key() + } + + fn choose(&mut self, ctx: &egui::Context, scheme: &'static Scheme) { + self.scheme = scheme; + self.wear(ctx, scheme); + } + + /// Wear `scheme`, in force or previewed. + fn wear(&mut self, ctx: &egui::Context, scheme: &'static Scheme) { + self.shown = scheme; + self.wanted = None; + theme::apply_scheme(ctx, scheme); + } + + /// The preview (owner, 2026-10-19: "when we hover over a scheme for + /// some time switch to it live; when we switch out of it go to either + /// the new thing we're hovering or back to the current one"). While + /// the menu is open, the scheme whose row is hovered, else the one in + /// force, is worn once the pointer has asked for it PREVIEW_AFTER + /// without change; the menu closed, the one in force is worn at once. + /// A preview is never kept: only a click chooses. + fn preview(&mut self, ctx: &egui::Context, open: bool, hovered: Option<&'static Scheme>) { + let want = match (open, hovered) { + (true, Some(s)) => s, + _ => self.scheme, + }; + if std::ptr::eq(want, self.shown) { + self.wanted = None; + return; + } + if !open { + self.wear(ctx, want); + return; + } + let now = ctx.input(|i| i.time); + match self.wanted { + Some((s, since)) if std::ptr::eq(s, want) => { + let waited = now - since; + if waited >= PREVIEW_AFTER { + self.wear(ctx, want); + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64( + PREVIEW_AFTER - waited, + )); + } + } + _ => { + self.wanted = Some((want, now)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(PREVIEW_AFTER)); + } + } + } + + /// The color scheme button and its menu: a filter (all, light, dark), + /// then each family with a flyout of its variants. `compact`: the + /// narrow rail's icon alone. + pub fn menu(&mut self, ui: &mut Ui, compact: bool) { + let p = pal(ui.ctx()); + let text = if compact { + RichText::new(icon::PALETTE).size(16.0).color(p.muted) + } else { + RichText::new(format!("{} {}", icon::PALETTE, self.scheme.label())) + .font(theme::regular(12.5)) + .color(p.muted) + }; + let mut button = egui::Button::new(text).frame(false); + if compact { + button = button.min_size(vec2(32.0, ui.spacing().interact_size.y + 4.0)); + } + // Open while the filter changes; closed when a scheme is chosen. + let config = egui::containers::menu::MenuConfig::new() + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let mut chosen = None; + let mut hovered = None; + let (response, open) = egui::containers::menu::MenuButton::from_button(button) + .config(config) + .ui(ui, |ui| { + ui.set_min_width(200.0); + ui.horizontal(|ui| { + for f in [Filter::All, Filter::Light, Filter::Dark] { + ui.selectable_value(&mut self.filter, f, f.name()); + } + }); + ui.separator(); + // Every family on screen at once, in as many columns as + // the window's height needs: nothing hides below a scroll. + let families = schemes::families(self.filter); + let rows = (((ui.ctx().content_rect().height() - 160.0) / FAMILY_ROW).floor() + as usize) + .clamp(6, families.len().max(6)); + let font = theme::regular(14.0); + let check = ui + .painter() + .layout_no_wrap(icon::CHECK.into(), font.clone(), p.accent) + .size() + .x; + ui.horizontal_top(|ui| { + for column in families.chunks(rows) { + // Each family's button as wide as its column, its + // flyout opening beside the column. + ui.allocate_ui_with_layout( + vec2(170.0, 0.0), + Layout::top_down_justified(Align::LEFT), + |ui| { + ui.set_width(170.0); + for (family, variants) in column { + let here = *family == self.scheme.family + && self.filter.shows(self.scheme); + // Only the family in force is checked; the + // others are indented by the check's width, + // so names line up and a screen reader hears + // the check only where it is. + let mut label = egui::text::LayoutJob::default(); + if here { + label.append( + icon::CHECK, + 0.0, + egui::TextFormat::simple(font.clone(), p.accent), + ); + } + let indent = if here { 8.0 } else { check + 8.0 }; + label.append( + family, + indent, + egui::TextFormat::simple(font.clone(), p.text), + ); + ui.menu_button(label, |ui| { + for v in variants { + let row = + scheme_row(ui, v, std::ptr::eq(*v, self.scheme)); + if row.hovered() { + hovered = Some(*v); + } + if row.clicked() { + chosen = Some(*v); + ui.close(); + } + } + }); + } + }, + ); + } + }); + }); + response.on_hover_text(format!("Color scheme: {}", self.scheme.label())); + match chosen { + Some(v) => self.choose(ui.ctx(), v), + None => self.preview(ui.ctx(), open.is_some(), hovered), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn kept(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let map: HashMap = pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + move |k| map.get(k).cloned() + } + + #[test] + fn the_kept_scheme_and_filter_come_back() { + let (s, f) = restored( + kept(&[ + ("scheme", "Ayu/Mirage"), + ("scheme_filter", "Dark"), + ("dark", "false"), + ]), + false, + ); + assert_eq!(s.key(), "Ayu/Mirage", "the scheme wins over the old choice"); + assert_eq!(f, Filter::Dark); + } + + #[test] + fn before_schemes_the_light_or_dark_choice_is_kept() { + let (s, f) = restored(kept(&[("dark", "true")]), false); + assert!(std::ptr::eq(s, schemes::own(true))); + assert_eq!(f, Filter::All); + let (s, _) = restored(kept(&[("dark", "false")]), true); + assert!(std::ptr::eq(s, schemes::own(false))); + } + + #[test] + fn with_nothing_kept_the_systems_mode_decides() { + for dark in [false, true] { + let (s, f) = restored(kept(&[]), dark); + assert!(std::ptr::eq(s, schemes::own(dark))); + assert_eq!(f, Filter::All); + } + } + + #[test] + fn a_lost_scheme_or_filter_falls_back() { + let (s, f) = restored( + kept(&[ + ("scheme", "Gone/Away"), + ("scheme_filter", "Sepia"), + ("dark", "true"), + ]), + false, + ); + assert!(std::ptr::eq(s, schemes::own(true))); + assert_eq!(f, Filter::All); + } +} diff --git a/crates/ledger-gui/src/tabs.rs b/crates/ledger-gui/src/tabs.rs new file mode 100644 index 00000000..a3b2ce4c --- /dev/null +++ b/crates/ledger-gui/src/tabs.rs @@ -0,0 +1,551 @@ +//! The tab bar along the top of the window: one tab per open company, a +//! close control on each, and a "+" that lists the companies of the data +//! root that are not open. It runs from the sidebar's right edge to the +//! window's right edge: the sidebar keeps the window's whole height, which +//! the owner's 1479x519 window needs (`tests/sidenav.rs`: with the bar +//! above the sidebar the links scroll there, even with a bar of 24 +//! points); with no company open there is no sidebar and it runs the whole +//! width. +//! +//! The bar spans the whole window, above the sidebar: a tab is the top +//! level, and the sidebar (its pages, its status card) is the company in +//! the tab's, which the layout shows. The tab is the company's identity +//! in the frame (badge and name); nothing else at the top of the window +//! repeats it, and the status card at the foot of the sidebar names it +//! again, in the same hue. With no company open +//! it is the window's top all the same. The "+" follows the last tab, and +//! stays at the right edge, whole, while the tabs scroll. +//! +//! ```text +//! GOAL: a person has several companies open at once, each in its own +//! tab, and moves between them, opens and closes them, without +//! any one disturbing another. +//! SOURCE: plan/p15-app-and-relay.md 3.2 and 3.3 (a tab per open +//! company); D-78 (one top-level tab per open company: a +//! company is reachable exactly while it has a tab). +//! INVARIANTS: +//! 1. One tab per open company, in the order opened, showing the +//! company's badge (its hue, from the id of its books: theme.rs +//! `hue_of`; the status card draws the same) and name (the name last known, else the id of its books, until it is +//! read). The bar is there with one company open, and with none. +//! 2. The tab shown is marked by more than colour: a heavier name, a +//! bar in the accent colour along its top edge, and "selected" to +//! assistive technology. +//! 3. Each tab has its own close control, labelled for assistive +//! technology with the company's name; a middle click on a tab +//! closes it as well. +//! 4. "+" lists only companies of the data root that are not open +//! (a company can't be opened twice), by name with the id of the +//! books beside it (the id alone for a company never opened), and +//! says so when there are none. +//! 5. Tabs never overlap or leave the bar: each is as wide as its +//! content between a least and a greatest width (a longer name is +//! cut, whole in its hover text), then the strip scrolls, with a +//! step control at each end; the tab shown is scrolled into view +//! when it changes. Each tab leaves room left of its close control +//! 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}; +use egui::{ + Align, CornerRadius, Frame, Layout, Margin, RichText, Sense, Stroke, Ui, UiBuilder, vec2, +}; +use egui_phosphor::regular as icon; +use std::time::{Duration, Instant}; + +/// The bar's height: what the bar takes from the window, which the tests +/// of the sidebar's fit add to their window heights (D-78). +pub const BAR_H: f32 = 36.0; +/// A tab's widest and least widths (a name is cut with an ellipsis to fit). +const TAB_MAX: f32 = 240.0; +const TAB_MIN: f32 = 110.0; +/// The close control's size. +const CLOSE: f32 = 20.0; +/// The badge's size, and its gap to the name. +const BADGE: f32 = 18.0; +const GAP: f32 = 8.0; +/// Room left of the close control for the connection state, which a later +/// unit draws there. +const STATE_W: f32 = 14.0; +/// The room round a tab's content: left and right. +const PAD_L: f32 = 10.0; +const PAD_R: f32 = 6.0; +/// The "+"'s width, and the gap before it. +const PLUS_W: f32 = 30.0; +const PLUS_GAP: f32 = 6.0; +/// The "+" list's width. +const LIST_W: f32 = 260.0; +/// The gap between tabs. +const TAB_GAP: f32 = 2.0; +/// How long a reading of the data root's companies is kept while "+" is +/// open. +const LIST_KEPT: Duration = Duration::from_millis(750); + +/// What a tab shows of its company. +pub struct Tab { + /// The company's name, else the id of its books. + pub title: String, + /// More about it, on hover. + pub detail: String, + /// 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 +/// dark: the one its tab and its status card both draw (theme.rs). +pub fn hue_of(book_id: &str, dark: bool) -> egui::Color32 { + theme::hue_of(book_id, dark) +} + +/// A company of the data root that is not open, as "+" lists it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Listed { + /// The id of its books. + pub id: String, + /// Its name as last known, if it was ever opened here. + pub name: Option, +} + +/// What a person asked of the bar. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TabAction { + /// Show tab `n`. + Show(usize), + /// Close tab `n`. + Close(usize), + /// Open the company of the data root with this id. + Open(String), +} + +/// The bar's memory: whether to scroll the shown tab into view, and the +/// data root's companies as last read for "+". +#[derive(Default)] +pub struct TabBar { + reveal: bool, + listed: Option<(Instant, Vec)>, +} + +impl TabBar { + /// The shown tab changed (or a tab was added): scroll it into view. + pub fn reveal(&mut self) { + self.reveal = true; + } + + /// The bar, across the top of the window. `shown` is the tab in + /// front, if there is one; `others` reads the companies of the root + /// that are not open (called now and then while "+" is open, never + /// otherwise). + pub fn show( + &mut self, + ui: &mut Ui, + tabs: &[Tab], + shown: Option, + others: &dyn Fn() -> Vec, + ) -> Option { + let p = pal(ui.ctx()); + let mut action = None; + let mut reveal = std::mem::take(&mut self.reveal); + egui::Panel::top("company_tabs") + .exact_size(BAR_H) + .resizable(false) + .frame(Frame::new().inner_margin(Margin::symmetric(8, 0))) + .show(ui, |ui| { + ui.spacing_mut().item_spacing = vec2(TAB_GAP, 0.0); + let bar = ui.max_rect(); + // The line along the bar's foot; the tab in front covers + // it, and so is one with what is below. + let outer = ui.clip_rect(); + ui.painter().rect_filled(outer, 0.0, p.sidebar); + ui.painter().hline( + outer.x_range(), + outer.bottom() - 0.5, + Stroke::new(1.0, p.border), + ); + // The tabs as wide as they are, the "+" right after them; + // when they don't fit, the "+" stays at the right edge + // and the tabs scroll. + let widths: Vec = tabs.iter().map(|t| tab_width(ui, t)).collect(); + let total: f32 = + widths.iter().sum::() + widths.len().saturating_sub(1) as f32 * TAB_GAP; + let room = (ui.available_width() - PLUS_W - PLUS_GAP).max(0.0); + let strip_w = total.min(room); + let strip = egui::Rect::from_min_size(bar.min, vec2(strip_w, bar.height())); + let mut strip_ui = ui.new_child( + UiBuilder::new() + .max_rect(strip) + .layout(Layout::left_to_right(Align::Max)), + ); + strip_ui.set_clip_rect(strip); + self.strip( + &mut strip_ui, + tabs, + &widths, + total > room + 0.5, + shown, + &mut reveal, + &mut action, + ); + let plus = egui::Rect::from_min_size( + egui::pos2(strip.right() + PLUS_GAP, bar.top()), + vec2(PLUS_W, bar.height()), + ); + let mut plus_ui = ui.new_child( + UiBuilder::new() + .max_rect(plus) + .layout(Layout::left_to_right(Align::Center)), + ); + self.plus(&mut plus_ui, others, &mut action); + ui.allocate_rect(bar, Sense::hover()); + }); + if reveal { + // The tab wasn't there to scroll to yet: try again next frame. + self.reveal = true; + } + action + } + + /// The tabs, scrolling sideways when they don't fit. + #[allow(clippy::too_many_arguments)] + fn strip( + &mut self, + ui: &mut Ui, + tabs: &[Tab], + widths: &[f32], + overflows: bool, + shown: Option, + reveal: &mut bool, + action: &mut Option, + ) { + let p = pal(ui.ctx()); + let room = ui.available_width(); + // A step control at each end while the tabs overflow. + let step_w = if overflows { 22.0 } else { 0.0 }; + let step_by = widths.first().copied().unwrap_or(TAB_MIN) + TAB_GAP; + let area_id = ui.id().with("tab_scroll"); + let mut step = 0.0_f32; + if overflows { + let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click()); + step_button(ui, r, &resp, icon::CARET_LEFT, "Earlier tabs"); + if resp.clicked() { + step = -step_by; + } + } + let view_w = room - 2.0 * step_w; + let mut state = egui::scroll_area::State::load(ui.ctx(), area_id).unwrap_or_default(); + if step != 0.0 { + state.offset.x = (state.offset.x + step).max(0.0); + state.store(ui.ctx(), area_id); + } + let out = egui::ScrollArea::horizontal() + .id_salt("tab_scroll") + .max_width(view_w.max(0.0)) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.x = TAB_GAP; + ui.horizontal_top(|ui| { + for (i, tab) in tabs.iter().enumerate() { + let here = shown == Some(i); + let r = one_tab(ui, i, tab, here, widths[i], &p, action); + if here && *reveal { + r.scroll_to_me(Some(Align::Center)); + *reveal = false; + } + } + }); + }); + if overflows { + let offset = out.state.offset.x; + let max = (out.content_size.x - out.inner_rect.width()).max(0.0); + let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click()); + step_button(ui, r, &resp, icon::CARET_RIGHT, "Later tabs"); + if resp.clicked() { + let mut s = out.state; + s.offset.x = (offset + step_by).min(max); + s.store(ui.ctx(), out.id); + } + } + if tabs.is_empty() { + *reveal = false; + } + } + + /// The "+" and its list. + fn plus( + &mut self, + ui: &mut Ui, + others: &dyn Fn() -> Vec, + action: &mut Option, + ) { + let p = pal(ui.ctx()); + let button = egui::Button::new(RichText::new(icon::PLUS).size(16.0).color(p.text)) + .frame(false) + .min_size(vec2(28.0, 28.0)); + let (response, open) = + egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| { + ui.set_min_width(LIST_W); + let stale = self + .listed + .as_ref() + .is_none_or(|(at, _)| at.elapsed() > LIST_KEPT); + if stale { + self.listed = Some((Instant::now(), others())); + } + ui.ctx().request_repaint_after(LIST_KEPT); + let list = self + .listed + .as_ref() + .map(|(_, l)| l.clone()) + .unwrap_or_default(); + if list.is_empty() { + ui.label( + RichText::new("Every company is already open.") + .font(theme::regular(13.0)) + .color(p.muted), + ); + } else { + ui.label( + RichText::new("Open a company") + .font(theme::regular(12.0)) + .color(p.muted), + ); + for c in &list { + if listed_row(ui, c, &p).clicked() { + *action = Some(TabAction::Open(c.id.clone())); + ui.close(); + } + } + } + }); + // Forget the list once it is closed, so it is read afresh. + if open.is_none() { + self.listed = None; + } + // Named as it always was for assistive technology; the hover says + // what it does. + response.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Open another company") + }); + response.on_hover_text("Open a company"); + } +} + +/// One company in the "+" list: its name, the id of its books beside it +/// in small text (the id alone when the name was never known). +fn listed_row(ui: &mut Ui, c: &Listed, p: &theme::Palette) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(vec2(LIST_W, 28.0), Sense::click()); + let primary = c.name.as_deref().unwrap_or(&c.id); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, primary)); + if resp.hovered() { + ui.painter() + .rect_filled(rect, CornerRadius::same(6), p.hover); + } + let mut right = rect.right() - 8.0; + if c.name.is_some() { + let g = ui + .painter() + .layout_no_wrap(c.id.clone(), theme::regular(11.0), p.muted); + right -= g.size().x; + ui.painter().galley( + egui::pos2(right, rect.center().y - g.size().y / 2.0), + g, + p.muted, + ); + } + let mut job = egui::text::LayoutJob::single_section( + primary.to_string(), + egui::TextFormat::simple(theme::regular(13.0), p.text), + ); + job.wrap.max_width = (right - 8.0 - (rect.left() + 8.0)).max(10.0); + job.wrap.max_rows = 1; + job.wrap.break_anywhere = true; + job.wrap.overflow_character = Some('…'); + let g = ui.painter().layout_job(job); + ui.painter().galley( + egui::pos2(rect.left() + 8.0, rect.center().y - g.size().y / 2.0), + g, + p.text, + ); + resp +} + +/// A step control at an end of the strip. +fn step_button(ui: &Ui, r: egui::Rect, resp: &egui::Response, glyph: &str, label: &'static str) { + let p = pal(ui.ctx()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); + if resp.hovered() { + ui.painter().rect_filled(r, CornerRadius::same(6), p.hover); + } + ui.painter().text( + r.center(), + egui::Align2::CENTER_CENTER, + glyph, + egui::FontId::proportional(13.0), + p.muted, + ); +} + +/// What a tab holds besides its name: the badge, the room for the state +/// mark, the close control and the room round them. +const TAB_FIXED: f32 = PAD_L + BADGE + GAP + GAP + STATE_W + CLOSE + PAD_R; + +/// A tab's width: its content's, between the least and the greatest. The +/// name is measured in the heavier face for every tab, so the tab in front +/// doesn't move the others. +fn tab_width(ui: &Ui, tab: &Tab) -> f32 { + let g = ui.painter().layout_no_wrap( + tab.title.clone(), + theme::semibold(13.0), + egui::Color32::PLACEHOLDER, + ); + (TAB_FIXED + g.size().x.ceil()).clamp(TAB_MIN, TAB_MAX) +} + +/// One tab, `width` wide. +fn one_tab( + ui: &mut Ui, + i: usize, + tab: &Tab, + here: bool, + width: f32, + p: &theme::Palette, + action: &mut Option, +) -> egui::Response { + let height = BAR_H - 4.0; + let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click()); + // The tab's own id for its close control: tabs are told apart by + // their place, and two tabs never share one. + let close_rect = egui::Rect::from_center_size( + egui::pos2(rect.right() - PAD_R - CLOSE / 2.0, rect.center().y), + vec2(CLOSE, CLOSE), + ); + let close = ui.interact(close_rect, resp.id.with("close"), Sense::click()); + resp.widget_info(|| { + egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, here, &tab.title) + }); + close.widget_info(|| { + egui::WidgetInfo::labeled( + egui::WidgetType::Button, + tab.held.is_none(), + format!("Close {}", tab.title), + ) + }); + if ui.is_rect_visible(rect) { + let painter = ui.painter(); + let top = CornerRadius { + nw: 8, + ne: 8, + sw: 0, + se: 0, + }; + if here { + // The lit tab: the page's surface, outlined on its top and + // sides, open at the foot where it meets what is below, with a + // bar in the accent colour along its top edge. + painter.rect_filled(rect, top, p.surface); + painter.rect_stroke( + rect, + top, + Stroke::new(1.0, p.border), + egui::StrokeKind::Inside, + ); + painter.rect_filled( + egui::Rect::from_min_max( + egui::pos2(rect.left() + 1.0, rect.bottom() - 1.0), + egui::pos2(rect.right() - 1.0, rect.bottom() + 1.0), + ), + 0.0, + p.surface, + ); + painter.rect_filled( + egui::Rect::from_min_size(rect.min, vec2(rect.width(), 3.0)), + top, + p.accent, + ); + } else if resp.hovered() || close.hovered() { + painter.rect_filled(rect.shrink2(vec2(0.0, 2.0)), CornerRadius::same(8), p.hover); + } + // The badge: the company's hue, as its status card draws it. + let badge = egui::Rect::from_center_size( + egui::pos2(rect.left() + PAD_L + BADGE / 2.0, rect.center().y + 1.0), + vec2(BADGE, BADGE), + ); + let initial = tab + .title + .chars() + .next() + .map(|c| c.to_uppercase().next().unwrap_or(c)) + .unwrap_or('W'); + theme::paint_badge( + painter, + badge, + 5, + initial, + theme::badge_hue(ui.ctx(), &tab.hue_key), + theme::bold(11.0), + ); + let font = if here { + theme::semibold(13.0) + } else { + theme::regular(13.0) + }; + let text_x = badge.right() + GAP; + let text_w = close_rect.left() - STATE_W - GAP - text_x; + let mut job = egui::text::LayoutJob::single_section( + tab.title.clone(), + egui::TextFormat::simple(font, p.text), + ); + job.wrap.max_width = text_w.max(10.0); + job.wrap.max_rows = 1; + job.wrap.break_anywhere = true; + job.wrap.overflow_character = Some('…'); + let galley = painter.layout_job(job); + painter.galley( + egui::pos2(text_x, rect.center().y - galley.size().y / 2.0 + 1.0), + galley, + p.text, + ); + if close.hovered() && tab.held.is_none() { + painter.rect_filled(close_rect, CornerRadius::same(5), p.selected); + } + painter.text( + close_rect.center(), + egui::Align2::CENTER_CENTER, + icon::X, + egui::FontId::proportional(12.0), + if tab.held.is_some() { + p.faint + } else if close.hovered() || here { + p.text + } else { + p.muted + }, + ); + } + 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. + 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)); + } + resp +} diff --git a/crates/ledger-gui/src/theme.rs b/crates/ledger-gui/src/theme.rs index fcfef087..70437888 100644 --- a/crates/ledger-gui/src/theme.rs +++ b/crates/ledger-gui/src/theme.rs @@ -90,6 +90,106 @@ pub const DARK: Palette = Palette { ], }; +/// The company badges' hues, light and dark: one per company, chosen by +/// [`hue_of`] from the id of its books. Each is dark enough (light) or +/// bright enough (dark) that its letter (black or white, whichever reads +/// better) has 4.5:1 on it and it has 3:1 on every surface a badge sits +/// on, in the viewer's own two themes (the test below). +pub const BADGE_HUES: [(Color32, Color32); 8] = [ + // indigo + ( + Color32::from_rgb(0x4F, 0x46, 0xE5), + Color32::from_rgb(0x8B, 0x93, 0xFA), + ), + // teal + ( + Color32::from_rgb(0x0F, 0x76, 0x6E), + Color32::from_rgb(0x2D, 0xD4, 0xBF), + ), + // orange + ( + Color32::from_rgb(0xB4, 0x53, 0x09), + Color32::from_rgb(0xFB, 0xBF, 0x24), + ), + // rose + ( + Color32::from_rgb(0xBE, 0x18, 0x5D), + Color32::from_rgb(0xF4, 0x72, 0xB6), + ), + // blue + ( + Color32::from_rgb(0x1D, 0x4E, 0xD8), + Color32::from_rgb(0x60, 0xA5, 0xFA), + ), + // green + ( + Color32::from_rgb(0x15, 0x80, 0x3D), + Color32::from_rgb(0x4A, 0xDE, 0x80), + ), + // violet + ( + Color32::from_rgb(0x7E, 0x22, 0xCE), + Color32::from_rgb(0xC0, 0x84, 0xFC), + ), + // cyan + ( + Color32::from_rgb(0x0E, 0x74, 0x90), + Color32::from_rgb(0x22, 0xD3, 0xEE), + ), +]; + +/// Which hue a company has: FNV-1a over the bytes of the id of its books, +/// modulo the number of hues. A function of the id alone (no seed, no +/// machine, no order of opening), so a company keeps its hue for ever and +/// on every machine; it is never changed without a new decision. +pub fn hue_index(book_id: &str) -> usize { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in book_id.bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x100_0000_01b3); + } + (h % BADGE_HUES.len() as u64) as usize +} + +/// The badge hue of the company whose books have id `book_id`, in the +/// light or dark table. +pub fn hue_of(book_id: &str, dark: bool) -> Color32 { + let (light, night) = BADGE_HUES[hue_index(book_id)]; + if dark { night } else { light } +} + +/// Whether the palette in force is a dark one (its page is darker than +/// its text). +fn is_dark(p: &Palette) -> bool { + crate::schemes::luminance(p.bg) < crate::schemes::luminance(p.text) +} + +/// The badge hue of a company, for the palette in force. +pub fn badge_hue(ctx: &Context, book_id: &str) -> Color32 { + hue_of(book_id, is_dark(&pal(ctx))) +} + +/// A company's badge: a rounded square in its hue with its initial in it +/// (black or white, whichever reads), drawn by the tab and the status +/// card alike. +pub fn paint_badge( + painter: &egui::Painter, + rect: egui::Rect, + radius: u8, + initial: char, + hue: Color32, + font: FontId, +) { + painter.rect_filled(rect, CornerRadius::same(radius), hue); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + initial, + font, + crate::schemes::on(hue), + ); +} + /// Where the palette in force is kept, in the context's memory. fn palette_id() -> egui::Id { egui::Id::new("wanderbooks-palette") @@ -317,6 +417,71 @@ pub fn apply_scheme(ctx: &Context, scheme: &crate::schemes::Scheme) { mod tests { use super::*; + /// The saturation of a colour in HSL (0 for a grey). + fn hsl_saturation(c: Color32) -> f32 { + let [r, g, b] = [c.r(), c.g(), c.b()].map(|v| f32::from(v) / 255.0); + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let l = (max + min) / 2.0; + if max == min { + 0.0 + } else { + (max - min) / (1.0 - (2.0 * l - 1.0).abs()) + } + } + + /// WCAG AA for each badge hue in both themes: its letter 4.5:1 on + /// it, and 3:1 for the badge against every surface it is drawn on. + /// Prints every measured ratio (`--nocapture`), and no hue is a grey + /// (HSL saturation at least 0.4: a grey badge reads as disabled). + #[test] + fn every_badge_hue_reads_in_both_themes() { + use crate::schemes::{contrast, on}; + let mut table = String::new(); + let mut failures = Vec::new(); + for (name, p, pick) in [("light", &LIGHT, 0), ("dark", &DARK, 1)] { + for (i, hues) in BADGE_HUES.iter().enumerate() { + let hue = if pick == 0 { hues.0 } else { hues.1 }; + let sat = hsl_saturation(hue); + let letter = contrast(on(hue), hue); + let mut line = format!("{name} hue {i} {hue:?}: sat {sat:.2} letter {letter:.2}"); + if sat < 0.4 { + failures.push(format!("{name} hue {i} {hue:?}: grey (sat {sat:.2})")); + } + if letter < 4.5 { + failures.push(format!("{name} hue {i} {hue:?}: letter {letter:.2}:1")); + } + // The tab's (in front, behind, hovered) and the card's. + for (what, ground) in [ + ("surface", p.surface), + ("sidebar", p.sidebar), + ("page", p.bg), + ("hover", p.hover), + ] { + let r = contrast(hue, ground); + line.push_str(&format!(" {what} {r:.2}")); + if r < 3.0 { + failures.push(format!("{name} hue {i} {hue:?} on {what}: {r:.2}:1")); + } + } + table.push_str(&line); + table.push('\n'); + } + } + println!("{table}"); + assert!(failures.is_empty(), "{failures:?}\n{table}"); + } + + #[test] + fn a_hue_is_a_function_of_the_book_id_alone() { + // Pinned: a change here recolours every company. + assert_eq!(hue_index("alpha"), hue_index("alpha")); + assert_eq!(hue_index(""), 0xcbf2_9ce4_8422_2325_u64 as usize % 8); + let all: std::collections::HashSet = + (0..200).map(|n| hue_index(&format!("books-{n}"))).collect(); + assert_eq!(all.len(), BADGE_HUES.len(), "every hue is used"); + } + /// font_definitions: every family ends with the PDFs' Noto fallbacks, /// in their order, after its own face, the icons and the symbol fonts, /// each Noto font the very bytes ledger-import bundles (the same diff --git a/crates/ledger-gui/src/widgets.rs b/crates/ledger-gui/src/widgets.rs index de58a636..21bd1804 100644 --- a/crates/ledger-gui/src/widgets.rs +++ b/crates/ledger-gui/src/widgets.rs @@ -61,6 +61,19 @@ pub fn page_header(ui: &mut Ui, title: &str, subtitle: &str) { ui.add_space(16.0); } +/// A page that opens with a sentence instead of a title (the Overview: +/// the company's name is the tab's, and the status card's, not the +/// page's): the sentence at the theme's heading size and weight, the +/// first thing on the page. +pub fn page_lead(ui: &mut Ui, sentence: &str) { + let w = ui.available_width().min(860.0); + ui.allocate_ui(vec2(w, 0.0), |ui| { + ui.set_max_width(w); + ui.label(RichText::new(sentence).font(theme::semibold(20.0))); + }); + ui.add_space(16.0); +} + /// A rounded tag. pub fn pill(ui: &mut Ui, text: &str, fg: Color32, bg: Color32) -> Response { Frame::new() 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/goldens/sidenav-1440x920.png b/crates/ledger-gui/tests/goldens/sidenav-1440x920.png index dad4a450..7a6b2dae 100644 Binary files a/crates/ledger-gui/tests/goldens/sidenav-1440x920.png and b/crates/ledger-gui/tests/goldens/sidenav-1440x920.png differ diff --git a/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes b/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes index c5220a62..9af8b64d 100644 --- a/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes +++ b/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes @@ -1 +1 @@ -b4c03adfe9dc03e6 +9e4be6e7e06cbefd 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/newer_journal.rs b/crates/ledger-gui/tests/newer_journal.rs index cb5e1cb5..8e0d26f8 100644 --- a/crates/ledger-gui/tests/newer_journal.rs +++ b/crates/ledger-gui/tests/newer_journal.rs @@ -132,9 +132,29 @@ fn the_viewer_says_update_for_newer_books_and_corrupt_for_damaged_ones() { assert!(!err.contains("newer"), "{err}"); } +/// The viewer's next error, within ten seconds. It never shows books it +/// can't read: an update carrying books is a failure. +fn next_error(loader: &Loader) -> String { + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + match loader.wait(Duration::from_millis(200)) { + Some(Update::Error(e)) => return e, + Some(Update::Books(_)) => panic!("the viewer read a line it doesn't know"), + _ => {} + } + } + panic!("the viewer never said anything about the line it doesn't know"); +} + /// Following: the viewer has the books open when a newer wanderbooks /// writes a line this one can't read. It says to update, and keeps the /// books it had. +/// +/// The writer's two lines are two writes, and the viewer may look between +/// them: with the newer line last, nothing can check it, and the viewer +/// says "newer or damaged" (BS-format-1) until the line after it lands. +/// Both are right, so this waits for the "update" and holds every message +/// before it to the "newer or damaged" one. #[test] fn a_live_viewer_says_update_when_the_books_move_ahead_of_it() { let data = books("live"); @@ -147,19 +167,46 @@ fn a_live_viewer_says_update_when_the_books_move_ahead_of_it() { w.append("entry.evidence_inherited", json!({"entry_id": 1})) .unwrap(); w.append("fx.rate_set", rate()).unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - let mut said = None; - while Instant::now() < deadline { - match loader.wait(Duration::from_millis(200)) { - Some(Update::Error(e)) => { - said = Some(e); - break; - } - Some(Update::Books(_)) => panic!("the viewer read a line it doesn't know"), - _ => {} + loop { + let said = next_error(&loader); + if said.starts_with("Journal line") { + says_newer_or_damaged(&said); + } else { + says_update(&said); + break; + } + } +} + +/// The viewer looks between the writer's two lines, as it can at any time: +/// with the newer line last it says "newer or damaged"; when the next line +/// lands it says "update", with no new look asked for. +#[test] +fn a_live_viewer_that_looks_between_the_two_lines_says_update_once_the_second_lands() { + let data = books("live-between"); + let loader = Loader::spawn(source(&data), egui::Context::default()); + match loader.wait(Duration::from_secs(10)) { + Some(Update::Books(_)) => {} + _ => panic!("no initial load"), + } + let mut w = JournalWriter::open(&data.join(JOURNAL_FILE)).unwrap(); + w.append("entry.evidence_inherited", json!({"entry_id": 1})) + .unwrap(); + // The viewer has looked and found the newer line last. + says_newer_or_damaged(&next_error(&loader)); + // The line after it lands: the first line is now checked, and known + // newer. (Looks made before the second line is read may repeat the + // last-line message; none may be anything else.) + w.append("fx.rate_set", rate()).unwrap(); + loop { + let said = next_error(&loader); + if said.starts_with("Journal line") { + says_newer_or_damaged(&said); + } else { + says_update(&said); + break; } } - says_update(&said.expect("the viewer never said to update")); } /// A declared format this version reads opens like any books, and the diff --git a/crates/ledger-gui/tests/sidenav.rs b/crates/ledger-gui/tests/sidenav.rs index 76193ddb..5a04f319 100644 --- a/crates/ledger-gui/tests/sidenav.rs +++ b/crates/ledger-gui/tests/sidenav.rs @@ -24,6 +24,7 @@ use ledger_core::{AccountType, Currency, Money, Side}; use ledger_gui::books::Books; use ledger_gui::nav::{Route, Section}; use ledger_gui::owner::{Agent, Owner, RestorePlan}; +use ledger_gui::tabs::BAR_H; use ledger_gui::{App, Source, data}; use ledger_store::{DiskCheck, Store}; use rust_decimal::Decimal; @@ -442,16 +443,19 @@ fn at_1479x519_every_link_shows_unscrolled() { } } -/// Folded, the card is one line that fits the card whole (never cut to -/// "Datab…"), naming the check that failed; hovered, it shows the three -/// checks. +/// Folded, the card is its heading alone, "Live · event N" at its right, +/// the seal after it, when every check passes; when one failed, a line +/// under the heading names it, whole (never cut to "Datab…"), the event +/// at its end. Either way it says Live or Snapshot and the event, and +/// hovered it shows the three checks. #[test] fn the_folded_card_shows_its_checks_on_hover() { let f = Fixture::new(); - for (footer, verdict, checks) in [ + for (footer, verdict, word, checks) in [ ( Footer::Owners, - "verified", + "event 6", + "Live", [ "Journal chain verified", "Database matches journal", @@ -460,8 +464,7 @@ fn the_folded_card_shows_its_checks_on_hover() { ), ( Footer::Snapshot, - // Its line is "Snapshot · event 555 · (seal)": no room for - // "verified", which the seal says. + "event 6", "Snapshot", [ "Journal chain verified", @@ -472,6 +475,7 @@ fn the_folded_card_shows_its_checks_on_hover() { ( Footer::Differs, "Database differs", + "Live", [ "Journal chain verified", "Database differs", @@ -481,6 +485,7 @@ fn the_folded_card_shows_its_checks_on_hover() { ( Footer::Unreadable, "Database unreadable", + "Live", [ "Journal chain verified", "Database unreadable", @@ -490,6 +495,7 @@ fn the_folded_card_shows_its_checks_on_hover() { ( Footer::Damaged, "2 files damaged", + "Live", [ "Journal chain verified", "Database matches journal", @@ -514,10 +520,28 @@ fn the_folded_card_shows_its_checks_on_hover() { ); let (_, footer_rect, _) = drawn(&h, Pane::Sidebar); let line = h.get_by_label_contains(verdict); - let card = line.rect(); + let card = h.get_by_label_contains(word).rect(); + // The live word is in the heading, above the line when there + // is one; the event is on the line, or after the word. + assert!(line.rect().bottom() <= footer_rect.bottom(), "{tag}"); + if verdict.starts_with("event") { + assert!( + (line.rect().center().y - card.center().y).abs() < 4.0, + "{tag}: the event is after the live word" + ); + } else { + assert!( + line.rect().top() > card.bottom() - 4.0, + "{tag}: a line under the heading" + ); + assert!( + h.query_all_by_label_contains("event ").count() >= 1, + "{tag}: the failure line ends with the event" + ); + } // Every piece of the line lies inside the card's margins: a // piece cut off or running out would reach past them. - for piece in ["Live", "Snapshot", "event 5", verdict] { + for piece in [word, "event ", verdict] { for n in h.query_all_by_label_contains(piece) { let r = n.rect(); if r.left() < Pane::Sidebar.panel() && r.top() >= footer_rect.top() { @@ -664,7 +688,9 @@ fn a_tall_sidebar_is_unchanged() { let png = dir.join("sidenav-1440x920.png"); match h.render() { Ok(img) => { - let side = image::imageops::crop_imm(&img, 0, 0, 224, img.height()).to_image(); + let side = + image::imageops::crop_imm(&img, 0, BAR_H as u32, 224, img.height() - BAR_H as u32) + .to_image(); if bless { side.save(&png).unwrap(); } else { @@ -687,7 +713,8 @@ fn a_tall_sidebar_is_unchanged() { fn sidebar_shapes(h: &Harness<'_, App>) -> u64 { let mut hash: u64 = 0xcbf2_9ce4_8422_2325; for s in &h.output().shapes { - if s.clip_rect.max.x <= 224.5 { + // Below the tab bar (D-78): the shapes that are the sidebar's. + if s.clip_rect.max.x <= 224.5 && s.clip_rect.min.y >= BAR_H - 0.5 { for b in format!("{:?}", s.shape).bytes() { hash ^= b as u64; hash = hash.wrapping_mul(0x100_0000_01b3); @@ -754,7 +781,7 @@ fn sidenav_screenshots() { } // The folded card's tooltip. let mut h = f.harness(Footer::Owners, Route::Projects, 1479.0, 519.0, 1.0); - if let Some(n) = h.query_by_label_contains("event 5") { + if let Some(n) = h.query_by_label_contains("event ") { let c = n.rect().center(); h.hover_at(c); h.run_steps(30); diff --git a/crates/ledger-gui/tests/snapshots/tabs_empty_dark.png b/crates/ledger-gui/tests/snapshots/tabs_empty_dark.png new file mode 100644 index 00000000..4c86a06a Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_empty_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_empty_light.png b/crates/ledger-gui/tests/snapshots/tabs_empty_light.png new file mode 100644 index 00000000..ff6b4c56 Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_empty_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_many_dark.png b/crates/ledger-gui/tests/snapshots/tabs_many_dark.png new file mode 100644 index 00000000..206e0564 Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_many_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_many_light.png b/crates/ledger-gui/tests/snapshots/tabs_many_light.png new file mode 100644 index 00000000..a5664d85 Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_many_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_one_dark.png b/crates/ledger-gui/tests/snapshots/tabs_one_dark.png new file mode 100644 index 00000000..2e57099a Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_one_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_one_light.png b/crates/ledger-gui/tests/snapshots/tabs_one_light.png new file mode 100644 index 00000000..11abb252 Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_one_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_plus_dark.png b/crates/ledger-gui/tests/snapshots/tabs_plus_dark.png new file mode 100644 index 00000000..8c2ec383 Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_plus_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_plus_light.png b/crates/ledger-gui/tests/snapshots/tabs_plus_light.png new file mode 100644 index 00000000..3e128f64 Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_plus_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_two_dark.png b/crates/ledger-gui/tests/snapshots/tabs_two_dark.png new file mode 100644 index 00000000..e578d10f Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_two_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_two_light.png b/crates/ledger-gui/tests/snapshots/tabs_two_light.png new file mode 100644 index 00000000..46436d3f Binary files /dev/null and b/crates/ledger-gui/tests/snapshots/tabs_two_light.png differ diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs new file mode 100644 index 00000000..11b346da --- /dev/null +++ b/crates/ledger-gui/tests/tabs.rs @@ -0,0 +1,2694 @@ +//! Tabs (tabs.rs, app.rs, company.rs; plan/p15-app-and-relay.md 3.2, D-78): +//! one window with a tab per open company, each tab a window on that +//! company alone. +//! +//! ```text +//! GOAL: several companies open at once, each in its own tab, none +//! disturbing another: not its page, its filters, its periods, its +//! egui state, its loader, its dock, or its books. +//! SOURCE: plan/p15-app-and-relay.md 3.2 (a `CompanyView` per tab; tests +//! look for state shared between tabs); D-78 (one top-level tab +//! per open company). +//! INVARIANTS: +//! 1. Two companies with different figures open in two tabs each show +//! their own, on the overview, a report and a register. +//! 2. What is done in one tab (a page, a filter, a period) leaves +//! another tab's state and what it draws as they were; egui's own +//! memory (a scrolled sidebar) isn't shared either. +//! 3. A tab that isn't in front follows its journal, and `books.show` +//! moves its page alone; showing it later is current at once. +//! 4. Closing a tab drops its loader's thread and its viewer presence +//! and ends its dock's agent; the others go on. +//! 5. A company can't be open twice: "+" lists only those not open, and +//! opening one that is open shows its tab. +//! 6. Start-up restores the open tabs, their order, the one in front +//! and each one's page and period; a company that is gone is skipped +//! without a word. +//! 7. Read-only: every tab, in front or not, leaves the books' bytes, +//! sizes and times as they were. +//! 8. The tab bar and the empty state look as pictured +//! (`tests/snapshots/`). +//! 9. The bar spans the whole window above the sidebar; its "+" is +//! right after the last tab, and at the right edge, whole, when the +//! tabs overflow. +//! 10. A company's name is remembered when it is loaded: the "+" list +//! shows it (the id alone for a company never opened), and so does a +//! tab whose books are not loaded yet. +//! 11. The tab is the company's identity in the frame: nothing else in +//! the top 120 points of the window shows its name, and the +//! Overview opens with its summary sentence, not a heading with the +//! name. +//! 12. The status card at the foot of the sidebar names the company in +//! front, with its badge, and follows the tab; the rail shows the +//! badge alone. +//! 13. A company's badge hue is a function of the id of its books alone +//! (so it is the same on its tab and its card, in both themes, after +//! a restart, in any order of opening), and every hue reads (the +//! contrast test is `theme::tests`, in the crate). +//! ``` + +use chrono::NaiveDate; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use ledger_core::settings::{Change, Source as Decided}; +use ledger_core::{AccountId, AccountType, Currency, Money, Side}; +use ledger_gui::data::{self, Source}; +use ledger_gui::nav::{ReportKind, Route}; +use ledger_gui::owner::{Agent, AgentStart, Owner, RestorePlan}; +use ledger_gui::{App, CompanyView, Start}; +use ledger_store::Store; +use ledger_store::root::{BookId, Root}; +use rust_decimal::Decimal; +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime}; + +fn today() -> NaiveDate { + NaiveDate::from_ymd_opt(2026, 10, 15).unwrap() +} + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +/// A data root of its own, with companies made in it. +struct World { + _dir: tempfile::TempDir, + root: PathBuf, +} + +/// A company made in a [`World`]. +struct Co { + data: PathBuf, + cash: AccountId, + capital: AccountId, + rent: AccountId, +} + +impl World { + fn new() -> World { + let dir = tempfile::Builder::new() + .prefix("wb-gui-tabs-") + .tempdir() + .unwrap(); + let home = dir.path().join("home"); + std::fs::create_dir_all(&home).unwrap(); + let root = dir.path().join("root"); + Root::setup(&home, Some(&root), None).unwrap(); + World { _dir: dir, root } + } + + /// A company `id` named `name`: its owner put in `capital` cents, it + /// paid `rent` cents of rent, on dates in the year of "today". + fn company(&self, id: &str, name: &str, capital: i64, rent: i64) -> Co { + let root = Root::find(Some(&self.root)).unwrap(); + let mut s = root + .create_book(&BookId::parse(id).unwrap(), Currency::USD) + .unwrap(); + let mut add = |code: &str, n: &str, ty| s.add_account(code, n, ty, None, false).unwrap(); + let cash = add("1000", "Cash", AccountType::Asset); + let capital_acct = add("3000", "Owner Capital", AccountType::Equity); + let rent_acct = add("6000", "Rent", AccountType::Expense); + s.change_settings( + &[Change { + key: "company.name".into(), + value: Some(serde_json::json!(name)), + }], + &Decided { + decided_by: "Test".into(), + decided_on: today(), + citation: None, + note: None, + }, + ) + .unwrap(); + let mut co = Co { + data: root.book_dir(&BookId::parse(id).unwrap()), + cash, + capital: capital_acct, + rent: rent_acct, + }; + post( + &mut s, + "Owner contribution", + d(2026, 9, 1), + cash, + capital_acct, + capital, + ); + post(&mut s, "Office rent", d(2026, 10, 1), rent_acct, cash, rent); + drop(s); + co.data = root.book_dir(&BookId::parse(id).unwrap()); + 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 + .root + .join("books") + .join(BookId::parse(id).unwrap().as_str()), + today: Some(today()), + } + } +} + +/// Post Dr `dr` / Cr `cr` `cents` on `date`, with a receipt. +fn post(s: &mut Store, what: &str, date: NaiveDate, dr: AccountId, cr: AccountId, cents: i64) { + let usd = Money::new(Decimal::new(cents, 2), Currency::USD); + let e = s.create_entry(date, what).unwrap(); + s.add_line(e, dr, Side::Debit, usd).unwrap(); + s.add_line(e, cr, Side::Credit, usd).unwrap(); + s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF r", None) + .unwrap(); + s.post_entry(e).unwrap(); +} + +/// The preferences the app kept, in memory. +#[derive(Default, Clone)] +struct Prefs(HashMap); + +impl eframe::Storage for Prefs { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_string(), value); + } + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + fn flush(&mut self) {} +} + +fn prefs(pairs: &[(&str, &str)]) -> Prefs { + Prefs( + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ) +} + +/// 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| { + use eframe::Storage; + App::start_with( + &cc.egui_ctx, + &|k| kept.get_string(k), + Start::Restore { root, fallback }, + ) + }); + h.run_steps(2); + h +} + +fn start_with_prefs(world: &World, pairs: &[(&str, &str)]) -> Harness<'static, App> { + start(world, prefs(pairs), egui::vec2(1280.0, 800.0)) +} + +/// Run frames until `ok` holds. +fn until(h: &mut Harness<'static, App>, what: &str, ok: impl Fn(&App) -> bool) { + let end = Instant::now() + Duration::from_secs(30); + loop { + h.run_steps(2); + if ok(h.state()) { + return; + } + assert!(Instant::now() < end, "never: {what}"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// Until every tab has its books. +fn loaded(h: &mut Harness<'static, App>) { + until(h, "every tab's books load", |a| { + !a.views().is_empty() && a.views().iter().all(|v| v.books().is_some()) + }); + h.run_steps(3); +} + +/// Every text the last frame painted. +fn texts(h: &Harness<'_, App>) -> Vec { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + 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.sort(); + all +} + +fn shows(h: &Harness<'_, App>, text: &str) -> bool { + texts(h).iter().any(|t| t.contains(text)) +} + +fn titles(h: &Harness<'_, App>) -> Vec { + h.state().views().iter().map(CompanyView::title).collect() +} + +/// Click the tab named `name`. +fn show_tab(h: &mut Harness<'static, App>, name: &str) { + h.get_by_role_and_label(Role::Button, name).click(); + h.run_steps(3); +} + +/// Click the close control of the tab named `name`. +fn close_tab(h: &mut Harness<'static, App>, name: &str) { + h.get_by_role_and_label(Role::Button, &format!("Close {name}")) + .click(); + h.run_steps(3); +} + +fn three() -> (World, Co, Co, Co) { + let w = World::new(); + let a = w.company("alpha", "Alpha Co", 1_000_000, 123_456); + let b = w.company("beta", "Beta Co", 2_500_000, 77_777); + let g = w.company("gamma", "Gamma Co", 500_000, 5_000); + (w, a, b, g) +} + +// ---- 1: each tab its own figures ---------------------------------------- + +#[test] +fn each_tab_shows_its_own_company_and_figures() { + let (w, a, b, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + assert_eq!(titles(&h), ["Alpha Co", "Beta Co"]); + assert_eq!(h.state().active(), Some(0)); + assert_eq!(h.state().window_title(), "Alpha Co · wanderbooks"); + + // Alpha: cash 10,000.00 less 1,234.56 rent is 8,765.44. + assert!(shows(&h, "8,765.44"), "alpha's cash: {:?}", texts(&h)); + assert!(!shows(&h, "24,222.23")); + h.state_mut() + .goto(Route::Reports(ReportKind::ProfitAndLoss)); + h.run_steps(3); + assert!(shows(&h, "1,234.56"), "alpha's rent in its P&L"); + assert!(!shows(&h, "777.77")); + h.state_mut().goto(Route::Account(a.rent)); + h.run_steps(3); + assert!(shows(&h, "1,234.56"), "alpha's rent register"); + assert!(!shows(&h, "777.77")); + + // Beta: cash 25,000.00 less 777.77 is 24,222.23. + show_tab(&mut h, "Beta Co"); + assert_eq!(h.state().active(), Some(1)); + assert_eq!(h.state().window_title(), "Beta Co · wanderbooks"); + assert!( + matches!(h.state().route(), Route::Overview), + "a tab opens on its overview, not on the page the other was on" + ); + assert!(shows(&h, "24,222.23"), "beta's cash: {:?}", texts(&h)); + assert!(!shows(&h, "8,765.44")); + h.state_mut() + .goto(Route::Reports(ReportKind::ProfitAndLoss)); + h.run_steps(3); + assert!(shows(&h, "777.77")); + assert!(!shows(&h, "1,234.56")); + h.state_mut().goto(Route::Account(b.rent)); + h.run_steps(3); + assert!(shows(&h, "777.77")); + assert!(!shows(&h, "1,234.56")); + // One of the two accounts is not the other's: ids are per books. + let _ = (a.cash, a.capital, b.cash, b.capital); +} + +// ---- 2: what is done in one tab leaves the other alone -------------------- + +#[test] +fn what_is_done_in_one_tab_changes_nothing_in_another() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + + // Beta as it is, before anything is done in alpha. + show_tab(&mut h, "Beta Co"); + h.run_steps(3); + let beta_before = texts(&h); + assert!(matches!(h.state().route(), Route::Overview)); + + // In alpha: a page, a search, a period, columns, a comparison. + show_tab(&mut h, "Alpha Co"); + h.state_mut().goto(Route::Transactions); + { + let st = h.state_mut().state_mut(); + st.transactions.query = "rent".into(); + st.reports.columns = ledger_gui::pages::reports::Columns::Month; + st.reports.compare = ledger_gui::pages::reports::Compare::PriorYear; + st.reports.range = ledger_gui::pages::reports::Range::LastMonth; + } + h.run_steps(3); + assert!(shows(&h, "Office rent"), "alpha's search shows its rent"); + + // Beta: nothing of that reached it, in its state or in what it draws. + show_tab(&mut h, "Beta Co"); + h.run_steps(3); + assert!(matches!(h.state().route(), Route::Overview)); + let st = h.state_mut().state_mut(); + assert_eq!(st.transactions.query, ""); + assert_eq!( + st.reports.columns, + ledger_gui::pages::reports::Columns::Total + ); + assert_eq!( + st.reports.compare, + ledger_gui::pages::reports::Compare::None + ); + assert_eq!( + st.reports.range, + ledger_gui::pages::reports::Range::YearToDate + ); + assert_eq!(texts(&h), beta_before, "beta draws what it drew"); + + // And the other way: beta's doings leave alpha's as they were. + h.state_mut().goto(Route::Reports(ReportKind::BalanceSheet)); + h.state_mut().state_mut().transactions.query = "other".into(); + h.run_steps(3); + show_tab(&mut h, "Alpha Co"); + h.run_steps(3); + assert!(matches!(h.state().route(), Route::Transactions)); + let st = h.state_mut().state_mut(); + assert_eq!(st.transactions.query, "rent"); + assert_eq!( + st.reports.columns, + ledger_gui::pages::reports::Columns::Month + ); +} + +/// egui's own memory isn't shared: a sidebar scrolled in one tab is as it +/// was left in the other. (The links scroll in a short window; their +/// scroll state is kept by egui under an id that is the same in every +/// tab unless each tab's ids are its own.) +#[test] +fn a_scrolled_sidebar_in_one_tab_is_not_scrolled_in_another() { + let (w, _, _, _) = three(); + let mut h = start( + &w, + prefs(&[("open_companies", "alpha,beta")]), + egui::vec2(1480.0, 330.0), + ); + loaded(&mut h); + let links_scroll = |h: &Harness<'_, App>| -> bool { + h.ctx + .data(|d| d.get_temp::(egui::Id::new("sidebar_links_scroll"))) + .expect("whether the links scroll") + }; + let view = |h: &Harness<'_, App>| -> egui::Rect { + h.ctx + .data(|d| d.get_temp::(egui::Id::new("sidebar_links_view"))) + .expect("the links' viewport") + }; + let overview_top = |h: &Harness<'_, App>| -> f32 { + h.get_all_by_role_and_label(Role::Button, "Overview") + .map(|n| n.rect()) + .min_by(|a, b| a.left().total_cmp(&b.left())) + .unwrap() + .top() + }; + h.run_steps(3); + assert!(links_scroll(&h), "a short window: the links scroll"); + assert!(overview_top(&h) >= view(&h).top() - 0.5, "alpha at the top"); + // Alpha's links scrolled a page on. + h.get_by_label("More links below").click(); + h.run_steps(4); + assert!( + overview_top(&h) < view(&h).top() - 0.5, + "alpha's links did not scroll" + ); + // Beta's are at the top: its own scroll state, not alpha's. + show_tab(&mut h, "Beta Co"); + h.run_steps(4); + assert!( + overview_top(&h) >= view(&h).top() - 0.5, + "beta's sidebar inherited alpha's scroll" + ); + // And alpha's are still where they were left. + show_tab(&mut h, "Alpha Co"); + h.run_steps(4); + assert!( + overview_top(&h) < view(&h).top() - 0.5, + "alpha's scroll was lost" + ); +} + +#[test] +fn no_two_views_have_the_same_id_or_key() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta,gamma")]); + loaded(&mut h); + let views = h.state().views(); + assert_eq!(views.len(), 3); + for i in 0..views.len() { + for j in i + 1..views.len() { + assert_ne!(views[i].id(), views[j].id()); + assert_ne!(views[i].key(), views[j].key()); + } + } +} + +// ---- 3: a background tab follows its journal ------------------------------ + +#[test] +fn a_background_tab_follows_its_journal_and_is_current_when_shown() { + let (w, _, b, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + assert_eq!(h.state().active(), Some(0)); + let beta_cash = h.state().views()[1].books().unwrap().kpis.cash; + + // Beta's journal changes while alpha is in front: 100.00 more cash. + let mut s = Store::open(&b.data).unwrap(); + post( + &mut s, + "Late contribution", + d(2026, 10, 10), + b.cash, + b.capital, + 10_000, + ); + drop(s); + // The entry is several journal lines, and the tab may read some of + // them first (its seq moves): wait for the one that posts it, whose + // 100.00 lands in cash. + let beta_cash_after = beta_cash + Decimal::new(10_000, 2); + until(&mut h, "the background tab reads the new entry", |a| { + a.views()[1].books().unwrap().kpis.cash == beta_cash_after + }); + assert_eq!(h.state().active(), Some(0), "nothing brought beta forward"); + + // Shown, it is current at once: no reload, no waiting for a load. + show_tab(&mut h, "Beta Co"); + assert!(shows(&h, "24,322.23"), "beta's cash now: {:?}", texts(&h)); + assert!(!shows(&h, "24,222.23")); +} + +#[test] +fn books_show_moves_the_tab_it_is_aimed_at_and_only_that_one() { + let (w, a, b, _) = three(); + ledger_store::ops::prepare(&a.data).unwrap(); + ledger_store::ops::prepare(&b.data).unwrap(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + assert!(matches!(h.state().views()[0].route(), Route::Overview)); + // The agent asks for beta's journal page; alpha is in front. + ledger_store::ops::request( + &b.data, + ledger_store::ops::ViewerTarget::Page { + page: "journal".into(), + }, + ) + .unwrap(); + until(&mut h, "beta's tab moves", |a| { + matches!(a.views()[1].route(), Route::Journal) + }); + assert!( + matches!(h.state().views()[0].route(), Route::Overview), + "the tab in front stayed where it was" + ); + assert_eq!(h.state().active(), Some(0), "no tab was brought forward"); +} + +// ---- 4: closing a tab ends what it started --------------------------------- + +/// An owner that starts a stand-in agent that says its process id. +struct Agentic { + pidfile: PathBuf, + dir: PathBuf, + asked: Mutex>, +} + +impl Owner for Agentic { + fn close_books(&self) -> Result { + Err("not here".into()) + } + fn new_books(&self, _: &str, _: &str) -> Result { + Err("not here".into()) + } + fn back_up_now(&self, _: &str) -> Result, String> { + Err("not here".into()) + } + fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + Err("not here".into()) + } + fn restore(&self, _: &RestorePlan) -> Result, String> { + Err("not here".into()) + } + 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, book: &str) -> Result { + self.asked.lock().unwrap().push(book.to_string()); + Ok(AgentStart::Ready { + label: "Claude Code".into(), + program: PathBuf::from("/bin/sh"), + args: vec![ + "-c".into(), + format!("echo $$ > '{}'; exec sleep 600", self.pidfile.display()), + ], + dir: self.dir.clone(), + env: vec![("TERM".into(), "xterm-256color".into())], + }) + } +} + +#[cfg(unix)] +fn alive(pid: u32) -> bool { + std::process::Command::new("kill") + .args(["-0", &pid.to_string()]) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()) +} + +#[cfg(unix)] +#[test] +fn closing_a_tab_releases_its_lock_its_threads_and_its_agent() { + let (w, a, b, _) = three(); + ledger_store::ops::prepare(&a.data).unwrap(); + ledger_store::ops::prepare(&b.data).unwrap(); + let work = tempfile::tempdir().unwrap(); + let owner = Arc::new(Agentic { + pidfile: work.path().join("agent.pid"), + dir: work.path().to_path_buf(), + asked: Mutex::new(Vec::new()), + }); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + // Each view has an owner of its own (no process global): only beta's + // runs an agent. + h.state_mut() + .view_mut(1) + .unwrap() + .set_owner(owner.clone() as Arc); + until(&mut h, "both viewers hold their books", |_| { + ledger_store::ops::viewer_open(&a.data) && ledger_store::ops::viewer_open(&b.data) + }); + let beta_loader = h.state().views()[1].loader_watch().expect("a loader"); + let alpha_loader = h.state().views()[0].loader_watch().expect("a loader"); + assert!(!beta_loader.ended()); + + // Beta in front, its dock open: its agent runs. + show_tab(&mut h, "Beta Co"); + h.state_mut().dock_mut().open = true; + let pid = { + let end = Instant::now() + Duration::from_secs(20); + loop { + h.run_steps(2); + if let Ok(text) = std::fs::read_to_string(&owner.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), "the agent runs"); + assert_eq!(*owner.asked.lock().unwrap(), ["beta"], "beta's own owner"); + + // 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)); + 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" + ); + assert!(beta_loader.ended(), "a closed tab's loader thread runs on"); + assert!(!alive(pid), "a closed tab's agent still runs"); + assert!(ledger_store::ops::viewer_open(&a.data), "alpha's lock held"); + assert!(!alpha_loader.ended(), "alpha's loader runs on"); + // Beta can be opened again: a new tab, a new lock. + h.get_by_label("Open another company").click(); + h.run_steps(3); + h.get_by_label("Beta Co").click(); + h.run_steps(3); + assert_eq!(titles(&h).len(), 2); + until(&mut h, "beta's lock is taken again", |_| { + ledger_store::ops::viewer_open(&b.data) + }); +} + +// ---- 5: a company is never open twice --------------------------------------- + +#[test] +fn plus_lists_only_the_companies_not_open_and_none_opens_twice() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + h.get_by_label("Open another company").click(); + h.run_steps(3); + assert!(h.query_by_label("gamma").is_some(), "gamma is offered"); + assert!(h.query_by_label("alpha").is_none(), "alpha is open"); + assert!(h.query_by_label("beta").is_none(), "beta is open"); + h.get_by_label("gamma").click(); + loaded(&mut h); + assert_eq!(titles(&h), ["Alpha Co", "Beta Co", "Gamma Co"]); + assert_eq!(h.state().active(), Some(2), "the new tab comes forward"); + // Every one is open: the list says so. + h.get_by_label("Open another company").click(); + h.run_steps(3); + assert!( + shows(&h, "Every company is already open."), + "{:?}", + texts(&h) + ); + // Opening an open company by other means shows its tab, never a second. + let ctx = h.ctx.clone(); + let n = h.state_mut().open(&ctx, w.source("beta")); + assert_eq!(n, 1); + assert_eq!(h.state().views().len(), 3); + assert_eq!(h.state().active(), Some(1)); + // Likewise a view of fixed books of the same folder. + let books = data::load_once(&w.source("alpha")).unwrap(); + let again = CompanyView::with_books(&ctx, books, Route::Cash); + assert_eq!(h.state_mut().add_view(again), 0); + assert_eq!(h.state().views().len(), 3); +} + +// ---- 6: start-up ------------------------------------------------------------- + +#[test] +fn start_up_restores_the_open_tabs_their_order_and_the_one_in_front() { + let (w, _, _, _) = three(); + // A company that is gone, and one listed twice, are skipped. + let mut h = start_with_prefs( + &w, + &[ + ("open_companies", "gamma,gone,alpha,gamma,not a book!,beta"), + ("active_company", "alpha"), + ], + ); + loaded(&mut h); + assert_eq!(titles(&h), ["Gamma Co", "Alpha Co", "Beta Co"]); + assert_eq!(h.state().active(), Some(1), "the same one in front"); + assert!(h.state().views().iter().all(|v| v.error().is_none())); + assert_eq!(h.state().window_title(), "Alpha Co · wanderbooks"); + + // No record: the data root's first, alone. + let h2 = start_with_prefs(&w, &[]); + assert_eq!(h2.state().views().len(), 1); + assert_eq!(h2.state().views()[0].book_id().as_deref(), Some("alpha")); + // A record of none that exists any more: the same. + let h3 = start_with_prefs(&w, &[("open_companies", "gone,vanished")]); + assert_eq!(h3.state().views().len(), 1); + assert_eq!(h3.state().views()[0].book_id().as_deref(), Some("alpha")); + // A front one that isn't among them is ignored: the first is in front. + let h4 = start_with_prefs( + &w, + &[ + ("open_companies", "beta,gamma"), + ("active_company", "alpha"), + ], + ); + assert_eq!(h4.state().active(), Some(0)); + // The company named on the command line is the only tab, whatever was + // kept. + let src = w.source("gamma"); + let h5 = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .build_eframe(move |cc| App::start_with(&cc.egui_ctx, &|_| None, Start::Only(src))); + assert_eq!(h5.state().views().len(), 1); + assert_eq!(h5.state().views()[0].book_id().as_deref(), Some("gamma")); +} + +#[test] +fn the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta,gamma")]); + loaded(&mut h); + // Alpha: a report, a custom period, columns, a comparison. Beta: its + // transactions. Gamma in front, on its accounts. + { + use ledger_gui::pages::reports::{Columns, Compare, Range}; + let a = h.state_mut().view_mut(0).unwrap(); + a.goto(Route::Reports(ReportKind::BalanceSheet)); + a.state_mut().reports.range = Range::Custom(d(2026, 1, 1), d(2026, 6, 30)); + a.state_mut().reports.columns = Columns::Quarter; + a.state_mut().reports.compare = Compare::PriorYear; + h.state_mut().view_mut(1).unwrap().goto(Route::Transactions); + h.state_mut().view_mut(2).unwrap().goto(Route::Accounts); + } + h.state_mut().activate(2); + h.run_steps(2); + let mut kept = Prefs::default(); + eframe::App::save(h.state_mut(), &mut kept); + 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!( + kept.0.contains_key(key), + "{key} not kept: {:?}", + kept.0.keys() + ); + } + drop(h); + + // Next time: the same tabs, order, front tab, pages and periods. + let mut h = start(&w, kept.clone(), egui::vec2(1280.0, 800.0)); + loaded(&mut h); + assert_eq!(titles(&h), ["Alpha Co", "Beta Co", "Gamma Co"]); + assert_eq!(h.state().active(), Some(2)); + let views = h.state().views(); + assert!(matches!( + views[0].route(), + Route::Reports(ReportKind::BalanceSheet) + )); + assert!(matches!(views[1].route(), Route::Transactions)); + assert!(matches!(views[2].route(), Route::Accounts)); + { + use ledger_gui::pages::reports::{Columns, Compare, Range}; + let r = &views[0].state().reports; + assert_eq!(r.range, Range::Custom(d(2026, 1, 1), d(2026, 6, 30))); + assert_eq!(r.columns, Columns::Quarter); + assert_eq!(r.compare, Compare::PriorYear); + // Beta's period is its own, untouched. + assert_eq!(views[1].state().reports.range, Range::YearToDate); + } + + // A tab closed in the run is remembered as it was left, and comes back + // as it was when opened again, in this run and the next. + close_tab(&mut h, "Alpha Co"); + h.get_by_label("Open another company").click(); + h.run_steps(3); + h.get_by_label("Alpha Co").click(); + h.run_steps(3); + let last = h.state().views().len() - 1; + assert!(matches!( + h.state().views()[last].route(), + Route::Reports(ReportKind::BalanceSheet) + )); + let mut again = Prefs::default(); + eframe::App::save(h.state_mut(), &mut again); + 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 { + let name = h.state().tab_title(0).unwrap(); + close_tab(&mut h, &name); + } + assert!(h.state().views().is_empty()); + let mut none = Prefs::default(); + eframe::App::save(h.state_mut(), &mut none); + 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); + assert_eq!(h.state().views()[0].book_id().as_deref(), Some("alpha")); +} + +// ---- closing and the empty state --------------------------------------------- + +#[test] +fn closing_the_front_tab_shows_a_neighbour_and_the_last_leaves_an_empty_window() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta,gamma")]); + loaded(&mut h); + show_tab(&mut h, "Beta Co"); + close_tab(&mut h, "Beta Co"); + assert_eq!(titles(&h), ["Alpha Co", "Gamma Co"]); + assert_eq!(h.state().window_title(), "Gamma Co · wanderbooks"); + // A tab behind the front one closing leaves the front one in front. + close_tab(&mut h, "Alpha Co"); + assert_eq!(titles(&h), ["Gamma Co"]); + assert_eq!(h.state().window_title(), "Gamma Co · wanderbooks"); + // The last one. + close_tab(&mut h, "Gamma Co"); + assert!(h.state().views().is_empty()); + assert_eq!(h.state().window_title(), "wanderbooks"); + assert!(shows(&h, "No company is open"), "{:?}", texts(&h)); + assert!( + shows(&h, "Open a company with the + at the top of the window."), + "{:?}", + texts(&h) + ); + // The bar is still there, and "+" opens a company from the empty window. + h.get_by_label("Open another company").click(); + h.run_steps(3); + h.get_by_label("Beta Co").click(); + loaded(&mut h); + assert_eq!(titles(&h), ["Beta Co"]); + assert!(!shows(&h, "No company is open")); +} + +#[test] +fn the_tab_in_front_is_marked_by_more_than_colour() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + let selected = |h: &Harness<'_, App>, name: &str| { + h.get_by_role_and_label(Role::Button, name) + .accesskit_node() + .toggled() + }; + assert_eq!( + selected(&h, "Alpha Co"), + Some(egui::accesskit::Toggled::True) + ); + assert_eq!( + selected(&h, "Beta Co"), + Some(egui::accesskit::Toggled::False) + ); + show_tab(&mut h, "Beta Co"); + assert_eq!( + selected(&h, "Alpha Co"), + Some(egui::accesskit::Toggled::False) + ); + assert_eq!( + selected(&h, "Beta Co"), + Some(egui::accesskit::Toggled::True) + ); + // A close control on each, named for its company. + h.get_by_role_and_label(Role::Button, "Close Alpha Co"); + h.get_by_role_and_label(Role::Button, "Close Beta Co"); +} + +// ---- 9: the bar's place -------------------------------------------------------- + +/// The fill of the bar: a rectangle from the window's corner, as wide as +/// the window and as high as the bar. +fn bar_rect(h: &Harness<'_, App>, size: egui::Vec2) -> Option { + fn walk(s: &egui::Shape, size: egui::Vec2, out: &mut Option) { + match s { + egui::Shape::Rect(r) + if r.rect.min.x.abs() < 0.5 + && r.rect.min.y.abs() < 0.5 + && (r.rect.height() - ledger_gui::tabs::BAR_H).abs() < 0.5 + && r.rect.width() >= size.x - 0.5 => + { + *out = Some(r.rect) + } + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, size, out)), + _ => {} + } + } + let mut found = None; + for c in &h.output().shapes { + walk(&c.shape, size, &mut found); + } + found +} + +#[test] +fn the_bar_spans_the_window_above_the_sidebar() { + let size = egui::vec2(1280.0, 600.0); + let w = World::new(); + let h = shown(&w, &["Wanderland Labs LLC", "Fernhill Studio"], false, size); + let bar = bar_rect(&h, size).expect("a bar the window's width, at its top"); + assert!(bar.max.x >= size.x - 0.5, "{bar:?}"); + // Every tab, and its close control, is inside the bar... + for name in ["Wanderland Labs LLC", "Fernhill Studio"] { + let tab = h + .get_by_role_and_label(egui::accesskit::Role::Button, name) + .rect(); + assert!(bar.contains_rect(tab), "{name}: {tab:?} is in {bar:?}"); + } + // ...and the first is over the sidebar's column, whose links, header + // and status all lie below the bar. + let first = h + .get_by_role_and_label(egui::accesskit::Role::Button, "Wanderland Labs LLC") + .rect(); + assert!(first.left() < 224.0, "the first tab is above the sidebar"); + for link in ["Overview", "Journal"] { + let r = h + .query_all_by_role_and_label(egui::accesskit::Role::Button, link) + .map(|n| n.rect()) + .min_by(|a, b| a.left().total_cmp(&b.left())) + .unwrap(); + assert!(r.top() >= bar.bottom() - 0.5, "{link} {r:?} under {bar:?}"); + } + // Nothing but the bar is drawn across the top strip of the sidebar's + // column: the sidebar's own panel starts where the bar ends. + let sidebar_top = h + .output() + .shapes + .iter() + .filter(|s| s.clip_rect.max.x <= 224.5 && s.clip_rect.min.y > 1.0) + .map(|s| s.clip_rect.min.y) + .fold(f32::MAX, f32::min); + assert!( + sidebar_top >= bar.bottom() - 0.5, + "the sidebar starts at {sidebar_top}, below the bar's {}", + bar.bottom() + ); +} + +#[test] +fn the_plus_follows_the_last_tab_and_stays_whole_when_the_tabs_overflow() { + let size = egui::vec2(1100.0, 200.0); + let rect = |h: &Harness<'_, App>, label: &str| { + h.get_by_role_and_label(egui::accesskit::Role::Button, label) + .rect() + }; + // Few tabs: the "+" is right after the last, not at the window's edge. + let w = World::new(); + let h = shown(&w, &["Wanderland Labs LLC", "Fernhill Studio"], false, size); + let last = rect(&h, "Fernhill Studio"); + let plus = rect(&h, "Open another company"); + assert!( + plus.left() >= last.right() && plus.left() - last.right() < 16.0, + "the + at {plus:?} is not just after the last tab {last:?}" + ); + assert!(plus.right() < size.x / 2.0, "the + sits at the far right"); + // Many: the "+" is at the right edge, whole; the tabs scroll behind it. + let names: Vec = (0..9).map(|i| format!("Company number {i}")).collect(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let w = World::new(); + let mut h = shown(&w, &refs, false, size); + h.state_mut().activate(8); + h.run_steps(6); + let plus = rect(&h, "Open another company"); + assert!( + plus.right() <= size.x && plus.right() > size.x - 24.0, + "the + at {plus:?} is not at the right edge" + ); + assert!( + plus.left() >= 0.0 && plus.width() >= 20.0, + "{plus:?} is whole" + ); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Later tabs"); + // The tab in front was scrolled into view, left of the "+". + let front = rect(&h, "Company number 8"); + assert!( + front.right() <= plus.left(), + "{front:?} under the + {plus:?}" + ); +} + +// ---- 10: names remembered --------------------------------------------------------- + +#[test] +fn a_name_is_remembered_and_shown_in_the_plus_list_and_on_a_loading_tab() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + assert_eq!(h.state().remembered_name("beta"), Some("Beta Co")); + assert_eq!(h.state().remembered_name("gamma"), None); + // Beta closed: "+" offers it by name with its id beside, and gamma, + // never opened here, by its id alone. + close_tab(&mut h, "Beta Co"); + h.get_by_label("Open another company").click(); + h.run_steps(3); + assert!(shows(&h, "Open a company"), "{:?}", texts(&h)); + assert!(shows(&h, "Beta Co") && texts(&h).contains(&"beta".to_string())); + assert!(texts(&h).contains(&"gamma".to_string()), "{:?}", texts(&h)); + assert!(!shows(&h, "Gamma Co"), "gamma's name was never read"); + h.get_by_label("Beta Co").click(); + loaded(&mut h); + // Kept with the app's other state... + let mut kept = Prefs::default(); + eframe::App::save(h.state_mut(), &mut kept); + assert_eq!( + 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(&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( + &ctx, + &|k| kept.0.get(k).cloned(), + Start::Restore { root, fallback }, + ); + assert_eq!(app.tab_title(0).as_deref(), Some("alpha"), "no name known"); + assert_eq!( + app.tab_title(1).as_deref(), + Some("Beta Co"), + "the name kept" + ); +} + +#[test] +fn the_plus_list_says_so_when_every_company_is_open() { + let w = World::new(); + w.company("alpha", "Alpha Co", 1_000_000, 100); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha")]); + loaded(&mut h); + h.get_by_label("Open another company").click(); + h.run_steps(3); + assert!( + shows(&h, "Every company is already open."), + "{:?}", + texts(&h) + ); + assert!(!shows(&h, "Open a company"), "no heading over nothing"); +} + +// ---- 7: read-only, in a tab that is not in front ----------------------------- + +type Tree = BTreeMap, u64, SystemTime)>; + +fn tree(root: &Path) -> Tree { + fn walk(root: &Path, d: &Path, out: &mut Tree) { + for e in std::fs::read_dir(d).unwrap() { + let p = e.unwrap().path(); + let m = std::fs::symlink_metadata(&p).unwrap(); + if m.is_dir() { + walk(root, &p, out); + } else { + out.insert( + p.strip_prefix(root).unwrap().to_path_buf(), + (std::fs::read(&p).unwrap(), m.len(), m.modified().unwrap()), + ); + } + } + } + let mut out = BTreeMap::new(); + walk(root, root, &mut out); + out +} + +/// Every file 0444 and folder 0555 (`read_only`), or back to 0644/0755. +#[cfg(unix)] +fn set_read_only(root: &Path, read_only: bool) { + use std::os::unix::fs::PermissionsExt; + fn walk(p: &Path, ro: bool) { + let m = std::fs::symlink_metadata(p).unwrap(); + if m.is_dir() { + if !ro { + std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + for e in std::fs::read_dir(p).unwrap() { + walk(&e.unwrap().path(), ro); + } + if ro { + std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o555)).unwrap(); + } + } else { + let mode = if ro { 0o444 } else { 0o644 }; + std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap(); + } + } + walk(root, read_only); +} + +/// Makes the books writable again when dropped, so a run that passes or +/// fails never leaves a folder no one can delete. +#[cfg(unix)] +struct Writable(PathBuf); + +#[cfg(unix)] +impl Drop for Writable { + fn drop(&mut self) { + if self.0.exists() { + set_read_only(&self.0, false); + let _ = std::fs::remove_dir_all(&self.0); + } + } +} + +#[cfg(unix)] +#[test] +fn every_tab_never_writes_into_its_books_in_front_or_not() { + let dir = std::env::temp_dir().join(format!("ledger-gui-tabs-ro-{}", std::process::id())); + if dir.exists() { + set_read_only(&dir, false); + std::fs::remove_dir_all(&dir).unwrap(); + } + let _restore = Writable(dir.clone()); + let t = d(2026, 10, 12); + ledger_gui::demo::build(&dir.join("one"), t).unwrap(); + ledger_gui::demo::build(&dir.join("two"), t).unwrap(); + let source = |n: &str| Source { + data_dir: dir.join(n).join("books-data"), + today: Some(t), + }; + set_read_only(&dir, true); + let before = tree(&dir); + + // The ids of what to show, from the second company's books. + let books = data::load_once(&source("two")).unwrap(); + let entry = books.entries.last().map(|e| e.id).unwrap(); + let cash = books.cash_accounts[0]; + let doc = books.attachments.last().map(|a| a.id).unwrap(); + let asset = books + .ledger + .registered_assets() + .next() + .map(|a| a.id) + .unwrap(); + let party = books.ledger.parties().next().map(|p| p.id).unwrap(); + let projects: Vec = books.ledger.list_classes().iter().map(|c| c.id).collect(); + drop(books); + + let (one, two) = (source("one"), source("two")); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .build_eframe(move |cc| { + let mut app = App::start_with(&cc.egui_ctx, &|_| None, Start::Only(one)); + app.open(&cc.egui_ctx, two); + // The first company in front: the second is a tab behind it. + app.activate(0); + app + }); + loaded(&mut h); + assert_eq!(h.state().active(), Some(0)); + // The tab behind follows live for a moment, unseen. + for _ in 0..10 { + h.run_steps(2); + std::thread::sleep(Duration::from_millis(30)); + } + // Then it is shown, and every page rendered in it, the other behind. + h.state_mut().activate(1); + let routes = [ + Route::Overview, + Route::Transactions, + Route::Entry(entry), + Route::Cash, + Route::Profit, + Route::Reports(ReportKind::ProfitAndLoss), + Route::Reports(ReportKind::BalanceSheet), + Route::Reports(ReportKind::CashFlow), + Route::Reports(ReportKind::TrialBalance), + Route::Reports(ReportKind::GeneralLedger), + Route::Reports(ReportKind::TaxSummary), + Route::Reports(ReportKind::Vendor1099), + Route::Reports(ReportKind::ArAging), + Route::Reports(ReportKind::ApAging), + Route::Reports(ReportKind::MembersEquity), + Route::Reports(ReportKind::FixedAssetRegister), + Route::Accounts, + Route::Account(cash), + Route::Assets, + Route::Asset(asset), + Route::Parties, + Route::Party(party), + Route::Projects, + Route::Document(doc), + Route::Documents, + Route::Company, + Route::Journal, + ]; + for route in routes + .into_iter() + .chain(projects.iter().map(|&c| Route::Project(c))) + { + h.state_mut().goto(route); + h.run_steps(3); + let ctx = h.ctx.clone(); + h.state_mut().settle(&ctx); + h.run_steps(2); + } + // Back and forth between the tabs. + for i in [0, 1, 0, 1] { + h.state_mut().activate(i); + h.run_steps(3); + } + drop(h); + let after = tree(&dir); + set_read_only(&dir, false); + let changed: Vec<_> = before + .keys() + .chain(after.keys()) + .filter(|k| before.get(*k) != after.get(*k)) + .collect(); + assert!(changed.is_empty(), "the viewer changed {changed:?}"); +} + +// ---- 8: how the bar looks ---------------------------------------------------- + +/// Pixels compared where there is a renderer; tolerant of antialiasing +/// (as the sidebar's are: sidenav.rs). +fn picture(h: &mut Harness<'_, App>, name: &str) { + if h.render().is_err() { + eprintln!("no renderer: {name} not compared"); + return; + } + let options = egui_kittest::SnapshotOptions::new() + .threshold(1.0) + .max_failed_pixels(60); + if let Err(e) = h.try_snapshot_options(name, &options) { + panic!("{e}"); + } +} + +/// An app of fixed books, one tab each named `names`, the first in +/// front, `size` large. `wide`: names long enough to be cut. +fn shown(world: &World, names: &[&str], dark: bool, size: egui::Vec2) -> Harness<'static, App> { + let ids: Vec = (0..names.len()).map(|i| format!("co-{i}")).collect(); + for (id, name) in ids.iter().zip(names) { + world.company(id, name, 1_000_000, 123_456); + } + let sources: Vec = ids.iter().map(|id| world.source(id)).collect(); + let mut h = Harness::builder().with_size(size).build_eframe(move |cc| { + let mut app: Option = None; + for s in sources { + let books = data::load_once(&s).unwrap(); + match app.as_mut() { + None => { + app = Some(App::with_books(&cc.egui_ctx, books, dark, Route::Overview)); + } + Some(a) => { + a.add_view(CompanyView::with_books( + &cc.egui_ctx, + books, + Route::Overview, + )); + } + } + } + let mut app = app.unwrap(); + app.activate(0); + app + }); + h.run_steps(4); + h +} + +const BAR_SIZE: egui::Vec2 = egui::vec2(900.0, 160.0); + +#[test] +fn the_tab_bar_with_one_two_and_many_tabs() { + for dark in [false, true] { + let mode = if dark { "dark" } else { "light" }; + let w = World::new(); + let mut h = shown(&w, &["Wanderland Labs LLC"], dark, BAR_SIZE); + picture(&mut h, &format!("tabs_one_{mode}")); + let w = World::new(); + let mut h = shown( + &w, + &["Wanderland Labs LLC", "Fernhill Studio"], + dark, + BAR_SIZE, + ); + picture(&mut h, &format!("tabs_two_{mode}")); + let w = World::new(); + let names = [ + "Wanderland Labs LLC", + "Fernhill Studio", + "Northgate Holdings Incorporated", + "Oak & Ash Carpentry", + "Harbor Lane Books", + "Quill and Compass", + "Mossy Rock Farm", + "Lantern Works", + "Birch Street Bakery", + "Tidewater Consulting Group", + ]; + let mut h = shown(&w, &names, dark, BAR_SIZE); + // The tab in front is the last: it is scrolled into view. + h.state_mut().activate(9); + h.run_steps(6); + picture(&mut h, &format!("tabs_many_{mode}")); + // Never overlapping: each tab's close control is inside the bar. + let bar = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(BAR_SIZE.x, 40.0)); + let plus = h + .get_by_role_and_label(Role::Button, "Open another company") + .rect(); + assert!(bar.contains_rect(plus), "the + is whole in the bar"); + } +} + +#[test] +fn the_empty_window_and_the_plus_list() { + for dark in [false, true] { + let mode = if dark { "dark" } else { "light" }; + let w = World::new(); + let mut h = shown(&w, &["Wanderland Labs LLC"], dark, egui::vec2(900.0, 420.0)); + close_tab(&mut h, "Wanderland Labs LLC"); + assert!(shows(&h, "No company is open")); + picture(&mut h, &format!("tabs_empty_{mode}")); + // "+" with companies to open. + let w = World::new(); + w.company("alpha", "Alpha Co", 1_000_000, 100); + w.company("beta", "Beta Co", 1_000_000, 100); + w.company("gamma", "Gamma Co", 1_000_000, 100); + let mut h = start( + &w, + prefs(&[ + ("open_companies", "alpha"), + ("dark", if dark { "true" } else { "false" }), + ]), + egui::vec2(900.0, 420.0), + ); + loaded(&mut h); + h.get_by_label("Open another company").click(); + h.run_steps(4); + picture(&mut h, &format!("tabs_plus_{mode}")); + } +} + +// ---- 11-13: the company's name and hue -------------------------------------- + +/// Every text the last frame painted, with where it starts. +fn placed(h: &Harness<'_, App>) -> Vec<(egui::Pos2, String)> { + fn walk(s: &egui::Shape, out: &mut Vec<(egui::Pos2, String)>) { + match s { + egui::Shape::Text(t) => out.push((t.pos, t.galley.text().to_string())), + 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 +} + +/// Every rectangle of exactly colour `color` the last frame painted. +fn fills(h: &Harness<'_, App>, color: egui::Color32) -> Vec { + fn walk(s: &egui::Shape, color: egui::Color32, out: &mut Vec) { + match s { + egui::Shape::Rect(r) if r.fill == color => out.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, color, out)), + _ => {} + } + } + let mut all = Vec::new(); + for c in &h.output().shapes { + walk(&c.shape, color, &mut all); + } + all +} + +/// The sidebar's column below the bar. +fn in_sidebar(r: egui::Rect) -> bool { + r.max.x <= 224.5 && r.min.y >= ledger_gui::tabs::BAR_H +} + +/// The hue ids of the books give: the light or dark one. +fn hue(id: &str, dark: bool) -> egui::Color32 { + ledger_gui::tabs::hue_of(id, dark) +} + +#[test] +fn nothing_in_the_top_of_the_window_but_the_tab_shows_the_company_name() { + use ledger_gui::tabs::BAR_H; + for dark in [false, true] { + for route in [Route::Overview, Route::Cash, Route::Journal] { + let w = World::new(); + let mut h = shown( + &w, + &["Wanderland Labs LLC", "Fernhill Studio"], + dark, + egui::vec2(1280.0, 700.0), + ); + h.state_mut().goto(route.clone()); + h.run_steps(4); + let tag = format!("{route:?}, dark {dark}"); + for name in ["Wanderland Labs LLC", "Fernhill Studio"] { + // Painted text: in the top 120 points it is only the tab's. + for (at, text) in placed(&h) { + if text.contains(name) && at.y < 120.0 { + assert!( + at.y < BAR_H, + "{tag}: {name} is painted at {at:?} below the bar: {text:?}" + ); + } + } + // The tree: only the tab and its close control, both in the bar. + for n in h.query_all_by_label_contains(name) { + let r = n.rect(); + if r.top() < 120.0 { + assert!( + r.bottom() <= BAR_H + 0.5, + "{tag}: a widget named {name} at {r:?} is under the bar" + ); + } + } + } + // And the one in front is named once more, lower: the card. + let card = placed(&h) + .into_iter() + .filter(|(at, t)| at.x < 224.0 && at.y > 120.0 && t == "Wanderland Labs LLC") + .count(); + assert_eq!(card, 1, "{tag}: the status card names the company"); + } + } +} + +#[test] +fn the_status_card_shows_the_company_in_front_and_follows_the_tab() { + for dark in [false, true] { + let (w, _, _, _) = three(); + let mode = if dark { "true" } else { "false" }; + let mut h = start( + &w, + prefs(&[("open_companies", "alpha,beta"), ("dark", mode)]), + egui::vec2(1280.0, 900.0), + ); + loaded(&mut h); + let card_names = |h: &Harness<'_, App>| -> Vec { + placed(h) + .into_iter() + .filter(|(at, t)| at.x < 224.0 && at.y > 120.0 && t.ends_with(" Co")) + .map(|(_, t)| t) + .collect() + }; + // The card's badge: its hue, a small square in the sidebar, near + // the foot (the tab's is in the bar). + let card_badge = |h: &Harness<'_, App>, id: &str| { + fills(h, hue(id, dark)) + .into_iter() + .filter(|r| in_sidebar(*r) && r.min.y > 120.0) + .collect::>() + }; + assert_eq!(card_names(&h), ["Alpha Co"], "dark {dark}"); + // The heading carries the live word, at the name's row and the + // card's right edge; no text of the card says the event (it is the + // heading's hover and its live mark's label). + let card_texts = |h: &Harness<'_, App>| -> Vec<(egui::Pos2, String)> { + placed(h) + .into_iter() + .filter(|(at, _)| at.x < 224.0 && at.y > 120.0) + .collect() + }; + let texts_now = card_texts(&h); + let name_y = texts_now.iter().find(|(_, t)| t == "Alpha Co").unwrap().0.y; + let live = texts_now + .iter() + .find(|(_, t)| t == "Live" || t == "Snapshot") + .expect("the live word is on the card"); + assert!( + (live.0.y - name_y).abs() < 6.0, + "the live word is in the heading" + ); + assert!( + live.0.x > 150.0, + "the live word is at the card's right edge: {:?}", + live.0 + ); + assert!( + texts_now + .iter() + .any(|(_, t)| t.ends_with("Journal chain verified")), + "the journal chain line is as it was, with no event" + ); + assert!( + !texts_now.iter().any(|(_, t)| t.contains("event")), + "no text of the card says the event" + ); + // The event is the live mark's accessible label. + assert_eq!( + h.query_all_by_label_contains("event ") + .filter(|n| n.rect().left() < 224.0) + .count(), + 1, + "one element carries the event" + ); + assert!( + h.query_all_by_label_contains("Live · event ") + .chain(h.query_all_by_label_contains("Snapshot · event ")) + .count() + == 1, + "the live mark's label is \"Live · event N\"" + ); + assert_eq!( + card_badge(&h, "alpha").len(), + 1, + "alpha's badge on its card" + ); + assert!( + card_badge(&h, "beta").is_empty(), + "beta's hue isn't on alpha's card" + ); + // The badge is small, and carries the initial. + let r = card_badge(&h, "alpha")[0]; + assert!(r.width() <= 20.0 && r.height() <= 20.0, "{r:?}"); + assert!( + placed(&h) + .iter() + .any(|(at, t)| t == "A" && r.contains(*at + egui::vec2(4.0, 4.0)) + || t == "A" && r.expand(4.0).contains(*at)), + "the initial is on the badge" + ); + show_tab(&mut h, "Beta Co"); + assert_eq!(card_names(&h), ["Beta Co"], "dark {dark}"); + assert_eq!(card_badge(&h, "beta").len(), 1, "beta's badge on its card"); + assert!( + card_badge(&h, "alpha").is_empty(), + "alpha's hue left the card" + ); + // The window's title still names the company. + assert_eq!(h.state().window_title(), "Beta Co · wanderbooks"); + } +} + +#[test] +fn the_rail_shows_the_badge_alone_with_the_name_on_hover() { + let (w, _, _, _) = three(); + let mut h = start( + &w, + prefs(&[("open_companies", "alpha,beta"), ("dark", "false")]), + egui::vec2(900.0, 700.0), + ); + loaded(&mut h); + let badge: Vec<_> = fills(&h, hue("alpha", false)) + .into_iter() + .filter(|r| in_sidebar(*r) && r.max.x <= 60.5) + .collect(); + assert_eq!(badge.len(), 1, "alpha's badge in the rail"); + assert!( + !placed(&h) + .iter() + .any(|(at, t)| at.x < 60.0 && at.y > 36.0 && t.contains("Alpha Co")), + "the rail has no room for the name" + ); + h.hover_at(badge[0].center()); + h.run_steps(30); + assert!(shows(&h, "Alpha Co"), "the name is on hover"); + assert!(shows(&h, "· event "), "the event is on hover"); + assert!( + shows(&h, "Alpha Co\n") || shows(&h, "Alpha Co"), + "the name leads the hover" + ); + assert!( + shows(&h, "Live") || shows(&h, "Snapshot"), + "the state is on hover" + ); + assert!( + shows(&h, "Journal chain verified"), + "the checks are on hover" + ); +} + +#[test] +fn a_hue_is_the_books_id_alone_on_the_tab_and_the_card_in_both_themes_and_after_a_restart() { + let (w, _, _, _) = three(); + for dark in [false, true] { + let mode = if dark { "true" } else { "false" }; + let size = egui::vec2(1280.0, 900.0); + // Two starts, the tabs opened in different orders: a restart, and + // an order of opening, change nothing. + let mut seen = Vec::new(); + for order in ["alpha,beta,gamma", "gamma,alpha,beta"] { + let mut h = start( + &w, + prefs(&[("open_companies", order), ("dark", mode)]), + size, + ); + loaded(&mut h); + for id in ["alpha", "beta", "gamma"] { + let name = format!("{} Co", id[..1].to_uppercase() + &id[1..]); + show_tab(&mut h, &name); + let want = hue(id, dark); + let tab: Vec<_> = fills(&h, want) + .into_iter() + .filter(|r| r.max.y <= ledger_gui::tabs::BAR_H) + .collect(); + let card: Vec<_> = fills(&h, want) + .into_iter() + .filter(|r| in_sidebar(*r)) + .collect(); + assert_eq!(tab.len(), 1, "{id} dark {dark}: its tab's badge in its hue"); + assert_eq!( + card.len(), + 1, + "{id} dark {dark}: its card's badge in its hue" + ); + seen.push((id, dark, want)); + } + } + // The same in both starts. + let (first, second) = seen.split_at(3); + let mut a = first.to_vec(); + let mut b = second.to_vec(); + a.sort_by_key(|x| x.0); + b.sort_by_key(|x| x.0); + assert_eq!(a, b); + } + // Pinned, with the rule: it never changes without a decision, and + // is a function of the id alone (not the name, nor the machine). + assert_eq!( + hue("alpha", false), + egui::Color32::from_rgb(0xBE, 0x18, 0x5D) + ); + assert_eq!( + hue("alpha", true), + egui::Color32::from_rgb(0xF4, 0x72, 0xB6) + ); + assert_eq!( + hue("beta", false), + egui::Color32::from_rgb(0x0E, 0x74, 0x90) + ); + assert_eq!( + hue("gamma", false), + egui::Color32::from_rgb(0xB4, 0x53, 0x09) + ); +} + +#[test] +fn the_overview_opens_with_its_summary_sentence_and_never_names_the_company() { + for dark in [false, true] { + let w = World::new(); + let mut h = shown(&w, &["Alpha Co"], dark, egui::vec2(1280.0, 800.0)); + h.run_steps(3); + // The page's first text: the first under the company's top bar + // (52 high, under the tab bar). + let page_top = ledger_gui::tabs::BAR_H + 52.0; + let mut page: Vec<(egui::Pos2, String)> = placed(&h) + .into_iter() + .filter(|(at, _)| at.x >= 224.0 && at.y >= page_top) + .collect(); + page.sort_by(|a, b| a.0.y.total_cmp(&b.0.y).then(a.0.x.total_cmp(&b.0.x))); + let (_, first) = page.first().expect("the page has text"); + assert!( + first.starts_with("You have $8,765.44 in cash and owe $0.00."), + "dark {dark}: the page opens with {first:?}" + ); + // Nothing on the page says the company's name: no sentence there + // used it. + assert!( + page.iter().all(|(_, t)| !t.contains("Alpha Co")), + "dark {dark}: {:?}", + page.iter() + .filter(|(_, t)| t.contains("Alpha Co")) + .collect::>() + ); + // It reads as the page's opening line: bigger than body text, + // smaller than a page's title (26). + let lead = h + .output() + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().starts_with("You have") => { + Some(t.galley.rows[0].height()) + } + _ => None, + }) + .expect("the lead"); + let body = 14.0 * 1.2; + assert!(lead > body * 1.2 && lead < 26.0 * 1.2, "lead row {lead}"); + } +} + +#[test] +fn the_overview_of_books_with_no_transactions_opens_the_same_way() { + let w = World::new(); + let id = "empty-co"; + let root = Root::find(Some(&w.root)).unwrap(); + let mut s = root + .create_book(&BookId::parse(id).unwrap(), Currency::USD) + .unwrap(); + s.add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + drop(s); + let source = w.source(id); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .build_eframe(move |cc| { + App::with_books( + &cc.egui_ctx, + data::load_once(&source).unwrap(), + false, + Route::Overview, + ) + }); + h.run_steps(4); + let page_top = ledger_gui::tabs::BAR_H + 52.0; + let mut page: Vec<_> = placed(&h) + .into_iter() + .filter(|(at, _)| at.x >= 224.0 && at.y >= page_top) + .collect(); + page.sort_by(|a, b| a.0.y.total_cmp(&b.0.y)); + assert!( + page[0].1.starts_with("No transactions yet."), + "opens with {:?}", + page[0].1 + ); +} + +/// Pictures of the whole window: one company, two tabs each in front once, +/// eight tabs, the "+" list open, the empty window, the rail, the +/// smallest window and the Overview at its top, for a person to look at +/// (`SHOT_DIR=… cargo test -p ledger-gui --test tabs -- --ignored pictures`). +#[test] +#[ignore] +fn pictures() { + let out = PathBuf::from(std::env::var("SHOT_DIR").expect("SHOT_DIR")); + std::fs::create_dir_all(&out).unwrap(); + let save = |h: &mut Harness<'_, App>, name: &str| { + h.render() + .unwrap() + .save(out.join(format!("{name}.png"))) + .unwrap(); + }; + for dark in [false, true] { + let mode = if dark { "dark" } else { "light" }; + // One company open. + let (w, _, _, _) = three(); + let mut h = start( + &w, + prefs(&[ + ("open_companies", "alpha"), + ("dark", if dark { "true" } else { "false" }), + ]), + egui::vec2(1440.0, 920.0), + ); + loaded(&mut h); + save(&mut h, &format!("one-company-{mode}")); + // The Overview scrolled down and back to its top. + h.hover_at(egui::pos2(900.0, 500.0)); + for dy in [-400.0, 800.0] { + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(6); + } + save(&mut h, &format!("overview-scrolled-to-top-{mode}")); + // The sidebar collapsed to its rail, two companies open. + let mut h = start( + &w, + prefs(&[ + ("open_companies", "alpha,beta"), + ("dark", if dark { "true" } else { "false" }), + ]), + egui::vec2(900.0, 700.0), + ); + loaded(&mut h); + save(&mut h, &format!("rail-two-companies-{mode}")); + let mut h = start( + &w, + prefs(&[ + ("open_companies", "alpha,beta"), + ("dark", if dark { "true" } else { "false" }), + ]), + egui::vec2(1440.0, 920.0), + ); + loaded(&mut h); + show_tab(&mut h, "Alpha Co"); + h.run_steps(6); + save(&mut h, &format!("two-tabs-alpha-in-front-{mode}")); + show_tab(&mut h, "Beta Co"); + h.run_steps(6); + save(&mut h, &format!("two-tabs-beta-in-front-{mode}")); + h.get_by_label("Open another company").click(); + h.run_steps(4); + save(&mut h, &format!("plus-list-open-{mode}")); + h.key_press(egui::Key::Escape); + h.run_steps(3); + close_tab(&mut h, "Alpha Co"); + close_tab(&mut h, "Beta Co"); + h.run_steps(4); + save(&mut h, &format!("empty-state-{mode}")); + // Eight companies open: the tabs scroll, the "+" stays at the edge. + let names: Vec = [ + "Wanderland Labs LLC", + "Fernhill Studio", + "Northgate Holdings Incorporated", + "Oak & Ash Carpentry", + "Harbor Lane Books", + "Quill and Compass", + "Mossy Rock Farm", + "Lantern Works", + ] + .map(String::from) + .to_vec(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let w = World::new(); + let mut h = shown(&w, &refs, dark, egui::vec2(1100.0, 600.0)); + h.state_mut().activate(6); + h.run_steps(6); + save(&mut h, &format!("eight-tabs-overflow-{mode}")); + // The smallest window the viewer allows, two tabs. + let w = World::new(); + let mut h = shown( + &w, + &["Wanderland Labs LLC", "Fernhill Studio"], + dark, + egui::vec2(360.0, 400.0 + ledger_gui::tabs::BAR_H), + ); + h.run_steps(4); + 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); +} diff --git a/docs/architecture.md b/docs/architecture.md index fbfb02fc..a7c7cb33 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -37,7 +37,7 @@ the specification in `bookspec/` (which never depends on the engine). | `ledger-package` | the shared read-only view over `Store` or `Snapshot` (`PackageBooks`): the CPA package, the 1099 worksheet, the invoice document, Needs attention | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-vault` | | `ledger-mcp` | the books server: the MCP tools (122), resources, the handbook, scopes, the door and the access log, backups' scheduling | all of the above | | `ledger-host` | the host and its leases, the agent bridge (`wanderbooks mcp`), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config` | -| `ledger-gui` | the viewer: read-only, live, egui; the Books menu hands work to the server; the agent dock and the first-run page (P11b) | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-package`, `ledger-vault`, `ledger-host` | +| `ledger-gui` | the viewer: read-only, live, egui, one window with a tab per open company (P15); the Books menu hands work to the server; the agent dock and the first-run page (P11b) | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-package`, `ledger-vault`, `ledger-host` | | `ledger-cli` | `wanderbooks`, the one executable: every mode (`serve`, `server`, `host`, `mcp`, `gui`, `setup`, `books`, `token`, `connect`, `doctor`, `licenses`, …) and the over-the-wire test suites | everything | | `bookspec/checker`, `bookspec/runner` | the example schema and parser, the rule catalogue, the `Engine` trait; the per-rule runner | nothing of ours (the adapter in `ledger-core`'s tests depends on them) | @@ -116,6 +116,88 @@ appended journal lines; the UI renders an immutable view model rebuilt per change. Statements and series come from `ledger-core` (`reports`, `analysis`); the GUI only arranges them. See `plan/gui.md`. +The viewer is **one window with a tab per open company** (P15, D-78; +`plan/p15-app-and-relay.md` 3.2). `App` (`app.rs`) holds what is the app's +(the color scheme and its menu, `scheme_menu.rs`; the tab bar, `tabs.rs`; +the data root the companies are in) and a list of `CompanyView`s +(`company.rs`), one per open company, with which is in front. The tab +bar runs across the whole window, above the sidebar: a tab is the top +level, and the sidebar (its pages, its status card) is the company in the +tab's. The tab is the company's identity in the frame (its badge and +name), and nothing else at the top of the window repeats it: the sidebar +has no header, its first link sits under the bar (`top_slot` in +`company.rs` is the empty place at the top of the sidebar and of the rail, +where the assistant's connection state is drawn later), and the Overview +opens with its summary sentence, not a heading with the name. The company +is named once more, at the opposite corner: the status card at the foot of +the sidebar begins with a heading row: the badge (small) and the name, cut +with an ellipsis, and at the card's right edge the live dot and "Live" (or +"Snapshot"); the name elides before the live word is ever clipped. The +heading's hover reads, a fact a line: the company's full name, "Live · +event N", then the checks; the live word's accessible label is "Live · +event N". The event is printed nowhere else in the card, and no text in it +wraps: every line is one row and elides (`the_status_card_never_wraps_in_any_state`). +The journal chain line is just "Journal chain verified". Folded (a short +window) the card is the heading alone, or, when a check failed, the heading +over one line naming it. The rail shows the badge with the live dot on its +corner (a warning there when a check failed), the name, state, event and +checks on hover. Each company has one badge +hue of eight (`theme::BADGE_HUES`, light and dark), chosen by a stable +hash of the id of its books (`theme::hue_index`, FNV-1a modulo eight: a +function of the id alone, so a company keeps its colour on every machine +and after a rename); its tab and its card draw the same one, and the +active tab's accent line stays the theme's. The bar's height (`tabs::BAR_H`) is taken from the +window; the viewer's smallest window is 400 points high, as before the bar. A tab is the company's badge and name, as wide as +that between a least and a greatest width; the "+" follows the last tab +and stays at the right edge, the tabs scrolling, when they overflow. The +app remembers each company's name when its books load (`company...name` +in its kept state, `` being a hash of the data root's canonical path), +for a tab's title before the books load and for the +"+" list, which never reads a journal for a name. A view owns +everything that is one company's: its loader thread (its watcher and its +viewer presence on the books), the books it last loaded, where it is +(`Nav`), its page state, its receipts' workers, its export and owner menus, +its palette, its dock (and so the agent process in it) and its handle to +the `Owner`. Nothing is shared between views: every egui id a view makes is +scoped by its own id (the app draws a view inside `push_id`), so egui's +memory (scroll offsets, remembered widths) never carries from one tab into +another (a panel's id is not scoped by `push_id`, so the view's panels are +given ids made from its own; what the tabs share on purpose is the app's and +says so: the assistant dock's panel, whose height is one layout in every +tab, the tab bar, and the color scheme's palette); closing a tab drops its +view and with it all of that. + +Every thread a view starts is counted in one registry of the view +(`jobs.rs`): its loader, its receipts' workers, an export, an owner's job, +the dock's start and the thread that reaps the dock's agent. Dropping the +view tells them all to stop, and the registry says when the last has ended +(`CompanyView::jobs_watch`). What each does on being told: the loader ends +(and the viewer's presence on the books is let go in the drop itself, not +when a refresh in flight is over), the receipts' workers end and write no +thumbnail, an export stops at its phase boundaries and saves nothing, a +read-only owner job (a backup, the check of a backup to restore) is not +begun or has its answer dropped, the dock's agent is hung up on and, if it +has not gone within two seconds, killed and reaped. One kind of job is never +abandoned: an owner's job that changes something (restore, the format +upgrade, new books, connect, close the books, update). While one runs, its +tab's close control is off and says what is running, and the window's close +is cancelled with a dialog that offers only to wait (`app.rs` INVARIANT 7; +`owner.rs` INVARIANT 6). A view that +is not in front still reads its loader every frame (so showing it later is +current at once) and takes the agent's `books.show` for its own page only. +`wanderbooks gui BOOK` opens that company as the only tab; with none named, +the companies that were open when the window last closed come back, in +their order, the same one in front, each with its page and its report's +period (`app.rs` INVARIANT 4). What is kept is filed under the data root +(a hash of its canonical path) and the company's id, with the books' +identity (the SHA-256 of the journal's first line) once they load: another +root's company of the same id, or the same id made again as other books, +inherits nothing, and a stored state whose identity is not the loaded +books' is discarded. A start that names a company never writes the list of +open companies, so one such start doesn't replace a set of tabs. The `Owner` the program installs +(`owner::set_owner`) is the program's, one per process; each view takes a +handle to it when it is made and a test can give a view another. + Two things sit beside the read-only view, both through the `Owner` the program gives the viewer (never a write of the books by the viewer): diff --git a/docs/testing.md b/docs/testing.md index dc40485e..4fde125a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4376,6 +4376,278 @@ a client trickling an upload on purpose). before it touches the book, and the gate's riding in the upload and download tasks. +## P15 A3a: a tab per company (2026-11-20, D-78) + +The viewer was a window on one company. It is now one window with a tab +per open company (`app.rs`, `company.rs`, `tabs.rs`). The work here is +the refactor and the tab bar; nothing starts or stops the books server and +no File menu is added. The tests look for exactly the failure a refactor +like this has: it compiles, the old tests pass, and two tabs share state. +Everything runs on scratch data roots that `Root::setup` makes in a temp +folder; no test touches an account's real books. + +`crates/ledger-gui/tests/tabs.rs` (the bar's pictures run where there is a +renderer, as the sidebar's do): + +- `each_tab_shows_its_own_company_and_figures`: two companies, cash + 8,765.44 and 24,222.23, open in two tabs; each shows its own cash on the + overview, its own rent (1,234.56 / 777.77) in the profit and loss and + in the rent account's register, and never the other's; the tab opens on + its overview, not on the page the other was on; the window's title names + the company in front. +- `what_is_done_in_one_tab_changes_nothing_in_another`: in one tab a page, + a search, a report's period, columns and comparison are set; in the + other the page, the search and the period are as they were and every + text it paints is the same as before (and the other way round). +- `a_scrolled_sidebar_in_one_tab_is_not_scrolled_in_another`: egui's own + memory. In a short window the sidebar's links scroll; one tab's is + scrolled a page on, the other's is at the top, and the first is still + scrolled when it comes back. Fails (checked) when the view is not + drawn inside `push_id`. +- `no_two_views_have_the_same_id_or_key`. +- `a_background_tab_follows_its_journal_and_is_current_when_shown`: an + entry posted to the company of the tab behind is read while another tab + is in front (nothing is brought forward); when shown, its cash is the + new one on the first frames, with no reload. +- `books_show_moves_the_tab_it_is_aimed_at_and_only_that_one`: a show + request for the second company moves that tab to the journal; the tab in + front stays on its overview and in front. +- `closing_a_tab_releases_its_lock_its_threads_and_its_agent` (Unix): the + second tab's owner is its own (`set_owner` on the view; no process + global), its dock runs a stand-in agent (`sh -c 'echo $$ > pid; exec + sleep 600'`); closing the tab with its close control, the company's + viewer lock (`ops::viewer_open`) is released, its loader's thread has + ended (`Loader::watch`), the agent's process is gone; the other tab's + lock and loader are held and running; the company opens again with a new + lock. +- `plus_lists_only_the_companies_not_open_and_none_opens_twice`: "+" lists + `gamma` and neither open company; choosing it opens a third tab, in + front; the list then says every company is open; `App::open` and + `add_view` of an open company show its tab and add none. +- `start_up_restores_the_open_tabs_their_order_and_the_one_in_front`: + `gamma,gone,alpha,gamma,not a book!,beta` kept with `alpha` in front + opens gamma, alpha, beta with alpha in front, no error; no record, or a + record of companies that are all gone, opens the data root's first; a + front company not among the open ones leaves the first in front; a + company named on the command line is the only tab. +- `the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back`: + `save` writes `open_companies`, `active_company`, the old per-app keys + and each company's page, period, columns and comparison; a second start + from them restores all of it, each tab's own; a tab closed and opened + again comes back as it was left; with every tab closed the next start + opens the first company. +- `closing_the_front_tab_shows_a_neighbour_and_the_last_leaves_an_empty_window`: + the tab after, else before; the last leaves "No company is open" and + "Open a company with the + at the top of the window.", the bar still + there, and "+" opens a company from it. +- `the_tab_in_front_is_marked_by_more_than_colour`: the tab in front is + "selected" to assistive technology, the others are not; each has a close + control named for its company. +- `every_tab_never_writes_into_its_books_in_front_or_not`: `read_only.rs`'s + guarantee on two demo companies made read-only on disk: one follows live + behind the other, then every page is rendered in it (as `read_only.rs` + does), then the tabs are shown in turn; afterwards every file holds the + same bytes, size and time in both. +- `the_tab_bar_with_one_two_and_many_tabs`: pictures of the bar, light and + dark (`tests/snapshots/tabs_one_*`, `tabs_two_*`, `tabs_many_*`); with + ten tabs the bar scrolls, the tab in front is scrolled into view, and + the "+" is whole in the bar. +- `the_empty_window_and_the_plus_list`: pictures of the empty window and of + the "+" list open, light and dark (`tabs_empty_*`, `tabs_plus_*`). +- `the_bar_spans_the_window_above_the_sidebar`: on the laid-out rectangles, + the bar's fill is the window's width and `BAR_H` high at its top, every + tab is inside it, the first is over the sidebar's column, and the + sidebar's links and panel start below it. +- `the_plus_follows_the_last_tab_and_stays_whole_when_the_tabs_overflow`: + with two tabs the "+" is just after the last; with nine it is at the right + edge, whole, with the step controls shown and the tab in front left of it. +- `a_name_is_remembered_and_shown_in_the_plus_list_and_on_a_loading_tab`: + a closed company is listed by name with its id beside it, one never + opened by its id alone; the name is saved as `company..name`, and an + app started from it titles a tab whose books aren't loaded by that name + (else by the id). +- `the_plus_list_says_so_when_every_company_is_open`: "Every company is + already open." and no heading. +- `nothing_in_the_top_of_the_window_but_the_tab_shows_the_company_name`: + per theme, on the Overview, Cash and the Journal, no painted text or + widget in the tree below the bar and above 120 points names the company + (the tab and its close control are in the bar), and the status card + names the company in front once. +- `the_status_card_shows_the_company_in_front_and_follows_the_tab`: the + card's heading is the tab in front's name and its badge, small, in that + company's hue (the other's is not on the card), and both change when + another tab is shown; the window's title is unchanged. +- `the_rail_shows_the_badge_alone_with_the_name_on_hover`. +- `a_hue_is_the_books_id_alone_on_the_tab_and_the_card_in_both_themes_and_after_a_restart`: + the hue a tab and a card draw is the one the id gives, light and dark, + the same after a restart and in another order of opening, and pinned + for three ids (a change recolours every company). +- `the_overview_opens_with_its_summary_sentence_and_never_names_the_company` + and `the_overview_of_books_with_no_transactions_opens_the_same_way`: the + first text of the page is the sentence ("You have $8,765.44 in cash …", + or "No transactions yet. …"), set bigger than body text and smaller than + a page title, and no text on the page names the company (no sentence + there used the name). +- In `theme.rs`: `every_badge_hue_reads_in_both_themes` computes, for each + of the eight hues in each theme, the letter's contrast on the badge + (4.5:1, WCAG AA) and the badge's on the surface, sidebar, page and hover + colours (3:1); `a_hue_is_a_function_of_the_book_id_alone` pins the hash + and that every hue is used. +- `pictures` (ignored; `SHOT_DIR`): the whole window with one company, each + of two tabs in front, eight tabs, the "+" list, the empty window, the + rail with two companies, the smallest window and the Overview at its + top, light and dark, for a person to look at. + +Unit tests moved with the code they test: the sidebar's fit tests, now +in `company.rs`; the scheme tests, in `scheme_menu.rs`. The tab bar runs +across the top of the window *above* the sidebar (D-78): a tab is the +top level, and the layout shows that the sidebar belongs to the company in +it. The bar takes `tabs::BAR_H` (36 points) of the window's height, which +the sidebar had to spare nowhere at the owner's 519 points. The status +card gave the height back (see "The sidebar tests' window sizes are +restored" below); the golden's crop and shapes hash cover only what is below +the bar. In `tabs.rs`, the +three tests that click a closed company in the "+" list by its id now click +it by its name, which the list shows once the company has been open; the +list's empty words are now "Every company is already open." The ten +`tabs_*` snapshots were regenerated for the new bar. + +The company's name once, not three times (the owner's review of the bar): +the sidebar's header (badge, name, "Books") is gone, and so is the +Overview's heading, whose summary sentence is now the page's lead; the +status card's new heading row carries the company instead, with its hue. +That removed 28 points and the gap under the header from the top of the +sidebar and added a row to the card, so the sidebar has more room at every +height (at 1479x519 the links' viewport is 331 points, was 311, and the +rows 23 high, were 22); no `sidenav.rs` assertion or window changed. The +tall sidebar's shapes golden and pixel golden (`sidenav-1440x920`) were +regenerated (the header gone and the links moved up, the card's heading +row, the badge's hue), and the `tabs_*` snapshots again (hue, no +Overview heading, the rail's badge); `tabs_empty_*` are as they were. + +**Not tested here:** the window title reaching the window system (the +harness has none: `window_title()` is what is tested); a company opened +from the viewer while its books are being created by the server (the +loader's retry loop is `live.rs`'s); macOS and Windows. + +**For P12 (mutation targets):** `App::close`'s active-index arithmetic (the +`i < active` and `active >= len` arms); `App::add_view`'s duplicate key +test; `start_with`'s skip of a missing or repeated id and its choice of the +front tab; `CompanyView::pump`'s `shown` flag (a background tab must still +apply `Update::Books` and `Update::Show`); `Loader`'s drop wake-up and its +`gone` check after waking; the `push_id` in `CompanyView::ui` (the sidebar +test above kills its removal); `Dock::closed_with` (a new tab's dock opens +closed); `route_from_key` and the period codes in `CompanyView::restore` +(a start after the end is never restored). + +## P15 A3a, the review's faults: threads, kept state, the dock (2026-11-20) + +An independent review of the tab work confirmed the viewer writes nothing +and no figure crosses tabs, and found six faults. Each is fixed and each +fix has a test that was seen to fail with the fix switched off (the +mutation column says what was switched off). + +1. **Jobs outlived their tab** (`jobs.rs`, `menu.rs`, `owner.rs`, + `dock.rs`, `receipts.rs`, `data.rs`). Every thread a tab starts is one + of a per-view registry that the view's drop tells to stop and that says, + on a condition, when the last has ended. +2. **Kept state was filed under the id alone** (`app.rs`, `company.rs`). + It is filed under the data root's hash and the id, with the books' + identity (the SHA-256 of the journal's first line). +3. **A named start erased the remembered tabs** (`app.rs`). +4. **The dock's height** is the app's one layout, said and tested; every + other id egui keys by a raw name was found and ruled on. +5. **Prompt release on close** (`data.rs`, `receipts.rs`). +6. **The sidebar tests' window sizes**: see below. + +`crates/ledger-gui/tests/tabs.rs` (sections 14 to 17), `format_upgrade.rs`, +`exports.rs`, `live.rs` and unit tests in `jobs.rs` and `receipts.rs`: + +- `closing_a_tab_releases_its_lock_its_threads_and_its_agent` (changed): the + tab's registry counts the loader, the receipts' and thumbnails' workers + and the dock's agent; after the close the test waits on the registry + (`Watch::wait_ended`, its limit a failure guard, 120 s, never what the + test relies on) and then asserts the viewer lock is free, the loader's + thread has ended and the agent's process is gone. It no longer polls. +- `a_restore_under_way_holds_its_tab_and_the_window_open`, + `an_upgrade_under_way_holds_its_tab_and_the_window_open` + (`format_upgrade.rs`): the owner's call is held in the test; while it + runs the tab's close control is disabled to assistive technology, a + click and `App::close` leave the tab, the window's close request is + cancelled and the dialog names the company and what runs and offers only + to wait; with nothing running the same request goes through; when the + call ends the dialog goes and the result is in the tab. +- `a_backup_only_reads_so_its_tab_closes_and_its_thread_ends`: a read-only + owner job holds nothing, its tab closes, its thread ends when the + owner's call does. +- `an_export_is_stopped_when_its_tab_closes` (the job is told) and + `a_stopped_export_leaves_no_file_whenever_it_is_told` (`exports.rs`: a + signal given after 0, 1, 2 and 3 looks, each leaving no file, the fifth + look none, which saves). +- `a_tab_closed_while_its_agent_is_starting_leaves_no_child_and_no_thread` + and `a_tab_closed_with_its_agent_running_ends_the_child_even_if_it_ignores_the_hangup` + (Unix): the start is one of the tab's threads and its answer, arriving + after the close, starts nothing; an agent that ignores the hang-up is + killed after `AGENT_GRACE` and reaped, and the registry says so. +- `another_data_root_with_a_company_of_the_same_id_inherits_nothing`, + `books_made_again_under_an_id_start_fresh_and_a_restart_of_the_same_books_does_not`, + `books_outside_any_data_root_are_kept_under_their_folder`, + `preferences_written_before_the_keys_had_a_root_are_read_and_not_used`: + the kept-state keys. (A set of books' identity says when it was made to + the second, so a test that makes other books under an id waits for the + clock's next second first.) +- `a_start_with_a_named_company_never_writes_the_list_of_open_companies`. +- `the_docks_height_and_layout_are_the_apps_one_for_every_tab`, + `no_panel_but_the_apps_own_is_keyed_by_an_id_every_tab_shares`, + `the_color_scheme_is_the_windows_one_for_every_tab`: what the tabs share + on purpose, and that nothing else is. +- `live.rs`: `a_loader_whose_books_cant_be_read_tries_no_more_once_it_is_dropped` + (counts `Snapshot::load` tries), `a_dropped_loader_lets_go_of_its_presence_at_once` + (no waiting for the thread). +- `receipts.rs`: `a_thumbnail_is_not_written_for_a_tab_that_has_closed`. +- `jobs.rs`: the registry itself (a count lives until the thread ends, + also on a panic; a kept job is what a tab is held for). + +**Each fix was switched off to see its test fail** (a temporary +`WB_MUT=` switch at each fix, removed again): the held owner jobs (two +switches: the hold, and the cancel of the window's close; the tab's off +control and `App::close`'s guard each), the stop signal, the thumbnail +write, the export's checks, the dock start's registration, the kill of an +agent that ignores its hang-up, the dock's raw panel id (scoped, the test +fails), the viewer presence's release in `Loader::drop`, the loader's gone +check and wake before a retry, the books' identity check, the root in the +key, the named start's write of the list, the panel ids of the sidebar, +and the receipts' workers' registration: each of the tests above that +covers it failed, and passed with the fix in. Not switchable and so not +shown to fail: `preferences_written_before_the_keys_had_a_root_are_read_and_not_used` +(it passes before and after: no migration is the rule) and +`books_outside_any_data_root_are_kept_under_their_folder`, whose second +folder is also told apart by its books' identity. + +**The sidebar tests' window sizes are restored.** The status card gave back +the bar's height: its heading carries the live dot and word ("Live", +"Snapshot") at the card's right edge, the heading row is its badge's 16 high +(not a button's) and the card's vertical padding is 8. The event is not +printed in the card: it is the heading's hover ("name", "Live · event N", +the checks) and the live word's accessible label. The three check lines are +as they were before, with no event. The four `sidenav.rs` tests are at their +original sizes (1479x519, the rail at 519, the grid at 520 px, the tall +sidebar at 1440x920) with every assertion unchanged; at 1479x519 the links +have 6 px to spare in the common footers and 2 px in the failing-check ones +(where the rows tighten). The minimum window height is 400. +`the_status_card_never_wraps_in_any_state` (in `company.rs`) lays the card +out in each state (live, snapshot, each check passing, warning and failing, +folded and not) with a very long name and event 1,234,567 at the sidebar's +width (224, fixed, not resizable) and 200, and asserts every text is one row, +none runs out of the card, and the card's height is its rows plus its +padding. In `tabs.rs` the status-card test now asserts the live word sits at +the right of the name's row, no card text contains "event", and the +live word's label is "Live · event N" (it asserted the visible +"· event N" on the journal chain line); the rail test also asserts the name +leads the hover. In `sidenav.rs`, `the_folded_card_shows_its_checks_on_hover` +and the `"event "` locators still find the event, now through the live +word's label, unchanged. + ## P12: the checklists The **For P12** paragraphs above (kept where they were written, with their