merge: P15 A3a, the viewer is one window with a tab per open company

The viewer was a read-only window on one company per process. D-78 makes
a company reachable exactly while it has a tab, so the window now holds
one tab per open company, each with its own loader, navigation, page
state and assistant dock, and nothing shared between them. The company
is named once in the frame, on its tab; the status card at the foot of
the sidebar carries its badge and name with the live state; each company
has its own badge colour. A restore or a format upgrade in progress is
never abandoned by closing its tab or the window. The viewer still
writes nothing to the books.

docs/testing.md: both units added their test records at the end; both
are kept.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-20 20:30:01 -07:00
commit b994a901bf
39 files changed
+8450 -1932

No files matched your search

Generated
+1
View File
@@ -3973,6 +3973,7 @@ dependencies = [
"ledger-package", "ledger-package",
"ledger-store", "ledger-store",
"ledger-vault", "ledger-vault",
"libc",
"notify", "notify",
"proptest", "proptest",
"rust_decimal", "rust_decimal",
+5
View File
@@ -40,6 +40,11 @@ zeroize = "1"
# The dock: a terminal emulator over a PTY (ConPTY on Windows), P11b # The dock: a terminal emulator over a PTY (ConPTY on Windows), P11b
alacritty_terminal = "0.26" alacritty_terminal = "0.26"
[target.'cfg(unix)'.dependencies]
# The dock ends a dropped session's child that ignores the hang-up (dock.rs
# INVARIANT 8): a SIGKILL to the pid this crate's own PTY started.
libc = "0.2"
[dev-dependencies] [dev-dependencies]
chrono = "0.4" chrono = "0.4"
egui_kittest = { version = "0.36", features = ["wgpu", "snapshot", "eframe"] } egui_kittest = { version = "0.36", features = ["wgpu", "snapshot", "eframe"] }
+686 -1819
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+178 -13
View File
@@ -34,29 +34,135 @@ pub enum Update {
Show(ledger_store::ops::ViewerTarget), Show(ledger_store::ops::ViewerTarget),
} }
/// The viewer's presence on the books (`ledger_store::ops::Presence`), held
/// by the loader's thread and let go by whichever comes first: the thread's
/// end, or the loader's drop (so a tab's close releases it at once, not
/// when a refresh in flight is over).
type PresenceSlot = Arc<std::sync::Mutex<Option<ledger_store::ops::Presence>>>;
/// What a loader's thread says of itself, for tests.
#[derive(Default)]
pub struct Probe {
attempts: std::sync::atomic::AtomicUsize,
/// Set while the thread waits to try the books again.
waiting: std::sync::atomic::AtomicBool,
}
pub struct Loader { pub struct Loader {
rx: Receiver<Update>, rx: Receiver<Update>,
/// Set when this is dropped: the loader's thread then ends, letting go /// Set when this is dropped: the loader's thread then ends, letting go
/// of the books (and the viewer's presence on them). /// of the books (and the viewer's presence on them).
gone: Arc<std::sync::atomic::AtomicBool>, gone: Arc<std::sync::atomic::AtomicBool>,
/// The viewer's presence, shared with the thread (INVARIANT: let go in
/// `drop`, taken by the thread only while `gone` is not set).
presence: PresenceSlot,
/// Wakes the thread at once when this is dropped, so it ends now and
/// not at its next look.
wake: Sender<()>,
/// Set by the thread as it ends.
ended: Arc<std::sync::atomic::AtomicBool>,
/// Counted by the thread at every full load it tries.
attempts: Arc<Probe>,
}
/// Says whether a loader's thread has ended, after the loader is gone.
#[derive(Clone)]
pub struct LoaderWatch(Arc<std::sync::atomic::AtomicBool>, Arc<Probe>);
impl LoaderWatch {
/// How many times the thread tried to load the books in full
/// (`Snapshot::load`), the first included (tests: a dropped loader
/// tries no more).
pub fn load_attempts(&self) -> usize {
self.1.attempts.load(std::sync::atomic::Ordering::SeqCst)
}
/// Whether the thread is waiting to try the books again, after one
/// that failed (tests: drop the loader then, with certainty).
pub fn waiting(&self) -> bool {
self.1.waiting.load(std::sync::atomic::Ordering::SeqCst)
}
/// Whether the thread has ended: its watcher, its hold on the books
/// and its viewer presence are released.
pub fn ended(&self) -> bool {
self.0.load(std::sync::atomic::Ordering::SeqCst)
}
}
/// Sets the flag when the loader's thread ends, however it ends.
struct Ends(Arc<std::sync::atomic::AtomicBool>);
impl Drop for Ends {
fn drop(&mut self) {
self.0.store(true, std::sync::atomic::Ordering::SeqCst);
}
} }
impl Drop for Loader { impl Drop for Loader {
fn drop(&mut self) { fn drop(&mut self) {
self.gone.store(true, std::sync::atomic::Ordering::SeqCst); self.gone.store(true, std::sync::atomic::Ordering::SeqCst);
// The viewer's presence goes now: the thread may be inside a
// refresh that takes a while, and the books are no longer looked
// at. The thread takes a presence only while `gone` is unset,
// under this lock, so none is taken after this.
drop(
self.presence
.lock()
.unwrap_or_else(|e| e.into_inner())
.take(),
);
let _ = self.wake.send(());
} }
} }
impl Loader { impl Loader {
/// A loader that no tab owns (tests, one-shot tools).
pub fn spawn(source: Source, ctx: egui::Context) -> Loader { pub fn spawn(source: Source, ctx: egui::Context) -> Loader {
Self::spawn_in(source, ctx, &crate::jobs::Spawner::default())
}
/// A loader whose thread is one of a tab's: counted in `jobs` until it
/// has ended (jobs.rs INVARIANT 1).
pub fn spawn_in(source: Source, ctx: egui::Context, jobs: &crate::jobs::Spawner) -> Loader {
let ticket = jobs.ticket("books-loader", crate::jobs::Hold::Free);
let presence: PresenceSlot = Arc::default();
let thread_presence = presence.clone();
let (tx, rx) = channel(); let (tx, rx) = channel();
let (wake, events) = channel();
let gone = Arc::new(std::sync::atomic::AtomicBool::new(false)); let gone = Arc::new(std::sync::atomic::AtomicBool::new(false));
let ended = Arc::new(std::sync::atomic::AtomicBool::new(false));
let attempts = Arc::new(Probe::default());
let thread_attempts = attempts.clone();
let stop = gone.clone(); let stop = gone.clone();
let ends = Ends(ended.clone());
let wake_to_watcher = wake.clone();
std::thread::Builder::new() std::thread::Builder::new()
.name("books-loader".into()) .name("books-loader".into())
.spawn(move || run(source, ctx, tx, &stop)) .spawn(move || {
// Dropped last: the thread has let go of everything.
let _ticket = ticket;
let _ends = ends;
run(
source,
ctx,
tx,
&stop,
&thread_presence,
&thread_attempts,
wake_to_watcher,
events,
)
})
.expect("spawn loader"); .expect("spawn loader");
Loader { rx, gone } Loader {
rx,
gone,
presence,
wake,
ended,
attempts,
}
} }
/// Every update since the last call, in order (books before the /// Every update since the last call, in order (books before the
@@ -69,6 +175,16 @@ impl Loader {
pub fn wait(&self, timeout: Duration) -> Option<Update> { pub fn wait(&self, timeout: Duration) -> Option<Update> {
self.rx.recv_timeout(timeout).ok() self.rx.recv_timeout(timeout).ok()
} }
/// Whether the thread has ended (it ends once this is dropped).
pub fn finished(&self) -> bool {
self.ended.load(std::sync::atomic::Ordering::SeqCst)
}
/// A handle that outlives the loader and says when its thread ended.
pub fn watch(&self) -> LoaderWatch {
LoaderWatch(self.ended.clone(), self.attempts.clone())
}
} }
/// Load once, synchronously (tests and one-shot tools). /// Load once, synchronously (tests and one-shot tools).
@@ -118,31 +234,56 @@ pub fn settings(snap: &Snapshot) -> BooksSettings {
) )
} }
#[allow(clippy::too_many_arguments)]
fn run( fn run(
source: Source, source: Source,
ctx: egui::Context, ctx: egui::Context,
tx: Sender<Update>, tx: Sender<Update>,
gone: &std::sync::atomic::AtomicBool, gone: &std::sync::atomic::AtomicBool,
presence: &PresenceSlot,
attempts: &Probe,
ev_tx: Sender<()>,
ev_rx: Receiver<()>,
) { ) {
let gone = || gone.load(std::sync::atomic::Ordering::SeqCst); let gone = || gone.load(std::sync::atomic::Ordering::SeqCst);
let send = |u: Update| { let send = |u: Update| {
let _ = tx.send(u); let _ = tx.send(u);
ctx.request_repaint(); ctx.request_repaint();
}; };
// Gone is looked at before every try and between the phases of a load
// (the load itself, the picture built from it, the send): a tab closed
// while the books can't be read costs no further load.
let mut snap = loop { let mut snap = loop {
match Snapshot::load(&source.data_dir) {
Ok(s) => break s,
Err(e) => {
send(Update::Error(problem(&e, || {
format!("Can't read the books in {}", source.data_dir.display())
})));
if gone() { if gone() {
return; return;
} }
std::thread::sleep(Duration::from_secs(2)); attempts
.attempts
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
match Snapshot::load(&source.data_dir) {
Ok(s) => break s,
Err(e) => {
if gone() {
return;
}
send(Update::Error(problem(&e, || {
format!("Can't read the books in {}", source.data_dir.display())
})));
// Woken at once by the loader's drop, not at the next try.
attempts
.waiting
.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = ev_rx.recv_timeout(Duration::from_secs(2));
attempts
.waiting
.store(false, std::sync::atomic::Ordering::SeqCst);
while ev_rx.try_recv().is_ok() {}
} }
} }
}; };
if gone() {
return;
}
let mut verified: HashSet<String> = HashSet::new(); let mut verified: HashSet<String> = HashSet::new();
// Build the picture; also return the database check it was built with. // Build the picture; also return the database check it was built with.
let mut build = |snap: &Snapshot, prev: Option<u64>| -> (Update, ledger_store::DiskCheck) { let mut build = |snap: &Snapshot, prev: Option<u64>| -> (Update, ledger_store::DiskCheck) {
@@ -158,6 +299,9 @@ fn run(
}; };
let (first, disk) = build(&snap, None); let (first, disk) = build(&snap, None);
let mut last_disk = Some(disk); let mut last_disk = Some(disk);
if gone() {
return;
}
send(first); send(first);
// Requests to show something: apply new ones, and on start one made in // Requests to show something: apply new ones, and on start one made in
@@ -180,7 +324,6 @@ fn run(
}; };
check_show(&send); check_show(&send);
let (ev_tx, ev_rx) = channel();
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| { let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if res.is_ok() { if res.is_ok() {
let _ = ev_tx.send(()); let _ = ev_tx.send(());
@@ -195,7 +338,6 @@ fn run(
// held there while it runs (ledger_store::ops INVARIANT 3). // held there while it runs (ledger_store::ops INVARIANT 3).
let ops = ledger_store::ops::ops_dir(&source.data_dir); let ops = ledger_store::ops::ops_dir(&source.data_dir);
let mut ops_watched = false; let mut ops_watched = false;
let mut presence: Option<ledger_store::ops::Presence> = None;
let mut look_at_ops = |watcher: &mut Option<notify::RecommendedWatcher>| { let mut look_at_ops = |watcher: &mut Option<notify::RecommendedWatcher>| {
if !ops_watched if !ops_watched
&& ops.is_dir() && ops.is_dir()
@@ -203,10 +345,17 @@ fn run(
{ {
ops_watched = w.watch(&ops, RecursiveMode::NonRecursive).is_ok(); ops_watched = w.watch(&ops, RecursiveMode::NonRecursive).is_ok();
} }
if presence.is_none() { // Taken under the slot's lock and only while not gone: the
presence = ledger_store::ops::Presence::hold(&source.data_dir); // loader's drop sets `gone` and then empties the slot, so a
// presence is never taken after a tab closed.
let mut held = presence.lock().unwrap_or_else(|e| e.into_inner());
if held.is_none() && !gone() {
*held = ledger_store::ops::Presence::hold(&source.data_dir);
} }
}; };
if gone() {
return;
}
look_at_ops(&mut watcher); look_at_ops(&mut watcher);
let day_now = |snap: &Snapshot| today(&source, &settings(snap)); let day_now = |snap: &Snapshot| today(&source, &settings(snap));
let mut day = day_now(&snap); let mut day = day_now(&snap);
@@ -222,9 +371,16 @@ fn run(
} }
Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => { Err(RecvTimeoutError::Disconnected) => {
if gone() {
return;
}
std::thread::sleep(Duration::from_secs(3)); 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 before = snap.journal_seq();
let grew = match snap.refresh() { let grew = match snap.refresh() {
Ok(n) => n > 0, Ok(n) => n > 0,
@@ -235,6 +391,9 @@ fn run(
continue; continue;
} }
}; };
if gone() {
return;
}
look_at_ops(&mut watcher); look_at_ops(&mut watcher);
let new_day = day_now(&snap); let new_day = day_now(&snap);
// The writer journals first and updates its database right after: // The writer journals first and updates its database right after:
@@ -248,8 +407,14 @@ fn run(
day = new_day; day = new_day;
let (update, disk) = build(&snap, grew.then_some(before)); let (update, disk) = build(&snap, grew.then_some(before));
last_disk = Some(disk); last_disk = Some(disk);
if gone() {
return;
}
send(update); send(update);
} }
if gone() {
return;
}
check_show(&send); check_show(&send);
} }
} }
+135 -11
View File
@@ -30,6 +30,23 @@
//! 7. Offered only where it has been checked to work (Linux and macOS): //! 7. Offered only where it has been checked to work (Linux and macOS):
//! a ConPTY agent on Windows must pass the four checks (it starts, //! a ConPTY agent on Windows must pass the four checks (it starts,
//! `/login` works, resize redraws, Ctrl-C reaches it) before it is. //! `/login` works, resize redraws, Ctrl-C reaches it) before it is.
//! 8. The agent belongs to its tab. The start (finding the agent and
//! making its books home, off the UI thread) is one of the tab's
//! threads (jobs.rs) and is told to stop with it; the child process
//! is started only by a tab that is shown, on the UI thread, once
//! the start's answer is in, so a tab closed mid-start starts none.
//! A session dropped (its tab closed, the agent restarted) is shut
//! down, its child hung up on (SIGHUP) and reaped, its terminal
//! closed; one that has not gone [`AGENT_GRACE`] later is killed
//! (SIGKILL, that pid alone, which this dock started) and reaped.
//! The reaping is a thread of the tab's, so the tab can say when
//! nothing of its agent is left (`CompanyView::jobs_watch`).
//! 9. The panel's height, and whether the dock is open by default, are
//! the app's, not a tab's: one layout for the assistant dock in
//! every tab. egui keys a panel's size by its id as given, `push_id`
//! scoping notwithstanding, so the panel's raw ids ("dock-open",
//! "dock-closed") are the one place the tabs share; that is the
//! rule, said and tested (`tests/tabs.rs`).
//! ``` //! ```
use crate::owner::{Agent, AgentStart, Installer, Owner}; use crate::owner::{Agent, AgentStart, Installer, Owner};
@@ -133,8 +150,65 @@ pub struct Session {
cells: Cells, cells: Cells,
exited: Arc<AtomicBool>, exited: Arc<AtomicBool>,
title: Arc<Mutex<String>>, title: Arc<Mutex<String>>,
/// The child's process id (this session started it).
pid: u32,
/// Waits for the event loop's thread to end and drops what it returns,
/// the PTY with it (which hangs up on the child and reaps it).
end: Option<Box<dyn FnOnce() + Send>>,
/// The session's count in its tab's threads, until it is reaped.
ticket: Option<crate::jobs::Ticket>,
} }
/// How long a dropped session's child has to end after the hang-up before
/// it is killed (INVARIANT 8).
pub const AGENT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
/// End a dropped session's child: wait for its hang-up to be answered,
/// kill it if it is not within [`AGENT_GRACE`], and reap it (INVARIANT 8).
fn reap(end: Box<dyn FnOnce() + Send>, pid: u32, ticket: Option<crate::jobs::Ticket>) {
let work = move || {
let _ticket = ticket;
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
// The hang-up and the wait for the child are the PTY's drop: it
// blocks for as long as the child does not end.
let dropper = std::thread::Builder::new()
.name("dock-pty-drop".into())
.spawn(move || {
end();
let _ = done_tx.send(());
});
let Ok(dropper) = dropper else {
return;
};
if done_rx.recv_timeout(AGENT_GRACE).is_err() {
kill(pid);
}
let _ = dropper.join();
};
// Without a thread to do it on, it is not done at all (the process is
// ending, or the system is out of threads): the PTY's own drop at
// thread end still hangs up.
let _ = std::thread::Builder::new()
.name("dock-reaper".into())
.spawn(work);
}
/// SIGKILL the child this dock started and has hung up on.
#[cfg(unix)]
fn kill(pid: u32) {
if let Ok(pid) = libc::pid_t::try_from(pid) {
// SAFETY: a plain signal to the pid of a child this process
// started and has not yet reaped (its PTY's drop is still
// waiting for it).
unsafe {
libc::kill(pid, libc::SIGKILL);
}
}
}
#[cfg(not(unix))]
fn kill(_pid: u32) {}
impl Session { impl Session {
/// Run `program args` in `dir` with `env` added, on a terminal of `cells`; /// Run `program args` in `dir` with `env` added, on a terminal of `cells`;
/// `wake` is called when there is something new to draw. /// `wake` is called when there is something new to draw.
@@ -145,6 +219,7 @@ impl Session {
env: &[(String, String)], env: &[(String, String)],
cells: Cells, cells: Cells,
wake: Arc<dyn Fn() + Send + Sync>, wake: Arc<dyn Fn() + Send + Sync>,
jobs: &crate::jobs::Spawner,
) -> Result<Session, String> { ) -> Result<Session, String> {
let window = WindowSize { let window = WindowSize {
num_lines: cells.rows, num_lines: cells.rows,
@@ -163,7 +238,9 @@ impl Session {
#[cfg(windows)] #[cfg(windows)]
escape_args: true, escape_args: true,
}; };
let ticket = jobs.ticket("dock agent", crate::jobs::Hold::Free);
let pty = tty::new(&options, window, 0).map_err(|e| e.to_string())?; let pty = tty::new(&options, window, 0).map_err(|e| e.to_string())?;
let pid = pty.child().id();
let exited = Arc::new(AtomicBool::new(false)); let exited = Arc::new(AtomicBool::new(false));
let to_pty = Arc::new(Mutex::new(None)); let to_pty = Arc::new(Mutex::new(None));
let size = Arc::new(Mutex::new(window)); let size = Arc::new(Mutex::new(window));
@@ -184,8 +261,9 @@ impl Session {
EventLoop::new(term.clone(), proxy, pty, true, false).map_err(|e| e.to_string())?; EventLoop::new(term.clone(), proxy, pty, true, false).map_err(|e| e.to_string())?;
let sender = event_loop.channel(); let sender = event_loop.channel();
*to_pty.lock().unwrap_or_else(|e| e.into_inner()) = Some(sender.clone()); *to_pty.lock().unwrap_or_else(|e| e.into_inner()) = Some(sender.clone());
// Its thread ends on Shutdown, and its terminal's child with it. // Its thread ends on Shutdown, and its terminal's child with it
drop(event_loop.spawn()); // (its drop, reaped by `reap`).
let handle = event_loop.spawn();
Ok(Session { Ok(Session {
term, term,
to_pty: sender, to_pty: sender,
@@ -193,6 +271,9 @@ impl Session {
cells, cells,
exited, exited,
title, title,
pid,
end: Some(Box::new(move || drop(handle.join()))),
ticket: Some(ticket),
}) })
} }
@@ -254,6 +335,9 @@ impl Session {
impl Drop for Session { impl Drop for Session {
fn drop(&mut self) { fn drop(&mut self) {
let _ = self.to_pty.send(Msg::Shutdown); let _ = self.to_pty.send(Msg::Shutdown);
if let Some(end) = self.end.take() {
reap(end, self.pid, self.ticket.take());
}
} }
} }
@@ -466,6 +550,15 @@ impl Default for Dock {
} }
impl Dock { 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. /// The dock as kept: the `agent` key and the `open` flag.
pub fn restored(get: impl Fn(&str) -> Option<String>) -> Dock { pub fn restored(get: impl Fn(&str) -> Option<String>) -> Dock {
Dock { Dock {
@@ -513,19 +606,43 @@ impl Dock {
/// Start (or restart) the agent for `book`: found and its books home /// Start (or restart) the agent for `book`: found and its books home
/// made off the UI thread, then run. /// made off the UI thread, then run.
fn start(&mut self, ctx: &egui::Context, owner: &Arc<dyn Owner>, book: &str) { fn start(
&mut self,
ctx: &egui::Context,
owner: &Arc<dyn Owner>,
book: &str,
jobs: &crate::jobs::Spawner,
) {
let (tx, rx) = channel(); let (tx, rx) = channel();
let (o, agent, b, ctx) = (owner.clone(), self.agent, book.to_string(), ctx.clone()); let (o, agent, b, ctx) = (owner.clone(), self.agent, book.to_string(), ctx.clone());
std::thread::spawn(move || { let started = jobs.spawn("agent start", crate::jobs::Hold::Free, move |stop| {
let _ = tx.send(o.agent_start(agent, &b)); if stop.requested() {
return;
}
let answer = o.agent_start(agent, &b);
// Its tab closed meanwhile: the answer is nobody's.
if stop.requested() {
return;
}
let _ = tx.send(answer);
ctx.request_repaint(); ctx.request_repaint();
}); });
self.state = State::Starting(rx); self.state = if started {
State::Starting(rx)
} else {
State::Failed("the system gave no thread to start it".into())
};
self.book = Some(book.to_string()); self.book = Some(book.to_string());
} }
/// The panel along the bottom of the window, for `book`'s agent. /// The panel along the bottom of the window, for `book`'s agent.
pub fn show(&mut self, ui: &mut Ui, owner: &Arc<dyn Owner>, book: &str) { pub fn show(
&mut self,
ui: &mut Ui,
owner: &Arc<dyn Owner>,
book: &str,
jobs: &crate::jobs::Spawner,
) {
let p = crate::theme::pal(ui.ctx()); let p = crate::theme::pal(ui.ctx());
// Another book is shown: its own agent, not the last one's. // Another book is shown: its own agent, not the last one's.
if self.book.as_deref().is_some_and(|b| b != book) { if self.book.as_deref().is_some_and(|b| b != book) {
@@ -556,6 +673,7 @@ impl Dock {
rows: 24, rows: 24,
}, },
wake, wake,
jobs,
) { ) {
Ok(s) => { Ok(s) => {
self.focused = true; self.focused = true;
@@ -569,7 +687,7 @@ impl Dock {
}; };
} }
if self.open && matches!(self.state, State::Idle) { if self.open && matches!(self.state, State::Idle) {
self.start(ui.ctx(), owner, book); self.start(ui.ctx(), owner, book, jobs);
} }
let header = 34.0; let header = 34.0;
let panel = // Its own id open and closed: a size is remembered for each. let panel = // Its own id open and closed: a size is remembered for each.
@@ -591,7 +709,7 @@ impl Dock {
if self.open { if self.open {
ui.set_min_height(ui.available_height()); ui.set_min_height(ui.available_height());
} }
self.header(ui, owner, book); self.header(ui, owner, book, jobs);
if !self.open { if !self.open {
return; return;
} }
@@ -600,7 +718,13 @@ impl Dock {
}); });
} }
fn header(&mut self, ui: &mut Ui, owner: &Arc<dyn Owner>, book: &str) { fn header(
&mut self,
ui: &mut Ui,
owner: &Arc<dyn Owner>,
book: &str,
jobs: &crate::jobs::Spawner,
) {
let p = crate::theme::pal(ui.ctx()); let p = crate::theme::pal(ui.ctx());
let mut restart = false; let mut restart = false;
ui.horizontal(|ui| { ui.horizontal(|ui| {
@@ -673,7 +797,7 @@ impl Dock {
}); });
if restart { if restart {
self.state = State::Idle; self.state = State::Idle;
self.start(ui.ctx(), owner, book); self.start(ui.ctx(), owner, book, jobs);
} }
} }
+322
View File
@@ -0,0 +1,322 @@
//! One owner for every background thread a tab starts.
//!
//! ```text
//! GOAL: a tab's threads (its loader, its receipts' workers, an export, an
//! owner's job, the dock's start and its agent's reaper) have one
//! owner that can tell them all to stop when the tab closes, and say
//! when every one of them has ended; and a job that must not be cut
//! off (an owner's change to the books) holds the tab and the window
//! open until it is done.
//! SOURCE: plan/p15-app-and-relay.md 3.2 (closing a tab ends what the tab
//! started); WB-GUI-2 (the viewer never abandons a change to the
//! books).
//! INVARIANTS:
//! 1. Every thread started through a [`Spawner`] is counted from before
//! it starts until it has ended, however it ends (a panic too): the
//! count is its [`Ticket`], dropped last.
//! 2. [`Jobs`] is dropped (or [`Jobs::stop`]ped) with its tab: every
//! [`Stop`] it handed out then says so, for good. A thread checks it
//! at its phase boundaries and between files, and stops there.
//! 3. A [`Watch`] outlives the tab and says, on a condition and not by
//! looking now and then, when no thread of the tab is left
//! ([`Watch::wait_ended`]).
//! 4. A thread started with [`Hold::Keep`] is one the tab's close
//! control and the window's close are held for: [`Jobs::holding`]
//! says what is running, in the words the close control shows.
//! ```
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant};
/// Whether a running thread may be cut off.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Hold {
/// It may: it is told to stop when its tab closes.
Free,
/// It may not: the tab and the window stay open until it ends. The
/// words say what is running ("Restoring these books: wait for it
/// to finish").
Keep(String),
}
struct Live {
id: u64,
name: String,
hold: Hold,
}
#[derive(Default)]
struct Table {
next: u64,
live: Vec<Live>,
}
struct Shared {
stop: AtomicBool,
table: Mutex<Table>,
ended: Condvar,
}
impl Shared {
fn new() -> Arc<Shared> {
Arc::new(Shared {
stop: AtomicBool::new(false),
table: Mutex::new(Table::default()),
ended: Condvar::new(),
})
}
fn table(&self) -> MutexGuard<'_, Table> {
self.table.lock().unwrap_or_else(|e| e.into_inner())
}
}
/// A tab's threads, and the means to stop them. Dropping it tells every
/// thread to stop (INVARIANT 2).
pub struct Jobs(Spawner);
/// A handle for starting threads in a tab's [`Jobs`] (cloneable; it does
/// not stop anything when dropped).
#[derive(Clone)]
pub struct Spawner(Arc<Shared>);
/// Tells a thread to stop (INVARIANT 2).
#[derive(Clone)]
pub struct Stop(Arc<Shared>, Option<Arc<std::sync::atomic::AtomicUsize>>);
/// The count of one thread: held from before it starts to after it ends.
pub struct Ticket {
shared: Arc<Shared>,
id: u64,
}
/// Says when a tab's threads have ended, after the tab is gone.
#[derive(Clone)]
pub struct Watch(Arc<Shared>);
impl Default for Jobs {
fn default() -> Self {
Self::new()
}
}
impl Jobs {
pub fn new() -> Jobs {
Jobs(Spawner(Shared::new()))
}
/// A handle to start threads with.
pub fn spawner(&self) -> Spawner {
self.0.clone()
}
/// Tell every thread to stop, now and for good.
pub fn stop(&self) {
self.0.0.stop.store(true, Ordering::SeqCst);
}
/// A handle that outlives the tab and says when its threads ended.
pub fn watch(&self) -> Watch {
Watch(self.0.0.clone())
}
/// The names of the threads running now.
pub fn running(&self) -> Vec<String> {
self.watch().running()
}
/// What the tab is held open for, if a [`Hold::Keep`] thread runs
/// (INVARIANT 4): its words.
pub fn holding(&self) -> Option<String> {
self.0.holding()
}
}
impl Drop for Jobs {
fn drop(&mut self) {
self.stop();
}
}
impl Default for Spawner {
/// A handle to a registry of its own that nothing owns: nothing ever
/// tells its threads to stop (a menu made outside a tab, in tests).
fn default() -> Self {
Spawner(Shared::new())
}
}
impl Spawner {
/// The stop signal of this registry.
pub fn stop_signal(&self) -> Stop {
Stop(self.0.clone(), None)
}
/// Count a thread to be started; the count ends when the ticket is
/// dropped.
pub fn ticket(&self, name: &str, hold: Hold) -> Ticket {
let mut table = self.0.table();
let id = table.next;
table.next += 1;
table.live.push(Live {
id,
name: name.to_string(),
hold,
});
Ticket {
shared: self.0.clone(),
id,
}
}
/// Run `work` on a thread of its own, counted (INVARIANT 1). It is
/// handed the stop signal to check at its phase boundaries. False when
/// the system refused the thread (nothing runs, nothing is counted).
pub fn spawn(&self, name: &str, hold: Hold, work: impl FnOnce(&Stop) + Send + 'static) -> bool {
let ticket = self.ticket(name, hold);
let stop = self.stop_signal();
std::thread::Builder::new()
.name(name.to_string())
.spawn(move || {
// Dropped last, whatever happens in `work`.
let _ticket = ticket;
work(&stop);
})
.is_ok()
}
/// What is held open for, if a [`Hold::Keep`] thread runs.
pub fn holding(&self) -> Option<String> {
self.0.table().live.iter().find_map(|l| match &l.hold {
Hold::Keep(words) => Some(words.clone()),
Hold::Free => None,
})
}
}
impl Stop {
/// Whether the tab asked for its threads to stop.
pub fn requested(&self) -> bool {
if self.0.stop.load(Ordering::SeqCst) {
return true;
}
// A signal that trips after so many looks (tests).
self.1.as_ref().is_some_and(|left| {
left.try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
.is_err()
})
}
/// A signal that is not given until it has been looked at `looks`
/// times, and is given at the next (tests: a job's every phase
/// boundary, one after another).
pub fn given_after(looks: usize) -> Stop {
Stop(
Shared::new(),
Some(Arc::new(std::sync::atomic::AtomicUsize::new(looks))),
)
}
/// A signal already given (tests of what a thread does once told to
/// stop).
pub fn given() -> Stop {
let shared = Shared::new();
shared.stop.store(true, Ordering::SeqCst);
Stop(shared, None)
}
/// A signal never given (what runs outside a tab).
pub fn never() -> Stop {
Stop(Shared::new(), None)
}
}
impl Drop for Ticket {
fn drop(&mut self) {
let mut table = self.shared.table();
table.live.retain(|l| l.id != self.id);
drop(table);
self.shared.ended.notify_all();
}
}
impl Watch {
/// The names of the threads running now.
pub fn running(&self) -> Vec<String> {
self.0.table().live.iter().map(|l| l.name.clone()).collect()
}
/// Whether every thread has ended.
pub fn ended(&self) -> bool {
self.0.table().live.is_empty()
}
/// Wait until every thread has ended, for at most `limit` (a failure
/// guard, never a stand-in for the other side getting there): whether
/// they have.
pub fn wait_ended(&self, limit: Duration) -> bool {
let end = Instant::now() + limit;
let mut table = self.0.table();
while !table.live.is_empty() {
let Some(left) = end.checked_duration_since(Instant::now()) else {
return false;
};
table = self
.0
.ended
.wait_timeout(table, left)
.unwrap_or_else(|e| e.into_inner())
.0;
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_thread_is_counted_until_it_has_ended_and_stop_reaches_it() {
let jobs = Jobs::new();
let watch = jobs.watch();
let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
let (seen_tx, seen_rx) = std::sync::mpsc::channel::<bool>();
assert!(jobs.spawner().spawn("w", Hold::Free, move |stop| {
let _ = go_rx.recv();
let _ = seen_tx.send(stop.requested());
}));
assert_eq!(watch.running(), ["w"]);
assert!(!watch.ended());
drop(jobs);
go_tx.send(()).unwrap();
assert!(seen_rx.recv().unwrap(), "dropping the jobs says stop");
assert!(watch.wait_ended(Duration::from_secs(30)));
assert!(watch.running().is_empty());
}
#[test]
fn a_kept_thread_is_what_the_tab_is_held_for() {
let jobs = Jobs::new();
let free = jobs.spawner().ticket("free", Hold::Free);
assert_eq!(jobs.holding(), None);
let keep = jobs
.spawner()
.ticket("restore", Hold::Keep("Restoring".into()));
assert_eq!(jobs.holding().as_deref(), Some("Restoring"));
drop(keep);
assert_eq!(jobs.holding(), None);
drop(free);
assert!(jobs.watch().ended());
}
#[test]
fn a_panic_still_ends_the_count() {
let jobs = Jobs::new();
let watch = jobs.watch();
jobs.spawner()
.spawn("boom", Hold::Free, |_| panic!("on purpose"));
assert!(watch.wait_ended(Duration::from_secs(30)));
}
}
+26 -9
View File
@@ -7,11 +7,13 @@ pub mod app;
pub mod attention; pub mod attention;
pub mod books; pub mod books;
pub mod charts; pub mod charts;
pub mod company;
pub mod data; pub mod data;
pub mod demo; pub mod demo;
pub mod dock; pub mod dock;
pub mod export; pub mod export;
pub mod fmt; pub mod fmt;
pub mod jobs;
pub mod menu; pub mod menu;
pub mod nav; pub mod nav;
pub mod owner; pub mod owner;
@@ -19,14 +21,17 @@ pub mod pages;
pub mod palette; pub mod palette;
mod prefs; mod prefs;
mod receipts; mod receipts;
mod scheme_menu;
mod schemes; mod schemes;
pub mod tabs;
#[cfg(test)] #[cfg(test)]
mod test_support; mod test_support;
mod theme; mod theme;
pub mod welcome; pub mod welcome;
mod widgets; mod widgets;
pub use app::App; pub use app::{App, Start};
pub use company::CompanyView;
pub use data::Source; pub use data::Source;
use std::path::PathBuf; use std::path::PathBuf;
@@ -52,10 +57,12 @@ impl std::error::Error for Exit {}
/// window closes. An unknown argument returns [`Exit`] (code 2). /// window closes. An unknown argument returns [`Exit`] (code 2).
/// ///
/// `ledger-gui [--root PATH] [--book ID] [--today YYYY-MM-DD] [--demo]`: /// `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 /// `--root`, else the root `wanderbooks setup` made, never the current
/// directory or a settings file; `--book` names one, else the root's only /// directory or a settings file; `--book` names one, which is then the
/// one (or the first, by id). With no books yet, and an owner to set them /// 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 /// 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 /// of ending. `--demo` builds a demo company in a temp directory and opens
/// that. /// that.
@@ -100,11 +107,21 @@ pub fn run(
} }
// The books to show, or a first run (no books yet, and the program gave // 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. // 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 mut first_run = None;
let data_dir = match data_dir { let start = match data_dir {
Some(d) => Some(d), Some(d) => Some(Start::Only(Source { data_dir: d, today })),
None => match book_in_root(root.as_deref(), book.as_deref()) { 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() { Err(why) => match owner::current() {
// Named books that aren't there are a mistake, not a first run. // Named books that aren't there are a mistake, not a first run.
Some(owner) if book.is_none() => { Some(owner) if book.is_none() => {
@@ -135,8 +152,8 @@ pub fn run(
"wanderbooks", "wanderbooks",
options, options,
Box::new(move |cc| { Box::new(move |cc| {
Ok(Box::new(match (data_dir, first_run) { Ok(Box::new(match (start, first_run) {
(Some(data_dir), _) => App::new(cc, Source { data_dir, today }), (Some(start), _) => App::start(cc, start),
(None, state) => App::first_run(cc, root, today, state.unwrap_or_default()), (None, state) => App::first_run(cc, root, today, state.unwrap_or_default()),
})) }))
}), }),
+69 -3
View File
@@ -17,6 +17,16 @@
//! missing TIN never stops the file: the package lists the gaps. //! missing TIN never stops the file: the package lists the gaps.
//! 3. The file is saved as a new file in Downloads (export::save), never //! 3. The file is saved as a new file in Downloads (export::save), never
//! over one, off the UI thread; what came of it is shown. //! over one, off the UI thread; what came of it is shown.
//! 4. An export belongs to its tab: closing the tab, with no question,
//! tells the job to stop (jobs.rs). It checks at its phase
//! boundaries (before and after the books are read, after the file
//! is built, and just before it is saved) and stops there, saving
//! nothing: the save is one atomic write of a new file
//! (`ledger_store::saving`: written aside whole and linked in), so a
//! file is whole or is not there, and one that a stop reaches
//! too late to prevent (it came after the last check) is removed
//! again, being the job's own new file. What the builder
//! (`ledger_package`) does inside one call is not interrupted.
//! ``` //! ```
use crate::books::Books; use crate::books::Books;
@@ -35,9 +45,19 @@ pub type Done = Result<(PathBuf, Option<String>), String>;
pub struct Menu { pub struct Menu {
job: Option<(String, Receiver<Done>)>, job: Option<(String, Receiver<Done>)>,
done: Option<(String, Done)>, done: Option<(String, Done)>,
/// The tab's threads: the job is one of them (INVARIANT 4).
jobs: crate::jobs::Spawner,
} }
impl Menu { impl Menu {
/// A menu whose jobs are threads of a tab.
pub fn in_tab(jobs: crate::jobs::Spawner) -> Self {
Self {
jobs,
..Default::default()
}
}
/// The menu button, its items, and a note of the last job's outcome. /// The menu button, its items, and a note of the last job's outcome.
pub fn ui(&mut self, ui: &mut Ui, books: &Arc<Books>, compact: bool) { pub fn ui(&mut self, ui: &mut Ui, books: &Arc<Books>, compact: bool) {
let p = crate::theme::pal(ui.ctx()); let p = crate::theme::pal(ui.ctx());
@@ -117,13 +137,30 @@ impl Menu {
} }
fn start(&mut self, ctx: &egui::Context, books: Arc<Books>, job: Job) { fn start(&mut self, ctx: &egui::Context, books: Arc<Books>, job: Job) {
let (tx, rx) = channel();
let what = job.label(); let what = job.label();
self.start_with(ctx, what, Box::new(move |stop| job.run_until(&books, stop)));
}
/// Run `work` as an export job: off the UI thread, one of the tab's
/// threads, told to stop with the tab (INVARIANT 4).
pub fn start_with(
&mut self,
ctx: &egui::Context,
what: String,
work: Box<dyn FnOnce(&crate::jobs::Stop) -> Done + Send>,
) {
let (tx, rx) = channel();
let ctx = ctx.clone(); let ctx = ctx.clone();
std::thread::spawn(move || { let started = self
let _ = tx.send(job.run(&books)); .jobs
.spawn("export", crate::jobs::Hold::Free, move |stop| {
let _ = tx.send(work(stop));
ctx.request_repaint(); ctx.request_repaint();
}); });
if !started {
self.done = Some((what, Err("the system gave no thread for it".into())));
return;
}
self.job = Some((what, rx)); self.job = Some((what, rx));
self.done = None; self.done = None;
} }
@@ -148,7 +185,20 @@ impl Job {
/// Make the file and save it (INVARIANTS 1-3). /// Make the file and save it (INVARIANTS 1-3).
pub fn run(self, books: &Books) -> Done { pub fn run(self, books: &Books) -> Done {
self.run_until(books, &crate::jobs::Stop::never())
}
/// [`Self::run`], stopping at its phase boundaries when `stop` is
/// given, saving nothing (INVARIANT 4).
pub fn run_until(self, books: &Books, stop: &crate::jobs::Stop) -> Done {
let stopped = || -> Done { Err("stopped: its tab was closed".into()) };
if stop.requested() {
return stopped();
}
let snap = ledger_store::Snapshot::load(&books.data_dir).map_err(|e| e.to_string())?; let snap = ledger_store::Snapshot::load(&books.data_dir).map_err(|e| e.to_string())?;
if stop.requested() {
return stopped();
}
let ledger = snap.ledger(); let ledger = snap.ledger();
// The settings the rest of the viewer shows, read as the server // The settings the rest of the viewer shows, read as the server
// reads them (data::settings). // reads them (data::settings).
@@ -176,8 +226,17 @@ impl Job {
tins: Some(&tin), tins: Some(&tin),
}, },
)?; )?;
if stop.requested() {
return stopped();
}
let (stem, ext) = crate::export::split_name(&p.file_name); let (stem, ext) = crate::export::split_name(&p.file_name);
let path = crate::export::save(stem, ext, &p.zip)?; let path = crate::export::save(stem, ext, &p.zip)?;
if stop.requested() {
// Reached too late to stop the write: the new file it
// made is the job's own, and goes.
let _ = std::fs::remove_file(&path);
return stopped();
}
let mut notes = Vec::new(); let mut notes = Vec::new();
if !p.tin_gaps.is_empty() { if !p.tin_gaps.is_empty() {
notes.push(format!( notes.push(format!(
@@ -205,8 +264,15 @@ impl Job {
)?; )?;
let csv = ledger_package::vendor_1099_csv(&w, true); let csv = ledger_package::vendor_1099_csv(&w, true);
let name = ledger_package::vendor_1099_csv_name(year, true); let name = ledger_package::vendor_1099_csv_name(year, true);
if stop.requested() {
return stopped();
}
let (stem, ext) = crate::export::split_name(&name); let (stem, ext) = crate::export::split_name(&name);
let path = crate::export::save(stem, ext, csv.as_bytes())?; let path = crate::export::save(stem, ext, csv.as_bytes())?;
if stop.requested() {
let _ = std::fs::remove_file(&path);
return stopped();
}
let gaps = w let gaps = w
.lines .lines
.iter() .iter()
+167 -37
View File
@@ -29,6 +29,17 @@
//! owner's `upgrade_format` (the server checks it; nothing here //! owner's `upgrade_format` (the server checks it; nothing here
//! does). "Not now" changes nothing; a refusal (a wrong passphrase) //! does). "Not now" changes nothing; a refusal (a wrong passphrase)
//! is said in the dialog, which stays. //! is said in the dialog, which stays.
//! 6. An action that changes or replaces the books, their format or
//! what the owner holds (restore, the format upgrade, new books,
//! connect, close the books, check for updates, update) is never
//! abandoned: while one runs, its tab's close control is off, with
//! the words of what is running ("Restoring these books: wait for it
//! to finish"), and the window's close is held (app.rs); its result
//! is shown in that tab when it ends. A read-only one (back up now,
//! the restore's check of a backup) is stopped with the tab: it does
//! not start once the tab has closed, and what it sends after is
//! dropped (a request the books server already has it finishes: the
//! viewer only reads its answer).
//! ``` //! ```
use crate::books::Books; use crate::books::Books;
@@ -204,6 +215,11 @@ pub trait Owner: Send + Sync {
} }
} }
/// The owner the program gave the viewer, for every company's view that
/// isn't given one of its own. It is the program's (one per process, as
/// the program is one), not a company's: each view takes a handle to it
/// when it is made, and holds that (`CompanyView::with_owner` gives a view
/// another).
static OWNER: OnceLock<Arc<dyn Owner>> = OnceLock::new(); static OWNER: OnceLock<Arc<dyn Owner>> = OnceLock::new();
/// Give the viewer its owner (once, at start; INVARIANT 4). /// Give the viewer its owner (once, at start; INVARIANT 4).
@@ -213,10 +229,6 @@ pub fn set_owner(owner: Arc<dyn Owner>) {
/// The viewer's owner, if the program gave it one. /// The viewer's owner, if the program gave it one.
pub fn current() -> Option<Arc<dyn Owner>> { pub fn current() -> Option<Arc<dyn Owner>> {
owner()
}
fn owner() -> Option<Arc<dyn Owner>> {
OWNER.get().cloned() OWNER.get().cloned()
} }
@@ -230,6 +242,31 @@ pub fn book_id(books: &Books) -> Option<String> {
type Outcome = Result<Vec<String>, String>; type Outcome = Result<Vec<String>, String>;
/// What a job does to the books (INVARIANT 6).
#[derive(Clone, Copy)]
enum Effect {
/// It only reads: stopped with its tab.
Reads,
/// It changes something and is never abandoned; the words say what is
/// running ("Restoring these books").
Changes(&'static str),
}
impl Effect {
fn hold(self) -> crate::jobs::Hold {
match self {
Effect::Reads => crate::jobs::Hold::Free,
Effect::Changes(what) => {
crate::jobs::Hold::Keep(format!("{what}: wait for it to finish"))
}
}
}
}
/// A job to run off the UI thread: what it is called, what it does to the
/// books, and the work.
type Start = (String, Effect, Box<dyn FnOnce() -> Outcome + Send>);
/// A dialog open over the viewer. /// A dialog open over the viewer.
#[derive(Default)] #[derive(Default)]
enum Dialog { enum Dialog {
@@ -307,6 +344,9 @@ struct RestoreForm {
/// The menu's state: a dialog, the job under way, and the last outcome. /// The menu's state: a dialog, the job under way, and the last outcome.
#[derive(Default)] #[derive(Default)]
pub struct OwnerMenu { 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<egui::Id>,
/// The books last shown (by identity) and their id: found once for /// The books last shown (by identity) and their id: found once for
/// each load, not every frame. /// each load, not every frame.
book: Option<(usize, Option<String>)>, book: Option<(usize, Option<String>)>,
@@ -319,12 +359,24 @@ pub struct OwnerMenu {
/// The update waiting, as last read, and when (re-read every few /// The update waiting, as last read, and when (re-read every few
/// seconds and after any job). /// seconds and after any job).
update: Option<(std::time::Instant, Option<UpdateWaiting>)>, update: Option<(std::time::Instant, Option<UpdateWaiting>)>,
/// The tab's threads: every job is one of them (INVARIANT 6).
jobs: crate::jobs::Spawner,
} }
/// How long a reading of the waiting update is kept. /// How long a reading of the waiting update is kept.
const UPDATE_LOOK: std::time::Duration = std::time::Duration::from_secs(5); const UPDATE_LOOK: std::time::Duration = std::time::Duration::from_secs(5);
impl OwnerMenu { impl OwnerMenu {
/// A menu whose ids belong to the view `scope`, and whose jobs are
/// threads of that view (`jobs`).
pub fn scoped(scope: egui::Id, jobs: crate::jobs::Spawner) -> Self {
Self {
scope: Some(scope),
jobs,
..Default::default()
}
}
/// The id of the books shown, if they are books of a data root: found /// The id of the books shown, if they are books of a data root: found
/// once for each load. /// once for each load.
fn book_of(&mut self, books: &Arc<Books>) -> Option<String> { fn book_of(&mut self, books: &Arc<Books>) -> Option<String> {
@@ -355,8 +407,8 @@ impl OwnerMenu {
/// The standing notices above the page: an update waiting for the /// The standing notices above the page: an update waiting for the
/// owner's accept, and a format upgrade the books wait for, whose /// owner's accept, and a format upgrade the books wait for, whose
/// go-ahead is asked for once each open (INVARIANT 5). /// go-ahead is asked for once each open (INVARIANT 5).
pub fn notice(&mut self, ui: &mut Ui, books: &Arc<Books>) { pub fn notice(&mut self, ui: &mut Ui, owner: Option<Arc<dyn Owner>>, books: &Arc<Books>) {
let Some(owner) = owner() else { let Some(owner) = owner else {
return; return;
}; };
let Some(book) = self.book_of(books) else { let Some(book) = self.book_of(books) else {
@@ -399,7 +451,14 @@ impl OwnerMenu {
}); });
}); });
if let Some(work) = start { if let Some(work) = start {
self.start(ui.ctx(), "Update".into(), work); self.start(
ui.ctx(),
(
"Update".into(),
Effect::Changes("Updating wanderbooks"),
work,
),
);
} }
} }
let Some(upgrade) = books.format_upgrade.clone() else { let Some(upgrade) = books.format_upgrade.clone() else {
@@ -447,8 +506,14 @@ impl OwnerMenu {
} }
/// The menu button and a note of the last outcome; its dialogs. /// The menu button and a note of the last outcome; its dialogs.
pub fn ui(&mut self, ui: &mut Ui, books: &Arc<Books>, compact: bool) { pub fn ui(
let Some(owner) = owner() else { &mut self,
ui: &mut Ui,
owner: Option<Arc<dyn Owner>>,
books: &Arc<Books>,
compact: bool,
) {
let Some(owner) = owner else {
return; return;
}; };
let Some(book) = self.book_of(books) else { let Some(book) = self.book_of(books) else {
@@ -482,7 +547,7 @@ impl OwnerMenu {
} }
let busy = self.job.is_some(); let busy = self.job.is_some();
let waiting = self.update_waiting(ui.ctx(), &owner); let waiting = self.update_waiting(ui.ctx(), &owner);
let mut start: Option<(String, Box<dyn FnOnce() -> Outcome + Send>)> = None; let mut start: Option<Start> = None;
let response = ui let response = ui
.add_enabled_ui(!busy, |ui| { .add_enabled_ui(!busy, |ui| {
egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| { egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| {
@@ -493,7 +558,11 @@ impl OwnerMenu {
.clicked() .clicked()
{ {
let (o, b) = (owner.clone(), book.clone()); let (o, b) = (owner.clone(), book.clone());
start = Some(("Back up now".into(), Box::new(move || o.back_up_now(&b)))); start = Some((
"Back up now".into(),
Effect::Reads,
Box::new(move || o.back_up_now(&b)),
));
} }
if ui if ui
.button(format!("{} Restore…", icon::CLOCK_COUNTER_CLOCKWISE)) .button(format!("{} Restore…", icon::CLOCK_COUNTER_CLOCKWISE))
@@ -525,6 +594,10 @@ impl OwnerMenu {
let (o, b) = (owner.clone(), book.clone()); let (o, b) = (owner.clone(), book.clone());
start = Some(( start = Some((
format!("Connect {}", agent.label()), format!("Connect {}", agent.label()),
Effect::Changes(match agent {
Agent::Claude => "Connecting Claude Code to these books",
Agent::Codex => "Connecting Codex to these books",
}),
Box::new(move || o.connect(agent, &b)), Box::new(move || o.connect(agent, &b)),
)); ));
} }
@@ -546,7 +619,11 @@ impl OwnerMenu {
.clicked() .clicked()
{ {
let o = owner.clone(); let o = owner.clone();
start = Some(("Check for updates".into(), Box::new(move || o.check_for_updates()))); start = Some((
"Check for updates".into(),
Effect::Changes("Checking for updates"),
Box::new(move || o.check_for_updates()),
));
} }
if let Some(u) = &waiting if let Some(u) = &waiting
&& ui && ui
@@ -555,7 +632,11 @@ impl OwnerMenu {
.clicked() .clicked()
{ {
let o = owner.clone(); let o = owner.clone();
start = Some(("Update".into(), Box::new(move || o.apply_update()))); start = Some((
"Update".into(),
Effect::Changes("Updating wanderbooks"),
Box::new(move || o.apply_update()),
));
} }
ui.separator(); ui.separator();
if ui if ui
@@ -568,8 +649,8 @@ impl OwnerMenu {
}) })
}) })
.inner; .inner;
if let Some((what, work)) = start { if let Some(start) = start {
self.start(ui.ctx(), what, work); self.start(ui.ctx(), start);
} }
self.dialogs(ui.ctx(), &owner, &book); self.dialogs(ui.ctx(), &owner, &book);
let said = if self.job.is_some() { let said = if self.job.is_some() {
@@ -591,18 +672,21 @@ impl OwnerMenu {
} }
} }
fn start( fn start(&mut self, ctx: &egui::Context, (what, effect, work): Start) {
&mut self,
ctx: &egui::Context,
what: String,
work: Box<dyn FnOnce() -> Outcome + Send>,
) {
let (tx, rx) = channel(); let (tx, rx) = channel();
let ctx = ctx.clone(); let ctx = ctx.clone();
std::thread::spawn(move || { let started = self.jobs.spawn(&what.clone(), effect.hold(), move |stop| {
// A read-only job of a tab that has closed is not begun.
if matches!(effect, Effect::Reads) && stop.requested() {
return;
}
let _ = tx.send(work()); let _ = tx.send(work());
ctx.request_repaint(); ctx.request_repaint();
}); });
if !started {
self.done = Some((what, Err("the system gave no thread for it".into())));
return;
}
self.job = Some((what, rx)); self.job = Some((what, rx));
self.done = None; self.done = None;
} }
@@ -610,7 +694,8 @@ impl OwnerMenu {
/// The open dialog, if any, for the books `book`. /// The open dialog, if any, for the books `book`.
fn dialogs(&mut self, ctx: &egui::Context, owner: &Arc<dyn Owner>, book: &str) { fn dialogs(&mut self, ctx: &egui::Context, owner: &Arc<dyn Owner>, book: &str) {
let mut close = false; let mut close = false;
let mut run: Option<(String, Box<dyn FnOnce() -> Outcome + Send>)> = None; let mut run: Option<Start> = None;
let jobs = self.jobs.clone();
match &mut self.dialog { match &mut self.dialog {
Dialog::None => {} Dialog::None => {}
Dialog::Upgrade(form) => { Dialog::Upgrade(form) => {
@@ -636,17 +721,29 @@ impl OwnerMenu {
} }
} }
if !close { if !close {
upgrade_dialog(ctx, form, owner, book, &mut close); upgrade_dialog(
ctx,
self.scope.unwrap_or(egui::Id::NULL),
form,
owner,
book,
&jobs,
&mut close,
);
} }
} }
Dialog::Close => { 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.heading("Close the books?");
ui.label("Agents' sessions and everything else holding them let go. They open again when something holds them."); ui.label("Agents' sessions and everything else holding them let go. They open again when something holds them.");
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("Close the books").clicked() { if ui.button("Close the books").clicked() {
let o = owner.clone(); let o = owner.clone();
run = Some(("Close the books".into(), Box::new(move || o.close_books().map(|l| vec![l])))); run = Some((
"Close the books".into(),
Effect::Changes("Closing the books"),
Box::new(move || o.close_books().map(|l| vec![l])),
));
close = true; close = true;
} }
if ui.button("Cancel").clicked() { if ui.button("Cancel").clicked() {
@@ -656,7 +753,8 @@ impl OwnerMenu {
}); });
} }
Dialog::NewBooks { id, currency } => { Dialog::NewBooks { id, currency } => {
egui::Modal::new(egui::Id::new("owner-new-books")).show(ctx, |ui| { egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-new-books"))
.show(ctx, |ui| {
ui.heading("New books"); ui.heading("New books");
ui.label("Their id: lowercase letters, digits and hyphens."); ui.label("Their id: lowercase letters, digits and hyphens.");
ui.text_edit_singleline(id); ui.text_edit_singleline(id);
@@ -671,6 +769,7 @@ impl OwnerMenu {
let (o, i, c) = (owner.clone(), id.clone(), currency.clone()); let (o, i, c) = (owner.clone(), id.clone(), currency.clone());
run = Some(( run = Some((
"New books".into(), "New books".into(),
Effect::Changes("Making new books"),
Box::new(move || o.new_books(&i, &c).map(|l| vec![l])), Box::new(move || o.new_books(&i, &c).map(|l| vec![l])),
)); ));
close = true; close = true;
@@ -699,7 +798,7 @@ impl OwnerMenu {
_ => {} _ => {}
} }
} }
egui::Modal::new(egui::Id::new("owner-restore")).show(ctx, |ui| { egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-restore")).show(ctx, |ui| {
ui.set_max_width(520.0); ui.set_max_width(520.0);
ui.heading("Restore books"); ui.heading("Restore books");
ui.label("The backup: its repository's address, or its folder (the books' .git folder in your backup folder)."); ui.label("The backup: its repository's address, or its folder (the books' .git folder in your backup folder).");
@@ -754,13 +853,27 @@ impl OwnerMenu {
let (o, s, r) = (owner.clone(), form.source.clone(), form.replace); let (o, s, r) = (owner.clone(), form.source.clone(), form.replace);
let id = Some(form.id.trim().to_string()).filter(|i| !i.is_empty()); let id = Some(form.id.trim().to_string()).filter(|i| !i.is_empty());
let ctx = ui.ctx().clone(); let ctx = ui.ctx().clone();
std::thread::spawn(move || { // Only reads the backup: stopped with its tab.
let started = jobs.spawn(
"restore check",
crate::jobs::Hold::Free,
move |stop| {
if stop.requested() {
return;
}
let _ = tx.send(o.plan_restore(&s, id, r)); let _ = tx.send(o.plan_restore(&s, id, r));
ctx.request_repaint(); ctx.request_repaint();
}); },
let asked = (form.source.clone(), form.id.clone(), form.replace); );
if started {
let asked =
(form.source.clone(), form.id.clone(), form.replace);
form.planning = Some((rx, asked)); form.planning = Some((rx, asked));
form.problem = None; form.problem = None;
} else {
form.problem =
Some("the system gave no thread for it".into());
}
} }
if planning { if planning {
ui.label("Checking the backup…"); ui.label("Checking the backup…");
@@ -769,7 +882,11 @@ impl OwnerMenu {
Some(plan) => { Some(plan) => {
if ui.button("Restore it").clicked() { if ui.button("Restore it").clicked() {
let (o, plan) = (owner.clone(), plan.clone()); let (o, plan) = (owner.clone(), plan.clone());
run = Some(("Restore".into(), Box::new(move || o.restore(&plan)))); run = Some((
"Restore".into(),
Effect::Changes("Restoring these books"),
Box::new(move || o.restore(&plan)),
));
close = true; close = true;
} }
} }
@@ -784,8 +901,8 @@ impl OwnerMenu {
if close { if close {
self.dialog = Dialog::None; self.dialog = Dialog::None;
} }
if let Some((what, work)) = run { if let Some(run) = run {
self.start(ctx, what, work); self.start(ctx, run);
} }
} }
} }
@@ -794,13 +911,15 @@ impl OwnerMenu {
/// passphrase, and the go-ahead or not now. /// passphrase, and the go-ahead or not now.
fn upgrade_dialog( fn upgrade_dialog(
ctx: &egui::Context, ctx: &egui::Context,
scope: egui::Id,
form: &mut UpgradeForm, form: &mut UpgradeForm,
owner: &Arc<dyn Owner>, owner: &Arc<dyn Owner>,
book: &str, book: &str,
jobs: &crate::jobs::Spawner,
close: &mut bool, close: &mut bool,
) { ) {
let p = crate::theme::pal(ctx); 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.set_max_width(520.0);
ui.heading("Upgrade these books' format?"); ui.heading("Upgrade these books' format?");
ui.add_space(4.0); ui.add_space(4.0);
@@ -837,15 +956,26 @@ fn upgrade_dialog(
let (o, b) = (owner.clone(), book.to_string()); let (o, b) = (owner.clone(), book.to_string());
let (tx, rx) = channel(); let (tx, rx) = channel();
let ctx = ui.ctx().clone(); let ctx = ui.ctx().clone();
std::thread::spawn(move || { // Changes the books' format: never abandoned (INVARIANT 6).
let started = jobs.spawn(
"format upgrade",
crate::jobs::Hold::Keep(
"Upgrading these books' format: wait for it to finish".into(),
),
move |_| {
// The window is woken however this ends (a panic // The window is woken however this ends (a panic
// too), once the answer, or its absence, can be seen. // too), once the answer, or its absence, can be seen.
let _wake = Wake(ctx); let _wake = Wake(ctx);
let (tx, passphrase) = (tx, passphrase); let (tx, passphrase) = (tx, passphrase);
let _ = tx.send(o.upgrade_format(&b, &passphrase)); let _ = tx.send(o.upgrade_format(&b, &passphrase));
}); },
);
if started {
form.working = Some(rx); form.working = Some(rx);
form.problem = None; form.problem = None;
} else {
form.problem = Some("the system gave no thread for it".into());
}
} }
if ui if ui
.add_enabled(!working, egui::Button::new("Not now")) .add_enabled(!working, egui::Button::new("Not now"))
+3 -1
View File
@@ -166,7 +166,9 @@ pub fn split<T: ?Sized>(
ui.allocate_rect(rect, egui::Sense::hover()); ui.allocate_rect(rect, egui::Sense::hover());
return; 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 let mut detail_w: f32 = ui
.ctx() .ctx()
.data_mut(|d| d.get_persisted(key)) .data_mut(|d| d.get_persisted(key))
+1 -1
View File
@@ -20,7 +20,7 @@ use rust_decimal::Decimal;
pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
page(ui, "overview", |ui| { page(ui, "overview", |ui| {
let k = &b.kpis; let k = &b.kpis;
widgets::page_header(ui, b.company_name(), &headline(b)); widgets::page_lead(ui, &headline(b));
kpis(ui, b, shell); kpis(ui, b, shell);
let _ = k; let _ = k;
// What needs doing gets the page's full width, under the numbers: // What needs doing gets the page's full width, under the numbers:
+3 -1
View File
@@ -748,7 +748,9 @@ pub fn figures(
fiscal: bool, fiscal: bool,
) -> std::sync::Arc<PageFigures> { ) -> std::sync::Arc<PageFigures> {
type Stamp = (chrono::DateTime<chrono::Utc>, String, NaiveDate, bool); type Stamp = (chrono::DateTime<chrono::Utc>, 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); 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<PageFigures>)>(key)) if let Some((was, figs)) = ctx.data(|d| d.get_temp::<(Stamp, std::sync::Arc<PageFigures>)>(key))
&& was == stamp && was == stamp
+11 -1
View File
@@ -13,6 +13,9 @@ use egui_phosphor::regular as icon;
#[derive(Default)] #[derive(Default)]
pub struct Palette { 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<egui::Id>,
open: bool, open: bool,
query: String, query: String,
selected: usize, selected: usize,
@@ -29,6 +32,13 @@ pub struct Item {
} }
impl Palette { 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) { pub fn open(&mut self) {
self.open = true; self.open = true;
self.query.clear(); self.query.clear();
@@ -66,7 +76,7 @@ impl Palette {
self.open = false; self.open = false;
return Some(it.route.clone()); 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( .frame(
egui::Frame::new() egui::Frame::new()
.fill(p.surface) .fill(p.surface)
+80 -12
View File
@@ -112,11 +112,14 @@ pub struct Receipts {
} }
impl Receipts { impl Receipts {
pub fn new(ctx: &Context) -> Self { /// Receipts whose workers are threads of a tab: counted in `spawner`
/// until they have ended, which they do when this is dropped (their
/// queues' senders go) or the tab says stop (jobs.rs).
pub fn new(ctx: &Context, spawner: &crate::jobs::Spawner) -> Self {
let (done_tx, done) = channel(); let (done_tx, done) = channel();
let workers = std::thread::available_parallelism().map_or(2, |n| n.get().clamp(2, 4)); let workers = std::thread::available_parallelism().map_or(2, |n| n.get().clamp(2, 4));
let jobs = workers_for(ctx, &done_tx, "receipt-render", workers); let jobs = workers_for(ctx, spawner, &done_tx, "receipt-render", workers);
let thumb_jobs = workers_for(ctx, &done_tx, "thumb-render", 2); let thumb_jobs = workers_for(ctx, spawner, &done_tx, "thumb-render", 2);
Self { Self {
cache: HashMap::new(), cache: HashMap::new(),
thumbs: HashMap::new(), thumbs: HashMap::new(),
@@ -246,16 +249,23 @@ impl Receipts {
/// Workers taking jobs from one queue, sending what they render to /// Workers taking jobs from one queue, sending what they render to
/// `done`; the queue's sender. /// `done`; the queue's sender.
fn workers_for(ctx: &Context, done_tx: &Sender<Done>, name: &str, n: usize) -> Sender<Job> { fn workers_for(
ctx: &Context,
spawner: &crate::jobs::Spawner,
done_tx: &Sender<Done>,
name: &str,
n: usize,
) -> Sender<Job> {
let (jobs, job_rx) = channel::<Job>(); let (jobs, job_rx) = channel::<Job>();
let job_rx = std::sync::Arc::new(std::sync::Mutex::new(job_rx)); let job_rx = std::sync::Arc::new(std::sync::Mutex::new(job_rx));
for i in 0..n { for i in 0..n {
let ctx = ctx.clone(); let ctx = ctx.clone();
let job_rx = job_rx.clone(); let job_rx = job_rx.clone();
let done_tx = done_tx.clone(); let done_tx = done_tx.clone();
std::thread::Builder::new() spawner.spawn(
.name(format!("{name}-{i}")) &format!("{name}-{i}"),
.spawn(move || { crate::jobs::Hold::Free,
move |stop| {
loop { loop {
let job = match job_rx.lock() { let job = match job_rx.lock() {
Ok(rx) => rx.recv(), Ok(rx) => rx.recv(),
@@ -264,13 +274,17 @@ fn workers_for(ctx: &Context, done_tx: &Sender<Done>, name: &str, n: usize) -> S
let Ok(job) = job else { let Ok(job) = job else {
return; return;
}; };
// The tab is gone: what is still queued isn't rendered.
if stop.requested() {
return;
}
// A file that crashes its renderer is that file's // A file that crashes its renderer is that file's
// error, not the end of the worker (and every file // error, not the end of the worker (and every file
// queued after it). // queued after it).
let result = let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
match &job.thumb { match &job.thumb {
Some(dir) => render_thumb(&job, dir.as_deref()), Some(dir) => render_thumb(&job, dir.as_deref(), stop),
None => render(&job), None => render(&job),
} }
})) }))
@@ -283,8 +297,8 @@ fn workers_for(ctx: &Context, done_tx: &Sender<Done>, name: &str, n: usize) -> S
}); });
ctx.request_repaint(); ctx.request_repaint();
} }
}) },
.expect("spawn renderer"); );
} }
jobs jobs
} }
@@ -297,7 +311,11 @@ fn workers_for(ctx: &Context, done_tx: &Sender<Done>, name: &str, n: usize) -> S
/// A text file's thumbnail is the start of its text, kept nowhere: it is /// A text file's thumbnail is the start of its text, kept nowhere: it is
/// cheaper to read than a picture. A thumbnail that can't be kept is /// cheaper to read than a picture. A thumbnail that can't be kept is
/// still shown. /// still shown.
fn render_thumb(job: &Job, dir: Option<&std::path::Path>) -> Result<Rendered, String> { fn render_thumb(
job: &Job,
dir: Option<&std::path::Path>,
stop: &crate::jobs::Stop,
) -> Result<Rendered, String> {
let bytes = BlobStore::open_read_only(&job.root) let bytes = BlobStore::open_read_only(&job.root)
.get(&job.sha) .get(&job.sha)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
@@ -348,7 +366,9 @@ fn render_thumb(job: &Job, dir: Option<&std::path::Path>) -> Result<Rendered, St
img img
}; };
let img = img.crop_imm(0, 0, img.width(), img.height().min(THUMB_MAX_H)); let img = img.crop_imm(0, 0, img.width(), img.height().min(THUMB_MAX_H));
if let Some(path) = &kept { // A thumbnail for a tab that has closed is not written: the cache is
// shared by every tab and every viewer, and nobody asked for this one.
if let Some(path) = kept.as_ref().filter(|_| !stop.requested()) {
let mut png = Vec::new(); let mut png = Vec::new();
if img if img
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
@@ -503,3 +523,51 @@ fn to_color_image(img: image::RgbaImage) -> ColorImage {
let size = [img.width() as usize, img.height() as usize]; let size = [img.width() as usize, img.height() as usize];
ColorImage::from_rgba_unmultiplied(size, img.as_raw()) ColorImage::from_rgba_unmultiplied(size, img.as_raw())
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::jobs::Stop;
/// A picture in a blob store, and a thumbnail job for it.
fn picture_job(blobs: &std::path::Path, cache: &std::path::Path) -> Job {
let mut png = Vec::new();
image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
40,
30,
image::Rgba([200, 30, 30, 255]),
))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let (sha, _) = BlobStore::open(blobs).unwrap().put(&png).unwrap();
Job {
sha,
mime: "image/png".into(),
root: blobs.to_path_buf(),
thumb: Some(Some(cache.to_path_buf())),
generation: 0,
}
}
/// A thumbnail is kept in the cache for a tab that is open, and not
/// written for one that has closed (the cache is shared by every tab
/// and every viewer).
#[test]
fn a_thumbnail_is_not_written_for_a_tab_that_has_closed() {
let dir = tempfile::tempdir().unwrap();
let cache = dir.path().join("cache");
let job = picture_job(&dir.path().join("blobs"), &cache);
let named = cache.join(format!("{}.png", job.sha));
// Closed: it is still drawn (the render is whole) but never kept.
let gone = render_thumb(&job, Some(&cache), &Stop::given());
assert!(matches!(gone, Ok(Rendered::Pages(_))));
assert!(!named.exists(), "a closed tab wrote into the shared cache");
assert!(!cache.exists(), "a closed tab made the shared cache folder");
// Open: kept, as before.
let open = render_thumb(&job, Some(&cache), &Stop::never());
assert!(matches!(open, Ok(Rendered::Pages(_))));
assert!(named.is_file(), "an open tab's thumbnail is kept");
}
}
+369
View File
@@ -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<String>, 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<String>, 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<String> {
let map: HashMap<String, String> = 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);
}
}
+551
View File
@@ -0,0 +1,551 @@
//! The tab bar along the top of the window: one tab per open company, a
//! close control on each, and a "+" that lists the companies of the data
//! root that are not open. It runs from the sidebar's right edge to the
//! window's right edge: the sidebar keeps the window's whole height, which
//! the owner's 1479x519 window needs (`tests/sidenav.rs`: with the bar
//! above the sidebar the links scroll there, even with a bar of 24
//! points); with no company open there is no sidebar and it runs the whole
//! width.
//!
//! The bar spans the whole window, above the sidebar: a tab is the top
//! level, and the sidebar (its pages, its status card) is the company in
//! the tab's, which the layout shows. The tab is the company's identity
//! in the frame (badge and name); nothing else at the top of the window
//! repeats it, and the status card at the foot of the sidebar names it
//! again, in the same hue. With no company open
//! it is the window's top all the same. The "+" follows the last tab, and
//! stays at the right edge, whole, while the tabs scroll.
//!
//! ```text
//! GOAL: a person has several companies open at once, each in its own
//! tab, and moves between them, opens and closes them, without
//! any one disturbing another.
//! SOURCE: plan/p15-app-and-relay.md 3.2 and 3.3 (a tab per open
//! company); D-78 (one top-level tab per open company: a
//! company is reachable exactly while it has a tab).
//! INVARIANTS:
//! 1. One tab per open company, in the order opened, showing the
//! company's badge (its hue, from the id of its books: theme.rs
//! `hue_of`; the status card draws the same) and name (the name last known, else the id of its books, until it is
//! read). The bar is there with one company open, and with none.
//! 2. The tab shown is marked by more than colour: a heavier name, a
//! bar in the accent colour along its top edge, and "selected" to
//! assistive technology.
//! 3. Each tab has its own close control, labelled for assistive
//! technology with the company's name; a middle click on a tab
//! closes it as well.
//! 4. "+" lists only companies of the data root that are not open
//! (a company can't be opened twice), by name with the id of the
//! books beside it (the id alone for a company never opened), and
//! says so when there are none.
//! 5. Tabs never overlap or leave the bar: each is as wide as its
//! content between a least and a greatest width (a longer name is
//! cut, whole in its hover text), then the strip scrolls, with a
//! step control at each end; the tab shown is scrolled into view
//! when it changes. Each tab leaves room left of its close control
//! for a state mark (drawn by a later unit, nothing now).
//! 6. This only says what was asked (show, close, open); the app does
//! it.
//! 7. A tab whose company has a job under way that changes its books
//! (`Tab::held`) has its close control off: disabled to assistive
//! technology, drawn faint, no click and no middle click closes it,
//! and its hover text says what is running.
//! ```
use crate::theme::{self, pal};
use egui::{
Align, CornerRadius, Frame, Layout, Margin, RichText, Sense, Stroke, Ui, UiBuilder, vec2,
};
use egui_phosphor::regular as icon;
use std::time::{Duration, Instant};
/// The bar's height: what the bar takes from the window, which the tests
/// of the sidebar's fit add to their window heights (D-78).
pub const BAR_H: f32 = 36.0;
/// A tab's widest and least widths (a name is cut with an ellipsis to fit).
const TAB_MAX: f32 = 240.0;
const TAB_MIN: f32 = 110.0;
/// The close control's size.
const CLOSE: f32 = 20.0;
/// The badge's size, and its gap to the name.
const BADGE: f32 = 18.0;
const GAP: f32 = 8.0;
/// Room left of the close control for the connection state, which a later
/// unit draws there.
const STATE_W: f32 = 14.0;
/// The room round a tab's content: left and right.
const PAD_L: f32 = 10.0;
const PAD_R: f32 = 6.0;
/// The "+"'s width, and the gap before it.
const PLUS_W: f32 = 30.0;
const PLUS_GAP: f32 = 6.0;
/// The "+" list's width.
const LIST_W: f32 = 260.0;
/// The gap between tabs.
const TAB_GAP: f32 = 2.0;
/// How long a reading of the data root's companies is kept while "+" is
/// open.
const LIST_KEPT: Duration = Duration::from_millis(750);
/// What a tab shows of its company.
pub struct Tab {
/// The company's name, else the id of its books.
pub title: String,
/// More about it, on hover.
pub detail: String,
/// What its badge's hue is chosen from: the id of its books
/// ([`hue_of`]).
pub hue_key: String,
/// Why the tab can't be closed now: a job that changes its books is
/// running ("Restoring these books: wait for it to finish"). Its close
/// control is off, and says so on hover.
pub held: Option<String>,
}
/// The badge hue of the company whose books have id `book_id`, light or
/// dark: the one its tab and its status card both draw (theme.rs).
pub fn hue_of(book_id: &str, dark: bool) -> egui::Color32 {
theme::hue_of(book_id, dark)
}
/// A company of the data root that is not open, as "+" lists it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Listed {
/// The id of its books.
pub id: String,
/// Its name as last known, if it was ever opened here.
pub name: Option<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<Listed>)>,
}
impl TabBar {
/// The shown tab changed (or a tab was added): scroll it into view.
pub fn reveal(&mut self) {
self.reveal = true;
}
/// The bar, across the top of the window. `shown` is the tab in
/// front, if there is one; `others` reads the companies of the root
/// that are not open (called now and then while "+" is open, never
/// otherwise).
pub fn show(
&mut self,
ui: &mut Ui,
tabs: &[Tab],
shown: Option<usize>,
others: &dyn Fn() -> Vec<Listed>,
) -> Option<TabAction> {
let p = pal(ui.ctx());
let mut action = None;
let mut reveal = std::mem::take(&mut self.reveal);
egui::Panel::top("company_tabs")
.exact_size(BAR_H)
.resizable(false)
.frame(Frame::new().inner_margin(Margin::symmetric(8, 0)))
.show(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(TAB_GAP, 0.0);
let bar = ui.max_rect();
// The line along the bar's foot; the tab in front covers
// it, and so is one with what is below.
let outer = ui.clip_rect();
ui.painter().rect_filled(outer, 0.0, p.sidebar);
ui.painter().hline(
outer.x_range(),
outer.bottom() - 0.5,
Stroke::new(1.0, p.border),
);
// The tabs as wide as they are, the "+" right after them;
// when they don't fit, the "+" stays at the right edge
// and the tabs scroll.
let widths: Vec<f32> = tabs.iter().map(|t| tab_width(ui, t)).collect();
let total: f32 =
widths.iter().sum::<f32>() + widths.len().saturating_sub(1) as f32 * TAB_GAP;
let room = (ui.available_width() - PLUS_W - PLUS_GAP).max(0.0);
let strip_w = total.min(room);
let strip = egui::Rect::from_min_size(bar.min, vec2(strip_w, bar.height()));
let mut strip_ui = ui.new_child(
UiBuilder::new()
.max_rect(strip)
.layout(Layout::left_to_right(Align::Max)),
);
strip_ui.set_clip_rect(strip);
self.strip(
&mut strip_ui,
tabs,
&widths,
total > room + 0.5,
shown,
&mut reveal,
&mut action,
);
let plus = egui::Rect::from_min_size(
egui::pos2(strip.right() + PLUS_GAP, bar.top()),
vec2(PLUS_W, bar.height()),
);
let mut plus_ui = ui.new_child(
UiBuilder::new()
.max_rect(plus)
.layout(Layout::left_to_right(Align::Center)),
);
self.plus(&mut plus_ui, others, &mut action);
ui.allocate_rect(bar, Sense::hover());
});
if reveal {
// The tab wasn't there to scroll to yet: try again next frame.
self.reveal = true;
}
action
}
/// The tabs, scrolling sideways when they don't fit.
#[allow(clippy::too_many_arguments)]
fn strip(
&mut self,
ui: &mut Ui,
tabs: &[Tab],
widths: &[f32],
overflows: bool,
shown: Option<usize>,
reveal: &mut bool,
action: &mut Option<TabAction>,
) {
let p = pal(ui.ctx());
let room = ui.available_width();
// A step control at each end while the tabs overflow.
let step_w = if overflows { 22.0 } else { 0.0 };
let step_by = widths.first().copied().unwrap_or(TAB_MIN) + TAB_GAP;
let area_id = ui.id().with("tab_scroll");
let mut step = 0.0_f32;
if overflows {
let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click());
step_button(ui, r, &resp, icon::CARET_LEFT, "Earlier tabs");
if resp.clicked() {
step = -step_by;
}
}
let view_w = room - 2.0 * step_w;
let mut state = egui::scroll_area::State::load(ui.ctx(), area_id).unwrap_or_default();
if step != 0.0 {
state.offset.x = (state.offset.x + step).max(0.0);
state.store(ui.ctx(), area_id);
}
let out = egui::ScrollArea::horizontal()
.id_salt("tab_scroll")
.max_width(view_w.max(0.0))
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)
.show(ui, |ui| {
ui.spacing_mut().item_spacing.x = TAB_GAP;
ui.horizontal_top(|ui| {
for (i, tab) in tabs.iter().enumerate() {
let here = shown == Some(i);
let r = one_tab(ui, i, tab, here, widths[i], &p, action);
if here && *reveal {
r.scroll_to_me(Some(Align::Center));
*reveal = false;
}
}
});
});
if overflows {
let offset = out.state.offset.x;
let max = (out.content_size.x - out.inner_rect.width()).max(0.0);
let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click());
step_button(ui, r, &resp, icon::CARET_RIGHT, "Later tabs");
if resp.clicked() {
let mut s = out.state;
s.offset.x = (offset + step_by).min(max);
s.store(ui.ctx(), out.id);
}
}
if tabs.is_empty() {
*reveal = false;
}
}
/// The "+" and its list.
fn plus(
&mut self,
ui: &mut Ui,
others: &dyn Fn() -> Vec<Listed>,
action: &mut Option<TabAction>,
) {
let p = pal(ui.ctx());
let button = egui::Button::new(RichText::new(icon::PLUS).size(16.0).color(p.text))
.frame(false)
.min_size(vec2(28.0, 28.0));
let (response, open) =
egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| {
ui.set_min_width(LIST_W);
let stale = self
.listed
.as_ref()
.is_none_or(|(at, _)| at.elapsed() > LIST_KEPT);
if stale {
self.listed = Some((Instant::now(), others()));
}
ui.ctx().request_repaint_after(LIST_KEPT);
let list = self
.listed
.as_ref()
.map(|(_, l)| l.clone())
.unwrap_or_default();
if list.is_empty() {
ui.label(
RichText::new("Every company is already open.")
.font(theme::regular(13.0))
.color(p.muted),
);
} else {
ui.label(
RichText::new("Open a company")
.font(theme::regular(12.0))
.color(p.muted),
);
for c in &list {
if listed_row(ui, c, &p).clicked() {
*action = Some(TabAction::Open(c.id.clone()));
ui.close();
}
}
}
});
// Forget the list once it is closed, so it is read afresh.
if open.is_none() {
self.listed = None;
}
// Named as it always was for assistive technology; the hover says
// what it does.
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Open another company")
});
response.on_hover_text("Open a company");
}
}
/// One company in the "+" list: its name, the id of its books beside it
/// in small text (the id alone when the name was never known).
fn listed_row(ui: &mut Ui, c: &Listed, p: &theme::Palette) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(LIST_W, 28.0), Sense::click());
let primary = c.name.as_deref().unwrap_or(&c.id);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, primary));
if resp.hovered() {
ui.painter()
.rect_filled(rect, CornerRadius::same(6), p.hover);
}
let mut right = rect.right() - 8.0;
if c.name.is_some() {
let g = ui
.painter()
.layout_no_wrap(c.id.clone(), theme::regular(11.0), p.muted);
right -= g.size().x;
ui.painter().galley(
egui::pos2(right, rect.center().y - g.size().y / 2.0),
g,
p.muted,
);
}
let mut job = egui::text::LayoutJob::single_section(
primary.to_string(),
egui::TextFormat::simple(theme::regular(13.0), p.text),
);
job.wrap.max_width = (right - 8.0 - (rect.left() + 8.0)).max(10.0);
job.wrap.max_rows = 1;
job.wrap.break_anywhere = true;
job.wrap.overflow_character = Some('…');
let g = ui.painter().layout_job(job);
ui.painter().galley(
egui::pos2(rect.left() + 8.0, rect.center().y - g.size().y / 2.0),
g,
p.text,
);
resp
}
/// A step control at an end of the strip.
fn step_button(ui: &Ui, r: egui::Rect, resp: &egui::Response, glyph: &str, label: &'static str) {
let p = pal(ui.ctx());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));
if resp.hovered() {
ui.painter().rect_filled(r, CornerRadius::same(6), p.hover);
}
ui.painter().text(
r.center(),
egui::Align2::CENTER_CENTER,
glyph,
egui::FontId::proportional(13.0),
p.muted,
);
}
/// What a tab holds besides its name: the badge, the room for the state
/// mark, the close control and the room round them.
const TAB_FIXED: f32 = PAD_L + BADGE + GAP + GAP + STATE_W + CLOSE + PAD_R;
/// A tab's width: its content's, between the least and the greatest. The
/// name is measured in the heavier face for every tab, so the tab in front
/// doesn't move the others.
fn tab_width(ui: &Ui, tab: &Tab) -> f32 {
let g = ui.painter().layout_no_wrap(
tab.title.clone(),
theme::semibold(13.0),
egui::Color32::PLACEHOLDER,
);
(TAB_FIXED + g.size().x.ceil()).clamp(TAB_MIN, TAB_MAX)
}
/// One tab, `width` wide.
fn one_tab(
ui: &mut Ui,
i: usize,
tab: &Tab,
here: bool,
width: f32,
p: &theme::Palette,
action: &mut Option<TabAction>,
) -> egui::Response {
let height = BAR_H - 4.0;
let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click());
// The tab's own id for its close control: tabs are told apart by
// their place, and two tabs never share one.
let close_rect = egui::Rect::from_center_size(
egui::pos2(rect.right() - PAD_R - CLOSE / 2.0, rect.center().y),
vec2(CLOSE, CLOSE),
);
let close = ui.interact(close_rect, resp.id.with("close"), Sense::click());
resp.widget_info(|| {
egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, here, &tab.title)
});
close.widget_info(|| {
egui::WidgetInfo::labeled(
egui::WidgetType::Button,
tab.held.is_none(),
format!("Close {}", tab.title),
)
});
if ui.is_rect_visible(rect) {
let painter = ui.painter();
let top = CornerRadius {
nw: 8,
ne: 8,
sw: 0,
se: 0,
};
if here {
// The lit tab: the page's surface, outlined on its top and
// sides, open at the foot where it meets what is below, with a
// bar in the accent colour along its top edge.
painter.rect_filled(rect, top, p.surface);
painter.rect_stroke(
rect,
top,
Stroke::new(1.0, p.border),
egui::StrokeKind::Inside,
);
painter.rect_filled(
egui::Rect::from_min_max(
egui::pos2(rect.left() + 1.0, rect.bottom() - 1.0),
egui::pos2(rect.right() - 1.0, rect.bottom() + 1.0),
),
0.0,
p.surface,
);
painter.rect_filled(
egui::Rect::from_min_size(rect.min, vec2(rect.width(), 3.0)),
top,
p.accent,
);
} else if resp.hovered() || close.hovered() {
painter.rect_filled(rect.shrink2(vec2(0.0, 2.0)), CornerRadius::same(8), p.hover);
}
// The badge: the company's hue, as its status card draws it.
let badge = egui::Rect::from_center_size(
egui::pos2(rect.left() + PAD_L + BADGE / 2.0, rect.center().y + 1.0),
vec2(BADGE, BADGE),
);
let initial = tab
.title
.chars()
.next()
.map(|c| c.to_uppercase().next().unwrap_or(c))
.unwrap_or('W');
theme::paint_badge(
painter,
badge,
5,
initial,
theme::badge_hue(ui.ctx(), &tab.hue_key),
theme::bold(11.0),
);
let font = if here {
theme::semibold(13.0)
} else {
theme::regular(13.0)
};
let text_x = badge.right() + GAP;
let text_w = close_rect.left() - STATE_W - GAP - text_x;
let mut job = egui::text::LayoutJob::single_section(
tab.title.clone(),
egui::TextFormat::simple(font, p.text),
);
job.wrap.max_width = text_w.max(10.0);
job.wrap.max_rows = 1;
job.wrap.break_anywhere = true;
job.wrap.overflow_character = Some('…');
let galley = painter.layout_job(job);
painter.galley(
egui::pos2(text_x, rect.center().y - galley.size().y / 2.0 + 1.0),
galley,
p.text,
);
if close.hovered() && tab.held.is_none() {
painter.rect_filled(close_rect, CornerRadius::same(5), p.selected);
}
painter.text(
close_rect.center(),
egui::Align2::CENTER_CENTER,
icon::X,
egui::FontId::proportional(12.0),
if tab.held.is_some() {
p.faint
} else if close.hovered() || here {
p.text
} else {
p.muted
},
);
}
let resp = resp.on_hover_text(&tab.detail);
// The close control sits over the tab and is the one under the pointer
// there: a click on it is its own, never the tab's.
let close_tip = match &tab.held {
Some(why) => why.clone(),
None => format!("Close {}", tab.title),
};
let closes = close.on_hover_text(close_tip).clicked() || resp.middle_clicked();
if closes && tab.held.is_none() {
*action = Some(TabAction::Close(i));
} else if closes {
// Held open: the click is the close control's, and does nothing.
} else if resp.clicked() {
*action = Some(TabAction::Show(i));
}
resp
}
+165
View File
@@ -90,6 +90,106 @@ pub const DARK: Palette = Palette {
], ],
}; };
/// The company badges' hues, light and dark: one per company, chosen by
/// [`hue_of`] from the id of its books. Each is dark enough (light) or
/// bright enough (dark) that its letter (black or white, whichever reads
/// better) has 4.5:1 on it and it has 3:1 on every surface a badge sits
/// on, in the viewer's own two themes (the test below).
pub const BADGE_HUES: [(Color32, Color32); 8] = [
// indigo
(
Color32::from_rgb(0x4F, 0x46, 0xE5),
Color32::from_rgb(0x8B, 0x93, 0xFA),
),
// teal
(
Color32::from_rgb(0x0F, 0x76, 0x6E),
Color32::from_rgb(0x2D, 0xD4, 0xBF),
),
// orange
(
Color32::from_rgb(0xB4, 0x53, 0x09),
Color32::from_rgb(0xFB, 0xBF, 0x24),
),
// rose
(
Color32::from_rgb(0xBE, 0x18, 0x5D),
Color32::from_rgb(0xF4, 0x72, 0xB6),
),
// blue
(
Color32::from_rgb(0x1D, 0x4E, 0xD8),
Color32::from_rgb(0x60, 0xA5, 0xFA),
),
// green
(
Color32::from_rgb(0x15, 0x80, 0x3D),
Color32::from_rgb(0x4A, 0xDE, 0x80),
),
// violet
(
Color32::from_rgb(0x7E, 0x22, 0xCE),
Color32::from_rgb(0xC0, 0x84, 0xFC),
),
// cyan
(
Color32::from_rgb(0x0E, 0x74, 0x90),
Color32::from_rgb(0x22, 0xD3, 0xEE),
),
];
/// Which hue a company has: FNV-1a over the bytes of the id of its books,
/// modulo the number of hues. A function of the id alone (no seed, no
/// machine, no order of opening), so a company keeps its hue for ever and
/// on every machine; it is never changed without a new decision.
pub fn hue_index(book_id: &str) -> usize {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in book_id.bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x100_0000_01b3);
}
(h % BADGE_HUES.len() as u64) as usize
}
/// The badge hue of the company whose books have id `book_id`, in the
/// light or dark table.
pub fn hue_of(book_id: &str, dark: bool) -> Color32 {
let (light, night) = BADGE_HUES[hue_index(book_id)];
if dark { night } else { light }
}
/// Whether the palette in force is a dark one (its page is darker than
/// its text).
fn is_dark(p: &Palette) -> bool {
crate::schemes::luminance(p.bg) < crate::schemes::luminance(p.text)
}
/// The badge hue of a company, for the palette in force.
pub fn badge_hue(ctx: &Context, book_id: &str) -> Color32 {
hue_of(book_id, is_dark(&pal(ctx)))
}
/// A company's badge: a rounded square in its hue with its initial in it
/// (black or white, whichever reads), drawn by the tab and the status
/// card alike.
pub fn paint_badge(
painter: &egui::Painter,
rect: egui::Rect,
radius: u8,
initial: char,
hue: Color32,
font: FontId,
) {
painter.rect_filled(rect, CornerRadius::same(radius), hue);
painter.text(
rect.center(),
egui::Align2::CENTER_CENTER,
initial,
font,
crate::schemes::on(hue),
);
}
/// Where the palette in force is kept, in the context's memory. /// Where the palette in force is kept, in the context's memory.
fn palette_id() -> egui::Id { fn palette_id() -> egui::Id {
egui::Id::new("wanderbooks-palette") egui::Id::new("wanderbooks-palette")
@@ -317,6 +417,71 @@ pub fn apply_scheme(ctx: &Context, scheme: &crate::schemes::Scheme) {
mod tests { mod tests {
use super::*; use super::*;
/// The saturation of a colour in HSL (0 for a grey).
fn hsl_saturation(c: Color32) -> f32 {
let [r, g, b] = [c.r(), c.g(), c.b()].map(|v| f32::from(v) / 255.0);
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let l = (max + min) / 2.0;
if max == min {
0.0
} else {
(max - min) / (1.0 - (2.0 * l - 1.0).abs())
}
}
/// WCAG AA for each badge hue in both themes: its letter 4.5:1 on
/// it, and 3:1 for the badge against every surface it is drawn on.
/// Prints every measured ratio (`--nocapture`), and no hue is a grey
/// (HSL saturation at least 0.4: a grey badge reads as disabled).
#[test]
fn every_badge_hue_reads_in_both_themes() {
use crate::schemes::{contrast, on};
let mut table = String::new();
let mut failures = Vec::new();
for (name, p, pick) in [("light", &LIGHT, 0), ("dark", &DARK, 1)] {
for (i, hues) in BADGE_HUES.iter().enumerate() {
let hue = if pick == 0 { hues.0 } else { hues.1 };
let sat = hsl_saturation(hue);
let letter = contrast(on(hue), hue);
let mut line = format!("{name} hue {i} {hue:?}: sat {sat:.2} letter {letter:.2}");
if sat < 0.4 {
failures.push(format!("{name} hue {i} {hue:?}: grey (sat {sat:.2})"));
}
if letter < 4.5 {
failures.push(format!("{name} hue {i} {hue:?}: letter {letter:.2}:1"));
}
// The tab's (in front, behind, hovered) and the card's.
for (what, ground) in [
("surface", p.surface),
("sidebar", p.sidebar),
("page", p.bg),
("hover", p.hover),
] {
let r = contrast(hue, ground);
line.push_str(&format!(" {what} {r:.2}"));
if r < 3.0 {
failures.push(format!("{name} hue {i} {hue:?} on {what}: {r:.2}:1"));
}
}
table.push_str(&line);
table.push('\n');
}
}
println!("{table}");
assert!(failures.is_empty(), "{failures:?}\n{table}");
}
#[test]
fn a_hue_is_a_function_of_the_book_id_alone() {
// Pinned: a change here recolours every company.
assert_eq!(hue_index("alpha"), hue_index("alpha"));
assert_eq!(hue_index(""), 0xcbf2_9ce4_8422_2325_u64 as usize % 8);
let all: std::collections::HashSet<usize> =
(0..200).map(|n| hue_index(&format!("books-{n}"))).collect();
assert_eq!(all.len(), BADGE_HUES.len(), "every hue is used");
}
/// font_definitions: every family ends with the PDFs' Noto fallbacks, /// font_definitions: every family ends with the PDFs' Noto fallbacks,
/// in their order, after its own face, the icons and the symbol fonts, /// in their order, after its own face, the icons and the symbol fonts,
/// each Noto font the very bytes ledger-import bundles (the same /// each Noto font the very bytes ledger-import bundles (the same
+13
View File
@@ -61,6 +61,19 @@ pub fn page_header(ui: &mut Ui, title: &str, subtitle: &str) {
ui.add_space(16.0); ui.add_space(16.0);
} }
/// A page that opens with a sentence instead of a title (the Overview:
/// the company's name is the tab's, and the status card's, not the
/// page's): the sentence at the theme's heading size and weight, the
/// first thing on the page.
pub fn page_lead(ui: &mut Ui, sentence: &str) {
let w = ui.available_width().min(860.0);
ui.allocate_ui(vec2(w, 0.0), |ui| {
ui.set_max_width(w);
ui.label(RichText::new(sentence).font(theme::semibold(20.0)));
});
ui.add_space(16.0);
}
/// A rounded tag. /// A rounded tag.
pub fn pill(ui: &mut Ui, text: &str, fg: Color32, bg: Color32) -> Response { pub fn pill(ui: &mut Ui, text: &str, fg: Color32, bg: Color32) -> Response {
Frame::new() Frame::new()
+39
View File
@@ -554,3 +554,42 @@ fn the_menus_worksheet_says_which_payees_lack_a_tin() {
"{note}" "{note}"
); );
} }
/// menu.rs INVARIANT 4: an export whose tab has closed is told to stop and
/// saves nothing, at any of its phase boundaries: told before it starts,
/// after the books are read, after the file is built, or too late to stop
/// the write (the file it just made is removed). Told at none, it saves.
#[test]
fn a_stopped_export_leaves_no_file_whenever_it_is_told() {
use ledger_gui::jobs::Stop;
downloads();
let f = root_book();
let b = load(&f.book);
// A year of its own (the other tests save 2026's): no other test's file has its name.
let mine = || -> Vec<String> {
saved_files()
.into_iter()
.filter(|n| n.contains("2025"))
.collect()
};
let mut told = 0;
for looks in 0..20 {
match Job::Worksheet(2025).run_until(&b, &Stop::given_after(looks)) {
Err(why) => {
assert!(why.starts_with("stopped"), "{why}");
assert_eq!(
mine(),
Vec::<String>::new(),
"told after {looks} looks, the export left a file"
);
told += 1;
}
Ok((path, _)) => {
assert_eq!(mine().len(), 1, "told too late: it saves");
std::fs::remove_file(path).unwrap();
break;
}
}
}
assert!(told >= 4, "its boundaries: only {told} told it to stop");
}
+144 -1
View File
@@ -8,7 +8,7 @@
use chrono::NaiveDate; use chrono::NaiveDate;
use egui_kittest::Harness; use egui_kittest::Harness;
use egui_kittest::kittest::Queryable; use egui_kittest::kittest::{NodeT, Queryable};
use ledger_core::Currency; use ledger_core::Currency;
use ledger_gui::App; use ledger_gui::App;
use ledger_gui::books::Books; use ledger_gui::books::Books;
@@ -23,6 +23,55 @@ use std::sync::{Arc, Mutex, OnceLock};
const PASS: &str = "correct horse battery"; const PASS: &str = "correct horse battery";
/// The passphrase on which the fake owner's worker dies, answering nothing. /// The passphrase on which the fake owner's worker dies, answering nothing.
const DIES: &str = "the worker dies on this one"; const DIES: &str = "the worker dies on this one";
/// The passphrase on which the fake owner's upgrade waits for the test to
/// let it go.
const HOLDS: &str = "the upgrade waits on this one";
/// A latch: opened once, it stays open.
struct Latch {
open: Mutex<bool>,
changed: std::sync::Condvar,
}
impl Latch {
const fn new() -> Latch {
Latch {
open: Mutex::new(false),
changed: std::sync::Condvar::new(),
}
}
fn open(&self) {
*self.open.lock().unwrap_or_else(|e| e.into_inner()) = true;
self.changed.notify_all();
}
fn is_open(&self) -> bool {
*self.open.lock().unwrap_or_else(|e| e.into_inner())
}
/// Wait for it to open (the limit is a failure guard).
fn wait(&self) -> bool {
let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
let mut open = self.open.lock().unwrap_or_else(|e| e.into_inner());
while !*open {
let Some(left) = end.checked_duration_since(std::time::Instant::now()) else {
return false;
};
open = self
.changed
.wait_timeout(open, left)
.unwrap_or_else(|e| e.into_inner())
.0;
}
true
}
}
/// Said by the owner when the held upgrade has begun; opened by the test
/// to let it end.
static HELD_BEGUN: Latch = Latch::new();
static HELD_LET_GO: Latch = Latch::new();
/// An owner that says what it was asked, and takes only PASS. /// An owner that says what it was asked, and takes only PASS.
#[derive(Default)] #[derive(Default)]
@@ -55,6 +104,11 @@ impl Owner for Fake {
Err("not in these tests".into()) Err("not in these tests".into())
} }
fn upgrade_format(&self, book: &str, passphrase: &str) -> Result<Vec<String>, String> { fn upgrade_format(&self, book: &str, passphrase: &str) -> Result<Vec<String>, String> {
if passphrase == HOLDS {
HELD_BEGUN.open();
assert!(HELD_LET_GO.wait(), "the test never let the upgrade go");
return Ok(vec![format!("Upgraded the books \"{book}\".")]);
}
// Slow enough to be seen at work. // Slow enough to be seen at work.
std::thread::sleep(std::time::Duration::from_millis(300)); std::thread::sleep(std::time::Duration::from_millis(300));
// A worker that dies on the way: no answer comes back. // A worker that dies on the way: no answer comes back.
@@ -394,3 +448,92 @@ fn screenshots() {
settle(&mut h, &f, n + 1); settle(&mut h, &f, n + 1);
shot(&mut h, "upgrade-done"); shot(&mut h, "upgrade-done");
} }
/// owner.rs INVARIANT 6: the upgrade changes the books' format, so it is
/// never abandoned: while it runs its tab's close control is off, saying
/// so, and the window's close is cancelled with a dialog that offers only
/// to wait; when it ends the dialog goes and the result shows in the tab.
#[test]
fn an_upgrade_under_way_holds_its_tab_and_the_window_open() {
let _alone = alone();
let _ = fake();
let (_dir, _book, b) = books(true, true);
let mut h = harness(b);
// Nothing runs: the window's close goes through.
assert!(!close_is_cancelled(&mut h));
type_passphrase(&mut h, HOLDS);
h.get_by_label("Upgrade").click();
for _ in 0..600 {
h.run_steps(2);
if HELD_BEGUN.is_open() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(HELD_BEGUN.is_open(), "the owner was never asked");
h.run_steps(3);
let words = "Upgrading these books' format: wait for it to finish";
assert_eq!(
h.state().holding(),
[("Unnamed company".to_string(), words.to_string())]
);
assert!(
h.get_by_role_and_label(egui::accesskit::Role::Button, "Close Unnamed company")
.accesskit_node()
.is_disabled(),
"the tab can be closed while its books' format is being upgraded"
);
assert!(
close_is_cancelled(&mut h),
"the window's close went through"
);
h.run_steps(3);
assert!(h.state().close_dialog_is_up());
assert!(
h.query_by_label_contains("The books are being changed")
.is_some()
);
assert!(
h.query_by_label_contains(&format!("Unnamed company: {words}"))
.is_some()
);
HELD_LET_GO.open();
for _ in 0..600 {
h.run_steps(2);
if h.state().holding().is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
h.run_steps(6);
assert!(h.state().holding().is_empty());
assert!(!h.state().close_dialog_is_up());
assert!(
h.query_by_label_contains("The books are being changed")
.is_none()
);
assert!(
h.query_by_label_contains("Format upgrade: Upgraded the books")
.is_some(),
"the result isn't shown in the tab"
);
}
/// Whether the window's close, asked for now, was cancelled by the app.
fn close_is_cancelled(h: &mut Harness<'static, App>) -> bool {
h.input_mut()
.viewports
.entry(egui::ViewportId::ROOT)
.or_default()
.events
.push(egui::ViewportEvent::Close);
h.run_steps(1);
h.output()
.viewport_output
.get(&egui::ViewportId::ROOT)
.is_some_and(|v| {
v.commands
.iter()
.any(|c| matches!(c, egui::ViewportCommand::CancelClose))
})
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 42 KiB

@@ -1 +1 @@
b4c03adfe9dc03e6 9e4be6e7e06cbefd
+83
View File
@@ -173,3 +173,86 @@ fn a_setting_changed_while_it_runs_is_followed() {
} }
} }
} }
/// A loader whose books can't be read is told to go (its tab closed): it
/// tries no further load, however long it was to wait before the next, and
/// it ends at once (the registry says when).
#[test]
fn a_loader_whose_books_cant_be_read_tries_no_more_once_it_is_dropped() {
let dir = std::env::temp_dir().join(format!("ledger-gui-live-gone-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let _cleanup = TestDir(dir.clone());
std::fs::create_dir_all(&dir).unwrap();
// Books that are not there: every try fails.
let data = dir.join("not-there");
let jobs = ledger_gui::jobs::Jobs::new();
let loader = Loader::spawn_in(
Source {
data_dir: data,
today: NaiveDate::from_ymd_opt(2026, 10, 12),
},
egui::Context::default(),
&jobs.spawner(),
);
let watch = loader.watch();
match loader.wait(Duration::from_secs(30)) {
Some(Update::Error(_)) => {}
_ => panic!("the books that aren't there didn't say so"),
}
// Dropped while it waits for its next try: waited for until it does.
let end = Instant::now() + Duration::from_secs(30);
while !watch.waiting() {
assert!(Instant::now() < end, "it never waited to try again");
std::thread::yield_now();
}
let tried = watch.load_attempts();
assert_eq!(tried, 1);
drop(loader);
assert!(
jobs.watch().wait_ended(Duration::from_secs(60)),
"the loader's thread runs on: {:?}",
jobs.running()
);
assert!(watch.ended());
assert_eq!(
watch.load_attempts(),
tried,
"a dropped loader tried to load the books again"
);
}
/// The viewer's presence is let go when the loader is dropped, not when its
/// thread gets to end: nothing waits on the thread.
#[test]
fn a_dropped_loader_lets_go_of_its_presence_at_once() {
let dir = std::env::temp_dir().join(format!("ledger-gui-live-presence-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let _cleanup = TestDir(dir.clone());
let data = dir.join("books-data");
drop(Store::create(&data, Currency::USD).unwrap());
ledger_store::ops::prepare(&data).unwrap();
let loader = Loader::spawn(
Source {
data_dir: data.clone(),
today: NaiveDate::from_ymd_opt(2026, 10, 12),
},
egui::Context::default(),
);
assert!(matches!(
loader.wait(Duration::from_secs(30)),
Some(Update::Books(_))
));
let deadline = Instant::now() + Duration::from_secs(30);
while !ledger_store::ops::viewer_open(&data) {
assert!(
Instant::now() < deadline,
"the viewer never held its presence"
);
std::thread::sleep(Duration::from_millis(5));
}
drop(loader);
assert!(
!ledger_store::ops::viewer_open(&data),
"a dropped loader still holds the books' presence"
);
}
+56 -9
View File
@@ -132,9 +132,29 @@ fn the_viewer_says_update_for_newer_books_and_corrupt_for_damaged_ones() {
assert!(!err.contains("newer"), "{err}"); assert!(!err.contains("newer"), "{err}");
} }
/// The viewer's next error, within ten seconds. It never shows books it
/// can't read: an update carrying books is a failure.
fn next_error(loader: &Loader) -> String {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
match loader.wait(Duration::from_millis(200)) {
Some(Update::Error(e)) => return e,
Some(Update::Books(_)) => panic!("the viewer read a line it doesn't know"),
_ => {}
}
}
panic!("the viewer never said anything about the line it doesn't know");
}
/// Following: the viewer has the books open when a newer wanderbooks /// Following: the viewer has the books open when a newer wanderbooks
/// writes a line this one can't read. It says to update, and keeps the /// writes a line this one can't read. It says to update, and keeps the
/// books it had. /// books it had.
///
/// The writer's two lines are two writes, and the viewer may look between
/// them: with the newer line last, nothing can check it, and the viewer
/// says "newer or damaged" (BS-format-1) until the line after it lands.
/// Both are right, so this waits for the "update" and holds every message
/// before it to the "newer or damaged" one.
#[test] #[test]
fn a_live_viewer_says_update_when_the_books_move_ahead_of_it() { fn a_live_viewer_says_update_when_the_books_move_ahead_of_it() {
let data = books("live"); let data = books("live");
@@ -147,19 +167,46 @@ fn a_live_viewer_says_update_when_the_books_move_ahead_of_it() {
w.append("entry.evidence_inherited", json!({"entry_id": 1})) w.append("entry.evidence_inherited", json!({"entry_id": 1}))
.unwrap(); .unwrap();
w.append("fx.rate_set", rate()).unwrap(); w.append("fx.rate_set", rate()).unwrap();
let deadline = Instant::now() + Duration::from_secs(10); loop {
let mut said = None; let said = next_error(&loader);
while Instant::now() < deadline { if said.starts_with("Journal line") {
match loader.wait(Duration::from_millis(200)) { says_newer_or_damaged(&said);
Some(Update::Error(e)) => { } else {
said = Some(e); says_update(&said);
break; break;
} }
Some(Update::Books(_)) => panic!("the viewer read a line it doesn't know"),
_ => {}
} }
} }
says_update(&said.expect("the viewer never said to update"));
/// The viewer looks between the writer's two lines, as it can at any time:
/// with the newer line last it says "newer or damaged"; when the next line
/// lands it says "update", with no new look asked for.
#[test]
fn a_live_viewer_that_looks_between_the_two_lines_says_update_once_the_second_lands() {
let data = books("live-between");
let loader = Loader::spawn(source(&data), egui::Context::default());
match loader.wait(Duration::from_secs(10)) {
Some(Update::Books(_)) => {}
_ => panic!("no initial load"),
}
let mut w = JournalWriter::open(&data.join(JOURNAL_FILE)).unwrap();
w.append("entry.evidence_inherited", json!({"entry_id": 1}))
.unwrap();
// The viewer has looked and found the newer line last.
says_newer_or_damaged(&next_error(&loader));
// The line after it lands: the first line is now checked, and known
// newer. (Looks made before the second line is read may repeat the
// last-line message; none may be anything else.)
w.append("fx.rate_set", rate()).unwrap();
loop {
let said = next_error(&loader);
if said.starts_with("Journal line") {
says_newer_or_damaged(&said);
} else {
says_update(&said);
break;
}
}
} }
/// A declared format this version reads opens like any books, and the /// A declared format this version reads opens like any books, and the
+39 -12
View File
@@ -24,6 +24,7 @@ use ledger_core::{AccountType, Currency, Money, Side};
use ledger_gui::books::Books; use ledger_gui::books::Books;
use ledger_gui::nav::{Route, Section}; use ledger_gui::nav::{Route, Section};
use ledger_gui::owner::{Agent, Owner, RestorePlan}; use ledger_gui::owner::{Agent, Owner, RestorePlan};
use ledger_gui::tabs::BAR_H;
use ledger_gui::{App, Source, data}; use ledger_gui::{App, Source, data};
use ledger_store::{DiskCheck, Store}; use ledger_store::{DiskCheck, Store};
use rust_decimal::Decimal; use rust_decimal::Decimal;
@@ -442,16 +443,19 @@ fn at_1479x519_every_link_shows_unscrolled() {
} }
} }
/// Folded, the card is one line that fits the card whole (never cut to /// Folded, the card is its heading alone, "Live · event N" at its right,
/// "Datab…"), naming the check that failed; hovered, it shows the three /// the seal after it, when every check passes; when one failed, a line
/// checks. /// under the heading names it, whole (never cut to "Datab…"), the event
/// at its end. Either way it says Live or Snapshot and the event, and
/// hovered it shows the three checks.
#[test] #[test]
fn the_folded_card_shows_its_checks_on_hover() { fn the_folded_card_shows_its_checks_on_hover() {
let f = Fixture::new(); let f = Fixture::new();
for (footer, verdict, checks) in [ for (footer, verdict, word, checks) in [
( (
Footer::Owners, Footer::Owners,
"verified", "event 6",
"Live",
[ [
"Journal chain verified", "Journal chain verified",
"Database matches journal", "Database matches journal",
@@ -460,8 +464,7 @@ fn the_folded_card_shows_its_checks_on_hover() {
), ),
( (
Footer::Snapshot, Footer::Snapshot,
// Its line is "Snapshot · event 555 · (seal)": no room for "event 6",
// "verified", which the seal says.
"Snapshot", "Snapshot",
[ [
"Journal chain verified", "Journal chain verified",
@@ -472,6 +475,7 @@ fn the_folded_card_shows_its_checks_on_hover() {
( (
Footer::Differs, Footer::Differs,
"Database differs", "Database differs",
"Live",
[ [
"Journal chain verified", "Journal chain verified",
"Database differs", "Database differs",
@@ -481,6 +485,7 @@ fn the_folded_card_shows_its_checks_on_hover() {
( (
Footer::Unreadable, Footer::Unreadable,
"Database unreadable", "Database unreadable",
"Live",
[ [
"Journal chain verified", "Journal chain verified",
"Database unreadable", "Database unreadable",
@@ -490,6 +495,7 @@ fn the_folded_card_shows_its_checks_on_hover() {
( (
Footer::Damaged, Footer::Damaged,
"2 files damaged", "2 files damaged",
"Live",
[ [
"Journal chain verified", "Journal chain verified",
"Database matches journal", "Database matches journal",
@@ -514,10 +520,28 @@ fn the_folded_card_shows_its_checks_on_hover() {
); );
let (_, footer_rect, _) = drawn(&h, Pane::Sidebar); let (_, footer_rect, _) = drawn(&h, Pane::Sidebar);
let line = h.get_by_label_contains(verdict); let line = h.get_by_label_contains(verdict);
let card = line.rect(); let card = h.get_by_label_contains(word).rect();
// The live word is in the heading, above the line when there
// is one; the event is on the line, or after the word.
assert!(line.rect().bottom() <= footer_rect.bottom(), "{tag}");
if verdict.starts_with("event") {
assert!(
(line.rect().center().y - card.center().y).abs() < 4.0,
"{tag}: the event is after the live word"
);
} else {
assert!(
line.rect().top() > card.bottom() - 4.0,
"{tag}: a line under the heading"
);
assert!(
h.query_all_by_label_contains("event ").count() >= 1,
"{tag}: the failure line ends with the event"
);
}
// Every piece of the line lies inside the card's margins: a // Every piece of the line lies inside the card's margins: a
// piece cut off or running out would reach past them. // piece cut off or running out would reach past them.
for piece in ["Live", "Snapshot", "event 5", verdict] { for piece in [word, "event ", verdict] {
for n in h.query_all_by_label_contains(piece) { for n in h.query_all_by_label_contains(piece) {
let r = n.rect(); let r = n.rect();
if r.left() < Pane::Sidebar.panel() && r.top() >= footer_rect.top() { if r.left() < Pane::Sidebar.panel() && r.top() >= footer_rect.top() {
@@ -664,7 +688,9 @@ fn a_tall_sidebar_is_unchanged() {
let png = dir.join("sidenav-1440x920.png"); let png = dir.join("sidenav-1440x920.png");
match h.render() { match h.render() {
Ok(img) => { Ok(img) => {
let side = image::imageops::crop_imm(&img, 0, 0, 224, img.height()).to_image(); let side =
image::imageops::crop_imm(&img, 0, BAR_H as u32, 224, img.height() - BAR_H as u32)
.to_image();
if bless { if bless {
side.save(&png).unwrap(); side.save(&png).unwrap();
} else { } else {
@@ -687,7 +713,8 @@ fn a_tall_sidebar_is_unchanged() {
fn sidebar_shapes(h: &Harness<'_, App>) -> u64 { fn sidebar_shapes(h: &Harness<'_, App>) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325; let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for s in &h.output().shapes { for s in &h.output().shapes {
if s.clip_rect.max.x <= 224.5 { // Below the tab bar (D-78): the shapes that are the sidebar's.
if s.clip_rect.max.x <= 224.5 && s.clip_rect.min.y >= BAR_H - 0.5 {
for b in format!("{:?}", s.shape).bytes() { for b in format!("{:?}", s.shape).bytes() {
hash ^= b as u64; hash ^= b as u64;
hash = hash.wrapping_mul(0x100_0000_01b3); hash = hash.wrapping_mul(0x100_0000_01b3);
@@ -754,7 +781,7 @@ fn sidenav_screenshots() {
} }
// The folded card's tooltip. // The folded card's tooltip.
let mut h = f.harness(Footer::Owners, Route::Projects, 1479.0, 519.0, 1.0); let mut h = f.harness(Footer::Owners, Route::Projects, 1479.0, 519.0, 1.0);
if let Some(n) = h.query_by_label_contains("event 5") { if let Some(n) = h.query_by_label_contains("event ") {
let c = n.rect().center(); let c = n.rect().center();
h.hover_at(c); h.hover_at(c);
h.run_steps(30); h.run_steps(30);
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

File diff suppressed because it is too large. Load diff
+83 -1
View File
@@ -37,7 +37,7 @@ the specification in `bookspec/` (which never depends on the engine).
| `ledger-package` | the shared read-only view over `Store` or `Snapshot` (`PackageBooks`): the CPA package, the 1099 worksheet, the invoice document, Needs attention | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-vault` | | `ledger-package` | the shared read-only view over `Store` or `Snapshot` (`PackageBooks`): the CPA package, the 1099 worksheet, the invoice document, Needs attention | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-vault` |
| `ledger-mcp` | the books server: the MCP tools (122), resources, the handbook, scopes, the door and the access log, backups' scheduling | all of the above | | `ledger-mcp` | the books server: the MCP tools (122), resources, the handbook, scopes, the door and the access log, backups' scheduling | all of the above |
| `ledger-host` | the host and its leases, the agent bridge (`wanderbooks mcp`), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config` | | `ledger-host` | the host and its leases, the agent bridge (`wanderbooks mcp`), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config` |
| `ledger-gui` | the viewer: read-only, live, egui; the Books menu hands work to the server; the agent dock and the first-run page (P11b) | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-package`, `ledger-vault`, `ledger-host` | | `ledger-gui` | the viewer: read-only, live, egui, one window with a tab per open company (P15); the Books menu hands work to the server; the agent dock and the first-run page (P11b) | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-package`, `ledger-vault`, `ledger-host` |
| `ledger-cli` | `wanderbooks`, the one executable: every mode (`serve`, `server`, `host`, `mcp`, `gui`, `setup`, `books`, `token`, `connect`, `doctor`, `licenses`, …) and the over-the-wire test suites | everything | | `ledger-cli` | `wanderbooks`, the one executable: every mode (`serve`, `server`, `host`, `mcp`, `gui`, `setup`, `books`, `token`, `connect`, `doctor`, `licenses`, …) and the over-the-wire test suites | everything |
| `bookspec/checker`, `bookspec/runner` | the example schema and parser, the rule catalogue, the `Engine` trait; the per-rule runner | nothing of ours (the adapter in `ledger-core`'s tests depends on them) | | `bookspec/checker`, `bookspec/runner` | the example schema and parser, the rule catalogue, the `Engine` trait; the per-rule runner | nothing of ours (the adapter in `ledger-core`'s tests depends on them) |
@@ -116,6 +116,88 @@ appended journal lines; the UI renders an immutable view model rebuilt per
change. Statements and series come from `ledger-core` (`reports`, change. Statements and series come from `ledger-core` (`reports`,
`analysis`); the GUI only arranges them. See `plan/gui.md`. `analysis`); the GUI only arranges them. See `plan/gui.md`.
The viewer is **one window with a tab per open company** (P15, D-78;
`plan/p15-app-and-relay.md` 3.2). `App` (`app.rs`) holds what is the app's
(the color scheme and its menu, `scheme_menu.rs`; the tab bar, `tabs.rs`;
the data root the companies are in) and a list of `CompanyView`s
(`company.rs`), one per open company, with which is in front. The tab
bar runs across the whole window, above the sidebar: a tab is the top
level, and the sidebar (its pages, its status card) is the company in the
tab's. The tab is the company's identity in the frame (its badge and
name), and nothing else at the top of the window repeats it: the sidebar
has no header, its first link sits under the bar (`top_slot` in
`company.rs` is the empty place at the top of the sidebar and of the rail,
where the assistant's connection state is drawn later), and the Overview
opens with its summary sentence, not a heading with the name. The company
is named once more, at the opposite corner: the status card at the foot of
the sidebar begins with a heading row: the badge (small) and the name, cut
with an ellipsis, and at the card's right edge the live dot and "Live" (or
"Snapshot"); the name elides before the live word is ever clipped. The
heading's hover reads, a fact a line: the company's full name, "Live ·
event N", then the checks; the live word's accessible label is "Live ·
event N". The event is printed nowhere else in the card, and no text in it
wraps: every line is one row and elides (`the_status_card_never_wraps_in_any_state`).
The journal chain line is just "Journal chain verified". Folded (a short
window) the card is the heading alone, or, when a check failed, the heading
over one line naming it. The rail shows the badge with the live dot on its
corner (a warning there when a check failed), the name, state, event and
checks on hover. Each company has one badge
hue of eight (`theme::BADGE_HUES`, light and dark), chosen by a stable
hash of the id of its books (`theme::hue_index`, FNV-1a modulo eight: a
function of the id alone, so a company keeps its colour on every machine
and after a rename); its tab and its card draw the same one, and the
active tab's accent line stays the theme's. The bar's height (`tabs::BAR_H`) is taken from the
window; the viewer's smallest window is 400 points high, as before the bar. A tab is the company's badge and name, as wide as
that between a least and a greatest width; the "+" follows the last tab
and stays at the right edge, the tabs scrolling, when they overflow. The
app remembers each company's name when its books load (`company.<root>.<id>.name`
in its kept state, `<root>` being a hash of the data root's canonical path),
for a tab's title before the books load and for the
"+" list, which never reads a journal for a name. A view owns
everything that is one company's: its loader thread (its watcher and its
viewer presence on the books), the books it last loaded, where it is
(`Nav`), its page state, its receipts' workers, its export and owner menus,
its palette, its dock (and so the agent process in it) and its handle to
the `Owner`. Nothing is shared between views: every egui id a view makes is
scoped by its own id (the app draws a view inside `push_id`), so egui's
memory (scroll offsets, remembered widths) never carries from one tab into
another (a panel's id is not scoped by `push_id`, so the view's panels are
given ids made from its own; what the tabs share on purpose is the app's and
says so: the assistant dock's panel, whose height is one layout in every
tab, the tab bar, and the color scheme's palette); closing a tab drops its
view and with it all of that.
Every thread a view starts is counted in one registry of the view
(`jobs.rs`): its loader, its receipts' workers, an export, an owner's job,
the dock's start and the thread that reaps the dock's agent. Dropping the
view tells them all to stop, and the registry says when the last has ended
(`CompanyView::jobs_watch`). What each does on being told: the loader ends
(and the viewer's presence on the books is let go in the drop itself, not
when a refresh in flight is over), the receipts' workers end and write no
thumbnail, an export stops at its phase boundaries and saves nothing, a
read-only owner job (a backup, the check of a backup to restore) is not
begun or has its answer dropped, the dock's agent is hung up on and, if it
has not gone within two seconds, killed and reaped. One kind of job is never
abandoned: an owner's job that changes something (restore, the format
upgrade, new books, connect, close the books, update). While one runs, its
tab's close control is off and says what is running, and the window's close
is cancelled with a dialog that offers only to wait (`app.rs` INVARIANT 7;
`owner.rs` INVARIANT 6). A view that
is not in front still reads its loader every frame (so showing it later is
current at once) and takes the agent's `books.show` for its own page only.
`wanderbooks gui BOOK` opens that company as the only tab; with none named,
the companies that were open when the window last closed come back, in
their order, the same one in front, each with its page and its report's
period (`app.rs` INVARIANT 4). What is kept is filed under the data root
(a hash of its canonical path) and the company's id, with the books'
identity (the SHA-256 of the journal's first line) once they load: another
root's company of the same id, or the same id made again as other books,
inherits nothing, and a stored state whose identity is not the loaded
books' is discarded. A start that names a company never writes the list of
open companies, so one such start doesn't replace a set of tabs. The `Owner` the program installs
(`owner::set_owner`) is the program's, one per process; each view takes a
handle to it when it is made and a test can give a view another.
Two things sit beside the read-only view, both through the `Owner` the Two things sit beside the read-only view, both through the `Owner` the
program gives the viewer (never a write of the books by the viewer): program gives the viewer (never a write of the books by the viewer):
+272
View File
@@ -4376,6 +4376,278 @@ a client trickling an upload on purpose).
before it touches the book, and the gate's riding in the upload and before it touches the book, and the gate's riding in the upload and
download tasks. download tasks.
## P15 A3a: a tab per company (2026-11-20, D-78)
The viewer was a window on one company. It is now one window with a tab
per open company (`app.rs`, `company.rs`, `tabs.rs`). The work here is
the refactor and the tab bar; nothing starts or stops the books server and
no File menu is added. The tests look for exactly the failure a refactor
like this has: it compiles, the old tests pass, and two tabs share state.
Everything runs on scratch data roots that `Root::setup` makes in a temp
folder; no test touches an account's real books.
`crates/ledger-gui/tests/tabs.rs` (the bar's pictures run where there is a
renderer, as the sidebar's do):
- `each_tab_shows_its_own_company_and_figures`: two companies, cash
8,765.44 and 24,222.23, open in two tabs; each shows its own cash on the
overview, its own rent (1,234.56 / 777.77) in the profit and loss and
in the rent account's register, and never the other's; the tab opens on
its overview, not on the page the other was on; the window's title names
the company in front.
- `what_is_done_in_one_tab_changes_nothing_in_another`: in one tab a page,
a search, a report's period, columns and comparison are set; in the
other the page, the search and the period are as they were and every
text it paints is the same as before (and the other way round).
- `a_scrolled_sidebar_in_one_tab_is_not_scrolled_in_another`: egui's own
memory. In a short window the sidebar's links scroll; one tab's is
scrolled a page on, the other's is at the top, and the first is still
scrolled when it comes back. Fails (checked) when the view is not
drawn inside `push_id`.
- `no_two_views_have_the_same_id_or_key`.
- `a_background_tab_follows_its_journal_and_is_current_when_shown`: an
entry posted to the company of the tab behind is read while another tab
is in front (nothing is brought forward); when shown, its cash is the
new one on the first frames, with no reload.
- `books_show_moves_the_tab_it_is_aimed_at_and_only_that_one`: a show
request for the second company moves that tab to the journal; the tab in
front stays on its overview and in front.
- `closing_a_tab_releases_its_lock_its_threads_and_its_agent` (Unix): the
second tab's owner is its own (`set_owner` on the view; no process
global), its dock runs a stand-in agent (`sh -c 'echo $$ > pid; exec
sleep 600'`); closing the tab with its close control, the company's
viewer lock (`ops::viewer_open`) is released, its loader's thread has
ended (`Loader::watch`), the agent's process is gone; the other tab's
lock and loader are held and running; the company opens again with a new
lock.
- `plus_lists_only_the_companies_not_open_and_none_opens_twice`: "+" lists
`gamma` and neither open company; choosing it opens a third tab, in
front; the list then says every company is open; `App::open` and
`add_view` of an open company show its tab and add none.
- `start_up_restores_the_open_tabs_their_order_and_the_one_in_front`:
`gamma,gone,alpha,gamma,not a book!,beta` kept with `alpha` in front
opens gamma, alpha, beta with alpha in front, no error; no record, or a
record of companies that are all gone, opens the data root's first; a
front company not among the open ones leaves the first in front; a
company named on the command line is the only tab.
- `the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back`:
`save` writes `open_companies`, `active_company`, the old per-app keys
and each company's page, period, columns and comparison; a second start
from them restores all of it, each tab's own; a tab closed and opened
again comes back as it was left; with every tab closed the next start
opens the first company.
- `closing_the_front_tab_shows_a_neighbour_and_the_last_leaves_an_empty_window`:
the tab after, else before; the last leaves "No company is open" and
"Open a company with the + at the top of the window.", the bar still
there, and "+" opens a company from it.
- `the_tab_in_front_is_marked_by_more_than_colour`: the tab in front is
"selected" to assistive technology, the others are not; each has a close
control named for its company.
- `every_tab_never_writes_into_its_books_in_front_or_not`: `read_only.rs`'s
guarantee on two demo companies made read-only on disk: one follows live
behind the other, then every page is rendered in it (as `read_only.rs`
does), then the tabs are shown in turn; afterwards every file holds the
same bytes, size and time in both.
- `the_tab_bar_with_one_two_and_many_tabs`: pictures of the bar, light and
dark (`tests/snapshots/tabs_one_*`, `tabs_two_*`, `tabs_many_*`); with
ten tabs the bar scrolls, the tab in front is scrolled into view, and
the "+" is whole in the bar.
- `the_empty_window_and_the_plus_list`: pictures of the empty window and of
the "+" list open, light and dark (`tabs_empty_*`, `tabs_plus_*`).
- `the_bar_spans_the_window_above_the_sidebar`: on the laid-out rectangles,
the bar's fill is the window's width and `BAR_H` high at its top, every
tab is inside it, the first is over the sidebar's column, and the
sidebar's links and panel start below it.
- `the_plus_follows_the_last_tab_and_stays_whole_when_the_tabs_overflow`:
with two tabs the "+" is just after the last; with nine it is at the right
edge, whole, with the step controls shown and the tab in front left of it.
- `a_name_is_remembered_and_shown_in_the_plus_list_and_on_a_loading_tab`:
a closed company is listed by name with its id beside it, one never
opened by its id alone; the name is saved as `company.<id>.name`, and an
app started from it titles a tab whose books aren't loaded by that name
(else by the id).
- `the_plus_list_says_so_when_every_company_is_open`: "Every company is
already open." and no heading.
- `nothing_in_the_top_of_the_window_but_the_tab_shows_the_company_name`:
per theme, on the Overview, Cash and the Journal, no painted text or
widget in the tree below the bar and above 120 points names the company
(the tab and its close control are in the bar), and the status card
names the company in front once.
- `the_status_card_shows_the_company_in_front_and_follows_the_tab`: the
card's heading is the tab in front's name and its badge, small, in that
company's hue (the other's is not on the card), and both change when
another tab is shown; the window's title is unchanged.
- `the_rail_shows_the_badge_alone_with_the_name_on_hover`.
- `a_hue_is_the_books_id_alone_on_the_tab_and_the_card_in_both_themes_and_after_a_restart`:
the hue a tab and a card draw is the one the id gives, light and dark,
the same after a restart and in another order of opening, and pinned
for three ids (a change recolours every company).
- `the_overview_opens_with_its_summary_sentence_and_never_names_the_company`
and `the_overview_of_books_with_no_transactions_opens_the_same_way`: the
first text of the page is the sentence ("You have $8,765.44 in cash …",
or "No transactions yet. …"), set bigger than body text and smaller than
a page title, and no text on the page names the company (no sentence
there used the name).
- In `theme.rs`: `every_badge_hue_reads_in_both_themes` computes, for each
of the eight hues in each theme, the letter's contrast on the badge
(4.5:1, WCAG AA) and the badge's on the surface, sidebar, page and hover
colours (3:1); `a_hue_is_a_function_of_the_book_id_alone` pins the hash
and that every hue is used.
- `pictures` (ignored; `SHOT_DIR`): the whole window with one company, each
of two tabs in front, eight tabs, the "+" list, the empty window, the
rail with two companies, the smallest window and the Overview at its
top, light and dark, for a person to look at.
Unit tests moved with the code they test: the sidebar's fit tests, now
in `company.rs`; the scheme tests, in `scheme_menu.rs`. The tab bar runs
across the top of the window *above* the sidebar (D-78): a tab is the
top level, and the layout shows that the sidebar belongs to the company in
it. The bar takes `tabs::BAR_H` (36 points) of the window's height, which
the sidebar had to spare nowhere at the owner's 519 points. The status
card gave the height back (see "The sidebar tests' window sizes are
restored" below); the golden's crop and shapes hash cover only what is below
the bar. In `tabs.rs`, the
three tests that click a closed company in the "+" list by its id now click
it by its name, which the list shows once the company has been open; the
list's empty words are now "Every company is already open." The ten
`tabs_*` snapshots were regenerated for the new bar.
The company's name once, not three times (the owner's review of the bar):
the sidebar's header (badge, name, "Books") is gone, and so is the
Overview's heading, whose summary sentence is now the page's lead; the
status card's new heading row carries the company instead, with its hue.
That removed 28 points and the gap under the header from the top of the
sidebar and added a row to the card, so the sidebar has more room at every
height (at 1479x519 the links' viewport is 331 points, was 311, and the
rows 23 high, were 22); no `sidenav.rs` assertion or window changed. The
tall sidebar's shapes golden and pixel golden (`sidenav-1440x920`) were
regenerated (the header gone and the links moved up, the card's heading
row, the badge's hue), and the `tabs_*` snapshots again (hue, no
Overview heading, the rail's badge); `tabs_empty_*` are as they were.
**Not tested here:** the window title reaching the window system (the
harness has none: `window_title()` is what is tested); a company opened
from the viewer while its books are being created by the server (the
loader's retry loop is `live.rs`'s); macOS and Windows.
**For P12 (mutation targets):** `App::close`'s active-index arithmetic (the
`i < active` and `active >= len` arms); `App::add_view`'s duplicate key
test; `start_with`'s skip of a missing or repeated id and its choice of the
front tab; `CompanyView::pump`'s `shown` flag (a background tab must still
apply `Update::Books` and `Update::Show`); `Loader`'s drop wake-up and its
`gone` check after waking; the `push_id` in `CompanyView::ui` (the sidebar
test above kills its removal); `Dock::closed_with` (a new tab's dock opens
closed); `route_from_key` and the period codes in `CompanyView::restore`
(a start after the end is never restored).
## P15 A3a, the review's faults: threads, kept state, the dock (2026-11-20)
An independent review of the tab work confirmed the viewer writes nothing
and no figure crosses tabs, and found six faults. Each is fixed and each
fix has a test that was seen to fail with the fix switched off (the
mutation column says what was switched off).
1. **Jobs outlived their tab** (`jobs.rs`, `menu.rs`, `owner.rs`,
`dock.rs`, `receipts.rs`, `data.rs`). Every thread a tab starts is one
of a per-view registry that the view's drop tells to stop and that says,
on a condition, when the last has ended.
2. **Kept state was filed under the id alone** (`app.rs`, `company.rs`).
It is filed under the data root's hash and the id, with the books'
identity (the SHA-256 of the journal's first line).
3. **A named start erased the remembered tabs** (`app.rs`).
4. **The dock's height** is the app's one layout, said and tested; every
other id egui keys by a raw name was found and ruled on.
5. **Prompt release on close** (`data.rs`, `receipts.rs`).
6. **The sidebar tests' window sizes**: see below.
`crates/ledger-gui/tests/tabs.rs` (sections 14 to 17), `format_upgrade.rs`,
`exports.rs`, `live.rs` and unit tests in `jobs.rs` and `receipts.rs`:
- `closing_a_tab_releases_its_lock_its_threads_and_its_agent` (changed): the
tab's registry counts the loader, the receipts' and thumbnails' workers
and the dock's agent; after the close the test waits on the registry
(`Watch::wait_ended`, its limit a failure guard, 120 s, never what the
test relies on) and then asserts the viewer lock is free, the loader's
thread has ended and the agent's process is gone. It no longer polls.
- `a_restore_under_way_holds_its_tab_and_the_window_open`,
`an_upgrade_under_way_holds_its_tab_and_the_window_open`
(`format_upgrade.rs`): the owner's call is held in the test; while it
runs the tab's close control is disabled to assistive technology, a
click and `App::close` leave the tab, the window's close request is
cancelled and the dialog names the company and what runs and offers only
to wait; with nothing running the same request goes through; when the
call ends the dialog goes and the result is in the tab.
- `a_backup_only_reads_so_its_tab_closes_and_its_thread_ends`: a read-only
owner job holds nothing, its tab closes, its thread ends when the
owner's call does.
- `an_export_is_stopped_when_its_tab_closes` (the job is told) and
`a_stopped_export_leaves_no_file_whenever_it_is_told` (`exports.rs`: a
signal given after 0, 1, 2 and 3 looks, each leaving no file, the fifth
look none, which saves).
- `a_tab_closed_while_its_agent_is_starting_leaves_no_child_and_no_thread`
and `a_tab_closed_with_its_agent_running_ends_the_child_even_if_it_ignores_the_hangup`
(Unix): the start is one of the tab's threads and its answer, arriving
after the close, starts nothing; an agent that ignores the hang-up is
killed after `AGENT_GRACE` and reaped, and the registry says so.
- `another_data_root_with_a_company_of_the_same_id_inherits_nothing`,
`books_made_again_under_an_id_start_fresh_and_a_restart_of_the_same_books_does_not`,
`books_outside_any_data_root_are_kept_under_their_folder`,
`preferences_written_before_the_keys_had_a_root_are_read_and_not_used`:
the kept-state keys. (A set of books' identity says when it was made to
the second, so a test that makes other books under an id waits for the
clock's next second first.)
- `a_start_with_a_named_company_never_writes_the_list_of_open_companies`.
- `the_docks_height_and_layout_are_the_apps_one_for_every_tab`,
`no_panel_but_the_apps_own_is_keyed_by_an_id_every_tab_shares`,
`the_color_scheme_is_the_windows_one_for_every_tab`: what the tabs share
on purpose, and that nothing else is.
- `live.rs`: `a_loader_whose_books_cant_be_read_tries_no_more_once_it_is_dropped`
(counts `Snapshot::load` tries), `a_dropped_loader_lets_go_of_its_presence_at_once`
(no waiting for the thread).
- `receipts.rs`: `a_thumbnail_is_not_written_for_a_tab_that_has_closed`.
- `jobs.rs`: the registry itself (a count lives until the thread ends,
also on a panic; a kept job is what a tab is held for).
**Each fix was switched off to see its test fail** (a temporary
`WB_MUT=<name>` switch at each fix, removed again): the held owner jobs (two
switches: the hold, and the cancel of the window's close; the tab's off
control and `App::close`'s guard each), the stop signal, the thumbnail
write, the export's checks, the dock start's registration, the kill of an
agent that ignores its hang-up, the dock's raw panel id (scoped, the test
fails), the viewer presence's release in `Loader::drop`, the loader's gone
check and wake before a retry, the books' identity check, the root in the
key, the named start's write of the list, the panel ids of the sidebar,
and the receipts' workers' registration: each of the tests above that
covers it failed, and passed with the fix in. Not switchable and so not
shown to fail: `preferences_written_before_the_keys_had_a_root_are_read_and_not_used`
(it passes before and after: no migration is the rule) and
`books_outside_any_data_root_are_kept_under_their_folder`, whose second
folder is also told apart by its books' identity.
**The sidebar tests' window sizes are restored.** The status card gave back
the bar's height: its heading carries the live dot and word ("Live",
"Snapshot") at the card's right edge, the heading row is its badge's 16 high
(not a button's) and the card's vertical padding is 8. The event is not
printed in the card: it is the heading's hover ("name", "Live · event N",
the checks) and the live word's accessible label. The three check lines are
as they were before, with no event. The four `sidenav.rs` tests are at their
original sizes (1479x519, the rail at 519, the grid at 520 px, the tall
sidebar at 1440x920) with every assertion unchanged; at 1479x519 the links
have 6 px to spare in the common footers and 2 px in the failing-check ones
(where the rows tighten). The minimum window height is 400.
`the_status_card_never_wraps_in_any_state` (in `company.rs`) lays the card
out in each state (live, snapshot, each check passing, warning and failing,
folded and not) with a very long name and event 1,234,567 at the sidebar's
width (224, fixed, not resizable) and 200, and asserts every text is one row,
none runs out of the card, and the card's height is its rows plus its
padding. In `tabs.rs` the status-card test now asserts the live word sits at
the right of the name's row, no card text contains "event", and the
live word's label is "Live · event N" (it asserted the visible
"· event N" on the journal chain line); the rail test also asserts the name
leads the hover. In `sidenav.rs`, `the_folded_card_shows_its_checks_on_hover`
and the `"event "` locators still find the event, now through the live
word's label, unchanged.
## P12: the checklists ## P12: the checklists
The **For P12** paragraphs above (kept where they were written, with their The **For P12** paragraphs above (kept where they were written, with their