From 921c2e8a2c83ad308f8015b15bd8d39fb8fef913 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 14:39:08 -0500 Subject: [PATCH] red8 g5: app red round 8 fixes --- apps/pdfcraft-cli/src/ui.rs | 8 ++-- crates/engine/src/catalog.rs | 36 +++++++-------- crates/engine/src/session/save.rs | 10 +++-- crates/engine/src/signature_image.rs | 1 - .../ui-egui/examples/properties_scenarios.rs | 4 +- crates/ui-egui/src/canvas.rs | 3 ++ crates/ui-egui/src/commands.rs | 12 +++++ crates/ui-egui/src/panels/fields.rs | 6 ++- crates/ui-egui/src/tools/bulk_fields.rs | 8 ++-- crates/ui-egui/src/tools/calc_order_ui.rs | 6 ++- crates/ui-egui/src/tools/comments/colours.rs | 13 +++++- crates/ui-egui/src/tools/field_table_ui.rs | 5 ++- crates/ui-egui/src/tools/forms_ui.rs | 3 +- .../ui-egui/src/tools/prepare/properties.rs | 6 +-- crates/ui-egui/src/tools/prepare/tabs.rs | 17 ++++--- crates/ui-egui/src/tools/prepare/tool.rs | 38 ++++++++++++++++ crates/ui-egui/src/workflows/actions_ui.rs | 6 +-- crates/ui-egui/tests/it/bulk_fields.rs | 2 +- crates/ui-egui/tests/it/prepare.rs | 44 ++++++++++++------- 19 files changed, 154 insertions(+), 74 deletions(-) diff --git a/apps/pdfcraft-cli/src/ui.rs b/apps/pdfcraft-cli/src/ui.rs index 032b51642f..832140b16e 100644 --- a/apps/pdfcraft-cli/src/ui.rs +++ b/apps/pdfcraft-cli/src/ui.rs @@ -14,8 +14,7 @@ use super::{CliError, stdout_line}; /// One request to a running app's control channel (`pdfcraft --control PORT`). pub(crate) fn ui(args: &[String]) -> Result<(), CliError> { validate_options("ui", args, UI_OPTIONS)?; - let port = flag(args, "--control") - .ok_or("ui: missing --control PORT (start the app with `pdfcraft --control PORT`)")?; + let port = flag(args, "--control").ok_or("ui: missing --control PORT (start the app with `pdfcraft --control PORT`)")?; let port = control_port(port).map_err(|e| format!("ui: --control {port}: {e}"))?; let env = EnvNames::for_app("PDFCRAFT"); let env_token = std::env::var(&env.token).ok().filter(|v| !v.trim().is_empty()); @@ -28,9 +27,8 @@ pub(crate) fn ui(args: &[String]) -> Result<(), CliError> { let token = client_token(supplied.as_deref(), token_file_given.as_deref(), &FlagNames::default(), &env).map_err(|e| format!("ui: {e}"))?; let pos = positional(args, UI_OPTIONS); - let method = *pos - .first() - .ok_or("ui: missing method (state, inspect, click, move, release, type, key, command, commands, set, open, screenshot, …)")?; + let method = + *pos.first().ok_or("ui: missing method (state, inspect, click, move, release, type, key, command, commands, set, open, screenshot, …)")?; let method = if method.starts_with("ui.") { method.to_string() } else { format!("ui.{method}") }; let mut params = serde_json::Map::new(); for kv in pos.iter().skip(1) { diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs index 8affb889f1..ced85412f3 100644 --- a/crates/engine/src/catalog.rs +++ b/crates/engine/src/catalog.rs @@ -84,7 +84,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ title: "Export to", items: &[ item("Microsoft Word (.docx)", "file-text", "export.docx", Ready), - item("Spreadsheet (.xlsx)", "grid","export.xlsx", Planned("M10")), + item("Spreadsheet (.xlsx)", "grid", "export.xlsx", Planned("M10")), item("Presentation (.pptx)", "presentation", "export.pptx", Ready), item("Image (PNG)", "image", "export.image", Ready), item("Export all images", "image", "export.all_images", Ready), @@ -107,8 +107,8 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ items: &[ item("Add text", "type", "sign.fill.text", Ready), item("Checkmark", "check", "sign.fill.check", Ready), - item("Cross", "close","sign.fill.cross", Ready), - item("Dot", "target","sign.fill.dot", Ready), + item("Cross", "close", "sign.fill.cross", Ready), + item("Dot", "target", "sign.fill.dot", Ready), item("Line", "minus", "sign.fill.line", Ready), item("Date", "clock-3", "sign.fill.date", Ready), item("Signature", "signature", "sign.fill.signature", Ready), @@ -130,11 +130,11 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ title: "Modify page", items: &[ item("Edit text & images", "text-cursor-input", "edit.edit_text", Ready), - item("Rotate pages", "rotate_cw","page.rotate", Ready), + item("Rotate pages", "rotate_cw", "page.rotate", Ready), item("Insert pages", "file-plus-2", "page.insert", Ready), item("Delete pages", "trash-2", "page.delete", Ready), item("Extract pages", "file-output", "page.extract", Ready), - item("Organize pages", "layout_grid","page.organize", Ready), + item("Organize pages", "layout_grid", "page.organize", Ready), ], }, ToolSection { @@ -144,7 +144,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ item("Image", "image-plus", "edit.image", Ready), menu_item("Header and footer", "heading", &["edit.header_footer", "edit.header_footer.update", "edit.header_footer.remove"]), menu_item("Watermark", "stamp", &["edit.watermark", "edit.watermark.update", "edit.watermark.remove"]), - item("Link", "link","edit.link", Ready), + item("Link", "link", "edit.link", Ready), item("Bates numbering", "hash", "edit.bates", Ready), menu_item("Background", "palette", &["edit.background", "edit.background.update", "edit.background.remove"]), item("Attach file", "paperclip", "edit.attach", Ready), @@ -191,8 +191,8 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ ToolSection { title: "Page options", items: &[ - item("Page grid", "layout_grid","page.organize", Ready), - item("Rotate", "rotate_cw","page.rotate", Ready), + item("Page grid", "layout_grid", "page.organize", Ready), + item("Rotate", "rotate_cw", "page.rotate", Ready), item("Delete", "trash-2", "page.delete", Ready), item("Extract", "file-output", "page.extract", Ready), item("Insert", "file-plus-2", "page.insert", Ready), @@ -206,7 +206,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ item("Set page boxes", "square-dashed-mouse-pointer", "page.boxes", Ready), item("Crop pages", "crop", "page.crop", Ready), item("Duplicate pages", "copy-plus", "page.duplicate", Ready), - item("Reverse pages", "swap_vertical","page.reverse", Ready), + item("Reverse pages", "swap_vertical", "page.reverse", Ready), item("Page labels", "tag", "page.number", Ready), item("Page transitions", "presentation", "page.transitions", Planned("M4")), ], @@ -226,8 +226,8 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ items: &[ item("Sticky note", "sticky-note", "comment.note", Ready), item("Highlight text", "highlighter", "comment.highlight", Ready), - item("Underline", "text_underline","comment.underline", Ready), - item("Strikethrough", "text_strikethrough","comment.strikeout", Ready), + item("Underline", "text_underline", "comment.underline", Ready), + item("Strikethrough", "text_strikethrough", "comment.strikeout", Ready), item("Squiggly underline", "spline", "comment.squiggly", Ready), item("Text box", "type", "comment.freetext", Ready), ], @@ -283,7 +283,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ title: "Protect", items: &[ item("Protect with password", "lock", "protect.password", Ready), - item("Remove hidden information", "eye_off","protect.remove_hidden", Ready), + item("Remove hidden information", "eye_off", "protect.remove_hidden", Ready), ], }, ToolSection { @@ -291,7 +291,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ items: &[ item("Encrypt with certificate", "file-lock-2", "protect.certificate", Planned("M8")), item("Security properties", "shield-check", "protect.properties", Ready), - item("Remove security", "lock_open","protect.remove", Ready), + item("Remove security", "lock_open", "protect.remove", Ready), ], }, ], @@ -306,7 +306,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ sections: &[ToolSection { title: "Redact", items: &[ - item("Redact text and images", "rectangle","redact.mark", Ready), + item("Redact text and images", "rectangle", "redact.mark", Ready), item("Redact pages", "file-x", "redact.pages", Ready), item("Find text and redact", "file-search", "redact.search", Ready), item("Set properties", "settings-2", "redact.properties", Ready), @@ -347,7 +347,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ item("Field properties", "settings-2", "form.field.properties", Ready), item("Tab order by rows", "rows-3", "form.tab_order.row", Ready), item("Tab order by columns", "columns-3", "form.tab_order.column", Ready), - item("Calculation order", "list_numbered","form.calculation_order", Ready), + item("Calculation order", "list_numbered", "form.calculation_order", Ready), item("Flatten form fields", "layers", "form.flatten", Ready), item("Import data", "file-input", "form.import_data", Ready), item("Export data", "file-output", "form.export_data", Ready), @@ -357,10 +357,10 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ title: "Add form components", items: &[ item("Text field", "text-cursor-input", "form.add.text", Ready), - item("Text field table", "grid","form.add.text_table", Ready), + item("Text field table", "grid", "form.add.text_table", Ready), item("Checkbox", "check-circle-2", "form.add.checkbox", Ready), item("Radio button", "circle", "form.add.radio", Ready), - item("Drop-down list", "chevron_down","form.add.combo", Ready), + item("Drop-down list", "chevron_down", "form.add.combo", Ready), item("List box", "list", "form.add.list", Ready), item("Button", "square", "form.add.button", Ready), item("Image field", "image", "form.add.image", Ready), @@ -482,7 +482,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ item("Open accessibility report", "file-text", "a11y.report", Ready), item("Add alternate text", "image", "a11y.alt_text", Ready), item("Tags panel", "tag", "a11y.tags", Ready), - item("Fix reading order", "list_numbered","a11y.reading_order", Planned("M12")), + item("Fix reading order", "list_numbered", "a11y.reading_order", Planned("M12")), ], }], }, diff --git a/crates/engine/src/session/save.rs b/crates/engine/src/session/save.rs index 2e26be4056..52085888ab 100644 --- a/crates/engine/src/session/save.rs +++ b/crates/engine/src/session/save.rs @@ -212,10 +212,12 @@ impl Session { // The working bytes hold typed Password-field values (#3926, #3944): a recovery file // is written from a copy without them, and none is written if that copy fails. let bytes = match d.editor.as_ref().filter(|e| pdfcraft_forms::has_password_values(&e.cos) || pdfcraft_xfa::has_password_values(&e.cos)) { - Some(e) => match writable(&e.cos).and_then(|c| write_incremental(&c, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))) { - Ok(b) => Arc::new(b), - Err(_) => return None, - }, + Some(e) => { + match writable(&e.cos).and_then(|c| write_incremental(&c, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))) { + Ok(b) => Arc::new(b), + Err(_) => return None, + } + } None => d.bytes.clone(), }; Some(RecoverySnapshot { diff --git a/crates/engine/src/signature_image.rs b/crates/engine/src/signature_image.rs index dde9c0cd62..f9a22f4084 100644 --- a/crates/engine/src/signature_image.rs +++ b/crates/engine/src/signature_image.rs @@ -220,7 +220,6 @@ impl SignatureImage { pdfcraft_sign::Graphic::Image { width: side(self.size[0]), height: side(self.size[1]), rgba: self.rgba.clone() } } - /// The user-space box for the image with its left edge at `at` (a user-space point on `page`), /// vertically centered, with the same 150 pt width cap as typed names. Left and centered are /// as displayed: on a page with `/Rotate` the box runs along the turned page's axes. diff --git a/crates/ui-egui/examples/properties_scenarios.rs b/crates/ui-egui/examples/properties_scenarios.rs index ec21861d41..348709479c 100644 --- a/crates/ui-egui/examples/properties_scenarios.rs +++ b/crates/ui-egui/examples/properties_scenarios.rs @@ -8,12 +8,12 @@ use std::io::{BufRead, Read, Write}; use std::path::PathBuf; use std::sync::Arc; +use craft::ui::dialog::dialog_id; +use craft::ui::patterns::form_dialogs::HostedParamDialog; use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use pdfcraft_engine::{DocId, Edit, Session}; -use craft::ui::dialog::dialog_id; -use craft::ui::patterns::form_dialogs::HostedParamDialog; use pdfcraft_ui_egui::{PdfCraftApp, PropsTab}; use serde::Deserialize; use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a40c2043c9..a9f343984c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1252,6 +1252,9 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, .highlight_fields(session.highlight_fields) .show_at(ui, body.rect); } + if cx.preparing { + crate::prepare::tool::show_overlays(ui, body.rect, session, cx.form, cx.info, body.pages, cx.rotation); + } if cx.editing_content { let geo = cx.geometry(body); let added_hovered = match parts_out.hovered { diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 0140fb04b4..3c6b4e45da 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -294,6 +294,18 @@ impl PdfCraftApp { self.paste_from_clipboard(ctx, i); return true; } + // Edit ▸ Delete, and its key wherever the page's tool does not claim it, deletes the fields Prepare a form + // has selected. + if id == crate::menus::DELETE { + let Some(i) = self.active.filter(|&i| i < self.views.len()) else { return false }; + let allowed = self.session.get(self.views[i].id).is_some_and(|d| d.allows_modification()); + if !self.is_preparing() || !allowed { + return false; + } + let session = &mut self.views[i].session; + session.pending_edit = crate::prepare::delete_selected(session); + return session.pending_edit.is_some(); + } let Some(spec) = commands::command(id) else { return false }; if !self.command_enabled(spec) { let why = self.disabled_reason(spec); diff --git a/crates/ui-egui/src/panels/fields.rs b/crates/ui-egui/src/panels/fields.rs index 8d1b333ee0..194eaf69a9 100644 --- a/crates/ui-egui/src/panels/fields.rs +++ b/crates/ui-egui/src/panels/fields.rs @@ -174,9 +174,11 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult { list_row = list_row.optional(value.clone()); } if preparing && field.page.is_some() { + // Each arrow names the field it moves. + let named = |tip: &str| format!("{}: {}", tl!(tip), field.name); list_row = list_row - .trailing_part(EARLIER, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-up"))), tl!("Earlier in tab order").to_string()) - .trailing_part(LATER, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-down"))), tl!("Later in tab order").to_string()); + .trailing_part(EARLIER, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-up"))), named("Earlier in tab order")) + .trailing_part(LATER, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-down"))), named("Later in tab order")); } list_row }, diff --git a/crates/ui-egui/src/tools/bulk_fields.rs b/crates/ui-egui/src/tools/bulk_fields.rs index 8f560bf440..d86febddb9 100644 --- a/crates/ui-egui/src/tools/bulk_fields.rs +++ b/crates/ui-egui/src/tools/bulk_fields.rs @@ -500,12 +500,12 @@ fn optional_colour( label: &str, c: &mut Change>, request: &mut Option, - mut choice: impl FnMut(&mut Ui, Option<[f64; 3]>) -> colours::ColourChoice, + mut choice: impl FnMut(&mut Ui, Option<[f64; 3]>, bool) -> colours::ColourChoice, ) { let Change { value, mixed, apply } = c; GroupBox::apply(tl!(label).to_owned(), Bind::bound(apply)).show(ui, |ui, _| { let current = if *mixed { None } else { *value }; - let picked = choice(ui, current); + let picked = choice(ui, current, *mixed); if let Some(chosen) = picked.choice { *value = chosen; *mixed = false; @@ -583,8 +583,8 @@ fn appearance(ui: &mut Ui, d: &mut Draft, recent: &RecentColours, request: &mut }); text_colour(ui, "Text Color:", &mut d.text, recent, request); } - optional_colour(ui, "Border Color:", &mut d.border, request, |ui, current| colours::border_choice(ui, current, BORDER_KEY, recent)); - optional_colour(ui, "Fill Color:", &mut d.fill, request, |ui, current| colours::fill_choice(ui, current, FILL_KEY, recent)); + optional_colour(ui, "Border Color:", &mut d.border, request, |ui, current, mixed| colours::field_choice(ui, current, mixed, BORDER_KEY, recent)); + optional_colour(ui, "Fill Color:", &mut d.fill, request, |ui, current, mixed| colours::field_choice(ui, current, mixed, FILL_KEY, recent)); number(ui, "Line Thickness:", &mut d.width, 0.0..=12.0, Some("pt"), |v| *v, |v| v); let styles: Vec> = BorderStyle::ALL.into_iter().map(|style| Entry::new(style, tl!(style.label()).to_owned())).collect(); choose(ui, "Line Style:", &mut d.style, &styles); diff --git a/crates/ui-egui/src/tools/calc_order_ui.rs b/crates/ui-egui/src/tools/calc_order_ui.rs index 864239de14..2ee9c9d9af 100644 --- a/crates/ui-egui/src/tools/calc_order_ui.rs +++ b/crates/ui-egui/src/tools/calc_order_ui.rs @@ -580,11 +580,13 @@ fn order_row<'a>(k: usize, count: usize, f: &CalculatedField, row: &Row, editabl // 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 { + // Each arrow names the field it moves. + let named = |tip: &str| format!("{}: {}", tl!(tip), f.name); if k > 0 { - r = r.trailing_part_revealed(UP, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-up"))), tl!("Earlier in calculation order")); + r = r.trailing_part_revealed(UP, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-up"))), named("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 = r.trailing_part_revealed(DOWN, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-down"))), named("Later in calculation order")); } } r diff --git a/crates/ui-egui/src/tools/comments/colours.rs b/crates/ui-egui/src/tools/comments/colours.rs index 4e98e77857..5f3f0903f8 100644 --- a/crates/ui-egui/src/tools/comments/colours.rs +++ b/crates/ui-egui/src/tools/comments/colours.rs @@ -1,5 +1,5 @@ //! The comment colour rows: the named swatches as the framework palette takes them, the session's -//! recent custom colours, and the "no fill" / "same as text" choices above a palette. +//! recent custom colours, and the "no fill" / "same as text" / form fields' "no color" choices above a palette. use std::sync::{Arc, PoisonError, RwLock}; @@ -115,3 +115,14 @@ pub(crate) fn fill_choice(ui: &mut egui::Ui, current: Option, key: &str, re pub(crate) fn border_choice(ui: &mut egui::Ui, current: Option, key: &str, recent: &RecentColours) -> ColourChoice { choice(ui, tl!("Same as text"), current, key, recent) } + +/// "No color" above the palette, for a form field's border or fill: on, the field has none; off, it is black +/// until a colour is picked. Fields that differ (`mixed`) show it off, so it can be turned on for all of them. +pub(crate) fn field_choice(ui: &mut egui::Ui, current: Option, mixed: bool, key: &str, recent: &RecentColours) -> ColourChoice { + let was = !mixed && current.is_none(); + let mut none = was; + ToggleButton::new(tl!("No color").to_string(), Bind::bound(&mut none)).show(ui); + let pick = palette(ui, tl!("Colour"), current, key, recent); + let choice = if none != was { Some((!none).then_some([0.0; 3])) } else { pick.picked.map(Some) }; + ColourChoice { choice, request: pick.request } +} diff --git a/crates/ui-egui/src/tools/field_table_ui.rs b/crates/ui-egui/src/tools/field_table_ui.rs index 0323e22fae..e29e1add25 100644 --- a/crates/ui-egui/src/tools/field_table_ui.rs +++ b/crates/ui-egui/src/tools/field_table_ui.rs @@ -14,7 +14,7 @@ use craft::pages::ui::ColumnBar; use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::contract::{ - Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Scroll, Show as _, ShowContainer as _, clicked, + Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Scroll, Show as _, ShowContainer as _, SideLabel, clicked, }; use craft::ui::dialog::{DialogHost, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; @@ -345,7 +345,8 @@ fn names(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormFiel let width = layout.cells.as_ref().ok().and_then(|cells| cells.get(c)).map(|cell| cell.rect[2] - cell.rect[0]); let share = if total > 0.0 && total.is_finite() { column.width / total } else { 0.0 }; let size = width.map_or_else(|| "—".to_owned(), |w| format!("{w:.1} pt · {:.0}%", share * 100.0)); - Field::new(format!("{} ({size})", column_label(c))).id_salt(("field table column", c)).show(ui, |ui, _| { + // The column names the box; its width is the label's detail. + Field::new(column_label(c)).side(SideLabel::new().detail(size)).id_salt(("field table column", c)).show(ui, |ui, _| { TextField::new(column_label(c), Bind::bound(&mut column.pattern)).show(ui); }); } diff --git a/crates/ui-egui/src/tools/forms_ui.rs b/crates/ui-egui/src/tools/forms_ui.rs index c3e37e2b3a..6a387a15e8 100644 --- a/crates/ui-egui/src/tools/forms_ui.rs +++ b/crates/ui-egui/src/tools/forms_ui.rs @@ -771,8 +771,7 @@ fn paint_unbaked_widget( (f, wi, w): (&FormField, usize, &FormWidget), r: Rect, ) { - // PLAN: framework gap: `Draw` gives no `state.selected` colour, so the selected row still reads the visuals. - let selected_row = painter.ctx().global_style().visuals.selection.bg_fill; + let selected_row = draw.role(|c| c.state.selected).egui(); match f.kind { FormFieldKind::Text | FormFieldKind::Combo => { let text = f.value.first().map(String::as_str).unwrap_or(""); diff --git a/crates/ui-egui/src/tools/prepare/properties.rs b/crates/ui-egui/src/tools/prepare/properties.rs index ae0716e952..c9c5eab524 100644 --- a/crates/ui-egui/src/tools/prepare/properties.rs +++ b/crates/ui-egui/src/tools/prepare/properties.rs @@ -22,7 +22,7 @@ use craft::ui::text::{NumberField, TextField}; use super::draft::{FieldDraft, FieldTab}; use super::tabs::{actions_tab, calculate_tab, format_tab, validate_tab}; use super::{BorderStyle, FieldFont, FormFieldKind}; -use crate::comments::colours::{RecentColours, border_choice, fill_choice, palette}; +use crate::comments::colours::{RecentColours, field_choice, palette}; /// The Delete part of an item row of a choice field. const DELETE: TrailingPart = TrailingPart::new(0); @@ -212,14 +212,14 @@ fn appearance_tab(ui: &mut egui::Ui, d: &mut FieldDraft, recent: &RecentColours, }); Text::new(tl!("Borders and Colors")).show(ui); FieldGroup::new(tl!("Border Color:")).id_salt("border-colour").show(ui, |ui, _| { - let pick = border_choice(ui, l.border, "field.props.border", recent); + let pick = field_choice(ui, l.border, false, "field.props.border", recent); if let Some(c) = pick.choice { l.border = c; } park(pending, pick.request); }); FieldGroup::new(tl!("Fill Color:")).id_salt("fill-colour").show(ui, |ui, _| { - let pick = fill_choice(ui, l.fill, "field.props.fill", recent); + let pick = field_choice(ui, l.fill, false, "field.props.fill", recent); if let Some(c) = pick.choice { l.fill = c; } diff --git a/crates/ui-egui/src/tools/prepare/tabs.rs b/crates/ui-egui/src/tools/prepare/tabs.rs index e3010f58d7..85608e5deb 100644 --- a/crates/ui-egui/src/tools/prepare/tabs.rs +++ b/crates/ui-egui/src/tools/prepare/tabs.rs @@ -7,7 +7,7 @@ use craft::ui::contract::{ clicked, }; use craft::ui::display::Text; -use craft::ui::form::Field; +use craft::ui::form::{Field, Help}; use craft::ui::layout_components::Stack; use craft::ui::list::{List, ListRow, RowEvent, TrailingFace, TrailingPart}; use craft::ui::notices::{Notice, NoticeLayout}; @@ -385,18 +385,22 @@ fn custom_script(ui: &mut egui::Ui, js: &mut String, refused: &mut bool) { let note_text = crate::i18n::fmt(tl!("This script is too long to edit here ({kib} KiB); its start is shown. It is kept as it is."), &[("kib", &kib)]); let start = js.get(..js.floor_char_boundary(MAX_EDITED_SCRIPT)).unwrap_or_default().to_string(); - Field::new(label).id_salt("calc-script").show(ui, |ui, _| { + Field::new(label).id_salt("calc-script").help(Help::Text(note_text.into())).show(ui, |ui, _| { // A given value takes no edit: what is typed is not kept. TextField::new(label, Bind::given(start.clone())).lines(6).mono().show(ui); }); - note(ui, note_text); return; } // The box edits a copy: an edit that would take the script past the limit (a large paste) is refused and // said so, rather than hiding the box the user is typing in. The limit is on bytes (`len`), as the JavaScript // engine's is, so `TextField::limit`, which counts characters, is not used. + // The refusal is the box's help line, under it and in its description, until an edit is taken. let mut draft = js.clone(); - Field::new(label).id_salt("calc-script").show(ui, |ui, _| { + let mut field = Field::new(label).id_salt("calc-script"); + if *refused { + field = field.help(Help::Status(Tone::Bad, tl!("A script edited here can be at most 256 KiB long; that change wasn't made.").into())); + } + field.show(ui, |ui, _| { TextField::new(label, Bind::bound(&mut draft)).lines(6).mono().tab_inserts(true).placeholder("event.value = …;").show(ui); }); if draft != *js { @@ -405,9 +409,4 @@ fn custom_script(ui: &mut egui::Ui, js: &mut String, refused: &mut bool) { *js = draft; } } - if *refused { - Notice::new(Tone::Bad, tl!("A script edited here can be at most 256 KiB long; that change wasn't made.")) - .layout(NoticeLayout::Inline) - .show(ui); - } } diff --git a/crates/ui-egui/src/tools/prepare/tool.rs b/crates/ui-egui/src/tools/prepare/tool.rs index 2ad1bce03e..c67646e39b 100644 --- a/crates/ui-egui/src/tools/prepare/tool.rs +++ b/crates/ui-egui/src/tools/prepare/tool.rs @@ -177,6 +177,22 @@ impl<'a> PrepareTool<'a> { self.session.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) }); } + /// An arrow moves the selected field a point the way it points on screen, Shift and an arrow ten points, whatever + /// the zoom; one press is one edit. Whether there was a field to move. + fn nudge(&mut self, direction: Vec2, shift: bool) -> bool { + let Some(key) = self.session.prepare.selected.clone() else { return false }; + let Some((page, rect)) = widget_rect(self.xforms, self.info, self.form, &key) else { return false }; + let Some(xf) = transform_of(self.xforms, page) else { return false }; + // Screen points per page point: the page's width on screen over its width as turned. + let across = if xf.rot % 180 == 90 { xf.ph } else { xf.pw }; + let zoom = xf.rect.width() / across.max(1.0); + let step = if shift { 10.0 } else { 1.0 }; + let user = user_rect(&xf, self.info, page, rect.translate(direction * step * zoom)); + let (name, wi) = key; + self.session.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) }); + true + } + fn finish_marquee(&mut self, marquee: MarqueeSelect<(String, usize)>) { let hits = self.all_widgets().into_iter().filter(|(_, r)| r.intersects(marquee.rect())).collect::>(); let mut items = marquee.selection(hits).into_iter(); @@ -260,6 +276,7 @@ impl CanvasTool for PrepareTool<'_> { self.session.pending_edit = delete_selected(self.session); true } + ToolKey::Nudge { direction, mods, .. } => self.nudge(vec2(direction.x as f32, direction.y as f32), mods.shift), ToolKey::Cancel if self.session.prepare.selected.is_some() => { self.session.prepare.selected = None; self.session.prepare.also.clear(); @@ -334,6 +351,27 @@ pub(crate) fn selection_box(ui: &mut Ui, session: &mut PageSession, form: &[Form } } +/// While preparing: the fields' look on each of the placed `pages` and the selected field's resize box, over the +/// page body at `body`. +pub(crate) fn show_overlays( + ui: &mut Ui, + body: Rect, + session: &mut PageSession, + form: &[FormField], + info: &DocInfo, + pages: &[PlacedPage], + rotation: u16, +) { + let xforms = transforms(pages, info, rotation); + let tab_order = if session.prepare.show_tab_numbers { crate::forms_ui::tab_order(form, info) } else { Vec::new() }; + for &(page, _) in &xforms { + if let Some(overlay) = PrepareOverlay::new(form, &tab_order, session, info, &xforms, page) { + overlay.show_at(ui, body); + } + selection_box(ui, session, form, info, &xforms, page); + } +} + /// One field as the overlay draws it. struct OverlayField { rect: Rect, diff --git a/crates/ui-egui/src/workflows/actions_ui.rs b/crates/ui-egui/src/workflows/actions_ui.rs index 8f11d731ba..c5cfc7fdb3 100644 --- a/crates/ui-egui/src/workflows/actions_ui.rs +++ b/crates/ui-egui/src/workflows/actions_ui.rs @@ -279,8 +279,8 @@ impl PdfCraftApp { } let count = Arc::new(JobCount::default()); - let job_count = count.clone(); - let host = self.host.clone(); // PLAN: assumed `PdfCraftApp::host: Arc` (pdf-hub-w1) + let (job_count, wake) = (count.clone(), self.wake.clone()); + let host = self.host.clone(); // The summary is written on a worker thread: draw it in the UI's language. let lang = crate::i18n::current(); @@ -292,8 +292,8 @@ impl PdfCraftApp { let (mut ok, mut failed) = (0, Vec::new()); for (i, (name, bytes)) in files.into_iter().enumerate() { - // PLAN: framework gap: `Host` has no waker for a job's progress, so the card moves on the frames the queue's own wake and input give job_count.set(i, total); + wake.wake(); let r = pdfcraft_engine::actions::run_on(&action, &name, Arc::new(bytes), javascript, |_, _| {}) .and_then(|r| write_result(host.files(), &dir, &name, &r.bytes)); match r { diff --git a/crates/ui-egui/tests/it/bulk_fields.rs b/crates/ui-egui/tests/it/bulk_fields.rs index c309aa6e45..35a0ae1e67 100644 --- a/crates/ui-egui/tests/it/bulk_fields.rs +++ b/crates/ui-egui/tests/it/bulk_fields.rs @@ -188,7 +188,7 @@ fn cancelling_shared_properties_discards_only_the_draft() { h.run_steps(4); click_gate(&mut h, "Fill Color:"); h.run_steps(4); - h.get_by_role_and_label(Role::Group, "Fill Color:").get_by_label("No fill").click(); + h.get_by_role_and_label(Role::Group, "Fill Color:").get_by_label("No color").click(); h.run_steps(4); assert_eq!(shared(&h)["fill"]["apply"], true); assert!(shared(&h)["fill"]["value"].is_null(), "no fill is the draft's value"); diff --git a/crates/ui-egui/tests/it/prepare.rs b/crates/ui-egui/tests/it/prepare.rs index c36cd5d0f6..85c15aa583 100644 --- a/crates/ui-egui/tests/it/prepare.rs +++ b/crates/ui-egui/tests/it/prepare.rs @@ -133,15 +133,23 @@ fn undo_label(h: &Harness<'static, PdfCraftApp>) -> Option { h.state().session.get(h.state().views[0].id).unwrap().can_undo().map(str::to_owned) } -/// The text of every notice card the main window shows, oldest first. +/// What every notice card the main window shows says first, oldest first: a posted notice's text is +/// its card's title. fn notices(h: &Harness<'static, PdfCraftApp>) -> Vec { - toast::cards(&h.ctx, &WindowKey::main()).iter().map(|card| card.toast.message.as_str().to_owned()).collect() + toast::cards(&h.ctx, &WindowKey::main()).iter().map(|card| card.toast.title.as_ref().unwrap_or(&card.toast.message).as_str().to_owned()).collect() } -/// The row of the calculation order page for the field `name`, whatever its position and value. +/// The row of the calculation order page for the field `name`, whatever its position and value: the row says the +/// field's name and value, its number is the row's lead. fn order_row<'h>(h: &'h Harness<'static, PdfCraftApp>, name: &str) -> egui_kittest::Node<'h> { - let pattern = format!(". {name}:"); - h.get_by(move |node| node.label().is_some_and(|label| label.contains(&pattern))) + let pattern = format!("{name}: "); + h.get_by(move |node| node.label().is_some_and(|label| label.starts_with(&pattern))) +} + +/// Whether a card of the calculation order page says `text`, as its heading or one of its lines: a card +/// with lines is named by its heading and lines together. +fn card_says(h: &Harness<'static, PdfCraftApp>, text: &str) -> bool { + h.query_by_label_contains(text).is_some() } fn text_center_near(h: &Harness<'static, PdfCraftApp>, label: &str, expected: Pos2) -> Option { @@ -594,7 +602,13 @@ fn renaming_a_field_says_how_many_calculations_now_use_the_new_name() { assert_eq!(after.last().map(String::as_str), Some("1 calculation now uses the new name.")); rename(&mut h, "city", "town"); assert!(names(&h).contains(&"town".to_string())); - assert_eq!(notices(&h), after, "no formula reads the calculated field itself, so no new card"); + // Cards shown earlier may have timed out since; none is new. + let now = notices(&h); + let count = |cards: &[String], card: &String| cards.iter().filter(|c| *c == card).count(); + assert!( + now.iter().all(|card| count(&now, card) <= count(&after, card)), + "no formula reads the calculated field itself, so no new card: {after:?} → {now:?}" + ); h.execute("edit.undo"); h.execute("edit.undo"); h.run_steps(2); @@ -1155,7 +1169,7 @@ fn actions_tab_adds_and_removes_actions() { h.get_by_label("Select Trigger:"); h.get_by_label("No actions"); add_action(&mut h, "On Blur", "Open a web link", "https://example.org"); - h.get_by_label("Open a web link: https://example.org"); + h.get_by_label("On Blur: Open a web link: https://example.org"); add_action(&mut h, "Mouse Up", "Run a JavaScript", "app.alert('x')"); h.get_by_label("OK").click(); h.run_steps(3); @@ -1322,7 +1336,7 @@ fn actions_tab_shows_a_chain_and_keeps_it_when_the_first_action_is_replaced() { tab(h, "Actions"); }; open(&mut h); - h.get_by_label("Run a JavaScript, then 1 more action"); + h.get_by_label("Mouse Up: Run a JavaScript, then 1 more action"); // The menu bar's Edit menu and the Edit tab come first; the rows' follow (Mouse Up, On Blur). assert_eq!(h.get_all_by_label("Edit").count(), 4); h.get_all_by_label("Edit").nth(2).unwrap().click(); @@ -1338,7 +1352,7 @@ fn actions_tab_shows_a_chain_and_keeps_it_when_the_first_action_is_replaced() { h.get_by_label("OK").click(); h.run_steps(3); open(&mut h); - h.get_by_label("Open a web link: https://example.com, then 1 more action"); + h.get_by_label("Mouse Up: Open a web link: https://example.com, then 1 more action"); } /// Text field table: pick the tool and drag out an area in the empty lower part of page 1, 200 by @@ -1634,9 +1648,9 @@ fn the_calculation_order_is_moved_dragged_and_fixed() { assert_eq!(order(&h), ["total", "sub", "other"]); // The card says what is wrong, and each row shows its value as the field does: total // calculated before sub, so it still has sub's old value. - assert!(h.query_by_label("1 field shows an old value").is_some()); - assert!(h.query_by_label("total calculates before sub, which it reads.").is_some()); - for row in ["1. total: 0", "2. sub: 6", "3. other: $4.00"] { + assert!(card_says(&h, "1 field shows an old value")); + assert!(card_says(&h, "total calculates before sub, which it reads.")); + for row in ["total: 0", "sub: 6", "other: $4.00"] { assert!(h.query_by_label(row).is_some(), "{row}"); } // The selected field's arrows move it. @@ -1710,7 +1724,7 @@ fn a_loop_has_its_own_card_that_opens_the_formula() { h.run_steps(3); h.get_by_label("Calculation order").click(); h.run_steps(3); - assert!(h.query_by_label("a and b read each other").is_some()); + assert!(card_says(&h, "a and b read each other")); assert!(h.query_by_label("Every field outside a loop calculates after the fields it reads.").is_some()); assert!(h.query_by_label("Fix order").is_none(), "no order fixes a loop"); h.get_by_label("Edit a's formula").click(); @@ -1923,8 +1937,8 @@ fn a_formula_reading_a_missing_field_has_its_own_card() { let ctx_h = h.ctx.clone(); h.state_mut().apply_edit(&ctx_h, Edit::DeleteField { name: "discount".into() }); h.run_steps(3); - assert!(h.query_by_label("1 formula reads a field the form doesn't have").is_some()); - assert!(h.query_by_label("sub reads discount, which the form doesn't have.").is_some()); + assert!(card_says(&h, "1 formula reads a field the form doesn't have")); + assert!(card_says(&h, "sub reads discount, which the form doesn't have.")); assert!(h.query_by_label("Every field calculates after the fields it reads.").is_none(), "no all-clear while a formula is broken"); // Reordered, the order can be undone from the missing-field card; the all-clear still stays away. let ctx_h = h.ctx.clone();