diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 7da35dea..8e14ceb8 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -1,170 +1,165 @@ -//! 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. +//! 4. What is kept for next time: the open companies (`open_companies`, +//! the ids of their books, comma separated) and the one in front +//! (`active_company`); for each company its page, its report's +//! period, columns and comparison (`company..…`); and, as +//! before and under the same keys, the scheme and its filter +//! (`scheme`, `scheme_filter`, `dark`) and the dock (`dock_open`, +//! `dock_agent`, the front tab's). +//! 5. The window's title names the company in front. +//! 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::{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}; -/// 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. +pub const OPEN_KEY: &str = "open_companies"; +pub const ACTIVE_KEY: &str = "active_company"; -/// 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); - } -} - -/// 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) +/// 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, + /// 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), } +/// 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.root = ledger_store::root::root_of_book_dir(&source.data_dir) + .map(std::path::Path::to_path_buf); + app.remember_all(get); + 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) + .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) + .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 +168,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 +178,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 +198,181 @@ 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(), + dock_prefs: (None, None), + title: TITLE.to_string(), + welcome: None, + first_run_source: (None, None), + } + } + + // ---- 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 window's title now. + pub fn window_title(&self) -> String { + match self.active_view() { + Some(v) => format!("{} · {TITLE}", v.title()), + 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(id) = view.book_id() { + view.restore(&|k| self.kept.get(&format!("company.{id}.{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. + pub fn close(&mut self, i: usize) { + if i >= self.views.len() { + return; + } + let view = self.views.remove(i); + if let Some(id) = view.book_id() { + view.keep(&mut |k, v| { + self.kept.insert(format!("company.{id}.{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; + }; + for id in list_books(&root) { + for k in crate::company::KEPT_KEYS { + let key = format!("company.{id}.{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 +383,164 @@ 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 ids of the data root's companies that aren't open. + 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(); + move || { + root.as_deref() + .map(list_books) + .unwrap_or_default() + .into_iter() + .filter(|id| !open.contains(id)) + .collect() } } - /// The agent dock (tests). + /// 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, -} - -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 - } - } -} - -/// 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 +/// 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 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 +555,89 @@ 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); + } + let tabs: Vec = self + .views + .iter() + .map(|v| Tab { + title: v.title(), + detail: v.book_id().unwrap_or_else(|| v.title()), + }) + .collect(); + let shown = self.active(); + let others = self.not_open(); + let mut action = None; + // The bar goes where the front view says (beside its sidebar, which + // keeps the window's whole height), or across the window when + // there is no view. + let mut bar = |ui: &mut Ui| { + 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, &mut bar), + None => { + bar(ui); + self.empty(ui); } } - 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)); + 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 + 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); + } + } + } + // The companies open, in order, and the one in front. + let open: Vec<(String, usize)> = self + .views .iter() - .map(|(k, v)| (k.to_string(), v.to_string())) + .enumerate() + .filter_map(|(i, v)| Some((v.book_id()?, i))) .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) + storage.set_string( + OPEN_KEY, + open.iter() + .map(|(id, _)| id.as_str()) + .collect::>() + .join(","), ); - } - - #[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; + if let Some((id, _)) = open.iter().find(|(_, i)| *i == self.active) { + storage.set_string(ACTIVE_KEY, id.clone()); + } + // What was kept for the companies closed, then for those open + // (their own, as they are now). + for (k, v) in &self.kept { + storage.set_string(k, v.clone()); + } + for v in &self.views { + if let Some(id) = v.book_id() { + v.keep(&mut |k, val| storage.set_string(&format!("company.{id}.{k}"), val)); } } } - - #[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 - .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), - } - ); - 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..5ced75c5 --- /dev/null +++ b/crates/ledger-gui/src/company.rs @@ -0,0 +1,1925 @@ +//! 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. +//! 3. A view that is not shown still follows its journal and takes the +//! agent's `books.show` (its own page moves, nothing else does), so +//! showing it later is current at once. +//! 4. Dropping a view ends everything it started: its loader and its +//! watcher and viewer presence, its receipts' workers, and its +//! dock's agent process. +//! ``` + +use crate::books::Books; +use crate::data::{Loader, Source, Update}; +use crate::nav::{Nav, Route, Section}; +use crate::owner::Owner; +use crate::pages; +use crate::receipts::Receipts; +use crate::scheme_menu::SchemeMenu; +use crate::schemes; +use crate::theme::{self, pal}; +use egui::{ + Align, CornerRadius, Frame, Key, Layout, Margin, RichText, Sense, Stroke, Ui, UiBuilder, 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, +} + +/// 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)); + Self { + key, + id, + data_dir, + loader: None, + books: None, + error: None, + nav: Nav::new(Route::Overview), + receipts: Receipts::new(ctx), + state: PageState::default(), + palette: crate::palette::Palette::scoped(id), + updated_at: -1e9, + live_label: false, + menu: Default::default(), + owner_menu: crate::owner::OwnerMenu::scoped(id), + dock: Default::default(), + owner: crate::owner::current(), + prefetch_due: false, + } + } + + /// 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(source, ctx.clone())); + 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.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 tab's title: the name the books carry, else the id of the + /// books, else the folder's name. + pub fn title(&self) -> String { + let named = self + .books + .as_ref() + .map(|b| b.company_name().trim().to_string()) + .filter(|n| !n.is_empty()); + named + .or_else(|| self.book_id()) + .or_else(|| { + let dir = self.data_dir.as_deref()?; + // A demo's or a copy's folder is `books-data`: its parent + // names it. + 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(), + }) + }) + .unwrap_or_else(|| "Company".to_string()) + } + + /// 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) + } + + /// 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.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); + } + } + + /// The window: the sidebar, the top bar, the dock and the page, with + /// every id in them scoped to this view (INVARIANT 2). + /// + /// `bar` draws the app's tab bar. It goes where the sidebar has already + /// taken its column and nothing else has been laid out: along the top + /// of the rest of the window, so the sidebar keeps all the height the + /// owner's window gives it (`tests/sidenav.rs`), and in a scope of its + /// own, so the bar's ids are the app's and not this view's. + pub fn ui(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu, bar: &mut dyn FnMut(&mut Ui)) { + let id = self.id; + ui.push_id(id, |ui| self.window(ui, schemes, bar)); + } + + fn window(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu, bar: &mut dyn FnMut(&mut Ui)) { + self.handle_keys(ui); + let compact = ui.available_width() < COMPACT_BELOW; + self.sidebar(ui, schemes, compact); + // No space between the bar and what follows it (the scope's + // advance would add the item spacing: a strip of bare window). + let spacing = std::mem::take(&mut ui.spacing_mut().item_spacing); + ui.scope_builder( + UiBuilder::new().id(egui::Id::new("company_tab_bar")), + |ui| bar(ui), + ); + ui.spacing_mut().item_spacing = spacing; + 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(); + egui::Panel::left("sidebar") + .exact_size(224.0) + .resizable(false) + .frame( + Frame::new() + .fill(p.sidebar) + .inner_margin(Margin::symmetric(12, 16)), + ) + .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.label( + RichText::new("Books") + .font(theme::regular(11.5)) + .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); + } + 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, + ); + } + }); + 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(); + 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); + } + 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); + 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); + } + }); + }); + }); + }); + } +} + +/// The keys a view keeps its things under (after `company..`). +pub(crate) const KEPT_KEYS: [&str; 4] = ["page", "range", "columns", "compare"]; + +impl CompanyView { + /// 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(), + ); + } + + /// 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}; + 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 = 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, +} + +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 + } + } +} + +/// 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 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 +} + +#[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 event + // and the word "Live" have. + assert!( + lines + .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), + } + ); + 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] + ); + } +} diff --git a/crates/ledger-gui/src/data.rs b/crates/ledger-gui/src/data.rs index b7794ff3..744a3a7c 100644 --- a/crates/ledger-gui/src/data.rs +++ b/crates/ledger-gui/src/data.rs @@ -39,24 +39,63 @@ pub struct Loader { /// 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, + /// 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, +} + +/// Says whether a loader's thread has ended, after the loader is gone. +#[derive(Clone)] +pub struct LoaderWatch(Arc); + +impl LoaderWatch { + /// 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); + let _ = self.wake.send(()); } } impl Loader { pub fn spawn(source: Source, ctx: egui::Context) -> Loader { 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 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 || { + let _ends = ends; + run(source, ctx, tx, &stop, wake_to_watcher, events) + }) .expect("spawn loader"); - Loader { rx, gone } + Loader { + rx, + gone, + wake, + ended, + } } /// Every update since the last call, in order (books before the @@ -69,6 +108,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()) + } } /// Load once, synchronously (tests and one-shot tools). @@ -123,6 +172,8 @@ fn run( ctx: egui::Context, tx: Sender, gone: &std::sync::atomic::AtomicBool, + ev_tx: Sender<()>, + ev_rx: Receiver<()>, ) { let gone = || gone.load(std::sync::atomic::Ordering::SeqCst); let send = |u: Update| { @@ -180,7 +231,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(()); @@ -225,6 +275,10 @@ fn run( 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, diff --git a/crates/ledger-gui/src/dock.rs b/crates/ledger-gui/src/dock.rs index 68591d20..ee02a715 100644 --- a/crates/ledger-gui/src/dock.rs +++ b/crates/ledger-gui/src/dock.rs @@ -466,6 +466,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 { diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index 3f40ffaa..b3b57a33 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -7,6 +7,7 @@ pub mod app; pub mod attention; pub mod books; pub mod charts; +pub mod company; pub mod data; pub mod demo; pub mod dock; @@ -19,14 +20,17 @@ pub mod pages; pub mod palette; mod prefs; mod receipts; +mod scheme_menu; mod schemes; +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 +56,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 +106,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 +151,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/owner.rs b/crates/ledger-gui/src/owner.rs index 14af7717..518614dc 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -204,6 +204,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 +218,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() } @@ -307,6 +308,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)>, @@ -325,6 +329,14 @@ pub struct OwnerMenu { const UPDATE_LOOK: std::time::Duration = std::time::Duration::from_secs(5); impl OwnerMenu { + /// A menu whose ids belong to the view `scope`. + pub fn scoped(scope: egui::Id) -> Self { + Self { + scope: Some(scope), + ..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 +367,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 { @@ -447,8 +459,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 { @@ -636,11 +654,18 @@ 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, + &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| { @@ -656,30 +681,31 @@ 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(), + 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 +725,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)."); @@ -794,13 +820,14 @@ 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, 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); 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/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/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..bb7a1e34 --- /dev/null +++ b/crates/ledger-gui/src/tabs.rs @@ -0,0 +1,399 @@ +//! 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. +//! +//! ```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 name (the id of its books until the name 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), and says so when there are +//! none. +//! 5. Tabs never overlap or leave the bar: they shrink to a least +//! width, then the strip scrolls, with a step control at each end +//! that is clipped; the tab shown is scrolled into view when it +//! changes. +//! 6. This only says what was asked (show, close, open); the app does +//! it. +//! ``` + +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. +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 = 220.0; +const TAB_MIN: f32 = 120.0; +/// The close control's size. +const CLOSE: f32 = 20.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 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. `shown` is the tab in front, if there is one; `others` + /// reads the ids of the root's companies 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() + .fill(p.sidebar) + .inner_margin(Margin::symmetric(8, 0)) + .stroke(Stroke::new(1.0, p.border)), + ) + .show(ui, |ui| { + ui.spacing_mut().item_spacing = vec2(2.0, 0.0); + let bar = ui.max_rect(); + // The "+" at the right end, always whole; the tabs get the + // rest. + let plus_w = 30.0; + let strip_w = (ui.available_width() - plus_w - 6.0).max(0.0); + 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, shown, &mut reveal, &mut action); + let plus = egui::Rect::from_min_size( + egui::pos2(strip.right() + 6.0, 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. + fn strip( + &mut self, + ui: &mut Ui, + tabs: &[Tab], + shown: Option, + reveal: &mut bool, + action: &mut Option, + ) { + let p = pal(ui.ctx()); + let room = ui.available_width(); + let n = tabs.len().max(1) as f32; + let each = ((room - (n - 1.0) * 2.0) / n).clamp(TAB_MIN, TAB_MAX); + let overflows = each * n + (n - 1.0) * 2.0 > room + 0.5; + // A step control at each end while the tabs overflow. + let step_w = if overflows { 22.0 } else { 0.0 }; + 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 = -each; + } + } + 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 = 2.0; + ui.horizontal_top(|ui| { + for (i, tab) in tabs.iter().enumerate() { + let here = shown == Some(i); + let r = one_tab(ui, i, tab, here, each, &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 + each).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.muted)) + .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(200.0); + 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.as_slice()) + .unwrap_or(&[]); + if list.is_empty() { + ui.label( + RichText::new("Every company here is 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 id in list { + if ui.button(id).clicked() { + *action = Some(TabAction::Open(id.clone())); + ui.close(); + } + } + } + }); + // Forget the list once it is closed, so it is read afresh. + if open.is_none() { + self.listed = None; + } + response.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Open another company") + }); + response.on_hover_text("Open another company"); + } +} + +/// 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, + ); +} + +/// 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 - 6.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() - 6.0 - 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, + true, + 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, + }; + let fill = if here { + Some(p.bg) + } else if resp.hovered() || close.hovered() { + Some(p.hover) + } else { + None + }; + if let Some(fill) = fill { + painter.rect_filled(rect, top, fill); + } + if here { + // A bar along the top edge and the page's own fill: the tab + // in front is part of the page below it. + painter.rect_filled( + egui::Rect::from_min_size(rect.min, vec2(rect.width(), 3.0)), + CornerRadius { + nw: 8, + ne: 8, + sw: 0, + se: 0, + }, + p.accent, + ); + painter.rect_filled( + egui::Rect::from_min_max( + egui::pos2(rect.left(), rect.bottom() - 1.0), + egui::pos2(rect.right(), rect.bottom() + 1.0), + ), + 0.0, + p.bg, + ); + } + let font = if here { + theme::semibold(13.0) + } else { + theme::regular(13.0) + }; + let text_w = rect.width() - 14.0 - CLOSE - 10.0; + let mut job = egui::text::LayoutJob::single_section( + tab.title.clone(), + egui::TextFormat::simple(font, if here { p.text } else { p.muted }), + ); + 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( + rect.left() + 14.0, + rect.center().y - galley.size().y / 2.0 + 1.0, + ), + galley, + p.text, + ); + if close.hovered() { + 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 close.hovered() { 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. + if close + .on_hover_text(format!("Close {}", tab.title)) + .clicked() + || resp.middle_clicked() + { + *action = Some(TabAction::Close(i)); + } else if resp.clicked() { + *action = Some(TabAction::Show(i)); + } + resp +}