Files
wanderbooks/crates/ledger-gui/src/widgets.rs
T
swaitsandClaude Opus 5.5 b22a034746 MCP: short connect text, a handbook, tool annotations, safe local imports
- The 13K-character instructions (clients cut them short) become a
  connect text of at most 1,400 characters whose first 512 stand alone,
  plus books.handbook and books://handbook/{section}: the old guidance by
  section, with no helper commands, home paths, pull requests or
  file-reading suggestions (tool_text_lint).
- Every tool has a title and read-only/destructive hints; no
  requiresUserInteraction anywhere (owner decision 2026-10-16).
- books.import_local_file reads only regular files inside the import
  roots (the downloads folder by default, or --import-root), never the
  data dir, books dir, vault or the key's folder, no symlink escapes or
  hard links, and the file opened must be the file checked.
- The store lock is a tokio mutex taken off the runtime threads.
- get_info refreshes settings first; a bare books://digest reads.

Review fixes (P0 review, 2026-10-16):
- Fail closed: a tokio mutex never poisons and spawn_blocking caught the
  panic, so after a panic mid-mutation the server kept serving a Store
  behind its journal. A panic (the task, or while holding the store)
  now stops the shared store; every later request on every session is
  refused with a plain message; a restart re-verifies the journal. The
  join error goes through redact_refusal and never carries the panic's
  text.
- books.set_w9 w9_file_path read any path (a link named w9.pdf to the
  vault key was stored and get_w9 wrote it out): it now goes through the
  import roots' lockdown, its type judged on the canonical path.
- Sealed even inside a root: the key file in force, where a linked one
  leads, both folders, and the default key folder whatever the settings
  say. Refusals check the roots first, so outside them every path gets
  one message (no probing what exists); inside, other books-dir files say
  to copy them out first.
- The open is O_NOFOLLOW | O_NONBLOCK (a pipe swapped in after the check
  can't hang a thread) and must match the checked file's device and
  inode. New dependency: libc (unix only), for those two open flags,
  which std doesn't name.
- Default import roots are the downloads folder only (the plan); files
  with full TINs (get_w9, vendor_1099 include_tins, the CPA package with
  TINs) are never written into an import root, and the server refuses to
  import any file it wrote with TINs (by SHA-256).
- set_tin and set_w9 overwrite vault records: destructive_hint = true;
  annotations_complete pins the key tools' hints. The read-only hint is
  checked in behaviour on every spec_mcp call (journal and data-dir files
  unchanged).
- Text: the connect text names the settings file as the one local file
  to edit, says every entry balances on real accounts and names its
  party, says invoice/bill/payment/payroll tools post unchecked, rewords
  the exemptions, and shows the company name as one plain line; the
  handbook takes section "all", lists its ids in the schema and says to
  read contract first; books.settings drops the config.json path and no
  error names the data dir or the key file. tool_text_lint covers the
  whole tool JSON and resources and bans git/commit/WL-0001; tool
  descriptions over 700 characters are pinned to today's eight (P5).
- digest: an empty since= is bare; the default date is pinned on every
  day of a month.

Round-2 review fixes (2026-10-16):
- TIN files (B-26): the in-memory, per-session set of TIN-file hashes
  became one registry beside the vault (vault/tin-files.sha256, hashes
  only), shared by every session and every later server. It holds the
  W-9 set_w9 reads (recorded as read), get_w9 copies, 1099 worksheets
  with TINs, CPA packages with TINs and each file in one that holds a
  TIN; a file is recorded before it is written, and a failure refuses.
  import_local_file, attach_receipt and file_document (base64 was never
  checked) refuse a recorded file, and a text file (by type, name, or
  UTF-8/UTF-16 decoding) holding a full TIN. Not caught: an altered
  binary copy; the docs say so (P2/P7 remove the path tools).
- The text check is narrow (owner/engineer decision, 2026-10-16: bank
  exports are filed for reconciliation, and has_full_tin's "nine digits
  however separated" refused their routing numbers, long references and
  dates run into amounts). Text is refused when it holds (a) a TIN the
  vault holds for a party, anywhere, as nine digits, 3-2-4 joined by
  hyphens, spaces or dots, or 2-7 joined by a hyphen or space, compared
  on the server against the decrypted vault and never returned or
  logged (a vault that can't be opened leaves (b)); or (b) a stand-alone
  printed SSN (123-45-6789) or EIN (12-3456789) shape: no digit, and no
  hyphen or dot followed by a digit, beside it. Full-width digits and
  Unicode hyphens and spaces read as ASCII. has_full_tin still guards
  refusals and results (redact_refusal). Known limit, for P7: a refusal
  under (a) tells the agent a text it chose holds a vault TIN.
  New dependency: zeroize in ledger-mcp (already in the workspace
  through ledger-vault, same major version), so the vault's TINs decoded
  for the scan are wiped from memory on drop as the vault's own are.
- Mutation testing of the final P0 diff (docs/testing.md): tests for
  each law a survivor broke (handbook titles, a dropped default root, a
  .jpg W-9, the waker, the walk's folder flags against a link and a
  pipe, the 40-link limit, save paths refused as such, the package
  marking only its TIN files, a registry that can't be read, text types,
  the short receipt rule's counts and a 12-character code). Simpler
  code where only a race could tell: inspect places an existing path by
  canonicalize itself (no second comparison), read_checked's read limit
  is its one size check, openat fails on -1 as specified. The 25 MiB
  upload test removes its 50 MB of books however it ends.
- The GUI's stale-rule prompt no longer says to open a pull request: it
  asks the agent to find the figure from the rule's official authority,
  confirm it with the human, pass it explicitly, and tell the human so it
  can be reported upstream (as the handbook says); a lib test pins it and
  bans files, git, GitHub and pull requests from every attention prompt.
- Import roots (local_files.rs INVARIANT 0): XDG_DOWNLOAD_DIR="$HOME/"
  made $HOME (or /) the root. No root may be /, the home folder or hold
  it, or hold the books, data dir, vault or a key: a named one stops the
  server at startup, a default one is dropped; the default falls back to
  ~/Downloads only if that is a real folder other than $HOME; with no
  root, an import says so.
- The read is a component walk from / with openat(O_NOFOLLOW |
  O_DIRECTORY) per folder and O_NOFOLLOW | O_NONBLOCK for the file, so a
  folder swapped for a link after the check fails; no step may land on a
  protected inode (one renamed into a root); dev/ino and nlink stay. No
  /proc. Portable to macOS. (libc's openat, two small unsafe blocks.)
- One refusal for missing, dangling and outside paths: resolved()
  follows every link, dangling ones too, so a link's target existing or
  not no longer changes the answer.
- Sealing: the key files (in force, default) and their targets always;
  their folders only when not $HOME, not a root, not holding a root; and
  ~/.config/wanderbooks whatever XDG_CONFIG_HOME says.
- Agent text (I-12): RuleNotKnown names the authority (IRS, with its
  address) and says to tell the human, never a repo path, PR or GitHub;
  the digest's stale_rules drop the repo catalog and path for it; vault,
  outside-books, STOPPED and local-file refusals name no git, path or
  flag. tool_text_lint bans docs/, .md, /home, data dir, --data-dir,
  --import-root, vault.key, .jsonl, sqlite, .gitignore, github, pull
  request, and also lints every error template (scanned from source),
  built error texts, and the server's refusal constants.
- The receipt rule told (ReceiptPolicy::rule) is the one enforced: the
  exact threshold in the base currency (no "$", no rounding), required
  and exempt accounts, reversals exempt; the connect text fits 1,400
  characters by dropping reasons, then codes, never the rule.
- The connect text follows the parties setting; "offer books.digest"
  everywhere. shown_name drops Unicode format characters (bidi, zero
  width).
- read_only_tools_change_nothing compares file contents, the database
  by every row, the vault and the settings file (raw database bytes did
  not change either; rows are the stable comparison).
- import_local_file takes the name and type from the canonical path;
  the digest's journal repair says when the tail was set aside, not the
  journal's file name; "version-history messages" back in the TIN rule;
  openWorldHint false on every tool, pinned in annotations_complete.
- Outside the MCP crate, for the same texts: ledger-core's DatedRule
  gains `authority` (the statute or publication with its address) and
  RuleNotKnown carries it; ledger-store's "sqlite error" reads "database
  error"; ledger-config's ReceiptPolicy::rule takes the base currency.
  New dev-dependency: rusqlite in ledger-mcp (already in the workspace,
  same version and features as ledger-store), to read the database's
  rows in read_only_tools_change_nothing.
- The filing scan is no TIN oracle (tin_files.rs INVARIANT 4): text
  holding more than two TIN-shaped numbers (any rendering rule (a)
  reads) that end in a known TIN's last four (the books' TIN and W-9
  facts, via known_tin_last4, before the vault is opened; then the
  vault's own) is refused with TIN_PROBE, the same words whether or not
  one is the vault's TIN; only one or two candidates are compared
  against the vault. Tests: unit
  text_probing_for_a_tin_is_refused_alike_whether_or_not_it_holds_it,
  one_or_two_candidates_are_compared_against_the_vault; over HTTP
  text_probing_for_a_tin_is_refused_alike_by_every_filing_tool.

Plan: plan/served.md P0, section 6 "Immediate hole (P0)", 4.1, 4.3, 4.9.

Review round 3. S1: a panic stops the server for every session, so no
input may reach one. Dates are four-digit years (new ledger_core::
calendar, 0001-01-01..9999-12-31): the MCP's parse_date is strict
YYYY-MM-DD, periods are bounded, last_day_of_month returns a refusal
(server and store); schedules, assets, recurring entries, periods,
documents, disposals and entries refuse dates outside the calendar, and
replay refuses such journal dates. Every amount a command takes is at
most a line's (draft lines by size, document lines, payouts, payroll,
statements, shares, tax basis, proceeds, recurring templates), on
replay too, so sums are exact; the 1099 vendor part and the K-1
property share use checked products (TooLargeToCompute); a recurring
run makes at most 1,000 drafts. tests/hostile_args.rs drives every tool
with schema-derived hostile arguments and every resource with generated
URIs, asserting the server never stops; the audit's panics are pinned.
S2: a `.` or `..` path name is refused as NO_SUCH_FILE up front. S3:
NUL-interleaved UTF-16 without a byte-order mark is scanned both ways.
S4: resource-read refusals are TIN-redacted. S5: set_w9 records its W-9
only once the call passes every check, just before the vault write.
S8: idempotentHint only on verify, run_depreciation, run_schedules,
run_recurring, set_party_roles (a repeat leaves journal and vault
alone; spec_vault checks every candidate twice); every tool's hints
pinned in one table. C1: books.settings lists receipt_required_accounts
and receipt_exempt_accounts uncut. C2: the default company name reads
"a new company". C3: the parties rule names no-party reasons. C4/C5:
the handbook names the settings file only as books.settings' books_toml,
and restores "check books.digest and offer it". C6: an import root
inside the books, data dir or vault is refused at startup. The lint
catches `just` however it ends and where the books are;
digest_resource_bare_reads reads the server's month.

Review round 4 (2026-10-17): round 3's bounds ran in replay too, so
journals main wrote and reopened (an entry dated 0000-06-01 or
+10000-01-01, a draft line of 2e15, an asset ending past 9999, a basis
or share past the line limit, sub-cent document and payroll lines) no
longer opened. Posted is forever: the bounds are the commands' only.
- Replay applies main's rule exactly: parse_date takes any date chrono
  reads; replay_add_line(_fx) has no size bound (add_line/add_line_fx
  do); replay_register_asset/correct_asset (chrono overflow only),
  replay_set_asset_tax_basis (check_journaled), replay_set_entry_parties
  (check_shares_journaled), replay_register_recurring
  (validate_recurring_journaled), replay_register_schedule (months 1 to
  600), replay_create_period (order only), replay_dispose_asset, and no
  line, date, payment or payroll range checks in replay_invoice/bill,
  their payments and replay_payroll_run.
- Derived figures over such books refuse (TooLargeToCompute,
  DateOutOfRange), never panic: amortization plans, depreciation into
  chrono's last month (and the true-up for lives past 9999), intervals,
  document totals and aging, net pay and payroll plans, money flows and
  share resolution, the asset register, receipt-policy debits; the MCP
  tools and the viewer show what can't be computed.
- tests/fixtures/old-books: the review's 13 journals, its control and 15
  more edges, written by main's Store API with main's figures
  (expected.json); every one opens in the writer and the viewer to those
  figures, every derived figure computes or refuses, every MCP tool and
  GUI page answers; hostile_args restarts the server after each
  property; each bound has a command/replay test pair.

Final review: a schedule's plan refuses a total of 10^26 or more
(TooLargeToCompute) instead of letting Decimal round its cents silently,
and a null `remaining` in the schedule output is always explained by
plan_error. Replay is unaffected: no journaled schedule month can belong
to a total that large (the line limit bounds every posted month).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
2026-10-17 09:25:00 -06:00

589 lines
19 KiB
Rust

//! Small building blocks shared by every screen.
use crate::theme::{self, pal};
use egui::{
Align, Color32, CornerRadius, Frame, Layout, Margin, Response, RichText, Sense, Stroke, Ui,
vec2,
};
/// A white (or dark) rounded surface with a hairline border.
pub fn card<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R {
let p = pal(ui.ctx());
Frame::new()
.fill(p.surface)
.stroke(Stroke::new(1.0, p.border))
.corner_radius(CornerRadius::same(12))
.inner_margin(Margin::same(16))
.show(ui, |ui| {
ui.set_width(ui.available_width());
add(ui)
})
.inner
}
/// A card with a title row and a right-aligned extra (a link, a pill).
/// Returns what `extra` and `add` return.
pub fn titled_card<E, R>(
ui: &mut Ui,
title: &str,
extra: impl FnOnce(&mut Ui) -> E,
add: impl FnOnce(&mut Ui) -> R,
) -> (E, R) {
card(ui, |ui| {
let e = ui
.horizontal(|ui| {
ui.label(RichText::new(title).font(theme::semibold(14.0)));
ui.with_layout(Layout::right_to_left(Align::Center), extra)
.inner
})
.inner;
ui.add_space(8.0);
(e, add(ui))
})
}
/// Page title and the sentence under it.
pub fn page_header(ui: &mut Ui, title: &str, subtitle: &str) {
let p = pal(ui.ctx());
ui.label(RichText::new(title).font(theme::bold(26.0)));
if !subtitle.is_empty() {
ui.add_space(2.0);
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(subtitle)
.font(theme::regular(15.0))
.color(p.muted),
);
});
}
ui.add_space(16.0);
}
/// A rounded tag.
pub fn pill(ui: &mut Ui, text: &str, fg: Color32, bg: Color32) -> Response {
Frame::new()
.fill(bg)
.corner_radius(CornerRadius::same(255))
.inner_margin(Margin::symmetric(8, 2))
.show(ui, |ui| {
ui.label(RichText::new(text).font(theme::semibold(11.5)).color(fg))
})
.response
}
/// Text that looks like plain text until you hover it, then like a link.
pub fn link(ui: &mut Ui, text: RichText) -> Response {
link_label(ui, egui::Label::new(text))
}
/// [`link`] on one line, cut with an ellipsis where the space ends.
pub fn link_truncated(ui: &mut Ui, text: RichText) -> Response {
link_label(ui, egui::Label::new(text).truncate())
}
fn link_label(ui: &mut Ui, label: egui::Label) -> Response {
let p = pal(ui.ctx());
let r = ui.add(label.sense(Sense::click()));
if r.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
let rect = r.rect;
ui.painter().line_segment(
[
rect.left_bottom() + vec2(0.0, 1.0),
rect.right_bottom() + vec2(0.0, 1.0),
],
Stroke::new(1.0, p.accent),
);
}
r
}
/// An amount, right-aligned in a fixed-width cell, clickable when `drill`.
pub fn amount_cell(
ui: &mut Ui,
text: &str,
width: f32,
color: Color32,
strong: bool,
drill: bool,
) -> Response {
let font = if strong {
theme::semibold(14.0)
} else {
theme::regular(14.0)
};
// An amount copies as its plain decimal: a click when the cell doesn't
// drill down, the right-click menu when it does.
let copy = crate::fmt::plain(text);
let (rect, resp) = ui.allocate_exact_size(
vec2(width, 22.0),
if drill || copy.is_some() {
Sense::click()
} else {
Sense::hover()
},
);
let p = pal(ui.ctx());
let copy_id = resp.id.with("copy");
if let Some(v) = &copy {
if drill {
resp.context_menu(|ui| copy_item(ui, "Copy amount", v));
} else if resp.clicked() {
copy_now(ui, copy_id, v);
}
}
let copied = copy.is_some() && !drill && recently_copied(ui, copy_id);
if copy.is_some() && !drill && resp.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
let resp = if copy.is_some() && !drill {
resp.on_hover_text(if copied { "Copied" } else { "Click to copy" })
} else {
resp
};
let hovered = drill && resp.hovered();
let galley = ui.painter().layout_no_wrap(
text.to_string(),
font,
if hovered { p.accent } else { color },
);
let pos = egui::pos2(
rect.right() - galley.size().x,
rect.center().y - galley.size().y / 2.0,
);
if hovered {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
ui.painter().line_segment(
[
egui::pos2(pos.x, rect.center().y + galley.size().y / 2.0),
egui::pos2(rect.right(), rect.center().y + galley.size().y / 2.0),
],
Stroke::new(1.0, p.accent),
);
}
if copied {
ui.painter().text(
egui::pos2(pos.x - 4.0, rect.center().y),
egui::Align2::RIGHT_CENTER,
egui_phosphor::regular::CHECK,
egui::FontId::proportional(12.0),
p.positive,
);
}
ui.painter().galley(pos, galley, color);
resp
}
/// A big number with a label, a change line, and an optional sparkline.
pub struct Kpi<'a> {
pub label: &'a str,
pub value: String,
pub sub: Option<(String, Color32)>,
pub spark: Option<&'a [f64]>,
pub how: &'a str,
}
pub fn kpi(ui: &mut Ui, k: Kpi<'_>) -> Response {
let p = pal(ui.ctx());
let resp = Frame::new()
.fill(p.surface)
.stroke(Stroke::new(1.0, p.border))
.corner_radius(CornerRadius::same(12))
.inner_margin(Margin::same(14))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.set_min_height(104.0);
ui.label(
RichText::new(k.label)
.font(theme::regular(12.5))
.color(p.muted),
);
ui.add_space(4.0);
let font = fit_font(
ui,
&k.value,
theme::semibold,
24.0,
15.0,
ui.available_width(),
);
ui.add(egui::Label::new(RichText::new(&k.value).font(font)).truncate());
if let Some((text, color)) = &k.sub {
ui.add_space(2.0);
ui.label(RichText::new(text).font(theme::regular(12.0)).color(*color));
}
if let Some(values) = k.spark
&& values.len() > 1
{
ui.add_space(6.0);
let (rect, _) =
ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::hover());
crate::charts::sparkline(ui.painter(), rect, values, p.accent);
}
})
.response;
if !k.how.is_empty() {
resp.on_hover_text(k.how)
} else {
resp
}
}
/// A friendly placeholder when there's nothing to show yet.
pub fn empty(ui: &mut Ui, icon: &str, title: &str, text: &str) {
let p = pal(ui.ctx());
ui.vertical_centered(|ui| {
ui.add_space(18.0);
ui.label(RichText::new(icon).size(28.0).color(p.faint));
ui.add_space(4.0);
ui.label(
RichText::new(title)
.font(theme::semibold(14.0))
.color(p.muted),
);
ui.label(
RichText::new(text)
.font(theme::regular(12.5))
.color(p.faint),
);
ui.add_space(18.0);
});
}
/// Put `value` on the clipboard, remembering when under `id` (for the
/// brief "Copied" check).
pub fn copy_now(ui: &Ui, id: egui::Id, value: &str) {
ui.ctx().copy_text(value.to_string());
let now = ui.input(|i| i.time);
ui.ctx().data_mut(|d| d.insert_temp(id, now));
}
/// Whether `id` was copied in the last moment; keeps repainting until the
/// check fades.
pub fn recently_copied(ui: &Ui, id: egui::Id) -> bool {
let at: Option<f64> = ui.ctx().data(|d| d.get_temp(id));
let now = ui.input(|i| i.time);
let recent = at.is_some_and(|t| now - t < 1.2);
if recent {
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(200));
}
recent
}
/// A value that copies itself when clicked: a pointer and a copy icon on
/// hover, a check for a moment after.
pub fn copyable(ui: &mut Ui, text: RichText, value: &str) -> Response {
let id = ui.id().with(("copy", value));
let p = pal(ui.ctx());
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
let r = ui.add(egui::Label::new(text).sense(Sense::click()));
let recent = recently_copied(ui, id);
let (slot, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover());
if r.hovered() || recent {
ui.painter().text(
slot.center(),
egui::Align2::CENTER_CENTER,
if recent {
egui_phosphor::regular::CHECK
} else {
egui_phosphor::regular::COPY
},
egui::FontId::proportional(12.0),
if recent { p.positive } else { p.muted },
);
}
if r.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
let r = r.on_hover_text(if recent { "Copied" } else { "Click to copy" });
if r.clicked() {
copy_now(ui, id, value);
}
r
})
.inner
}
/// A secret that copies itself when clicked but is never drawn: `text` is
/// its masked form; `fetch` reads the real value, only on a click (or the
/// right-click menu's "Copy digits only"). A fetch that fails shows why,
/// beside it, for a few seconds.
pub fn secret_copyable(
ui: &mut Ui,
text: RichText,
hover: &str,
fetch: impl Fn() -> Result<String, String>,
) -> Response {
let id = ui.id().with(("secret-copy", text.text()));
let err_id = id.with("error");
let p = pal(ui.ctx());
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
let r = ui.add(egui::Label::new(text).sense(Sense::click()));
let recent = recently_copied(ui, id);
let (slot, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover());
if r.hovered() || recent {
ui.painter().text(
slot.center(),
egui::Align2::CENTER_CENTER,
if recent {
egui_phosphor::regular::CHECK
} else {
egui_phosphor::regular::COPY
},
egui::FontId::proportional(12.0),
if recent { p.positive } else { p.muted },
);
}
if r.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
let copy = |ui: &mut Ui, digits_only: bool| match fetch() {
Ok(v) => {
let v: String = if digits_only {
v.chars().filter(char::is_ascii_digit).collect()
} else {
v
};
ui.ctx().data_mut(|d| d.remove::<(f64, String)>(err_id));
copy_now(ui, id, &v);
}
Err(e) => {
let now = ui.input(|i| i.time);
ui.ctx().data_mut(|d| d.insert_temp(err_id, (now, e)));
}
};
let r = r.on_hover_text(if recent { "Copied" } else { hover });
if r.clicked() {
copy(ui, false);
}
r.context_menu(|ui| {
if ui
.button(format!("{} Copy", egui_phosphor::regular::COPY))
.clicked()
{
copy(ui, false);
ui.close();
}
if ui
.button(format!("{} Copy digits only", egui_phosphor::regular::COPY))
.clicked()
{
copy(ui, true);
ui.close();
}
});
let failed: Option<(f64, String)> = ui.ctx().data(|d| d.get_temp(err_id));
let now = ui.input(|i| i.time);
if let Some((at, e)) = failed.filter(|(at, _)| now - at < 6.0) {
ui.ctx()
.request_repaint_after(std::time::Duration::from_secs_f64(6.0 - (now - at)));
ui.add(
egui::Label::new(RichText::new(e).font(theme::regular(12.0)).color(p.warning))
.wrap(),
);
}
r
})
.inner
}
/// A "Copy …" item for a right-click menu.
pub fn copy_item(ui: &mut Ui, label: &str, value: &str) {
if ui
.button(format!("{} {label}", egui_phosphor::regular::COPY))
.clicked()
{
ui.ctx().copy_text(value.to_string());
ui.close();
}
}
/// "Copy prompt": puts an agent prompt on the clipboard.
pub fn copy_prompt(ui: &mut Ui, prompt: &str) {
let p = pal(ui.ctx());
let id = ui.id().with(("copied", prompt));
let copied_at: Option<f64> = ui.ctx().data(|d| d.get_temp(id));
let now = ui.input(|i| i.time);
let recently = copied_at.is_some_and(|t| now - t < 1.5);
let label = if recently {
format!("{} Copied", egui_phosphor::regular::CHECK)
} else {
format!("{} Ask the agent", egui_phosphor::regular::SPARKLE)
};
let r = ui
.add(
egui::Button::new(
RichText::new(label)
.font(theme::regular(12.0))
.color(p.accent),
)
.fill(p.accent_soft)
.stroke(Stroke::NONE)
.corner_radius(CornerRadius::same(6)),
)
.on_hover_text(format!(
"Copies this prompt for your agent session:\n\n{prompt}"
));
if r.clicked() {
ui.ctx().copy_text(prompt.to_string());
ui.ctx().data_mut(|d| d.insert_temp(id, now));
}
if recently {
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(300));
}
}
/// A horizontal rule in the border color.
pub fn rule(ui: &mut Ui) {
let p = pal(ui.ctx());
let w = ui.available_width();
let (rect, _) = ui.allocate_exact_size(vec2(w, 1.0), Sense::hover());
ui.painter().rect_filled(rect, 0.0, p.border);
}
/// Selectable segmented control.
pub fn segmented<T: PartialEq + Copy>(ui: &mut Ui, value: &mut T, options: &[(T, &str)]) -> bool {
let p = pal(ui.ctx());
let mut changed = false;
Frame::new()
.fill(p.hover)
.corner_radius(CornerRadius::same(8))
.inner_margin(Margin::same(2))
.show(ui, |ui| {
ui.spacing_mut().item_spacing.x = 2.0;
ui.horizontal(|ui| {
for (v, label) in options {
let on = *value == *v;
let b = egui::Button::new(
RichText::new(*label)
.font(if on {
theme::semibold(12.5)
} else {
theme::regular(12.5)
})
.color(if on { p.text } else { p.muted }),
)
.fill(if on { p.surface } else { Color32::TRANSPARENT })
.stroke(if on {
Stroke::new(1.0, p.border)
} else {
Stroke::NONE
})
.corner_radius(CornerRadius::same(6))
.min_size(vec2(0.0, 24.0));
if ui.add(b).clicked() && !on {
*value = *v;
changed = true;
}
}
});
});
changed
}
/// Left-aligned single-line text, vertically centered at `pos`, cut with
/// an ellipsis at `max_width` so it never runs into whatever is to its
/// right (an amount, a date).
pub fn clipped_text(
painter: &egui::Painter,
pos: egui::Pos2,
text: &str,
font: egui::FontId,
color: Color32,
max_width: f32,
) {
use egui::text::{LayoutJob, TextFormat, TextWrapping};
let mut job = LayoutJob::single_section(text.to_string(), TextFormat::simple(font, color));
job.wrap = TextWrapping {
max_width: max_width.max(10.0),
max_rows: 1,
break_anywhere: true,
overflow_character: Some('…'),
};
let galley = painter.layout_job(job);
let y = pos.y - galley.size().y / 2.0;
painter.galley(egui::pos2(pos.x, y), galley, color);
}
/// How many columns at least `min_width` wide (with `gap` between) fit
/// in `avail`, never fewer than one nor more than `max`.
pub fn fit_columns(avail: f32, min_width: f32, gap: f32, max: usize) -> usize {
(((avail + gap) / (min_width + gap)).floor() as usize).clamp(1, max.max(1))
}
/// The width of each of `n` right-aligned amount columns in a painted
/// table `width` wide, leaving at least `label_min` for the label on the
/// left: `max` when there's room, shrinking to a floor that still fits an
/// amount. Pair with [`min_width`] so a table that can't fit scrolls.
pub fn amount_col_w(width: f32, n: usize, label_min: f32, max: f32) -> f32 {
((width - label_min) / n.max(1) as f32).clamp(AMOUNT_MIN, max)
}
/// The narrowest an amount column gets ("(1,234,567.89)" at 13.5px).
pub const AMOUNT_MIN: f32 = 92.0;
/// Lay out `add` at least `width` wide: as is when there's room, in a
/// sideways scroll when the window is narrower, so a table never paints
/// over itself or past the edge.
pub fn min_width<R>(ui: &mut Ui, id: &str, width: f32, add: impl FnOnce(&mut Ui) -> R) -> R {
if ui.available_width() >= width {
return add(ui);
}
egui::ScrollArea::horizontal()
.id_salt(id)
.show(ui, |ui| {
ui.set_width(width);
add(ui)
})
.inner
}
/// The largest size up to `size` at which `text` fits on one line in
/// `width` (down to `floor`): big numbers shrink rather than wrap.
pub fn fit_font(
ui: &Ui,
text: &str,
font: impl Fn(f32) -> egui::FontId,
size: f32,
floor: f32,
width: f32,
) -> egui::FontId {
let measured = ui
.painter()
.layout_no_wrap(text.to_string(), font(size), Color32::WHITE)
.size()
.x;
if measured <= width {
return font(size);
}
font((size * width / measured).floor().max(floor))
}
/// A date picker for `d` (`id` its egui id salt), returning the date
/// picked. The picker's calendar holds years -9999 through 9999; a date
/// outside them (books an earlier version wrote may hold one, rules.md
/// B-28) is shown as text and kept, never truncated into another year.
pub fn date_picker(ui: &mut Ui, id: &str, d: chrono::NaiveDate) -> chrono::NaiveDate {
use chrono::Datelike;
let jiff_date = i16::try_from(d.year())
.ok()
.and_then(|y| jiff::civil::Date::new(y, d.month() as i8, d.day() as i8).ok());
let Some(mut j) = jiff_date else {
ui.label(crate::fmt::date(d));
return d;
};
ui.add(
egui_extras::DatePickerButton::new(&mut j)
.id_salt(id)
.calendar_week(false),
);
chrono::NaiveDate::from_ymd_opt(i32::from(j.year()), j.month() as u32, j.day() as u32)
.unwrap_or(d)
}