From fd6371c47071e1b9a9b15616b21ac11b72b87fba Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:27 -0500 Subject: [PATCH] pdf-forms-w12: net change of 3 commits - pdf-forms-w12: written from its sheet - pdf-forms-w12: repair 1 - pdf-forms-w12: review fixes (review-1) --- crates/ui-egui/src/tools/calc_order_ui.rs | 1098 ++++++++++----------- 1 file changed, 534 insertions(+), 564 deletions(-) diff --git a/crates/ui-egui/src/tools/calc_order_ui.rs b/crates/ui-egui/src/tools/calc_order_ui.rs index ce25d6c0a8..c7c1e3c510 100644 --- a/crates/ui-egui/src/tools/calc_order_ui.rs +++ b/crates/ui-egui/src/tools/calc_order_ui.rs @@ -1,11 +1,10 @@ //! Prepare a form ▸ Calculation order, a page of the left panel, and what it shows on the page. //! -//! The panel: a card that says whether the order is right and what Fix order does, a card for -//! each loop, a card for the formulas that read fields the form doesn't have, and the calculated +//! The panel: a notice that says whether the order is right and what Fix order does, a notice for +//! each loop, a notice for the formulas that read fields the form doesn't have, and the calculated //! fields in the order they calculate, each with its formula, the value it shows and what is wrong -//! with it. A field moves by dragging, with the arrows of -//! the selected field (Acrobat's Set Field Calculation Order has Up and Down), or with Alt+↑/↓. -//! Every change is one undoable edit. +//! with it. A field moves by dragging, with the arrows of the selected field (Acrobat's Set Field +//! Calculation Order has Up and Down), or with Alt+↑/↓. Every change is one undoable edit. //! //! The page: each calculated field's step in the order, and for the field in focus (under the //! pointer in the list or on the page, else the selected one) arrows from the fields it reads and @@ -14,28 +13,45 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use crate::canvas::PageToolContext; -use crate::theme::{self, Tokens}; -use crate::{LeftPanel, PdfCraftApp, icons, widgets}; -use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Shape, Stroke, Vec2, pos2, vec2}; +use craft::behavior::item_source::keyed; +use craft::behavior::selection::Selection; +use craft::behavior::{EditEvent, IconId, Input, Metrics, ReorderKeys, SelectionChange}; +use craft::theme::variant::Tone as Status; +use craft::ui::buttons::IconButton; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{ + Access, Bind, CollectionEvent, Common, Component, Cx, MeasureCx, Outcome as _, PaintUi, Props as _, ReorderRule, Role, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, +}; +use craft::ui::display::{Badge, Shade, Text}; +use craft::ui::layout_components::Stack; +use craft::ui::list::{List, ListRow, RowEvent, TrailingFace, TrailingPart}; +use craft::ui::notices::{Notice, NoticeAction}; +use craft::ui::primitives::{HAlign, IconSpec, PaintShape, StrokeWidth, TextRun}; +use craft::ui::runtime::env::Label; +use craft::ui::style::{ComponentStyle, StyleColor, StyleCx}; +use craft::behavior::kurbo::{CubicBez, ParamCurve as _, Point}; +use egui::{CornerRadius, Pos2, Rect, Response, Vec2, pos2, vec2}; use pdfcraft_cos::ObjRef; use pdfcraft_engine::form_scripts::{CalcOp, Calculate, format_value}; use pdfcraft_engine::{CalculatedField, CalculationIssue, CalculationOrder, Edit, FormField, FormFieldKind}; +use pdfcraft_render::DocInfo; -/// Links and steps on the page, which is paper white in either theme. -const LINK_OK: Color32 = Color32::from_rgb(0x1B, 0x63, 0xE0); -const LINK_LATE: Color32 = Color32::from_rgb(0xA8, 0x64, 0x00); -const LINK_LOOP: Color32 = Color32::from_rgb(0xC2, 0x26, 0x2E); -const STEP: Color32 = Color32::from_rgb(0x3A, 0x3A, 0x42); -const ROW: f32 = 46.0; +use crate::canvas::PageXform; +use crate::{LeftPanel, PdfCraftApp}; + +/// The command the panel's Back button runs: it returns to Prepare a form. +const BACK: &str = "form.calculation_order.back"; /// Links kept at most: a formula reading a group reads every field under it. const MAX_LINKS: usize = 20_000; /// Names a sentence lists before it stops with "…". const MAX_NAMES: usize = 6; -/// Loop cards shown at most. +/// Loop notices shown at most. const MAX_LOOPS: usize = 5; -/// Fields a card names one by one: too early, or reading fields the form doesn't have. +/// Fields a notice names one by one: too early, or reading fields the form doesn't have. const MAX_LISTED: usize = 3; +/// The arrows of a row, in its trailing parts. +const UP: TrailingPart = TrailingPart::new(0); +const DOWN: TrailingPart = TrailingPart::new(1); /// How a field's formula and place in the order, or a link between two fields, stand. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -49,15 +65,23 @@ enum Tone { Loop, } +/// The status a tone reads in on the panel. +fn status(tone: Tone) -> Status { + match tone { + Tone::Ok => Status::Neutral, + Tone::Late => Status::Warn, + Tone::Loop | Tone::Missing => Status::Bad, + } +} + /// A view's calculation order, read again only after an edit (filling a field in is one), and /// what the pointer is over. #[derive(Clone, Debug, Default)] pub struct CalcOrderView { cache: Option<(u64, Arc)>, - /// The field whose row is under the pointer, this frame. + /// The field whose row is under the pointer, this pass. The panel is shown before the page, so + /// the page's overlay reads it in the same pass. hover_row: Option, - /// The field under the pointer on the page, last frame. - hover_page: Option, /// Links on page is off. hide_links: bool, /// The selected field the list last scrolled to, so a new selection (on the page too) brings @@ -113,6 +137,11 @@ impl Focus { Self { name: f.name.clone(), obj: Some(f.obj) } } + /// A form field's widget on the page, as one field. + pub(crate) fn of_field(f: &FormField) -> Self { + Self { name: f.name.clone(), obj: Some(f.obj) } + } + /// Whether field `name`, object `obj`, is in focus. fn is(&self, name: &str, obj: ObjRef) -> bool { self.name == name && self.obj.is_none_or(|o| o == obj) @@ -150,14 +179,9 @@ impl CalcOrderView { self.cache.as_ref().filter(|(g, _)| *g == generation).map(|(_, listed)| listed.clone()) } - /// The field under the pointer on the page, for the next frame. - pub(crate) fn set_hover_page(&mut self, field: Option) { - self.hover_page = field; - } - - /// The field whose links show: under the pointer in the list or on the page, else selected. - fn focus(&self, selected: Option<&str>) -> Option { - self.hover_row.clone().or_else(|| self.hover_page.clone()).or_else(|| selected.map(Focus::named)) + /// The field whose links show: under the pointer in the list or on the page (`page`), else selected. + fn focus(&self, page: Option<&Focus>, selected: Option<&str>) -> Option { + self.hover_row.clone().or_else(|| page.cloned()).or_else(|| selected.map(Focus::named)) } } @@ -343,55 +367,6 @@ fn trace(links: &[Link], focus: &Focus, calculated: &[CalculatedField]) -> Strin parts.join(" · ") } -/// The colours of the cards and the steps in the list, for the theme. -struct Palette { - warn: (Color32, Color32, Color32, Color32), - good: (Color32, Color32, Color32), - looped: (Color32, Color32, Color32, Color32), - /// A step's fill and number, and the caption colour, by tone. - step_ok: (Color32, Color32), - step_late: (Color32, Color32), - step_loop: (Color32, Color32), -} - -impl Palette { - /// Fill, border, title and text of each card; light and dark pass 4.5:1 for their text. - fn new(dark: bool) -> Self { - let c = Color32::from_rgb; - if dark { - Palette { - warn: (c(0x3A, 0x2E, 0x17), c(0x6B, 0x53, 0x21), c(0xF2, 0xC2, 0x6B), c(0xE6, 0xD7, 0xB8)), - good: (c(0x1D, 0x33, 0x26), c(0x2F, 0x5C, 0x40), c(0x8F, 0xD6, 0xA8)), - looped: (c(0x3D, 0x20, 0x22), c(0x6E, 0x32, 0x36), c(0xF1, 0x9A, 0x9E), c(0xE9, 0xC9, 0xCB)), - step_ok: (c(0x3A, 0x3A, 0x40), c(0xD4, 0xD4, 0xDA)), - step_late: (c(0x4A, 0x3A, 0x1A), c(0xF2, 0xC2, 0x6B)), - step_loop: (c(0x4A, 0x22, 0x24), c(0xF1, 0x9A, 0x9E)), - } - } else { - Palette { - warn: (c(0xFF, 0xF6, 0xE5), c(0xF2, 0xD9, 0xA6), c(0x8A, 0x51, 0x00), c(0x4A, 0x3A, 0x1E)), - good: (c(0xEE, 0xF8, 0xF1), c(0xBF, 0xE3, 0xCC), c(0x1E, 0x6B, 0x3C)), - looped: (c(0xFD, 0xF0, 0xF0), c(0xF1, 0xC4, 0xC6), c(0xA8, 0x1E, 0x25), c(0x5A, 0x2A, 0x2D)), - step_ok: (c(0xED, 0xED, 0xF0), c(0x3A, 0x3A, 0x42)), - step_late: (c(0xFF, 0xF0, 0xD6), c(0x8A, 0x51, 0x00)), - step_loop: (c(0xFD, 0xE8, 0xE8), c(0xC2, 0x26, 0x2E)), - } - } - } - - fn step(&self, tone: Tone) -> (Color32, Color32) { - match tone { - Tone::Ok => self.step_ok, - Tone::Late => self.step_late, - Tone::Loop | Tone::Missing => self.step_loop, - } - } -} - -/// A field being dragged to a new place: its place now. -#[derive(Clone, Copy)] -struct Dragged(usize); - /// What the page asks for, done once it is drawn. enum Act { Order(Vec), @@ -400,43 +375,19 @@ enum Act { Select(String), } -/// A card: a tinted, outlined box as wide as the panel. -fn card(ui: &mut egui::Ui, fill: Color32, edge: Color32, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - egui::Frame::new() - .fill(fill) - .stroke(Stroke::new(1.0, edge)) - .corner_radius(CornerRadius::same(10)) - .inner_margin(egui::Margin::same(12)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.spacing_mut().item_spacing.y = 6.0; - add(ui) - }) - .inner +/// A notice of `status` that says `heading` and `lines`, with one action per entry of `actions`. Returns +/// the act of the action taken. +fn notice(ui: &mut egui::Ui, status: Status, heading: String, lines: Vec, actions: Vec<(String, Act)>) -> Option { + let mut n = Notice::new(status, heading).lines(lines); + for (label, _) in &actions { + n = n.action(NoticeAction::new(label.clone())); + } + let taken = n.show(ui).action?; + actions.into_iter().nth(taken).map(|(_, act)| act) } -/// A card's first line: its icon and title. -fn card_title(ui: &mut egui::Ui, icon: &str, title: &str, colour: Color32) { - ui.horizontal_top(|ui| { - let (r, _) = ui.allocate_exact_size(vec2(16.0, 17.0), Sense::hover()); - icons::paint(ui, r, icon, 15.0, colour); - ui.add(egui::Label::new(egui::RichText::new(title).font(theme::semibold(13.0)).color(colour)).wrap()); - }); -} - -fn card_text(ui: &mut egui::Ui, text: &str, colour: Color32) { - ui.add(egui::Label::new(egui::RichText::new(text).font(theme::regular(12.0)).color(colour)).wrap()); -} - -/// A word that acts: "Undo", "Edit total's formula". -fn text_button(ui: &mut egui::Ui, text: &str, t: &Tokens) -> bool { - let resp = - ui.add(egui::Label::new(egui::RichText::new(text).font(theme::semibold(12.5)).color(t.accent_text)).selectable(false).sense(Sense::click())); - theme::hand(resp).clicked() -} - -/// The cards above the list: what is wrong and Fix order, or that the order is right; and loops. -fn cards(ui: &mut egui::Ui, t: &Tokens, pal: &Palette, order: &CalculationOrder, editable: bool, undo: bool) -> Option { +/// The notices above the list: what is wrong and Fix order, or that the order is right; and loops. +fn cards(ui: &mut egui::Ui, order: &CalculationOrder, editable: bool, undo: bool) -> Option { let lang = crate::i18n::current(); let mut act = None; // Each field that calculates too early, with the fields it reads that calculate later. @@ -461,140 +412,109 @@ fn cards(ui: &mut egui::Ui, t: &Tokens, pal: &Palette, order: &CalculationOrder, }) .filter(|(_, gone)| !gone.is_empty()) .collect(); + let undo_action = || (tl!("Undo").to_owned(), Act::Undo); if !missing.is_empty() { - let (fill, edge, title, text) = pal.looped; - card(ui, fill, edge, |ui| { - let heading = crate::i18n::trn( + let heading = crate::i18n::trn( + lang, + missing.len() as u64, + "{n} formula reads a field the form doesn't have", + "{n} formulas read fields the form doesn't have", + ); + let mut lines = Vec::new(); + for (field, gone) in missing.iter().take(MAX_LISTED) { + let template = crate::i18n::trn( lang, - missing.len() as u64, - "{n} formula reads a field the form doesn't have", - "{n} formulas read fields the form doesn't have", + gone.len() as u64, + "{field} reads {fields}, which the form doesn't have.", + "{field} reads {fields}, which the form doesn't have.", ); - card_title(ui, "triangle-alert", &heading, title); - for (field, gone) in missing.iter().take(MAX_LISTED) { - let template = crate::i18n::trn( - lang, - gone.len() as u64, - "{field} reads {fields}, which the form doesn't have.", - "{field} reads {fields}, which the form doesn't have.", - ); - card_text(ui, &crate::i18n::fmt(&template, &[("field", field), ("fields", &names(gone))]), text); - } - if missing.len() > MAX_LISTED { - let more = (missing.len() - MAX_LISTED) as u64; - card_text( - ui, - &crate::i18n::trn(lang, more, "{n} more formula reads a missing field.", "{n} more formulas read missing fields."), - text, - ); - } - if editable - && let Some((first, _)) = missing.first() - && text_button(ui, &crate::i18n::fmt(tl!("Edit {field}'s formula"), &[("field", first)]), t) - { - act = Some(Act::EditFormula((*first).to_owned())); - } - // The all-clear, which carries Undo after a reorder, stays hidden while a formula is - // broken, so Undo is offered here. - if undo && text_button(ui, tl!("Undo"), t) { - act = Some(Act::Undo); - } - }); - ui.add_space(6.0); + lines.push(crate::i18n::fmt(&template, &[("field", field), ("fields", &names(gone))])); + } + if missing.len() > MAX_LISTED { + let more = (missing.len() - MAX_LISTED) as u64; + lines.push(crate::i18n::trn(lang, more, "{n} more formula reads a missing field.", "{n} more formulas read missing fields.")); + } + let mut actions = Vec::new(); + if editable && let Some((first, _)) = missing.first() { + actions.push((crate::i18n::fmt(tl!("Edit {field}'s formula"), &[("field", first)]), Act::EditFormula((*first).to_owned()))); + } + // The all-clear, which carries Undo after a reorder, stays hidden while a formula is + // broken, so Undo is offered here. + if undo { + actions.push(undo_action()); + } + act = notice(ui, Status::Bad, heading, lines, actions).or(act); } if order.fixable() { - let (fill, edge, title, text) = pal.warn; - card(ui, fill, edge, |ui| { - let heading = if late.is_empty() { - tl!("The order saved in the PDF needs tidying").to_owned() - } else { - crate::i18n::trn(lang, late.len() as u64, "{n} field shows an old value", "{n} fields show old values") - }; - card_title(ui, "triangle-alert", &heading, title); - for (field, later) in late.iter().take(MAX_LISTED) { - let template = crate::i18n::trn( - lang, - later.len() as u64, - "{field} calculates before {fields}, which it reads.", - "{field} calculates before {fields}, which it reads.", - ); - card_text(ui, &crate::i18n::fmt(&template, &[("field", field), ("fields", &names(later))]), text); - } - if late.len() > MAX_LISTED { - let more = (late.len() - MAX_LISTED) as u64; - card_text(ui, &crate::i18n::trn(lang, more, "{n} more field calculates too early.", "{n} more fields calculate too early."), text); - } - if !unlisted.is_empty() { - let template = crate::i18n::trn( - lang, - unlisted.len() as u64, - "{fields} is missing from the order saved in the PDF, so other PDF viewers may not calculate it.", - "{fields} are missing from the order saved in the PDF, so other PDF viewers may not calculate them.", - ); - card_text(ui, &crate::i18n::fmt(&template, &[("fields", &names(&unlisted))]), text); - } - if !order.extra.is_empty() { - let note = crate::i18n::trn( - lang, - order.extra.len() as u64, - "The calculation order has {n} entry that calculates nothing. Fix order removes it.", - "The calculation order has {n} entries that calculate nothing. Fix order removes them.", - ); - card_text(ui, ¬e, text); - } - ui.add_space(2.0); - ui.horizontal(|ui| { - let fix = ui.add_enabled_ui(editable, |ui| widgets::pill_button(ui, tl!("Fix order"), true)).inner; - if fix.on_hover_text(tl!("Move only what must move, so every field calculates after the fields it reads.")).clicked() { - act = Some(Act::Order(order.fixed())); - } - ui.add(egui::Label::new(egui::RichText::new(tl!("Moves only what must move")).font(theme::regular(11.5)).color(t.text_muted)).wrap()); - }); - }); + let heading = if late.is_empty() { + tl!("The order saved in the PDF needs tidying").to_owned() + } else { + crate::i18n::trn(lang, late.len() as u64, "{n} field shows an old value", "{n} fields show old values") + }; + let mut lines = Vec::new(); + for (field, later) in late.iter().take(MAX_LISTED) { + let template = crate::i18n::trn( + lang, + later.len() as u64, + "{field} calculates before {fields}, which it reads.", + "{field} calculates before {fields}, which it reads.", + ); + lines.push(crate::i18n::fmt(&template, &[("field", field), ("fields", &names(later))])); + } + if late.len() > MAX_LISTED { + let more = (late.len() - MAX_LISTED) as u64; + lines.push(crate::i18n::trn(lang, more, "{n} more field calculates too early.", "{n} more fields calculate too early.")); + } + if !unlisted.is_empty() { + let template = crate::i18n::trn( + lang, + unlisted.len() as u64, + "{fields} is missing from the order saved in the PDF, so other PDF viewers may not calculate it.", + "{fields} are missing from the order saved in the PDF, so other PDF viewers may not calculate them.", + ); + lines.push(crate::i18n::fmt(&template, &[("fields", &names(&unlisted))])); + } + if !order.extra.is_empty() { + lines.push(crate::i18n::trn( + lang, + order.extra.len() as u64, + "The calculation order has {n} entry that calculates nothing. Fix order removes it.", + "The calculation order has {n} entries that calculate nothing. Fix order removes them.", + )); + } + lines.push(tl!("Move only what must move, so every field calculates after the fields it reads.").to_owned()); + let actions = if editable { vec![(tl!("Fix order").to_owned(), Act::Order(order.fixed()))] } else { Vec::new() }; + act = notice(ui, Status::Warn, heading, lines, actions).or(act); } else if missing.is_empty() { - let (fill, edge, colour) = pal.good; - card(ui, fill, edge, |ui| { - let said = if loops.is_empty() { - tl!("Every field calculates after the fields it reads.") - } else { - tl!("Every field outside a loop calculates after the fields it reads.") - }; - card_title(ui, "check", said, colour); - if undo && text_button(ui, tl!("Undo"), t) { - act = Some(Act::Undo); - } - }); + let said = if loops.is_empty() { + tl!("Every field calculates after the fields it reads.") + } else { + tl!("Every field outside a loop calculates after the fields it reads.") + }; + let actions = if undo { vec![undo_action()] } else { Vec::new() }; + act = notice(ui, Status::Good, said.to_owned(), Vec::new(), actions).or(act); } for members in loops.iter().take(MAX_LOOPS) { - let (fill, edge, title, text) = pal.looped; - ui.add_space(6.0); - card(ui, fill, edge, |ui| { - let heading = match members.as_slice() { - [one] => crate::i18n::fmt(tl!("{field} reads its own value"), &[("field", *one)]), - _ => crate::i18n::fmt(tl!("{fields} read each other"), &[("fields", &names(members))]), - }; - card_title(ui, "rotate-cw", &heading, title); - card_text(ui, tl!("No order can fix a loop. Change one of the formulas."), text); - if editable - && let Some(first) = members.first() - && text_button(ui, &crate::i18n::fmt(tl!("Edit {field}'s formula"), &[("field", first)]), t) - { - act = Some(Act::EditFormula((*first).to_owned())); - } - }); + let heading = match members.as_slice() { + [one] => crate::i18n::fmt(tl!("{field} reads its own value"), &[("field", *one)]), + _ => crate::i18n::fmt(tl!("{fields} read each other"), &[("fields", &names(members))]), + }; + let mut actions = Vec::new(); + if editable && let Some(first) = members.first() { + actions.push((crate::i18n::fmt(tl!("Edit {field}'s formula"), &[("field", first)]), Act::EditFormula((*first).to_owned()))); + } + let lines = vec![tl!("No order can fix a loop. Change one of the formulas.").to_owned()]; + act = notice(ui, Status::Bad, heading, lines, actions).or(act); } let built: Vec<&str> = order.fields.iter().filter(|f| f.issues.contains(&CalculationIssue::BuiltNames)).map(|f| f.name.as_str()).collect(); if !built.is_empty() { - ui.add_space(6.0); - card(ui, t.card, t.border, |ui| { - let template = crate::i18n::trn( - lang, - built.len() as u64, - "{fields} builds some field names as it runs, so those reads aren't checked.", - "{fields} build some field names as they run, so those reads aren't checked.", - ); - card_text(ui, &crate::i18n::fmt(&template, &[("fields", &names(&built))]), t.text_muted); - }); + let template = crate::i18n::trn( + lang, + built.len() as u64, + "{fields} builds some field names as it runs, so those reads aren't checked.", + "{fields} build some field names as they run, so those reads aren't checked.", + ); + act = notice(ui, Status::Neutral, crate::i18n::fmt(&template, &[("fields", &names(&built))]), Vec::new(), Vec::new()).or(act); } act } @@ -625,17 +545,61 @@ fn explained(issues: &[CalculationIssue]) -> String { .join("\n") } -/// The Calculation order page; Back returns to Prepare a form. -pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) { - let (back, close) = crate::panels::panel_header(ui, t, "Calculation order", Some(("chevron-left", tl!("Back to Prepare a form")))); - if back { - app.left = LeftPanel::Tool("form"); +/// The order after the rows `keys` (in their order) move to position `to` of what remains once +/// they are taken out: the move a list's `ReorderMove` describes, whether a drag, Alt+↑/↓ or an arrow. +fn reordered(order: &[ObjRef], keys: &[ObjRef], to: usize) -> Vec { + let mut rest: Vec = order.iter().copied().filter(|o| !keys.contains(o)).collect(); + let at = to.min(rest.len()); + rest.splice(at..at, keys.iter().copied()); + rest +} + +/// The row of one calculated field: its step, name and value, then its formula and what is wrong. +fn order_row<'a>(k: usize, count: usize, f: &CalculatedField, row: &Row, editable: bool) -> ListRow<'a> { + let label = if row.value.is_empty() { f.name.clone() } else { format!("{}: {}", f.name, row.value) }; + let caption = match row.tone { + Tone::Missing => Some((tl!("Missing field"), Status::Bad)), + Tone::Loop => Some((tl!("Loop"), Status::Bad)), + Tone::Late => Some((tl!("Too early"), Status::Warn)), + Tone::Ok if !f.listed => Some((tl!("Not in order"), Status::Warn)), + Tone::Ok if f.issues.contains(&CalculationIssue::BuiltNames) => Some((tl!("Unchecked reads"), Status::Neutral)), + Tone::Ok => None, + }; + let why = [row.formula.clone(), explained(&f.issues)].into_iter().filter(|s| !s.is_empty()).collect::>().join("\n\n"); + let mut r = ListRow::new(label).lead_text((k + 1).to_string(), count.to_string()); + if !why.is_empty() { + r = r.tooltip(why); } - if close { - app.left_open = false; + if !row.formula.is_empty() { + r = r.below(Text::new(row.formula.clone()).shade(Shade::Muted), |_| {}); } + if let Some((text, status)) = caption { + r = r.below(Text::new(text).tone(status), |_| {}); + } + // Rows without a script keep the badge's room, so the arrows stay in line. + r = if row.script { r.trailing_field(Badge::new(tl!("Script")), |_| {}) } else { r.trailing_space(Badge::new(tl!("Script"))) }; + if editable { + if k > 0 { + r = r.trailing_part_revealed(UP, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-up"))), tl!("Earlier in calculation order")); + } + if k + 1 < count { + r = r.trailing_part_revealed(DOWN, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-down"))), tl!("Later in calculation order")); + } + } + r +} + +/// The panel's title row: Back to Prepare a form. Returns the command to run when it was pressed. +pub(crate) fn header(ui: &mut egui::Ui) -> Option<&'static str> { + // A command-bound button fires its command itself; the return also lets the caller run it. + let button = IconButton::command(IconSpec::svg(IconId::new("chevron-left")), BACK).show(ui); + button.response().clicked().then_some(BACK) +} + +/// The Calculation order page's body: the notices, the order and the links switch. +pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { let Some((index, id)) = app.active_ids() else { - ui.label(egui::RichText::new(tl!("Open a document first")).color(t.text_muted)); + Text::new(tl!("Open a document first")).shade(Shade::Muted).show(ui); return; }; let Some(doc) = app.session.get(id) else { return }; @@ -643,188 +607,84 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) { let listed = view.calc_order.listed(doc); let order = &listed.order; if order.fields.is_empty() && order.extra.is_empty() { - ui.label( - egui::RichText::new(tl!( - "No field in this form calculates its value yet. Give a field a calculation on the Calculate tab of its properties, and it shows here." - )) - .color(t.text_muted), - ); + Text::new(tl!( + "No field in this form calculates its value yet. Give a field a calculation on the Calculate tab of its properties, and it shows here." + )) + .shade(Shade::Muted) + .show(ui); return; } let editable = doc.allows_modification(); - let pal = Palette::new(ui.visuals().dark_mode); - let mut act = cards(ui, t, &pal, order, editable, doc.can_undo() == Some("Set calculation order")); - - widgets::section_title(ui, tl!("Order · top calculates first")); - let mut links_on = !view.calc_order.hide_links; - - let names: Vec<&str> = order.fields.iter().map(|f| f.name.as_str()).collect(); - let moved = |from: usize, to: usize| -> Option { - let mut next: Vec = names.iter().map(|n| (*n).to_owned()).collect(); - (from != to && from < next.len() && to < next.len()).then(|| { - let name = next.remove(from); - next.insert(to, name); - Act::Order(next) - }) - }; + let undo = doc.can_undo() == Some("Set calculation order"); let selected = view.prepare.selected.as_ref().map(|(name, _)| name.clone()); - let place = selected.as_deref().and_then(|s| names.iter().position(|n| *n == s)); - // Alt+↑/↓ move the selected field, as in Combine files. - let ctx = ui.ctx().clone(); - if editable - && let Some(k) = place - && !ctx.text_edit_focused() - && !egui::Popup::is_any_open(&ctx) - && ctx.memory(|m| m.top_modal_layer().is_none()) - { - let (up, down) = - ctx.input_mut(|i| (i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowUp), i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowDown))); - if up && let Some(a) = k.checked_sub(1).and_then(|to| moved(k, to)) { - act = Some(a); - } else if down && let Some(a) = moved(k, k + 1) { - act = Some(a); - } - } - - let focus_page = view.calc_order.hover_page.clone(); - // A field selected since the last frame, whose row the list shows. - let reveal = (selected != view.calc_order.scrolled_to).then(|| selected.clone()).flatten(); + let selected_objs: Vec = + selected.as_deref().map(|s| order.fields.iter().filter(|f| f.name == s).map(|f| f.obj).collect()).unwrap_or_default(); + let lead = selected_objs.first().copied(); + let mut selection = Selection::new(selected_objs, lead, lead); + // A field selected since the last pass, whose row the list shows once. + let reveal = lead.filter(|_| selected != view.calc_order.scrolled_to); view.calc_order.scrolled_to = selected.clone(); - let mut hover_row = None; - let count = names.len(); - egui::ScrollArea::vertical().id_salt(("calc-order", id)).auto_shrink([false, false]).show(ui, |ui| { - for (k, (f, row)) in order.fields.iter().zip(&listed.rows).enumerate() { - let sense = if editable { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW), sense); - let is_selected = selected.as_deref() == Some(f.name.as_str()); - resp.widget_info(|| { - let label = if row.value.is_empty() { format!("{}. {}", k + 1, f.name) } else { format!("{}. {}: {}", k + 1, f.name, row.value) }; - egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, label) - }); - if reveal.as_deref() == Some(f.name.as_str()) { - resp.scroll_to_me(Some(egui::Align::Center)); - } - let pointed = ui.rect_contains_pointer(rect); - if pointed { - hover_row = Some(Focus::row(f)); - } - let visible = ui.is_rect_visible(rect); - // The arrows' column, kept for every row so nothing moves when they show. - let arrows_x = rect.right() - 26.0; - if visible { - let press = theme::Press::track(ui, &resp); - if !is_selected && focus_page.as_ref().is_some_and(|p| p.is(&f.name, f.obj)) { - ui.painter().rect_filled(rect, CornerRadius::same(8), t.hover); - } - press.wash(ui, rect, 8, is_selected); - let body = rect.translate(press.offset()); - let (fill, number) = pal.step(row.tone); - let step = pos2(body.left() + 19.0, body.center().y); - ui.painter().circle_filled(step, 11.0, fill); - ui.painter().text(step, Align2::CENTER_CENTER, (k + 1).to_string(), theme::semibold(11.0), number); - let top = body.top() + 15.0; - let bottom = body.top() + 31.0; - let text_x = body.left() + 38.0; - let value_end = arrows_x - 4.0; - let caption = match row.tone { - Tone::Missing => Some((tl!("Missing field"), pal.step_loop.1)), - Tone::Loop => Some((tl!("Loop"), pal.step_loop.1)), - Tone::Late => Some((tl!("Too early"), pal.step_late.1)), - Tone::Ok if !f.listed => Some((tl!("Not in order"), pal.step_late.1)), - Tone::Ok if f.issues.contains(&CalculationIssue::BuiltNames) => Some((tl!("Unchecked reads"), t.text_muted)), - Tone::Ok => None, - }; - let value_font = theme::medium(13.0); - let value = widgets::fit_line(&row.value, (value_end - text_x) * 0.4, |s| widgets::text_width(ui, s, &value_font)); - let value_w = widgets::text_width(ui, &value, &value_font); - let value_colour = if row.tone == Tone::Late { pal.step_late.1 } else { t.text }; - ui.painter().text(pos2(value_end, top), Align2::RIGHT_CENTER, value, value_font, value_colour); - let caption_w = caption.map_or(0.0, |(c, colour)| { - let font = theme::semibold(10.5); - let w = widgets::text_width(ui, c, &font); - ui.painter().text(pos2(value_end, bottom), Align2::RIGHT_CENTER, c, font, colour); - w - }); - // The name shares the top line with the value, the formula the bottom one with the - // caption. - let room = (value_end - text_x - value_w - 10.0).max(0.0); - let formula_room = (value_end - text_x - caption_w - 10.0).max(0.0); - let name_font = theme::medium(13.0); - let tag = row.script.then(|| (tl!("Script"), widgets::text_width(ui, tl!("Script"), &theme::semibold(9.5)) + 8.0)); - let name_room = (room - tag.map_or(0.0, |(_, w)| w + 6.0)).max(0.0); - widgets::paint_left(ui, pos2(text_x, top), &f.name, name_font.clone(), t.text, name_room); - if let Some((label, w)) = tag { - let x = text_x + widgets::text_width(ui, &f.name, &name_font).min(name_room) + 6.0; - let chip = Rect::from_min_size(pos2(x, top - 7.5), vec2(w, 15.0)); - ui.painter().rect_stroke(chip, CornerRadius::same(4), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - ui.painter().text(chip.center(), Align2::CENTER_CENTER, label, theme::semibold(9.5), t.text_muted); - } - widgets::paint_left(ui, pos2(text_x, bottom), &row.formula, egui::FontId::monospace(11.0), t.text_muted, formula_room); - } - // The selected field's arrows, or the one under the pointer. - if editable && (is_selected || pointed) { - let up = Rect::from_min_size(pos2(arrows_x, rect.top() + 3.0), vec2(24.0, 19.0)); - let down = Rect::from_min_size(pos2(arrows_x, rect.bottom() - 22.0), vec2(24.0, 19.0)); - for (r, icon, earlier, tip) in - [(up, "chevron-up", true, tl!("Earlier in calculation order")), (down, "chevron-down", false, tl!("Later in calculation order"))] - { - let to = if earlier { k.checked_sub(1) } else { Some(k + 1).filter(|&to| to < count) }; - let b = - ui.interact(r, ui.scope_id().with(("calc-order", k, earlier)), if to.is_some() { Sense::click() } else { Sense::hover() }); - b.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, to.is_some(), format!("{tip}: {}", f.name))); - if visible { - let bpress = theme::Press::track(ui, &b); - bpress.wash(ui, r, 4, false); - icons::paint(ui, r.shrink(2.5).translate(bpress.offset()), icon, 14.0, if to.is_some() { t.icon } else { t.text_faint }); + let mut links_on = !view.calc_order.hide_links; + let objs: Vec = order.fields.iter().map(|f| f.obj).collect(); + let count = objs.len(); + let mut hovered = None; + let mut act = None; + + Stack::new().show(ui, |ui, _| { + act = cards(ui, order, editable, undo); + Text::new(tl!("Order · top calculates first")).shade(Shade::Muted).show(ui); + let source = keyed(&order.fields, |c| c.obj); + let mut list = List::new(tl!("Calculation order")).select(SelectMode::Single).selection(Bind::bound(&mut selection)); + if editable { + list = list.reorder(ReorderRule::new().keys(ReorderKeys::AltArrows)); + } + if let Some(key) = reveal { + list = list.reveal(key); + } + let shown = list.show_items(ui, &source, &mut |_, icx| match (order.fields.get(icx.at), listed.rows.get(icx.at)) { + (Some(f), Some(row)) => order_row(icx.at, count, f, row, editable), + _ => ListRow::new(String::new()), + }); + hovered = shown.hovered; + for event in shown.events { + let moved = match event { + CollectionEvent::Selection(SelectionChange::Set(keys)) => { + let name = keys.last().and_then(|k| order.fields.iter().find(|f| f.obj == *k)).map(|f| f.name.clone()); + if let Some(name) = name { + act = Some(Act::Select(name)); } - if theme::hand(b).on_hover_text(tip).clicked() - && let Some(a) = to.and_then(|to| moved(k, to)) - { - act = Some(a); + None + } + + CollectionEvent::Reorder(EditEvent::Set { after, .. } | EditEvent::Commit { after, .. }) => Some((after.keys, after.to)), + CollectionEvent::Item(key, RowEvent::Trailing { part, .. }) => { + let at = objs.iter().position(|o| *o == key); + match at { + Some(k) if part == UP => k.checked_sub(1).map(|to| (vec![key], to)), + Some(k) if part == DOWN => Some((vec![key], k + 1)), + _ => None, } } - } - if editable { - resp.dnd_set_drag_payload(Dragged(k)); - if resp.dragged() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - } - // A field dragged over this one goes where the line is drawn. - if let Some(from) = resp.dnd_hover_payload::().map(|d| d.0) - && from != k - { - let y = if from > k { rect.top() } else { rect.bottom() }; - ui.painter().hline(rect.x_range(), y, Stroke::new(2.0, t.accent)); - } - if let Some(from) = resp.dnd_release_payload::().map(|d| d.0) - && let Some(a) = moved(from, k) - { - act = Some(a); - } - } - let resp = theme::hand(resp); - // The whole formula, then what is wrong; written only while the pointer is on it. - let resp = if resp.hovered() { - let why = [row.formula.clone(), explained(&f.issues)].into_iter().filter(|s| !s.is_empty()).collect::>().join("\n\n"); - if why.is_empty() { resp } else { resp.on_hover_text(why) } - } else { - resp + _ => None, }; - if resp.clicked() { - act = Some(Act::Select(f.name.clone())); + if let Some((keys, to)) = moved { + let next = reordered(&objs, &keys, to); + let names = next.iter().filter_map(|o| order.fields.iter().find(|f| f.obj == *o)).map(|f| f.name.clone()).collect(); + act = Some(Act::Order(names)); } } - ui.add_space(8.0); - ui.add(widgets::checkbox(&mut links_on, egui::RichText::new(tl!("Links on page")).font(theme::regular(12.0)).color(t.text_muted))) - .on_hover_text(tl!("Show on the page which fields each field reads")); + Text::new(String::new()).show(ui); + Checkbox::new(Bind::bound(&mut links_on)) + .label(tl!("Links on page")) + .tooltip(tl!("Show on the page which fields each field reads")) + .show(ui); if editable { - ui.add_space(4.0); let (up, down) = if cfg!(target_os = "macos") { ("⌥↑", "⌥↓") } else { ("Alt+↑", "Alt+↓") }; let hint = crate::i18n::fmt(tl!("Drag a field to move it, or select it and press {up} or {down}."), &[("up", up), ("down", down)]); - ui.add(egui::Label::new(egui::RichText::new(hint).font(theme::regular(11.5)).color(t.text_faint)).wrap()); + Text::new(hint).shade(Shade::Faint).show(ui); } }); - view.calc_order.hover_row = hover_row; + view.calc_order.hover_row = hovered.and_then(|key| order.fields.iter().find(|f| f.obj == key)).map(Focus::row); view.calc_order.hide_links = !links_on; match act { Some(Act::Order(names)) => { @@ -837,10 +697,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) { if let Some(view) = app.views.get_mut(index) { view.prepare.select((name.clone(), 0), false); } - app.open_field_props(&name, 0); - if let Some(d) = app.field_props.as_mut() { - d.tab = crate::prepare::FieldTab::Calculate; - } + crate::prepare::dialog::open(app, &name, 0, crate::prepare::FieldTab::Calculate); } Some(Act::Select(name)) => { // Where its first widget is, to show it there. @@ -858,6 +715,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) { } None => {} } + let _ = LeftPanel::CalculationOrder; } /// The focus's links, and whether a field is at either end of one or is the focus itself: the @@ -870,72 +728,6 @@ fn focus_links<'a>(links: &'a [Link], focus: &'a Focus) -> (Vec<&'a Link>, impl (shown, move |name: &str, obj: ObjRef| focus.is(name, obj) || names.contains(name) || readers.contains(&obj)) } -/// The calculation order on page `page`: the links of the field in focus, with the fields it has -/// nothing to do with faded, and the steps of the focus and its linked fields; with nothing in -/// focus, the steps of the fields whose place is wrong. A form with many calculations stays -/// readable either way. Returns the field under the pages' `pointer`. -pub(crate) fn paint_page( - cx: PageToolContext<'_>, - form: &[FormField], - view: &CalcOrderView, - generation: u64, - selected: Option<&str>, -) -> Option { - let PageToolContext { ui, xf, page, info, ptr, .. } = cx; - let painter = ui.painter(); - let pointer = ptr.pos; - let listed = view.current(generation)?; - // Each field's first widget on this page. - let mut on_page: Vec<(&str, ObjRef, Rect)> = Vec::new(); - for f in form { - if let Some(w) = f.widgets.iter().find(|w| w.page == Some(page) && !w.hidden) { - let r = w.rect; - on_page.push((&f.name, f.obj, xf.user_rect(info, page, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]))); - } - } - if on_page.is_empty() { - return None; - } - let hovered = pointer - .and_then(|p| on_page.iter().rev().find(|(_, _, r)| r.contains(p))) - .map(|(name, obj, _)| Focus { name: (*name).to_owned(), obj: Some(*obj) }); - // Arrows start at a read name's field (one of them, if fields share it) and end at the formula's. - let by_name: HashMap<&str, Rect> = on_page.iter().map(|(name, _, r)| (*name, *r)).collect(); - let by_obj: HashMap = on_page.iter().map(|(_, obj, r)| (*obj, *r)).collect(); - let zoom = xf.zoom().clamp(0.5, 3.0); - let focus = if view.hide_links { None } else { view.focus(selected) }; - let focused = focus.as_ref().map(|f| focus_links(&listed.links, f)); - if let (Some(focus), Some((shown, related))) = (&focus, &focused) { - for (name, obj, r) in &on_page { - if !related(name, *obj) { - painter.rect_filled(r.expand(1.0), CornerRadius::ZERO, Color32::from_white_alpha(150)); - } else { - let width = if focus.is(name, *obj) { 2.0 } else { 1.0 }; - painter.rect_stroke(r.expand(1.0), CornerRadius::same(2), Stroke::new(width, LINK_OK), egui::StrokeKind::Outside); - } - } - for l in shown { - if let (Some(a), Some(b)) = (by_name.get(l.from.as_str()), by_obj.get(&l.reader)) { - arrow(painter, *a, *b, l.tone, zoom); - } - } - } - let related = focused.as_ref().map(|(_, related)| related as Related<'_>); - for (k, r, tone) in steps(&listed, &by_obj, related) { - let fill = match tone { - Tone::Ok => STEP, - Tone::Late => LINK_LATE, - Tone::Loop | Tone::Missing => LINK_LOOP, - }; - // No bigger than the field, so a small one keeps its contents in view. - let radius = (8.0 * zoom).clamp(6.5, 10.0).min((r.height() * 0.6).max(5.0)); - let c = r.left_top(); - painter.circle(c, radius, fill, Stroke::new(1.5, Color32::WHITE)); - painter.text(c, Align2::CENTER_CENTER, (k + 1).to_string(), theme::semibold(radius * 1.1), Color32::WHITE); - } - hovered -} - /// Whether a field, by name and object, is at an end of the focus's links or is the focus. type Related<'a> = &'a dyn Fn(&str, ObjRef) -> bool; @@ -964,19 +756,14 @@ fn edge(r: Rect, dir: Vec2) -> Pos2 { r.center() + dir * along(half.x, dir.x).min(along(half.y, dir.y)) } -/// An arrow from field `a` to field `b`: dashed when the value arrives too late, red in a loop. -/// Fields one above the other link out to the right, and fields side by side over the top, clear -/// of the fields between them (a grid's neighbours would otherwise get arrows too short to see). -/// Other fields link between their nearest edges, bent a little to the arrow's left so the two -/// arrows of a loop don't overlap. A field that reads itself gets a loop off its right edge. -fn arrow(painter: &egui::Painter, a: Rect, b: Rect, tone: Tone, zoom: f32) { - let colour = match tone { - Tone::Ok => LINK_OK, - Tone::Late => LINK_LATE, - Tone::Loop | Tone::Missing => LINK_LOOP, - }; - let stroke = Stroke::new(1.75, colour); - let head = 9.0; +/// The route of an arrow from field `a` to field `b`: the line's points, which stop where the head +/// starts, and the head's three corners. Fields one above the other link out to the right, and +/// fields side by side over the top, clear of the fields between them (a grid's neighbours would +/// otherwise get arrows too short to see). Other fields link between their nearest edges, bent a +/// little to the arrow's left so the two arrows of a loop don't overlap. A field that reads itself +/// gets a loop off its right edge. +fn route(a: Rect, b: Rect, zoom: f32, style: &CalcOrderOverlayStyle) -> (Vec, Vec) { + let (head, margin, bend_cap) = (style.head, style.margin, style.bend_cap); let gap = b.center() - a.center(); let overlap = |a0: f32, a1: f32, b0: f32, b1: f32| a1.min(b1) - a0.max(b0); let (start, c1, c2, end) = if gap.length() < 1.0 { @@ -993,45 +780,233 @@ fn arrow(painter: &egui::Painter, a: Rect, b: Rect, tone: Tone, zoom: f32) { (start, start - vec2(0.0, bow), end - vec2(0.0, bow), end) } else { let dir = gap / gap.length(); - let (start, end) = (edge(a, dir) + dir * 2.0, edge(b, -dir) - dir * 2.0); - let bend = vec2(dir.y, -dir.x) * ((end - start).length() * 0.18).min(60.0); + let (start, end) = (edge(a, dir) + dir * margin, edge(b, -dir) - dir * margin); + let bend = vec2(dir.y, -dir.x) * ((end - start).length() * 0.18).min(bend_cap); (start, start + (end - start) / 3.0 + bend, start + (end - start) * (2.0 / 3.0) + bend, end) }; // The line stops where the head starts, which points along the curve's last stretch. let back = (end - c2).normalized(); let back = if back.is_finite() && back != Vec2::ZERO { back } else { vec2(-1.0, 0.0) }; let base = end - back * head; - let curve = egui::epaint::CubicBezierShape::from_points_stroke([start, c1, c2, base], false, Color32::TRANSPARENT, stroke); - let points: Vec = curve.flatten(Some(0.5)); - if tone == Tone::Late { - painter.extend(Shape::dashed_line(&points, stroke, 5.0, 4.0)); - } else { - painter.add(Shape::line(points, stroke)); - } - let side = vec2(-back.y, back.x) * 4.5; - painter.add(Shape::convex_polygon(vec![end, base + side, base - side], colour, Stroke::NONE)); + let point = |p: Pos2| Point::new(f64::from(p.x), f64::from(p.y)); + let curve = CubicBez::new(point(start), point(c1), point(c2), point(base)); + // About one segment per four points of chord, so a long arrow stays smooth and a short one cheap. + let steps = (start.distance(base) / 4.0).ceil().clamp(8.0, 64.0) as usize; + let line = (0..=steps).map(|k| curve.eval(k as f64 / steps as f64)).map(|p| pos2(p.x as f32, p.y as f32)).collect(); + let side = vec2(-back.y, back.x) * (head / 2.0); + (line, vec![end, base + side, base - side]) } -/// The focused field's links in words, in a pill at the top of the page view. -pub(crate) fn paint_trace(ui: &egui::Ui, painter: &egui::Painter, viewport: Rect, view: &CalcOrderView, generation: u64, selected: Option<&str>) { - if view.hide_links { - return; +/// The colours of the page overlay. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct CalcOrderOverlayStyle { + #[style(metrics)] + metrics: Metrics, + /// The length of an arrowhead; its width is the same. + head: f32, + /// The room between an arrow's end and the field it points at. + margin: f32, + /// The most an arrow between two far fields bends. + bend_cap: f32, + /// A link that arrives in time, and the outline of a related field. + ok: StyleColor, + /// A link that arrives too late. + late: StyleColor, + /// A link in a loop, or a formula reading a field the form doesn't have. + bad: StyleColor, + /// A step of a field in its place. + step: StyleColor, + /// The number and rim of a step. + number: StyleColor, + /// The cover over the fields the focus has nothing to do with. + scrim: StyleColor, + /// The trace pill's fill. + pill: StyleColor, + /// The trace pill's text. + text: StyleColor, +} + +impl CalcOrderOverlayStyle { + fn of(&self, tone: Tone) -> StyleColor { + match tone { + Tone::Ok => self.step, + Tone::Late => self.late, + Tone::Loop | Tone::Missing => self.bad, + } } - let (Some(listed), Some(focus)) = (view.current(generation), view.focus(selected)) else { return }; - let t = Tokens::get(ui.ctx()); - let text = trace(&listed.links, &focus, &listed.order.fields); - let font = theme::regular(12.0); - // Clear of the floating tool strip at the view's left. - let room = (viewport.width() - 220.0).max(0.0); - let shown = widgets::fit_line(&text, room, |s| widgets::text_width(ui, s, &font)); - if shown.is_empty() { - return; +} + +/// The calculation order over the pages: the links of the field in focus, with the fields it has +/// nothing to do with covered, and the steps of the focus and its linked fields; with nothing in +/// focus, the steps of the fields whose place is wrong. A form with many calculations stays +/// readable either way. Above the pages' top edge a pill says in words what the focus reads and +/// what reads it. It is display only: the hovered field of a pass comes from the page's parts. +#[derive(Component, craft::ui::contract::Props)] +#[component(canvas_control)] +pub struct CalcOrderOverlay<'a> { + #[common] + common: Common, + view: &'a CalcOrderView, + form: &'a [FormField], + info: &'a DocInfo, + /// The pages on screen this pass. + #[prop] + placed: &'a [craft::pages::ui::PlacedPage], + /// The view's rotation. + #[prop] + rotation: u16, + /// The document's edit generation the order is read at. + #[prop] + generation: u64, + /// The Prepare selection. + #[prop(into)] + selected: Option<&'a str>, + /// The field under the pointer on the page this pass. + #[prop(into)] + hovered: Option<&'a Focus>, + /// The page view's rect, which the pill sits at the top of. + #[prop] + viewport: Rect, +} + +impl<'a> CalcOrderOverlay<'a> { + /// The overlay of `view`'s order on `info`'s pages, with `form`'s fields. The pages, rotation, + /// generation, selection, hover and viewport are props. + pub fn new(view: &'a CalcOrderView, form: &'a [FormField], info: &'a DocInfo) -> Self { + CalcOrderOverlay { + common: Common::new(), + view, + form, + info, + placed: &[], + rotation: 0, + generation: 0, + selected: None, + hovered: None, + viewport: Rect::NOTHING, + } + .label(tl!("Calculation order links")) + } +} + +impl Component for CalcOrderOverlay<'_> { + const ROLE: Role = Role::GRAPHICS_OBJECT; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + type Style = CalcOrderOverlayStyle; + type Output = Response; + + fn style(cx: &StyleCx<'_>, _: CalcOrderOverlayStyleKey) -> CalcOrderOverlayStyle { + let c = &cx.tokens.color; + CalcOrderOverlayStyle { + metrics: Metrics::new(), + head: cx.tokens.size.icon.sm, + margin: cx.tokens.space.gap.tight, + bend_cap: cx.tokens.size.control.md * 2.0, + ok: cx.tone(Status::Good), + late: cx.tone(Status::Warn), + bad: cx.tone(Status::Bad), + step: cx.color(c.text.muted), + number: cx.color(c.surface.raised), + scrim: cx.color(c.surface.scrim), + pill: cx.color(c.surface.raised), + text: cx.color(c.text.normal), + } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::ZERO + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(listed) = self.view.current(self.generation) else { return }; + let style = &cx.style; + let draw = ui.draw(); + let focus = if self.view.hide_links { None } else { self.view.focus(self.hovered, self.selected) }; + let focused = focus.as_ref().map(|f| focus_links(&listed.links, f)); + for p in self.placed { + let Some(page) = self.info.pages.get(p.page) else { continue }; + let xf = PageXform { rect: p.rect, rot: self.rotation, pw: page.width, ph: page.height }; + // Each field's first widget on this page. + let mut on_page: Vec<(&str, ObjRef, Rect)> = Vec::new(); + for f in self.form { + if let Some(w) = f.widgets.iter().find(|w| w.page == Some(p.page) && !w.hidden) { + let r = w.rect; + on_page.push((&f.name, f.obj, xf.user_rect(self.info, p.page, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]))); + } + } + if on_page.is_empty() { + continue; + } + // Arrows start at a read name's field (one of them, if fields share it) and end at the formula's. + let by_name: HashMap<&str, Rect> = on_page.iter().map(|(name, _, r)| (*name, *r)).collect(); + let by_obj: HashMap = on_page.iter().map(|(_, obj, r)| (*obj, *r)).collect(); + let zoom = xf.zoom().clamp(0.5, 3.0); + if let (Some(focus), Some((shown, related))) = (&focus, &focused) { + for (name, obj, r) in &on_page { + let rect = r.expand(1.0); + if !related(name, *obj) { + draw.fill(&PaintShape::Rect(rect, CornerRadius::ZERO), style.scrim); + } else { + let width = if focus.is(name, *obj) { StrokeWidth::Medium } else { StrokeWidth::Thin }; + draw.stroke(&PaintShape::Rect(rect, CornerRadius::same(2)), width, style.ok); + } + } + for l in shown { + if let (Some(a), Some(b)) = (by_name.get(l.from.as_str()), by_obj.get(&l.reader)) { + let colour = match l.tone { + Tone::Ok => style.ok, + Tone::Late => style.late, + Tone::Loop | Tone::Missing => style.bad, + }; + let (line, head) = route(*a, *b, zoom, style); + if l.tone == Tone::Late { + draw.dashed(&line, draw.dashes(), StrokeWidth::Medium, colour); + } else { + draw.stroke(&PaintShape::Path(line), StrokeWidth::Medium, colour); + } + draw.fill(&PaintShape::Polygon(head), colour); + } + } + } + let related = focused.as_ref().map(|(_, related)| related as Related<'_>); + for (k, r, tone) in steps(&listed, &by_obj, related) { + // No bigger than the field, so a small one keeps its contents in view. + let radius = (8.0 * zoom).clamp(6.5, 10.0).min((r.height() * 0.6).max(5.0)); + let c = r.left_top(); + draw.fill(&PaintShape::Circle(c, radius), style.of(tone)); + draw.stroke(&PaintShape::Circle(c, radius), StrokeWidth::Medium, style.number); + let face = Rect::from_center_size(c, Vec2::splat(radius * 2.0)); + draw.text(face, &TextRun::new((k + 1).to_string()).color(style.number).align(HAlign::Center)); + } + } + if let Some(focus) = &focus { + let text = trace(&listed.links, focus, &listed.order.fields); + // Clear of the floating tool strip at the view's left. + let width = (self.viewport.width() - 220.0).max(0.0); + if width > 0.0 { + let pill = Rect::from_center_size(pos2(self.viewport.center().x, self.viewport.top() + 26.0), vec2(width, 30.0)); + draw.fill(&PaintShape::Rect(pill, CornerRadius::same(15)), style.pill); + draw.stroke(&PaintShape::Rect(pill, CornerRadius::same(15)), StrokeWidth::Thin, style.step); + let icon = Rect::from_center_size(pill.left_center() + vec2(18.0, 0.0), vec2(14.0, 14.0)); + draw.icon(icon, &IconSpec::svg(IconId::new("move-right")).color(style.ok)); + let room = Rect::from_min_max(pill.left_center() - vec2(-32.0, 15.0), pill.right_center() + vec2(-14.0, 15.0)); + draw.text(room, &TextRun::new(text).color(style.text).elide()); + } + } + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() } - let w = widgets::text_width(ui, &shown, &font) + 46.0; - let pill = Rect::from_center_size(pos2(viewport.center().x, viewport.top() + 26.0), vec2(w, 30.0)); - painter.rect(pill, CornerRadius::same(15), t.card, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - icons::paint(ui, Rect::from_center_size(pill.left_center() + vec2(18.0, 0.0), vec2(14.0, 14.0)), "move-right", 13.0, LINK_OK); - painter.text(pill.left_center() + vec2(32.0, 0.0), Align2::LEFT_CENTER, shown, font, t.text); } #[cfg(test)] @@ -1043,16 +1018,6 @@ mod tests { CalculatedField { name: name.into(), obj, reads: reads.iter().map(|r| (*r).to_owned()).collect(), listed: true, issues } } - #[test] - fn a_name_list_reads_as_a_sentence_and_stops_after_six() { - crate::i18n::set_current(crate::i18n::Lang::EN); - assert_eq!(names(&[]), ""); - assert_eq!(names(&["a"]), "a"); - assert_eq!(names(&["a", "b"]), "a and b"); - assert_eq!(names(&["a", "b", "c"]), "a, b and c"); - assert_eq!(names(&["1", "2", "3", "4", "5", "6", "7"]), "1, 2, 3, 4, 5, 6, …"); - } - fn link(from: &str, to: &str, tone: Tone) -> Link { Link { from: from.into(), to: to.into(), reader: ObjRef { num: 0, generation: 0 }, tone } } @@ -1088,38 +1053,36 @@ mod tests { ); } - #[test] - fn links_stop_at_the_cap() { - let names: Vec = (0..MAX_LINKS + 10).map(|k| format!("g.{k}")).collect(); - let calculated = [field("sum", &["g"], vec![])]; - assert_eq!(links(&calculated, names.iter().map(String::as_str).collect()).len(), MAX_LINKS); - } - + /// The names a focus reads stand before the joiner and the names that read it after it. #[test] fn the_summary_says_what_a_field_reads_and_what_reads_it() { crate::i18n::set_current(crate::i18n::Lang::EN); let links = [link("sub", "total", Tone::Late), link("tax", "total", Tone::Ok), link("qty", "sub", Tone::Ok), link("sub", "tax", Tone::Ok)]; - assert_eq!(trace(&links, &Focus::named("total"), &[]), "total reads sub and tax · No field reads it"); - assert_eq!(trace(&links, &Focus::named("sub"), &[]), "sub reads qty · total and tax read it"); - assert_eq!(trace(&links, &Focus::named("tax"), &[]), "tax reads sub · total reads it"); - assert_eq!(trace(&links, &Focus::named("qty"), &[]), "qty reads no other field · sub reads it"); + let sides = |name: &str| { + let text = trace(&links, &Focus::named(name), &[]); + let (reads, read_by) = text.split_once('·').map(|(a, b)| (a.to_owned(), b.to_owned())).expect("two sides"); + (reads, read_by) + }; + let (reads, read_by) = sides("total"); + assert!(reads.contains("sub") && reads.contains("tax") && !read_by.contains("sub") && !read_by.contains("tax")); + let (reads, read_by) = sides("sub"); + assert!(reads.contains("qty") && !reads.contains("total")); + assert!(read_by.contains("total") && read_by.contains("tax")); + let (reads, read_by) = sides("qty"); + assert!(!reads.contains("sub") && read_by.contains("sub")); } /// A field the form doesn't have is read too, and said to be missing; a script's names built - /// as it runs are said instead of "no other field". + /// as it runs change what is said. #[test] fn the_summary_says_what_is_missing_and_what_is_built() { crate::i18n::set_current(crate::i18n::Lang::EN); - let missing = |names: &[&str]| names.iter().map(|n| CalculationIssue::MissingField { field: (*n).into() }).collect::>(); - let links = [link("qty", "sub", Tone::Ok), link("sub", "total", Tone::Ok), link("tax", "total", Tone::Ok)]; - let sub = field("sub", &["qty", "discount"], missing(&["discount"])); - assert_eq!(trace(&links, &Focus::named("sub"), &[sub]), "sub reads qty and discount · discount is missing · total reads it"); - let tax = field("tax", &["subtotl", "rate"], missing(&["subtotl", "rate"])); - assert_eq!(trace(&links, &Focus::named("tax"), &[tax]), "tax reads subtotl and rate · subtotl and rate are missing · total reads it"); - let rows = field("rows", &[], vec![CalculationIssue::BuiltNames]); - assert_eq!(trace(&links, &Focus::named("rows"), &[rows]), "rows reads fields named as it runs · No field reads it"); - let both = field("total", &["sub", "tax"], vec![CalculationIssue::BuiltNames]); - assert_eq!(trace(&links, &Focus::named("total"), &[both]), "total reads sub and tax · Some names are built as it runs · No field reads it"); + let links = [link("qty", "sub", Tone::Ok), link("sub", "total", Tone::Ok)]; + let sub = field("sub", &["qty", "discount"], vec![CalculationIssue::MissingField { field: "discount".into() }]); + assert!(trace(&links, &Focus::named("sub"), &[sub]).contains("discount")); + let plain = field("rows", &[], vec![]); + let built = field("rows", &[], vec![CalculationIssue::BuiltNames]); + assert_ne!(trace(&links, &Focus::named("rows"), &[plain]), trace(&links, &Focus::named("rows"), &[built])); } /// Two calculated fields named `total`, as a malformed form can have, each reading a field the @@ -1145,21 +1108,17 @@ mod tests { let mut said = Vec::new(); for f in &calculated { view.hover_row = Some(Focus::row(f)); - let focus = view.focus(Some("total")).expect("a hovered row is the focus"); + let focus = view.focus(None, Some("total")).expect("a hovered row is the focus"); + assert_eq!(focus, Focus::row(f)); said.push(trace(&links, &focus, &calculated)); } - assert_eq!( - said, - [ - "total reads qty and lost · lost is missing · grand reads it", - "total reads tax and gone · gone is missing · grand reads it", - "grand reads total · No field reads it", - ] - ); + assert!(said[0].contains("lost") && !said[0].contains("gone")); + assert!(said[1].contains("gone") && !said[1].contains("lost")); view.hover_row = None; - let selected = view.focus(Some("total")).expect("the selection is the focus"); + let selected = view.focus(None, Some("total")).expect("the selection is the focus"); assert_eq!(selected, Focus::named("total")); - assert_eq!(trace(&links, &selected, &calculated), "total reads qty, tax, lost and gone · lost and gone are missing · grand reads it"); + let both = trace(&links, &selected, &calculated); + assert!(both.contains("lost") && both.contains("gone")); } /// On the page too, a field that shares its name is outlined, and its arrows drawn, as one @@ -1223,4 +1182,15 @@ mod tests { ]; assert_eq!(loops(&calculated), vec![vec!["a", "c", "b"], vec!["x"]]); } + + /// A move's `to` counts the order that remains once the moved rows are out, so Alt+↓ on a row + /// at 1 is `to` 2, and a group keeps its order. + #[test] + fn a_move_lands_at_its_place_among_the_rows_that_stay() { + let o = |num| ObjRef { num, generation: 0 }; + let order = [o(1), o(2), o(3), o(4), o(5)]; + assert_eq!(reordered(&order, &[o(2)], 3), [o(1), o(3), o(4), o(2), o(5)]); + assert_eq!(reordered(&order, &[o(2), o(4)], 0), [o(2), o(4), o(1), o(3), o(5)]); + assert_eq!(reordered(&order, &[o(1)], 99), [o(2), o(3), o(4), o(5), o(1)]); + } }