feat(gui): a tab owns its threads; kept state belongs to its books; one dock layout
An independent review of the tab work found that closing a tab did not end what the tab started, that what the viewer keeps was filed under the book id alone, and a few smaller things. All of it is the viewer's own state: nothing here writes the books. Threads: every thread a tab starts (loader, receipts' workers, export, owner job, the dock's start and its agent's reaper) is counted in one per-view registry (jobs.rs). Dropping the view tells them to stop and the registry says, on a condition, when the last has ended. An owner job that changes something (restore, format upgrade, new books, connect, close the books, check for updates, update) is never abandoned: its tab's close control is off with a hover text saying what runs, App::close refuses, and the window's close request is cancelled with a dialog that offers only to wait. Read-only jobs (an export, a backup, the restore's check) stop with the tab: an export checks at its phase boundaries and saves nothing (the save is one atomic write of a new file; one the stop reaches too late is removed). The dock's agent is hung up on and, if it ignores that for two seconds, killed and reaped; the window's drop waits for that. Release on close: the loader checks "gone" before every retry and between the phases of a load, its retry wait is woken by the drop, and the viewer presence is let go in the drop itself, not when a refresh in flight ends. A thumbnail for a closed tab is not written. Kept state: filed under a hash of the data root's canonical path and the id (books outside any root: under their folder), with the books' identity, the SHA-256 of the journal's first line, taken once they load. A stored state whose identity differs from the loaded books' is discarded with the remembered name. Old unkeyed keys are read without error and not used. A start that names a company never writes the list of open companies. The dock's height is the app's one layout in every tab (said in the spec block and tested); the sidebar, rail and top bar panels now take ids made from their view's, since egui keys a panel's size by the id as given. Every new test was seen to fail with its fix switched off. The four sidenav tests keep their BAR_H: at the owner's 519 they fail by 15 points (sidebar) and 11 (rail) without it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5cd0eded36
commit
ec436cfc02
16 files changed
+2388
-154
No files matched your search
+203
-40
@@ -19,15 +19,37 @@
|
||||
//! otherwise the companies open when the app last closed, in their
|
||||
//! order, the same one in front; a company that is gone is skipped
|
||||
//! without a word, and when none remains the data root's first opens.
|
||||
//! 4. What is kept for next time: the open companies (`open_companies`,
|
||||
//! A session started with a company named never writes the list of
|
||||
//! open companies, whatever it opens or closes: a plain start's list
|
||||
//! is not replaced by a one-tab session's. (Each company's own page
|
||||
//! and period are kept in both.)
|
||||
//! 4. What is kept for next time is kept for a company of a data root,
|
||||
//! by the root and the id: the open companies (`open_companies.<R>`,
|
||||
//! the ids of their books, comma separated) and the one in front
|
||||
//! (`active_company`); for each company its page, its report's
|
||||
//! period, columns and comparison and its name as last known
|
||||
//! (`company.<id>.…`); and, as
|
||||
//! before and under the same keys, the scheme and its filter
|
||||
//! (`scheme`, `scheme_filter`, `dark`) and the dock (`dock_open`,
|
||||
//! `dock_agent`, the front tab's).
|
||||
//! (`active_company.<R>`), `R` being a hash of the root's canonical
|
||||
//! path (`company::path_hash`); for each company its page, its
|
||||
//! report's period, columns and comparison, its name as last known
|
||||
//! and the identity of its books (`company.<R>.<id>.…`; books in a
|
||||
//! folder outside any root: `company.dir.<hash of the folder>.…`);
|
||||
//! and, under their own keys, the scheme and its filter (`scheme`,
|
||||
//! `scheme_filter`, `dark`) and the dock's preferences (`dock_open`,
|
||||
//! `dock_agent`, the front tab's: the app's). Another root holding a
|
||||
//! company of the same id, or the same id made again, is not this
|
||||
//! company: a stored state is used only for the books it was kept
|
||||
//! for, which each company's identity says once it loads
|
||||
//! (company.rs INVARIANT 5): a stored identity that is not the
|
||||
//! loaded books' discards the stored state and the remembered name,
|
||||
//! and they are kept anew for these books. Files written before the
|
||||
//! keys carried a root (`open_companies`, `company.<id>.…`) are
|
||||
//! read without error and not used.
|
||||
//! 5. The window's title names the company in front.
|
||||
//! 7. While a job that changes the books runs in any tab (an owner's
|
||||
//! restore or format upgrade: owner.rs INVARIANT 6), the window is
|
||||
//! not closed and that tab's close control is off, saying what is
|
||||
//! running; a request to close the window is cancelled and a dialog
|
||||
//! says what is running and offers only to wait; it goes when the
|
||||
//! job ends, and its result is shown in the tab. A read-only job
|
||||
//! (an export, a backup) is stopped with its tab, with no question.
|
||||
//! 6. The viewer stays read-only: a tab not in front reads what a tab
|
||||
//! in front reads, and writes nothing either.
|
||||
//! ```
|
||||
@@ -43,12 +65,34 @@ use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use crate::company::{COMPACT_BELOW, PageState, Shell};
|
||||
use crate::company::{kept_scope_of, path_hash};
|
||||
|
||||
/// Where the viewer keeps the companies that were open (the ids of their
|
||||
/// books, comma separated), and the one in front.
|
||||
/// books, comma separated), and the one in front: under these names, then
|
||||
/// the data root (`open_key`, `active_key`; INVARIANT 4).
|
||||
pub const OPEN_KEY: &str = "open_companies";
|
||||
pub const ACTIVE_KEY: &str = "active_company";
|
||||
|
||||
/// The key the open companies of the data root at `root` are kept under.
|
||||
pub fn open_key(root: &std::path::Path) -> String {
|
||||
format!("{OPEN_KEY}.{}", path_hash(root))
|
||||
}
|
||||
|
||||
/// The key the company in front, of the data root at `root`, is kept under.
|
||||
pub fn active_key(root: &std::path::Path) -> String {
|
||||
format!("{ACTIVE_KEY}.{}", path_hash(root))
|
||||
}
|
||||
|
||||
/// The key `thing` ("page", "range", "columns", "compare", "identity",
|
||||
/// "name") of the company whose books are in `data_dir` is kept under.
|
||||
pub fn company_key(data_dir: &std::path::Path, thing: &str) -> String {
|
||||
stored(&kept_scope_of(data_dir), thing)
|
||||
}
|
||||
|
||||
fn stored(scope: &str, thing: &str) -> String {
|
||||
format!("company.{scope}.{thing}")
|
||||
}
|
||||
|
||||
/// How the app starts.
|
||||
pub enum Start {
|
||||
/// This company alone: the one named on the command line, or the demo.
|
||||
@@ -88,6 +132,12 @@ pub struct App {
|
||||
/// What a first run opens its books with: the data root named, and
|
||||
/// "today".
|
||||
first_run_source: (Option<PathBuf>, Option<chrono::NaiveDate>),
|
||||
/// The window was asked to close while a job that changes the books
|
||||
/// ran, and the dialog that says so is up (INVARIANT 7).
|
||||
close_dialog: bool,
|
||||
/// Whether the list of open companies is written when the app saves
|
||||
/// (INVARIANT 3: not after a start that named a company).
|
||||
writes_open_list: bool,
|
||||
}
|
||||
|
||||
/// What a window is called when no company is in front.
|
||||
@@ -116,9 +166,11 @@ impl App {
|
||||
match start {
|
||||
Start::Only(source) => {
|
||||
app.today = source.today;
|
||||
app.writes_open_list = false;
|
||||
app.root = ledger_store::root::root_of_book_dir(&source.data_dir)
|
||||
.map(std::path::Path::to_path_buf);
|
||||
app.remember_all(get);
|
||||
app.remember_scope(get, &kept_scope_of(&source.data_dir));
|
||||
app.open(ctx, source);
|
||||
}
|
||||
Start::Restore { root, fallback } => {
|
||||
@@ -126,7 +178,7 @@ impl App {
|
||||
app.root = Some(root.clone());
|
||||
app.remember_all(get);
|
||||
let there = list_books(&root);
|
||||
let wanted: Vec<String> = get(OPEN_KEY)
|
||||
let wanted: Vec<String> = get(&open_key(&root))
|
||||
.map(|v| v.split(',').map(str::to_string).collect())
|
||||
.unwrap_or_default();
|
||||
let mut opened = Vec::new();
|
||||
@@ -152,7 +204,7 @@ impl App {
|
||||
app.open(ctx, fallback);
|
||||
} else {
|
||||
// The one in front last time, else the first.
|
||||
app.active = get(ACTIVE_KEY)
|
||||
app.active = get(&active_key(&root))
|
||||
.and_then(|front| opened.iter().position(|id| *id == front))
|
||||
.unwrap_or(0);
|
||||
// The dock left open was the front tab's.
|
||||
@@ -233,6 +285,8 @@ impl App {
|
||||
title: TITLE.to_string(),
|
||||
welcome: None,
|
||||
first_run_source: (None, None),
|
||||
close_dialog: false,
|
||||
writes_open_list: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,6 +326,54 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The jobs that change the books, running now in any tab, as the
|
||||
/// window is held open for them: each tab's name and what runs there
|
||||
/// (INVARIANT 7).
|
||||
pub fn holding(&self) -> Vec<(String, String)> {
|
||||
self.views
|
||||
.iter()
|
||||
.filter_map(|v| Some((self.title_of(v), v.closing_is_held()?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the dialog that says the window is held open is up (tests).
|
||||
pub fn close_dialog_is_up(&self) -> bool {
|
||||
self.close_dialog
|
||||
}
|
||||
|
||||
/// A request to close the window while a job that changes the books
|
||||
/// runs is cancelled and the dialog that says why is put up; the
|
||||
/// dialog goes when the job ends (INVARIANT 7).
|
||||
fn guard_close(&mut self, ctx: &egui::Context) {
|
||||
let held = self.holding();
|
||||
if held.is_empty() {
|
||||
self.close_dialog = false;
|
||||
return;
|
||||
}
|
||||
if ctx.input(|i| i.viewport().close_requested()) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
self.close_dialog = true;
|
||||
}
|
||||
if !self.close_dialog {
|
||||
return;
|
||||
}
|
||||
egui::Modal::new(egui::Id::new("wanderbooks-close-held")).show(ctx, |ui| {
|
||||
ui.set_max_width(460.0);
|
||||
ui.heading("The books are being changed");
|
||||
ui.add_space(4.0);
|
||||
ui.label(
|
||||
"The window stays open until this is done, so that nothing is cut off half way:",
|
||||
);
|
||||
for (company, what) in &held {
|
||||
ui.label(format!("{company}: {what}"));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
if ui.button("Wait for it to finish").clicked() {
|
||||
self.close_dialog = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The window's title now.
|
||||
pub fn window_title(&self) -> String {
|
||||
match self.active_view() {
|
||||
@@ -293,8 +395,8 @@ impl App {
|
||||
// What was kept for it (last run's, or from when it was closed
|
||||
// earlier in this one) comes back.
|
||||
let mut view = view;
|
||||
if let Some(id) = view.book_id() {
|
||||
view.restore(&|k| self.kept.get(&format!("company.{id}.{k}")).cloned());
|
||||
if let Some(scope) = view.kept_scope() {
|
||||
view.restore(&|k| self.kept.get(&stored(&scope, k)).cloned());
|
||||
}
|
||||
self.views.push(view);
|
||||
self.active = at;
|
||||
@@ -320,14 +422,20 @@ impl App {
|
||||
|
||||
/// Close tab `i`: its view is dropped (INVARIANT 2). The tab after it,
|
||||
/// else the one before, comes to the front when it was the front one.
|
||||
/// A tab with a job that changes the books under way is not closed
|
||||
/// (INVARIANT 7).
|
||||
pub fn close(&mut self, i: usize) {
|
||||
if i >= self.views.len() {
|
||||
return;
|
||||
}
|
||||
// A job that changes the books is never abandoned: its tab stays.
|
||||
if self.views[i].closing_is_held().is_some() {
|
||||
return;
|
||||
}
|
||||
let view = self.views.remove(i);
|
||||
if let Some(id) = view.book_id() {
|
||||
if let Some(scope) = view.kept_scope() {
|
||||
view.keep(&mut |k, v| {
|
||||
self.kept.insert(format!("company.{id}.{k}"), v);
|
||||
self.kept.insert(stored(&scope, k), v);
|
||||
});
|
||||
}
|
||||
drop(view);
|
||||
@@ -361,15 +469,22 @@ impl App {
|
||||
let Some(root) = self.root.clone() else {
|
||||
return;
|
||||
};
|
||||
let root_hash = path_hash(&root);
|
||||
for id in list_books(&root) {
|
||||
if let Some(name) = get(&format!("company.{id}.name")) {
|
||||
if let Some(name) = get(&stored(&format!("{root_hash}.{id}"), "name")) {
|
||||
self.names.insert(id.clone(), name);
|
||||
}
|
||||
for k in crate::company::KEPT_KEYS {
|
||||
let key = format!("company.{id}.{k}");
|
||||
if let Some(v) = get(&key) {
|
||||
self.kept.insert(key, v);
|
||||
}
|
||||
self.remember_scope(get, &format!("{root_hash}.{id}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// What was kept under `scope` (a company's), for the view that opens
|
||||
/// for it.
|
||||
fn remember_scope(&mut self, get: &dyn Fn(&str) -> Option<String>, scope: &str) {
|
||||
for k in crate::company::KEPT_KEYS {
|
||||
let key = stored(scope, k);
|
||||
if let Some(v) = get(&key) {
|
||||
self.kept.insert(key, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -412,6 +527,28 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Books that are not the books a company's kept state was kept for
|
||||
/// (their identity differs: made again under the id, or restored over
|
||||
/// it): the kept state and the remembered name are dropped, to be
|
||||
/// kept anew for these books (company.rs INVARIANT 5).
|
||||
fn check_identities(&mut self) {
|
||||
let mut stale = Vec::new();
|
||||
for v in &mut self.views {
|
||||
if v.check_identity() {
|
||||
stale.push((v.kept_scope(), v.book_id()));
|
||||
}
|
||||
}
|
||||
for (scope, id) in stale {
|
||||
if let Some(scope) = scope {
|
||||
let prefix = format!("company.{scope}.");
|
||||
self.kept.retain(|k, _| !k.starts_with(&prefix));
|
||||
}
|
||||
if let Some(id) = id {
|
||||
self.names.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Note the name of every company whose books are loaded.
|
||||
fn learn_names(&mut self) {
|
||||
for v in &self.views {
|
||||
@@ -581,6 +718,21 @@ fn list_books(root: &std::path::Path) -> Vec<String> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
impl Drop for App {
|
||||
/// The window is closing: every tab's threads are told to stop and
|
||||
/// waited for, so a dock's agent that ignored its hang-up is killed and
|
||||
/// reaped before the process ends and not left to outlive it. Bounded:
|
||||
/// the agent's grace and a little more.
|
||||
fn drop(&mut self) {
|
||||
let watches: Vec<_> = self.views.iter().map(CompanyView::jobs_watch).collect();
|
||||
self.views.clear();
|
||||
let limit = crate::dock::AGENT_GRACE + std::time::Duration::from_secs(3);
|
||||
for w in watches {
|
||||
w.wait_ended(limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
|
||||
// A first run: the page that sets the books up, until there are some.
|
||||
@@ -605,6 +757,8 @@ impl eframe::App for App {
|
||||
for (i, v) in self.views.iter_mut().enumerate() {
|
||||
v.pump(&ctx, i == self.active);
|
||||
}
|
||||
self.guard_close(&ctx);
|
||||
self.check_identities();
|
||||
self.learn_names();
|
||||
let tabs: Vec<Tab> = self
|
||||
.views
|
||||
@@ -612,6 +766,7 @@ impl eframe::App for App {
|
||||
.map(|v| {
|
||||
let title = self.title_of(v);
|
||||
Tab {
|
||||
held: v.closing_is_held(),
|
||||
detail: match v.book_id() {
|
||||
Some(id) if id != title => format!("{title}\n{id}"),
|
||||
_ => title.clone(),
|
||||
@@ -657,34 +812,42 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The companies open, in order, and the one in front.
|
||||
let open: Vec<(String, usize)> = self
|
||||
.views
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, v)| Some((v.book_id()?, i)))
|
||||
.collect();
|
||||
storage.set_string(
|
||||
OPEN_KEY,
|
||||
open.iter()
|
||||
.map(|(id, _)| id.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
);
|
||||
if let Some((id, _)) = open.iter().find(|(_, i)| *i == self.active) {
|
||||
storage.set_string(ACTIVE_KEY, id.clone());
|
||||
// The companies open, in order, and the one in front: not after a
|
||||
// start that named a company (INVARIANT 3).
|
||||
if self.writes_open_list
|
||||
&& let Some(root) = self.root.clone()
|
||||
{
|
||||
let open: Vec<(String, usize)> = self
|
||||
.views
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, v)| Some((v.book_id()?, i)))
|
||||
.collect();
|
||||
storage.set_string(
|
||||
&open_key(&root),
|
||||
open.iter()
|
||||
.map(|(id, _)| id.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
);
|
||||
if let Some((id, _)) = open.iter().find(|(_, i)| *i == self.active) {
|
||||
storage.set_string(&active_key(&root), id.clone());
|
||||
}
|
||||
}
|
||||
// What was kept for the companies closed, then for those open
|
||||
// (their own, as they are now).
|
||||
for (k, v) in &self.kept {
|
||||
storage.set_string(k, v.clone());
|
||||
}
|
||||
for (id, name) in &self.names {
|
||||
storage.set_string(&format!("company.{id}.name"), name.clone());
|
||||
if let Some(root) = &self.root {
|
||||
let root_hash = path_hash(root);
|
||||
for (id, name) in &self.names {
|
||||
storage.set_string(&stored(&format!("{root_hash}.{id}"), "name"), name.clone());
|
||||
}
|
||||
}
|
||||
for v in &self.views {
|
||||
if let Some(id) = v.book_id() {
|
||||
v.keep(&mut |k, val| storage.set_string(&format!("company.{id}.{k}"), val));
|
||||
if let Some(scope) = v.kept_scope() {
|
||||
v.keep(&mut |k, val| storage.set_string(&stored(&scope, k), val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,17 +16,38 @@
|
||||
//! 2. Every egui id a view makes is scoped by the view's own id (the app
|
||||
//! draws a view inside `push_id`), so egui's memory (scroll offsets,
|
||||
//! collapsed headers, focus, remembered widths) never carries from
|
||||
//! one company's tab into another's.
|
||||
//! one company's tab into another's. A panel's id is not scoped by
|
||||
//! `push_id` (egui keys a panel's size by the id it is given), so
|
||||
//! the view's panels (sidebar, rail, top bar) are given ids made from
|
||||
//! the view's own. What is not scoped is the app's, on purpose, and
|
||||
//! says so: the assistant dock's panel (one height, one layout in
|
||||
//! every tab: dock.rs INVARIANT 9), the tab bar's panel, the colour
|
||||
//! scheme's palette (one scheme for the window), and the footer and
|
||||
//! link rects published at fixed ids for the tests, which nothing
|
||||
//! reads back (`tests/tabs.rs` says each).
|
||||
//! 3. A view that is not shown still follows its journal and takes the
|
||||
//! agent's `books.show` (its own page moves, nothing else does), so
|
||||
//! showing it later is current at once.
|
||||
//! 4. Dropping a view ends everything it started: its loader and its
|
||||
//! watcher and viewer presence, its receipts' workers, and its
|
||||
//! dock's agent process.
|
||||
//! watcher and viewer presence, its receipts' workers, an export,
|
||||
//! the dock's start and its agent's process. They are all counted in
|
||||
//! one registry of the view (jobs.rs), which the drop tells to stop
|
||||
//! and which says when the last has ended (`jobs_watch`); the
|
||||
//! viewer's presence on the books is let go at the drop, not when a
|
||||
//! refresh in flight is over. One exception, by decision: a job that
|
||||
//! changes the books (an owner's restore or format upgrade, owner.rs
|
||||
//! INVARIANT 6) is never abandoned: while one runs the view cannot
|
||||
//! be closed (`closing_is_held`), nor the window (app.rs).
|
||||
//! 5. What the view keeps for next time is filed under the data root
|
||||
//! and the books' id (`kept_scope`), with the books' identity (the
|
||||
//! SHA-256 of the journal's first line, which no other books share)
|
||||
//! once they load; a stored state whose identity is not the loaded
|
||||
//! books' is another set of books' and is discarded (`check_identity`).
|
||||
//! ```
|
||||
|
||||
use crate::books::Books;
|
||||
use crate::data::{Loader, Source, Update};
|
||||
use crate::jobs::Jobs;
|
||||
use crate::nav::{Nav, Route, Section};
|
||||
use crate::owner::Owner;
|
||||
use crate::pages;
|
||||
@@ -98,6 +119,25 @@ pub struct CompanyView {
|
||||
/// Books arrived while the view wasn't shown: their receipts are
|
||||
/// prefetched when it is.
|
||||
prefetch_due: bool,
|
||||
/// Every thread this view started (INVARIANT 4): the loader, the
|
||||
/// receipts' workers, an export, an owner's job, the dock's start and
|
||||
/// its agent's reaper. Told to stop when the view drops (`Drop`).
|
||||
jobs: Jobs,
|
||||
/// What identifies these books, taken from the books themselves once
|
||||
/// they load, as it was kept (until then) or is now (INVARIANT 5).
|
||||
identity: Option<String>,
|
||||
/// The identity of the books as last loaded (None while there is no
|
||||
/// journal line to take it from).
|
||||
loaded_identity: Option<String>,
|
||||
}
|
||||
|
||||
impl Drop for CompanyView {
|
||||
/// The tab is closing: every thread it started is told to stop before
|
||||
/// anything else of the view goes (an export that hasn't saved yet
|
||||
/// saves nothing; a thumbnail not written is not written).
|
||||
fn drop(&mut self) {
|
||||
self.jobs.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// The key that tells a company's views apart: its books' folder, as the
|
||||
@@ -112,6 +152,8 @@ pub(crate) fn key_of(data_dir: &std::path::Path) -> String {
|
||||
impl CompanyView {
|
||||
fn bare(key: String, data_dir: Option<std::path::PathBuf>, ctx: &egui::Context) -> Self {
|
||||
let id = egui::Id::new(("company", &key));
|
||||
let jobs = Jobs::new();
|
||||
let spawner = jobs.spawner();
|
||||
Self {
|
||||
key,
|
||||
id,
|
||||
@@ -120,16 +162,19 @@ impl CompanyView {
|
||||
books: None,
|
||||
error: None,
|
||||
nav: Nav::new(Route::Overview),
|
||||
receipts: Receipts::new(ctx),
|
||||
receipts: Receipts::new(ctx, &spawner),
|
||||
state: PageState::default(),
|
||||
palette: crate::palette::Palette::scoped(id),
|
||||
updated_at: -1e9,
|
||||
live_label: false,
|
||||
menu: Default::default(),
|
||||
owner_menu: crate::owner::OwnerMenu::scoped(id),
|
||||
menu: crate::menu::Menu::in_tab(spawner.clone()),
|
||||
owner_menu: crate::owner::OwnerMenu::scoped(id, spawner),
|
||||
dock: Default::default(),
|
||||
owner: crate::owner::current(),
|
||||
prefetch_due: false,
|
||||
jobs,
|
||||
identity: None,
|
||||
loaded_identity: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +183,7 @@ impl CompanyView {
|
||||
pub fn open(ctx: &egui::Context, source: Source) -> Self {
|
||||
let mut view = Self::bare(key_of(&source.data_dir), Some(source.data_dir.clone()), ctx);
|
||||
view.receipts.thumb_dir = crate::receipts::thumb_dir();
|
||||
view.loader = Some(Loader::spawn(source, ctx.clone()));
|
||||
view.loader = Some(Loader::spawn_in(source, ctx.clone(), &view.jobs.spawner()));
|
||||
view
|
||||
}
|
||||
|
||||
@@ -146,6 +191,7 @@ impl CompanyView {
|
||||
pub fn with_books(ctx: &egui::Context, books: Books, start: Route) -> Self {
|
||||
let mut view = Self::bare(key_of(&books.data_dir), Some(books.data_dir.clone()), ctx);
|
||||
view.receipts.prefetch(&books);
|
||||
view.loaded_identity = identity_of(&books);
|
||||
view.books = Some(Arc::new(books));
|
||||
view.nav = Nav::new(start);
|
||||
view
|
||||
@@ -274,6 +320,38 @@ impl CompanyView {
|
||||
self.loader.as_ref().map(Loader::watch)
|
||||
}
|
||||
|
||||
/// A handle that says when every thread this view started has ended,
|
||||
/// which outlives the view: its loader, its receipts' workers, its
|
||||
/// exports and owner's jobs, the dock's start and its agent's reaper
|
||||
/// (INVARIANT 4; tests).
|
||||
pub fn jobs_watch(&self) -> crate::jobs::Watch {
|
||||
self.jobs.watch()
|
||||
}
|
||||
|
||||
/// What this view's threads hold its tab open for, if a job that
|
||||
/// changes the books runs (INVARIANT 4): the words the tab's close
|
||||
/// control shows.
|
||||
pub fn closing_is_held(&self) -> Option<String> {
|
||||
self.jobs.holding()
|
||||
}
|
||||
|
||||
/// Tell this view's threads to stop, as its close does; the signal a
|
||||
/// thread of it was given (tests).
|
||||
pub fn stop_signal(&self) -> crate::jobs::Stop {
|
||||
self.jobs.spawner().stop_signal()
|
||||
}
|
||||
|
||||
/// Start `work` as this view's export job would be started (tests: a
|
||||
/// job whose steps the test controls).
|
||||
pub fn start_export_for_tests(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
what: &str,
|
||||
work: Box<dyn FnOnce(&crate::jobs::Stop) -> crate::menu::Done + Send>,
|
||||
) {
|
||||
self.menu.start_with(ctx, what.to_string(), work);
|
||||
}
|
||||
|
||||
/// The agent dock (tests).
|
||||
pub fn dock_mut(&mut self) -> &mut crate::dock::Dock {
|
||||
&mut self.dock
|
||||
@@ -348,6 +426,7 @@ impl CompanyView {
|
||||
} else {
|
||||
self.prefetch_due = true;
|
||||
}
|
||||
self.loaded_identity = identity_of(&b);
|
||||
self.books = Some(b);
|
||||
self.error = None;
|
||||
}
|
||||
@@ -375,7 +454,7 @@ impl CompanyView {
|
||||
return;
|
||||
};
|
||||
if let Some(book) = crate::owner::book_id(&books) {
|
||||
self.dock.show(ui, &owner, &book);
|
||||
self.dock.show(ui, &owner, &book, &self.jobs.spawner());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,7 +702,7 @@ impl CompanyView {
|
||||
let p = pal(ui.ctx());
|
||||
let books = self.books.clone();
|
||||
let head = self.card_head(ui.ctx());
|
||||
egui::Panel::left("sidebar")
|
||||
egui::Panel::left(ui.id().with("sidebar"))
|
||||
.exact_size(224.0)
|
||||
.resizable(false)
|
||||
.frame(
|
||||
@@ -745,7 +824,7 @@ impl CompanyView {
|
||||
let p = pal(ui.ctx());
|
||||
let books = self.books.clone();
|
||||
let head = self.card_head(ui.ctx());
|
||||
egui::Panel::left("rail")
|
||||
egui::Panel::left(ui.id().with("rail"))
|
||||
.exact_size(RAIL_W)
|
||||
.resizable(false)
|
||||
.frame(
|
||||
@@ -877,7 +956,7 @@ impl CompanyView {
|
||||
/// nothing ever overlaps.
|
||||
fn topbar(&mut self, ui: &mut Ui) {
|
||||
let p = pal(ui.ctx());
|
||||
egui::Panel::top("topbar")
|
||||
egui::Panel::top(ui.id().with("topbar"))
|
||||
.exact_size(52.0)
|
||||
.frame(
|
||||
Frame::new()
|
||||
@@ -1000,10 +1079,84 @@ impl CompanyView {
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys a view keeps its things under (after `company.<id>.`).
|
||||
pub(crate) const KEPT_KEYS: [&str; 4] = ["page", "range", "columns", "compare"];
|
||||
/// The keys a view keeps its things under (after `company.<scope>.`; the
|
||||
/// company's name is kept by the app beside them, under `name`).
|
||||
pub(crate) const KEPT_KEYS: [&str; 5] = ["page", "range", "columns", "compare", "identity"];
|
||||
|
||||
/// A short, stable name for a place on disk: FNV-1a (64 bits) of its
|
||||
/// canonical path's bytes, in twelve hex digits. Stable across runs and
|
||||
/// versions (it is a key in a file); not a secret.
|
||||
pub fn path_hash(path: &std::path::Path) -> String {
|
||||
let real = ledger_store::root::canonical(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in real.as_os_str().as_encoded_bytes() {
|
||||
h ^= u64::from(*b);
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
format!("{:012x}", h & 0xffff_ffff_ffff)
|
||||
}
|
||||
|
||||
/// What a company's kept things are filed under: for books in a data
|
||||
/// root, the root (a hash of its canonical path) and the books' id,
|
||||
/// `<root hash>.<id>`; for books in a folder outside any root, that
|
||||
/// folder (`dir.<hash of its canonical path>`). Two roots' companies of
|
||||
/// one id are two companies.
|
||||
pub fn kept_scope_of(data_dir: &std::path::Path) -> String {
|
||||
match (
|
||||
ledger_store::root::root_of_book_dir(data_dir),
|
||||
data_dir.file_name().and_then(|n| n.to_str()),
|
||||
) {
|
||||
(Some(root), Some(id)) => format!("{}.{id}", path_hash(root)),
|
||||
_ => format!("dir.{}", path_hash(data_dir)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What identifies a set of books, from the books themselves: the SHA-256
|
||||
/// of the journal's first line (its canonical bytes: the very value the
|
||||
/// second line's `prev` repeats). Every set of books has its own first
|
||||
/// line (its timestamp, its first event); books made again under an old
|
||||
/// id, or restored over it from another set, do not share it. None until
|
||||
/// the journal has a line.
|
||||
pub fn identity_of(books: &Books) -> Option<String> {
|
||||
books
|
||||
.journal
|
||||
.first()
|
||||
.map(|l| ledger_store::journal::sha256_hex(l.to_canonical().as_bytes()))
|
||||
}
|
||||
|
||||
impl CompanyView {
|
||||
/// What this company's kept things are filed under ([`kept_scope_of`]),
|
||||
/// when its books are read from a folder.
|
||||
pub fn kept_scope(&self) -> Option<String> {
|
||||
self.data_dir.as_deref().map(kept_scope_of)
|
||||
}
|
||||
|
||||
/// The books' identity as kept, or as last loaded ([`identity_of`]).
|
||||
pub fn identity(&self) -> Option<&str> {
|
||||
self.identity.as_deref()
|
||||
}
|
||||
|
||||
/// Compare the identity kept with the loaded books' (INVARIANT 5).
|
||||
/// First load with nothing kept: the books' identity is taken and
|
||||
/// nothing changes. Kept, and the same: nothing changes. Kept, and
|
||||
/// not the same: these are other books than the kept state was of
|
||||
/// (made again under the id, or restored over it), so the state kept
|
||||
/// is dropped, this view starts as for new books, and true is
|
||||
/// returned: the caller drops what else it kept for them (their
|
||||
/// name).
|
||||
pub fn check_identity(&mut self) -> bool {
|
||||
let Some(now) = self.loaded_identity.clone() else {
|
||||
return false;
|
||||
};
|
||||
let changed = self.identity.as_ref().is_some_and(|kept| *kept != now);
|
||||
if changed {
|
||||
self.nav = Nav::new(Route::Overview);
|
||||
self.state.reports = Default::default();
|
||||
}
|
||||
self.identity = Some(now);
|
||||
changed
|
||||
}
|
||||
|
||||
/// What a person expects to come back to: the page and the report's
|
||||
/// period, columns and comparison. (A detail page comes back as its
|
||||
/// list: the entry or the party may not be there any more.)
|
||||
@@ -1043,12 +1196,16 @@ impl CompanyView {
|
||||
}
|
||||
.to_string(),
|
||||
);
|
||||
if let Some(identity) = &self.identity {
|
||||
set("identity", identity.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Take back what [`Self::keep`] kept (`get` reads a key; what isn't
|
||||
/// there, or isn't understood, is left as it is).
|
||||
pub fn restore(&mut self, get: &dyn Fn(&str) -> Option<String>) {
|
||||
use crate::pages::reports::{Columns, Compare, Range};
|
||||
self.identity = get("identity");
|
||||
if let Some(route) = get("page").and_then(|k| route_from_key(&k)) {
|
||||
self.nav = Nav::new(route);
|
||||
}
|
||||
|
||||
+121
-10
@@ -34,23 +34,55 @@ pub enum Update {
|
||||
Show(ledger_store::ops::ViewerTarget),
|
||||
}
|
||||
|
||||
/// The viewer's presence on the books (`ledger_store::ops::Presence`), held
|
||||
/// by the loader's thread and let go by whichever comes first: the thread's
|
||||
/// end, or the loader's drop (so a tab's close releases it at once, not
|
||||
/// when a refresh in flight is over).
|
||||
type PresenceSlot = Arc<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 {
|
||||
rx: Receiver<Update>,
|
||||
/// Set when this is dropped: the loader's thread then ends, letting go
|
||||
/// of the books (and the viewer's presence on them).
|
||||
gone: Arc<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>);
|
||||
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 {
|
||||
@@ -70,31 +102,66 @@ impl Drop for Ends {
|
||||
impl Drop for Loader {
|
||||
fn drop(&mut self) {
|
||||
self.gone.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
// The viewer's presence goes now: the thread may be inside a
|
||||
// refresh that takes a while, and the books are no longer looked
|
||||
// at. The thread takes a presence only while `gone` is unset,
|
||||
// under this lock, so none is taken after this.
|
||||
drop(
|
||||
self.presence
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.take(),
|
||||
);
|
||||
let _ = self.wake.send(());
|
||||
}
|
||||
}
|
||||
|
||||
impl Loader {
|
||||
/// A loader that no tab owns (tests, one-shot tools).
|
||||
pub fn spawn(source: Source, ctx: egui::Context) -> Loader {
|
||||
Self::spawn_in(source, ctx, &crate::jobs::Spawner::default())
|
||||
}
|
||||
|
||||
/// A loader whose thread is one of a tab's: counted in `jobs` until it
|
||||
/// has ended (jobs.rs INVARIANT 1).
|
||||
pub fn spawn_in(source: Source, ctx: egui::Context, jobs: &crate::jobs::Spawner) -> Loader {
|
||||
let ticket = jobs.ticket("books-loader", crate::jobs::Hold::Free);
|
||||
let presence: PresenceSlot = Arc::default();
|
||||
let thread_presence = presence.clone();
|
||||
let (tx, rx) = channel();
|
||||
let (wake, events) = channel();
|
||||
let gone = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let ended = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let attempts = Arc::new(Probe::default());
|
||||
let thread_attempts = attempts.clone();
|
||||
let stop = gone.clone();
|
||||
let ends = Ends(ended.clone());
|
||||
let wake_to_watcher = wake.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("books-loader".into())
|
||||
.spawn(move || {
|
||||
// Dropped last: the thread has let go of everything.
|
||||
let _ticket = ticket;
|
||||
let _ends = ends;
|
||||
run(source, ctx, tx, &stop, wake_to_watcher, events)
|
||||
run(
|
||||
source,
|
||||
ctx,
|
||||
tx,
|
||||
&stop,
|
||||
&thread_presence,
|
||||
&thread_attempts,
|
||||
wake_to_watcher,
|
||||
events,
|
||||
)
|
||||
})
|
||||
.expect("spawn loader");
|
||||
Loader {
|
||||
rx,
|
||||
gone,
|
||||
presence,
|
||||
wake,
|
||||
ended,
|
||||
attempts,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,7 +183,7 @@ impl Loader {
|
||||
|
||||
/// A handle that outlives the loader and says when its thread ended.
|
||||
pub fn watch(&self) -> LoaderWatch {
|
||||
LoaderWatch(self.ended.clone())
|
||||
LoaderWatch(self.ended.clone(), self.attempts.clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,11 +234,14 @@ pub fn settings(snap: &Snapshot) -> BooksSettings {
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run(
|
||||
source: Source,
|
||||
ctx: egui::Context,
|
||||
tx: Sender<Update>,
|
||||
gone: &std::sync::atomic::AtomicBool,
|
||||
presence: &PresenceSlot,
|
||||
attempts: &Probe,
|
||||
ev_tx: Sender<()>,
|
||||
ev_rx: Receiver<()>,
|
||||
) {
|
||||
@@ -180,20 +250,40 @@ fn run(
|
||||
let _ = tx.send(u);
|
||||
ctx.request_repaint();
|
||||
};
|
||||
// Gone is looked at before every try and between the phases of a load
|
||||
// (the load itself, the picture built from it, the send): a tab closed
|
||||
// while the books can't be read costs no further load.
|
||||
let mut snap = loop {
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
attempts
|
||||
.attempts
|
||||
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
match Snapshot::load(&source.data_dir) {
|
||||
Ok(s) => break s,
|
||||
Err(e) => {
|
||||
send(Update::Error(problem(&e, || {
|
||||
format!("Can't read the books in {}", source.data_dir.display())
|
||||
})));
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
send(Update::Error(problem(&e, || {
|
||||
format!("Can't read the books in {}", source.data_dir.display())
|
||||
})));
|
||||
// Woken at once by the loader's drop, not at the next try.
|
||||
attempts
|
||||
.waiting
|
||||
.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let _ = ev_rx.recv_timeout(Duration::from_secs(2));
|
||||
attempts
|
||||
.waiting
|
||||
.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
while ev_rx.try_recv().is_ok() {}
|
||||
}
|
||||
}
|
||||
};
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
let mut verified: HashSet<String> = HashSet::new();
|
||||
// Build the picture; also return the database check it was built with.
|
||||
let mut build = |snap: &Snapshot, prev: Option<u64>| -> (Update, ledger_store::DiskCheck) {
|
||||
@@ -209,6 +299,9 @@ fn run(
|
||||
};
|
||||
let (first, disk) = build(&snap, None);
|
||||
let mut last_disk = Some(disk);
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
send(first);
|
||||
|
||||
// Requests to show something: apply new ones, and on start one made in
|
||||
@@ -245,7 +338,6 @@ fn run(
|
||||
// held there while it runs (ledger_store::ops INVARIANT 3).
|
||||
let ops = ledger_store::ops::ops_dir(&source.data_dir);
|
||||
let mut ops_watched = false;
|
||||
let mut presence: Option<ledger_store::ops::Presence> = None;
|
||||
let mut look_at_ops = |watcher: &mut Option<notify::RecommendedWatcher>| {
|
||||
if !ops_watched
|
||||
&& ops.is_dir()
|
||||
@@ -253,10 +345,17 @@ fn run(
|
||||
{
|
||||
ops_watched = w.watch(&ops, RecursiveMode::NonRecursive).is_ok();
|
||||
}
|
||||
if presence.is_none() {
|
||||
presence = ledger_store::ops::Presence::hold(&source.data_dir);
|
||||
// Taken under the slot's lock and only while not gone: the
|
||||
// loader's drop sets `gone` and then empties the slot, so a
|
||||
// presence is never taken after a tab closed.
|
||||
let mut held = presence.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if held.is_none() && !gone() {
|
||||
*held = ledger_store::ops::Presence::hold(&source.data_dir);
|
||||
}
|
||||
};
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
look_at_ops(&mut watcher);
|
||||
let day_now = |snap: &Snapshot| today(&source, &settings(snap));
|
||||
let mut day = day_now(&snap);
|
||||
@@ -272,6 +371,9 @@ fn run(
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
@@ -289,6 +391,9 @@ fn run(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
look_at_ops(&mut watcher);
|
||||
let new_day = day_now(&snap);
|
||||
// The writer journals first and updates its database right after:
|
||||
@@ -302,8 +407,14 @@ fn run(
|
||||
day = new_day;
|
||||
let (update, disk) = build(&snap, grew.then_some(before));
|
||||
last_disk = Some(disk);
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
send(update);
|
||||
}
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
check_show(&send);
|
||||
}
|
||||
}
|
||||
+126
-11
@@ -30,6 +30,23 @@
|
||||
//! 7. Offered only where it has been checked to work (Linux and macOS):
|
||||
//! a ConPTY agent on Windows must pass the four checks (it starts,
|
||||
//! `/login` works, resize redraws, Ctrl-C reaches it) before it is.
|
||||
//! 8. The agent belongs to its tab. The start (finding the agent and
|
||||
//! making its books home, off the UI thread) is one of the tab's
|
||||
//! threads (jobs.rs) and is told to stop with it; the child process
|
||||
//! is started only by a tab that is shown, on the UI thread, once
|
||||
//! the start's answer is in, so a tab closed mid-start starts none.
|
||||
//! A session dropped (its tab closed, the agent restarted) is shut
|
||||
//! down, its child hung up on (SIGHUP) and reaped, its terminal
|
||||
//! closed; one that has not gone [`AGENT_GRACE`] later is killed
|
||||
//! (SIGKILL, that pid alone, which this dock started) and reaped.
|
||||
//! The reaping is a thread of the tab's, so the tab can say when
|
||||
//! nothing of its agent is left (`CompanyView::jobs_watch`).
|
||||
//! 9. The panel's height, and whether the dock is open by default, are
|
||||
//! the app's, not a tab's: one layout for the assistant dock in
|
||||
//! every tab. egui keys a panel's size by its id as given, `push_id`
|
||||
//! scoping notwithstanding, so the panel's raw ids ("dock-open",
|
||||
//! "dock-closed") are the one place the tabs share; that is the
|
||||
//! rule, said and tested (`tests/tabs.rs`).
|
||||
//! ```
|
||||
|
||||
use crate::owner::{Agent, AgentStart, Installer, Owner};
|
||||
@@ -133,8 +150,65 @@ pub struct Session {
|
||||
cells: Cells,
|
||||
exited: Arc<AtomicBool>,
|
||||
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 {
|
||||
/// Run `program args` in `dir` with `env` added, on a terminal of `cells`;
|
||||
/// `wake` is called when there is something new to draw.
|
||||
@@ -145,6 +219,7 @@ impl Session {
|
||||
env: &[(String, String)],
|
||||
cells: Cells,
|
||||
wake: Arc<dyn Fn() + Send + Sync>,
|
||||
jobs: &crate::jobs::Spawner,
|
||||
) -> Result<Session, String> {
|
||||
let window = WindowSize {
|
||||
num_lines: cells.rows,
|
||||
@@ -163,7 +238,9 @@ impl Session {
|
||||
#[cfg(windows)]
|
||||
escape_args: true,
|
||||
};
|
||||
let ticket = jobs.ticket("dock agent", crate::jobs::Hold::Free);
|
||||
let pty = tty::new(&options, window, 0).map_err(|e| e.to_string())?;
|
||||
let pid = pty.child().id();
|
||||
let exited = Arc::new(AtomicBool::new(false));
|
||||
let to_pty = Arc::new(Mutex::new(None));
|
||||
let size = Arc::new(Mutex::new(window));
|
||||
@@ -184,8 +261,9 @@ impl Session {
|
||||
EventLoop::new(term.clone(), proxy, pty, true, false).map_err(|e| e.to_string())?;
|
||||
let sender = event_loop.channel();
|
||||
*to_pty.lock().unwrap_or_else(|e| e.into_inner()) = Some(sender.clone());
|
||||
// Its thread ends on Shutdown, and its terminal's child with it.
|
||||
drop(event_loop.spawn());
|
||||
// Its thread ends on Shutdown, and its terminal's child with it
|
||||
// (its drop, reaped by `reap`).
|
||||
let handle = event_loop.spawn();
|
||||
Ok(Session {
|
||||
term,
|
||||
to_pty: sender,
|
||||
@@ -193,6 +271,9 @@ impl Session {
|
||||
cells,
|
||||
exited,
|
||||
title,
|
||||
pid,
|
||||
end: Some(Box::new(move || drop(handle.join()))),
|
||||
ticket: Some(ticket),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -254,6 +335,9 @@ impl Session {
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.to_pty.send(Msg::Shutdown);
|
||||
if let Some(end) = self.end.take() {
|
||||
reap(end, self.pid, self.ticket.take());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,19 +606,43 @@ impl Dock {
|
||||
|
||||
/// Start (or restart) the agent for `book`: found and its books home
|
||||
/// made off the UI thread, then run.
|
||||
fn start(&mut self, ctx: &egui::Context, owner: &Arc<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 (o, agent, b, ctx) = (owner.clone(), self.agent, book.to_string(), ctx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(o.agent_start(agent, &b));
|
||||
let started = jobs.spawn("agent start", crate::jobs::Hold::Free, move |stop| {
|
||||
if stop.requested() {
|
||||
return;
|
||||
}
|
||||
let answer = o.agent_start(agent, &b);
|
||||
// Its tab closed meanwhile: the answer is nobody's.
|
||||
if stop.requested() {
|
||||
return;
|
||||
}
|
||||
let _ = tx.send(answer);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
self.state = State::Starting(rx);
|
||||
self.state = if started {
|
||||
State::Starting(rx)
|
||||
} else {
|
||||
State::Failed("the system gave no thread to start it".into())
|
||||
};
|
||||
self.book = Some(book.to_string());
|
||||
}
|
||||
|
||||
/// The panel along the bottom of the window, for `book`'s agent.
|
||||
pub fn show(&mut self, ui: &mut Ui, owner: &Arc<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());
|
||||
// Another book is shown: its own agent, not the last one's.
|
||||
if self.book.as_deref().is_some_and(|b| b != book) {
|
||||
@@ -565,6 +673,7 @@ impl Dock {
|
||||
rows: 24,
|
||||
},
|
||||
wake,
|
||||
jobs,
|
||||
) {
|
||||
Ok(s) => {
|
||||
self.focused = true;
|
||||
@@ -578,7 +687,7 @@ impl Dock {
|
||||
};
|
||||
}
|
||||
if self.open && matches!(self.state, State::Idle) {
|
||||
self.start(ui.ctx(), owner, book);
|
||||
self.start(ui.ctx(), owner, book, jobs);
|
||||
}
|
||||
let header = 34.0;
|
||||
let panel = // Its own id open and closed: a size is remembered for each.
|
||||
@@ -600,7 +709,7 @@ impl Dock {
|
||||
if self.open {
|
||||
ui.set_min_height(ui.available_height());
|
||||
}
|
||||
self.header(ui, owner, book);
|
||||
self.header(ui, owner, book, jobs);
|
||||
if !self.open {
|
||||
return;
|
||||
}
|
||||
@@ -609,7 +718,13 @@ impl Dock {
|
||||
});
|
||||
}
|
||||
|
||||
fn header(&mut self, ui: &mut Ui, owner: &Arc<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 mut restart = false;
|
||||
ui.horizontal(|ui| {
|
||||
@@ -682,7 +797,7 @@ impl Dock {
|
||||
});
|
||||
if restart {
|
||||
self.state = State::Idle;
|
||||
self.start(ui.ctx(), owner, book);
|
||||
self.start(ui.ctx(), owner, book, jobs);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub mod demo;
|
||||
pub mod dock;
|
||||
pub mod export;
|
||||
pub mod fmt;
|
||||
pub mod jobs;
|
||||
pub mod menu;
|
||||
pub mod nav;
|
||||
pub mod owner;
|
||||
|
||||
@@ -17,6 +17,16 @@
|
||||
//! missing TIN never stops the file: the package lists the gaps.
|
||||
//! 3. The file is saved as a new file in Downloads (export::save), never
|
||||
//! over one, off the UI thread; what came of it is shown.
|
||||
//! 4. An export belongs to its tab: closing the tab, with no question,
|
||||
//! tells the job to stop (jobs.rs). It checks at its phase
|
||||
//! boundaries (before and after the books are read, after the file
|
||||
//! is built, and just before it is saved) and stops there, saving
|
||||
//! nothing: the save is one atomic write of a new file
|
||||
//! (`ledger_store::saving`: written aside whole and linked in), so a
|
||||
//! file is whole or is not there, and one that a stop reaches
|
||||
//! too late to prevent (it came after the last check) is removed
|
||||
//! again, being the job's own new file. What the builder
|
||||
//! (`ledger_package`) does inside one call is not interrupted.
|
||||
//! ```
|
||||
|
||||
use crate::books::Books;
|
||||
@@ -35,9 +45,19 @@ pub type Done = Result<(PathBuf, Option<String>), String>;
|
||||
pub struct Menu {
|
||||
job: Option<(String, Receiver<Done>)>,
|
||||
done: Option<(String, Done)>,
|
||||
/// The tab's threads: the job is one of them (INVARIANT 4).
|
||||
jobs: crate::jobs::Spawner,
|
||||
}
|
||||
|
||||
impl Menu {
|
||||
/// A menu whose jobs are threads of a tab.
|
||||
pub fn in_tab(jobs: crate::jobs::Spawner) -> Self {
|
||||
Self {
|
||||
jobs,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu button, its items, and a note of the last job's outcome.
|
||||
pub fn ui(&mut self, ui: &mut Ui, books: &Arc<Books>, compact: bool) {
|
||||
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) {
|
||||
let (tx, rx) = channel();
|
||||
let what = job.label();
|
||||
self.start_with(ctx, what, Box::new(move |stop| job.run_until(&books, stop)));
|
||||
}
|
||||
|
||||
/// Run `work` as an export job: off the UI thread, one of the tab's
|
||||
/// threads, told to stop with the tab (INVARIANT 4).
|
||||
pub fn start_with(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
what: String,
|
||||
work: Box<dyn FnOnce(&crate::jobs::Stop) -> Done + Send>,
|
||||
) {
|
||||
let (tx, rx) = channel();
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(job.run(&books));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
let started = self
|
||||
.jobs
|
||||
.spawn("export", crate::jobs::Hold::Free, move |stop| {
|
||||
let _ = tx.send(work(stop));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
if !started {
|
||||
self.done = Some((what, Err("the system gave no thread for it".into())));
|
||||
return;
|
||||
}
|
||||
self.job = Some((what, rx));
|
||||
self.done = None;
|
||||
}
|
||||
@@ -148,7 +185,20 @@ impl Job {
|
||||
|
||||
/// Make the file and save it (INVARIANTS 1-3).
|
||||
pub fn run(self, books: &Books) -> Done {
|
||||
self.run_until(books, &crate::jobs::Stop::never())
|
||||
}
|
||||
|
||||
/// [`Self::run`], stopping at its phase boundaries when `stop` is
|
||||
/// given, saving nothing (INVARIANT 4).
|
||||
pub fn run_until(self, books: &Books, stop: &crate::jobs::Stop) -> Done {
|
||||
let stopped = || -> Done { Err("stopped: its tab was closed".into()) };
|
||||
if stop.requested() {
|
||||
return stopped();
|
||||
}
|
||||
let snap = ledger_store::Snapshot::load(&books.data_dir).map_err(|e| e.to_string())?;
|
||||
if stop.requested() {
|
||||
return stopped();
|
||||
}
|
||||
let ledger = snap.ledger();
|
||||
// The settings the rest of the viewer shows, read as the server
|
||||
// reads them (data::settings).
|
||||
@@ -176,8 +226,17 @@ impl Job {
|
||||
tins: Some(&tin),
|
||||
},
|
||||
)?;
|
||||
if stop.requested() {
|
||||
return stopped();
|
||||
}
|
||||
let (stem, ext) = crate::export::split_name(&p.file_name);
|
||||
let path = crate::export::save(stem, ext, &p.zip)?;
|
||||
if stop.requested() {
|
||||
// Reached too late to stop the write: the new file it
|
||||
// made is the job's own, and goes.
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return stopped();
|
||||
}
|
||||
let mut notes = Vec::new();
|
||||
if !p.tin_gaps.is_empty() {
|
||||
notes.push(format!(
|
||||
@@ -205,8 +264,15 @@ impl Job {
|
||||
)?;
|
||||
let csv = ledger_package::vendor_1099_csv(&w, true);
|
||||
let name = ledger_package::vendor_1099_csv_name(year, true);
|
||||
if stop.requested() {
|
||||
return stopped();
|
||||
}
|
||||
let (stem, ext) = crate::export::split_name(&name);
|
||||
let path = crate::export::save(stem, ext, csv.as_bytes())?;
|
||||
if stop.requested() {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return stopped();
|
||||
}
|
||||
let gaps = w
|
||||
.lines
|
||||
.iter()
|
||||
|
||||
+140
-37
@@ -29,6 +29,17 @@
|
||||
//! owner's `upgrade_format` (the server checks it; nothing here
|
||||
//! does). "Not now" changes nothing; a refusal (a wrong passphrase)
|
||||
//! is said in the dialog, which stays.
|
||||
//! 6. An action that changes or replaces the books, their format or
|
||||
//! what the owner holds (restore, the format upgrade, new books,
|
||||
//! connect, close the books, check for updates, update) is never
|
||||
//! abandoned: while one runs, its tab's close control is off, with
|
||||
//! the words of what is running ("Restoring these books: wait for it
|
||||
//! to finish"), and the window's close is held (app.rs); its result
|
||||
//! is shown in that tab when it ends. A read-only one (back up now,
|
||||
//! the restore's check of a backup) is stopped with the tab: it does
|
||||
//! not start once the tab has closed, and what it sends after is
|
||||
//! dropped (a request the books server already has it finishes: the
|
||||
//! viewer only reads its answer).
|
||||
//! ```
|
||||
|
||||
use crate::books::Books;
|
||||
@@ -231,6 +242,31 @@ pub fn book_id(books: &Books) -> Option<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.
|
||||
#[derive(Default)]
|
||||
enum Dialog {
|
||||
@@ -323,16 +359,20 @@ pub struct OwnerMenu {
|
||||
/// The update waiting, as last read, and when (re-read every few
|
||||
/// seconds and after any job).
|
||||
update: Option<(std::time::Instant, Option<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.
|
||||
const UPDATE_LOOK: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
impl OwnerMenu {
|
||||
/// A menu whose ids belong to the view `scope`.
|
||||
pub fn scoped(scope: egui::Id) -> Self {
|
||||
/// A menu whose ids belong to the view `scope`, and whose jobs are
|
||||
/// threads of that view (`jobs`).
|
||||
pub fn scoped(scope: egui::Id, jobs: crate::jobs::Spawner) -> Self {
|
||||
Self {
|
||||
scope: Some(scope),
|
||||
jobs,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -411,7 +451,14 @@ impl OwnerMenu {
|
||||
});
|
||||
});
|
||||
if let Some(work) = start {
|
||||
self.start(ui.ctx(), "Update".into(), work);
|
||||
self.start(
|
||||
ui.ctx(),
|
||||
(
|
||||
"Update".into(),
|
||||
Effect::Changes("Updating wanderbooks"),
|
||||
work,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
let Some(upgrade) = books.format_upgrade.clone() else {
|
||||
@@ -500,7 +547,7 @@ impl OwnerMenu {
|
||||
}
|
||||
let busy = self.job.is_some();
|
||||
let waiting = self.update_waiting(ui.ctx(), &owner);
|
||||
let mut start: Option<(String, Box<dyn FnOnce() -> Outcome + Send>)> = None;
|
||||
let mut start: Option<Start> = None;
|
||||
let response = ui
|
||||
.add_enabled_ui(!busy, |ui| {
|
||||
egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| {
|
||||
@@ -511,7 +558,11 @@ impl OwnerMenu {
|
||||
.clicked()
|
||||
{
|
||||
let (o, b) = (owner.clone(), book.clone());
|
||||
start = Some(("Back up now".into(), Box::new(move || o.back_up_now(&b))));
|
||||
start = Some((
|
||||
"Back up now".into(),
|
||||
Effect::Reads,
|
||||
Box::new(move || o.back_up_now(&b)),
|
||||
));
|
||||
}
|
||||
if ui
|
||||
.button(format!("{} Restore…", icon::CLOCK_COUNTER_CLOCKWISE))
|
||||
@@ -543,6 +594,10 @@ impl OwnerMenu {
|
||||
let (o, b) = (owner.clone(), book.clone());
|
||||
start = Some((
|
||||
format!("Connect {}", agent.label()),
|
||||
Effect::Changes(match agent {
|
||||
Agent::Claude => "Connecting Claude Code to these books",
|
||||
Agent::Codex => "Connecting Codex to these books",
|
||||
}),
|
||||
Box::new(move || o.connect(agent, &b)),
|
||||
));
|
||||
}
|
||||
@@ -564,7 +619,11 @@ impl OwnerMenu {
|
||||
.clicked()
|
||||
{
|
||||
let o = owner.clone();
|
||||
start = Some(("Check for updates".into(), Box::new(move || o.check_for_updates())));
|
||||
start = Some((
|
||||
"Check for updates".into(),
|
||||
Effect::Changes("Checking for updates"),
|
||||
Box::new(move || o.check_for_updates()),
|
||||
));
|
||||
}
|
||||
if let Some(u) = &waiting
|
||||
&& ui
|
||||
@@ -573,7 +632,11 @@ impl OwnerMenu {
|
||||
.clicked()
|
||||
{
|
||||
let o = owner.clone();
|
||||
start = Some(("Update".into(), Box::new(move || o.apply_update())));
|
||||
start = Some((
|
||||
"Update".into(),
|
||||
Effect::Changes("Updating wanderbooks"),
|
||||
Box::new(move || o.apply_update()),
|
||||
));
|
||||
}
|
||||
ui.separator();
|
||||
if ui
|
||||
@@ -586,8 +649,8 @@ impl OwnerMenu {
|
||||
})
|
||||
})
|
||||
.inner;
|
||||
if let Some((what, work)) = start {
|
||||
self.start(ui.ctx(), what, work);
|
||||
if let Some(start) = start {
|
||||
self.start(ui.ctx(), start);
|
||||
}
|
||||
self.dialogs(ui.ctx(), &owner, &book);
|
||||
let said = if self.job.is_some() {
|
||||
@@ -609,18 +672,21 @@ impl OwnerMenu {
|
||||
}
|
||||
}
|
||||
|
||||
fn start(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
what: String,
|
||||
work: Box<dyn FnOnce() -> Outcome + Send>,
|
||||
) {
|
||||
fn start(&mut self, ctx: &egui::Context, (what, effect, work): Start) {
|
||||
let (tx, rx) = channel();
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let started = self.jobs.spawn(&what.clone(), effect.hold(), move |stop| {
|
||||
// A read-only job of a tab that has closed is not begun.
|
||||
if matches!(effect, Effect::Reads) && stop.requested() {
|
||||
return;
|
||||
}
|
||||
let _ = tx.send(work());
|
||||
ctx.request_repaint();
|
||||
});
|
||||
if !started {
|
||||
self.done = Some((what, Err("the system gave no thread for it".into())));
|
||||
return;
|
||||
}
|
||||
self.job = Some((what, rx));
|
||||
self.done = None;
|
||||
}
|
||||
@@ -628,7 +694,8 @@ impl OwnerMenu {
|
||||
/// The open dialog, if any, for the books `book`.
|
||||
fn dialogs(&mut self, ctx: &egui::Context, owner: &Arc<dyn Owner>, book: &str) {
|
||||
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 {
|
||||
Dialog::None => {}
|
||||
Dialog::Upgrade(form) => {
|
||||
@@ -660,6 +727,7 @@ impl OwnerMenu {
|
||||
form,
|
||||
owner,
|
||||
book,
|
||||
&jobs,
|
||||
&mut close,
|
||||
);
|
||||
}
|
||||
@@ -671,7 +739,11 @@ impl OwnerMenu {
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Close the books").clicked() {
|
||||
let o = owner.clone();
|
||||
run = Some(("Close the books".into(), Box::new(move || o.close_books().map(|l| vec![l]))));
|
||||
run = Some((
|
||||
"Close the books".into(),
|
||||
Effect::Changes("Closing the books"),
|
||||
Box::new(move || o.close_books().map(|l| vec![l])),
|
||||
));
|
||||
close = true;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
@@ -697,6 +769,7 @@ impl OwnerMenu {
|
||||
let (o, i, c) = (owner.clone(), id.clone(), currency.clone());
|
||||
run = Some((
|
||||
"New books".into(),
|
||||
Effect::Changes("Making new books"),
|
||||
Box::new(move || o.new_books(&i, &c).map(|l| vec![l])),
|
||||
));
|
||||
close = true;
|
||||
@@ -780,13 +853,27 @@ impl OwnerMenu {
|
||||
let (o, s, r) = (owner.clone(), form.source.clone(), form.replace);
|
||||
let id = Some(form.id.trim().to_string()).filter(|i| !i.is_empty());
|
||||
let ctx = ui.ctx().clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(o.plan_restore(&s, id, r));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
let asked = (form.source.clone(), form.id.clone(), form.replace);
|
||||
form.planning = Some((rx, asked));
|
||||
form.problem = None;
|
||||
// Only reads the backup: stopped with its tab.
|
||||
let started = jobs.spawn(
|
||||
"restore check",
|
||||
crate::jobs::Hold::Free,
|
||||
move |stop| {
|
||||
if stop.requested() {
|
||||
return;
|
||||
}
|
||||
let _ = tx.send(o.plan_restore(&s, id, r));
|
||||
ctx.request_repaint();
|
||||
},
|
||||
);
|
||||
if started {
|
||||
let asked =
|
||||
(form.source.clone(), form.id.clone(), form.replace);
|
||||
form.planning = Some((rx, asked));
|
||||
form.problem = None;
|
||||
} else {
|
||||
form.problem =
|
||||
Some("the system gave no thread for it".into());
|
||||
}
|
||||
}
|
||||
if planning {
|
||||
ui.label("Checking the backup…");
|
||||
@@ -795,7 +882,11 @@ impl OwnerMenu {
|
||||
Some(plan) => {
|
||||
if ui.button("Restore it").clicked() {
|
||||
let (o, plan) = (owner.clone(), plan.clone());
|
||||
run = Some(("Restore".into(), Box::new(move || o.restore(&plan))));
|
||||
run = Some((
|
||||
"Restore".into(),
|
||||
Effect::Changes("Restoring these books"),
|
||||
Box::new(move || o.restore(&plan)),
|
||||
));
|
||||
close = true;
|
||||
}
|
||||
}
|
||||
@@ -810,8 +901,8 @@ impl OwnerMenu {
|
||||
if close {
|
||||
self.dialog = Dialog::None;
|
||||
}
|
||||
if let Some((what, work)) = run {
|
||||
self.start(ctx, what, work);
|
||||
if let Some(run) = run {
|
||||
self.start(ctx, run);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -824,6 +915,7 @@ fn upgrade_dialog(
|
||||
form: &mut UpgradeForm,
|
||||
owner: &Arc<dyn Owner>,
|
||||
book: &str,
|
||||
jobs: &crate::jobs::Spawner,
|
||||
close: &mut bool,
|
||||
) {
|
||||
let p = crate::theme::pal(ctx);
|
||||
@@ -864,15 +956,26 @@ fn upgrade_dialog(
|
||||
let (o, b) = (owner.clone(), book.to_string());
|
||||
let (tx, rx) = channel();
|
||||
let ctx = ui.ctx().clone();
|
||||
std::thread::spawn(move || {
|
||||
// The window is woken however this ends (a panic
|
||||
// too), once the answer, or its absence, can be seen.
|
||||
let _wake = Wake(ctx);
|
||||
let (tx, passphrase) = (tx, passphrase);
|
||||
let _ = tx.send(o.upgrade_format(&b, &passphrase));
|
||||
});
|
||||
form.working = Some(rx);
|
||||
form.problem = None;
|
||||
// Changes the books' format: never abandoned (INVARIANT 6).
|
||||
let started = jobs.spawn(
|
||||
"format upgrade",
|
||||
crate::jobs::Hold::Keep(
|
||||
"Upgrading these books' format: wait for it to finish".into(),
|
||||
),
|
||||
move |_| {
|
||||
// The window is woken however this ends (a panic
|
||||
// too), once the answer, or its absence, can be seen.
|
||||
let _wake = Wake(ctx);
|
||||
let (tx, passphrase) = (tx, passphrase);
|
||||
let _ = tx.send(o.upgrade_format(&b, &passphrase));
|
||||
},
|
||||
);
|
||||
if started {
|
||||
form.working = Some(rx);
|
||||
form.problem = None;
|
||||
} else {
|
||||
form.problem = Some("the system gave no thread for it".into());
|
||||
}
|
||||
}
|
||||
if ui
|
||||
.add_enabled(!working, egui::Button::new("Not now"))
|
||||
|
||||
@@ -112,11 +112,14 @@ pub struct Receipts {
|
||||
}
|
||||
|
||||
impl Receipts {
|
||||
pub fn new(ctx: &Context) -> Self {
|
||||
/// Receipts whose workers are threads of a tab: counted in `spawner`
|
||||
/// until they have ended, which they do when this is dropped (their
|
||||
/// queues' senders go) or the tab says stop (jobs.rs).
|
||||
pub fn new(ctx: &Context, spawner: &crate::jobs::Spawner) -> Self {
|
||||
let (done_tx, done) = channel();
|
||||
let workers = std::thread::available_parallelism().map_or(2, |n| n.get().clamp(2, 4));
|
||||
let jobs = workers_for(ctx, &done_tx, "receipt-render", workers);
|
||||
let thumb_jobs = workers_for(ctx, &done_tx, "thumb-render", 2);
|
||||
let jobs = workers_for(ctx, spawner, &done_tx, "receipt-render", workers);
|
||||
let thumb_jobs = workers_for(ctx, spawner, &done_tx, "thumb-render", 2);
|
||||
Self {
|
||||
cache: HashMap::new(),
|
||||
thumbs: HashMap::new(),
|
||||
@@ -246,16 +249,23 @@ impl Receipts {
|
||||
|
||||
/// Workers taking jobs from one queue, sending what they render to
|
||||
/// `done`; the queue's sender.
|
||||
fn workers_for(ctx: &Context, done_tx: &Sender<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 job_rx = std::sync::Arc::new(std::sync::Mutex::new(job_rx));
|
||||
for i in 0..n {
|
||||
let ctx = ctx.clone();
|
||||
let job_rx = job_rx.clone();
|
||||
let done_tx = done_tx.clone();
|
||||
std::thread::Builder::new()
|
||||
.name(format!("{name}-{i}"))
|
||||
.spawn(move || {
|
||||
spawner.spawn(
|
||||
&format!("{name}-{i}"),
|
||||
crate::jobs::Hold::Free,
|
||||
move |stop| {
|
||||
loop {
|
||||
let job = match job_rx.lock() {
|
||||
Ok(rx) => rx.recv(),
|
||||
@@ -264,13 +274,17 @@ fn workers_for(ctx: &Context, done_tx: &Sender<Done>, name: &str, n: usize) -> S
|
||||
let Ok(job) = job else {
|
||||
return;
|
||||
};
|
||||
// The tab is gone: what is still queued isn't rendered.
|
||||
if stop.requested() {
|
||||
return;
|
||||
}
|
||||
// A file that crashes its renderer is that file's
|
||||
// error, not the end of the worker (and every file
|
||||
// queued after it).
|
||||
let result =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
match &job.thumb {
|
||||
Some(dir) => render_thumb(&job, dir.as_deref()),
|
||||
Some(dir) => render_thumb(&job, dir.as_deref(), stop),
|
||||
None => render(&job),
|
||||
}
|
||||
}))
|
||||
@@ -283,8 +297,8 @@ fn workers_for(ctx: &Context, done_tx: &Sender<Done>, name: &str, n: usize) -> S
|
||||
});
|
||||
ctx.request_repaint();
|
||||
}
|
||||
})
|
||||
.expect("spawn renderer");
|
||||
},
|
||||
);
|
||||
}
|
||||
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
|
||||
/// cheaper to read than a picture. A thumbnail that can't be kept is
|
||||
/// still shown.
|
||||
fn render_thumb(job: &Job, dir: Option<&std::path::Path>) -> Result<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)
|
||||
.get(&job.sha)
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -348,7 +366,9 @@ fn render_thumb(job: &Job, dir: Option<&std::path::Path>) -> Result<Rendered, St
|
||||
img
|
||||
};
|
||||
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();
|
||||
if img
|
||||
.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];
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,10 @@
|
||||
//! for a state mark (drawn by a later unit, nothing now).
|
||||
//! 6. This only says what was asked (show, close, open); the app does
|
||||
//! it.
|
||||
//! 7. A tab whose company has a job under way that changes its books
|
||||
//! (`Tab::held`) has its close control off: disabled to assistive
|
||||
//! technology, drawn faint, no click and no middle click closes it,
|
||||
//! and its hover text says what is running.
|
||||
//! ```
|
||||
|
||||
use crate::theme::{self, pal};
|
||||
@@ -92,6 +96,10 @@ pub struct Tab {
|
||||
/// What its badge's hue is chosen from: the id of its books
|
||||
/// ([`hue_of`]).
|
||||
pub hue_key: String,
|
||||
/// Why the tab can't be closed now: a job that changes its books is
|
||||
/// running ("Restoring these books: wait for it to finish"). Its close
|
||||
/// control is off, and says so on hover.
|
||||
pub held: Option<String>,
|
||||
}
|
||||
|
||||
/// The badge hue of the company whose books have id `book_id`, light or
|
||||
@@ -428,7 +436,7 @@ fn one_tab(
|
||||
close.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(
|
||||
egui::WidgetType::Button,
|
||||
true,
|
||||
tab.held.is_none(),
|
||||
format!("Close {}", tab.title),
|
||||
)
|
||||
});
|
||||
@@ -507,7 +515,7 @@ fn one_tab(
|
||||
galley,
|
||||
p.text,
|
||||
);
|
||||
if close.hovered() {
|
||||
if close.hovered() && tab.held.is_none() {
|
||||
painter.rect_filled(close_rect, CornerRadius::same(5), p.selected);
|
||||
}
|
||||
painter.text(
|
||||
@@ -515,7 +523,9 @@ fn one_tab(
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::X,
|
||||
egui::FontId::proportional(12.0),
|
||||
if close.hovered() || here {
|
||||
if tab.held.is_some() {
|
||||
p.faint
|
||||
} else if close.hovered() || here {
|
||||
p.text
|
||||
} else {
|
||||
p.muted
|
||||
@@ -525,12 +535,15 @@ fn one_tab(
|
||||
let resp = resp.on_hover_text(&tab.detail);
|
||||
// The close control sits over the tab and is the one under the pointer
|
||||
// there: a click on it is its own, never the tab's.
|
||||
if close
|
||||
.on_hover_text(format!("Close {}", tab.title))
|
||||
.clicked()
|
||||
|| resp.middle_clicked()
|
||||
{
|
||||
let close_tip = match &tab.held {
|
||||
Some(why) => why.clone(),
|
||||
None => format!("Close {}", tab.title),
|
||||
};
|
||||
let closes = close.on_hover_text(close_tip).clicked() || resp.middle_clicked();
|
||||
if closes && tab.held.is_none() {
|
||||
*action = Some(TabAction::Close(i));
|
||||
} else if closes {
|
||||
// Held open: the click is the close control's, and does nothing.
|
||||
} else if resp.clicked() {
|
||||
*action = Some(TabAction::Show(i));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user