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..fe615bbd4c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -949,7 +949,10 @@ fn page_parts_of( let map = comments::PageMap::new(cx.info, body.pages, cx.rotation, body.view); let pointer = ui.input(|i| i.pointer.hover_pos()).map(|p| craft::behavior::kurbo::Point::new(p.x.into(), p.y.into())); let (tolerance, icon_side) = (map.doc_len(env.hit_reach()), map.doc_len(env.tokens.size.icon.md)); - parts.extend(comments::parts(cx.info, &map, cx.prefs, cx.tool, pointer, &session.comments.tool, tolerance, icon_side)); + let on_link = ui + .input(|i| i.pointer.hover_pos()) + .is_some_and(|p| parts.iter().any(|part| matches!(part.owner, Owner::Link { .. } | Owner::TextLink { .. }) && part.shape.hit(p))); + parts.extend(comments::parts(cx.info, &map, cx.prefs, cx.tool, pointer, &session.comments.tool, tolerance, icon_side, on_link)); } // Fields take the page's presses under Select only: another tool's press over a field is the tool's (a new // text box, a mark, a stamp). @@ -971,8 +974,8 @@ fn page_parts_of( tabs.push((placed.page, xf, overlay.tabs)); } if cx.preparing { - // PLAN: assumed `prepare::tool::page_parts(out, session, form, info, pages, rotation)` (pdf-forms-w9). - crate::prepare::tool::page_parts(&mut parts, session, cx.form, cx.info, body.pages, cx.rotation); + let field_tool = matches!(cx.tool, QuickTool::Field(_)); + crate::prepare::tool::page_parts(&mut parts, session, cx.form, cx.info, body.pages, cx.rotation, field_tool); } if cx.tool == QuickTool::EditText && cx.can_modify { crate::object_ui::page_parts(&mut parts, session, cx.doc, cx.info, body.pages, geo); @@ -1068,6 +1071,12 @@ fn route_press( } // Add text's menu is the page's. session.menu_for = menu_for.filter(|_| !(cx.tool == QuickTool::AddText && cx.can_modify)); + // A Prepare field is selected for its menu, under a field tool too. + if let Owner::PrepareField { .. } = press.owner + && cx.can_modify + { + crate::prepare::tool::field_press(session, cx.form, press); + } // A link reads its own right-click too: its context event selects it for the Link tool's menu. if !matches!(press.owner, Owner::Link { .. } | Owner::TextLink { .. }) { return; @@ -1076,6 +1085,12 @@ fn route_press( let clicked = matches!(press.phase, PressPhase::Release { click: true, .. }); // A press a part takes is no picture pick, and takes back an earlier click whose picture is still being found. session.pending_pick = None; + // A press on anything but a comment (a field, added text, a link) leaves the selected comments unselected, as a + // press on the page does: the part takes it, so the comments tool never sees it. + let primary = pressed_by(&press.phase, PointerButton::Primary); + if primary && (matches!(press.phase, PressPhase::Down { .. }) || press.phase.is_click()) && !matches!(press.owner, Owner::Comment { .. }) { + session.comments.clear_selection(); + } match &press.owner { Owner::Link { .. } | Owner::TextLink { .. } => { // Read before acting: the links borrow the session. diff --git a/crates/ui-egui/src/canvas/page_parts.rs b/crates/ui-egui/src/canvas/page_parts.rs index 9f0ac35aa4..910c3e75c9 100644 --- a/crates/ui-egui/src/canvas/page_parts.rs +++ b/crates/ui-egui/src/canvas/page_parts.rs @@ -169,6 +169,7 @@ pub(crate) struct PagePart { cursor: Option, tip: Option, passes_drag: bool, + context_only: bool, focusable: bool, } @@ -176,7 +177,15 @@ impl PagePart { /// `owner` on `page`, hit by `shape`, ranked by `layer`. It takes clicks, drags and secondary clicks, and shows the /// default cursor and no tip. pub(crate) fn new(owner: Owner, page: usize, shape: impl Into, layer: PageLayer) -> Self { - PagePart { owner, page, shape: shape.into(), layer, cursor: None, tip: None, passes_drag: false, focusable: false } + PagePart { owner, page, shape: shape.into(), layer, cursor: None, tip: None, passes_drag: false, context_only: false, focusable: false } + } + + /// The part takes only secondary clicks: a primary press goes to what lies below (a highlight over a link, whose + /// click follows the link while its right-click opens the highlight's menu). + #[must_use] + pub(crate) fn context_only(mut self) -> Self { + self.context_only = true; + self } /// The cursor over the part. @@ -208,8 +217,12 @@ impl PagePart { self } - /// What the part senses: a click, a secondary click and a drag of its own, or a click that passes its drag on. + /// What the part senses: a click, a secondary click and a drag of its own, or a click that passes its drag on, or + /// a secondary click alone. fn sense(&self) -> Sense { + if self.context_only { + return Sense::CONTEXT_CLICK; + } let drag = if self.passes_drag { Sense::PASSES_DRAG } else { Sense::DRAG }; Sense::CLICK | Sense::CONTEXT_CLICK | drag } diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index b367f70d7a..accc6b0b3c 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -340,7 +340,7 @@ pub(crate) fn page_tool<'a>( Arm::Measure(MeasureTool::new(&mut session.measure, cx.doc, map, cx.info, t, cx.units, cx.author, cx.host, cx.wake.clone())) } QuickTool::Crop => Arm::Crop(CropTool::new(cx.can_crop, &mut session.box_drag, cx.pages, cx.rotation, size)), - QuickTool::EnhanceCamera => Arm::Camera(CameraTool::new(cx.can_modify, cx.pages)), + QuickTool::EnhanceCamera => Arm::Camera(CameraTool::new(cx.can_modify, cx.pages, press)), QuickTool::Fill(fill_tool) => { let input = FillInput { tool: fill_tool, @@ -354,7 +354,7 @@ pub(crate) fn page_tool<'a>( fill_text: &mut session.fill_text, comments: &mut session.comments, }; - Arm::Area(Box::new(FillSignTool::new(&cx, input, fill))) + Arm::Area(Box::new(FillSignTool::new(&cx, input, fill, *press))) } QuickTool::Field(field_tool) => Arm::Area(Box::new(PrepareTool::new(Some(field_tool), cx.can_modify, cx.form, session, cx.info, xforms))), QuickTool::AddText => Arm::Area(Box::new(crate::tools::content_ui::AddTextTool::new(session, cx.doc, cx.pages, cx.text_style))), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cfc728a4f3..e8a2134460 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -638,6 +638,8 @@ fn replace_all_is_one_undo_step_and_counts_pages_whose_matches_had_no_paragraph( find.query = "fox".into(); find.case_query = "fox".into(); find.replacement = "owl".into(); + // A query set here, not typed into the field, starts its search as the field's edit does. + view.rerun_find(); } // The text layers arrive over a few frames; the matches of the two pages with text follow. for _ in 0..200 { diff --git a/crates/ui-egui/src/dialogs/marks_ui.rs b/crates/ui-egui/src/dialogs/marks_ui.rs index 4aa1f0ce0c..d8e68c45c3 100644 --- a/crates/ui-egui/src/dialogs/marks_ui.rs +++ b/crates/ui-egui/src/dialogs/marks_ui.rs @@ -897,20 +897,6 @@ fn overlay(kind: MarkKind, d: &MarksDraft, size: (f64, f64)) -> SharedOverlay { }) } -/// What a pick (the file the Browse button chose) answers: its name and bytes. -fn picked_file(picked: craft::host::Picked) -> Option<(String, Vec)> { - match picked { - craft::host::Picked::Contents(files) => files.into_iter().next(), - craft::host::Picked::Paths(paths) => { - let path = paths.into_iter().next()?; - let name = path.file_name()?.to_string_lossy().into_owned(); - let bytes = std::fs::read(&path).ok()?; - Some((name, bytes)) - } - craft::host::Picked::Cancelled | craft::host::Picked::Unavailable(_) => None, - } -} - impl PdfCraftApp { /// Opens the dialog for `kind`: Add, or Update when `replace`. The draft carries over from the /// last opening; the preview starts at the current page. @@ -1022,8 +1008,11 @@ impl PdfCraftApp { } let target = self.pick_target(Some(doc_id)); self.pick_file(pick, target, move |app: &mut PdfCraftApp, _: &egui::Context, picked| { - if let Some((name, bytes)) = picked_file(picked) { - app.marks_picked(kind, serial, name, bytes); + // The file Browse chose, read through the host's file service as every pick is. + match app.read_picked(picked).map(|files| files.into_iter().next()) { + Ok(Some((name, bytes))) => app.marks_picked(kind, serial, name, bytes), + Ok(None) => {} + Err((name, e)) => app.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e)]), } }); } diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index 2bb6bafb0d..397e7a22ab 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -212,6 +212,12 @@ mod tests { } }); h.run_steps(4); - assert_eq!(h.get_all_by_role_and_label(egui::accesskit::Role::ListItem, tl!(label)).count(), 1, "one tile for the tool"); + // The tiles of Home's two tool grids; the All tools panel beside Home lists the tool too. + let tiles: usize = [tl!("Recommended tools"), tl!("Pinned Tools")] + .into_iter() + .filter_map(|grid| h.query_by_role_and_label(egui::accesskit::Role::ListBox, grid)) + .map(|grid| grid.query_all_by_role_and_label(egui::accesskit::Role::ListItem, tl!(label)).count()) + .sum(); + assert_eq!(tiles, 1, "one tile for the tool"); } } diff --git a/crates/ui-egui/src/hotbar.rs b/crates/ui-egui/src/hotbar.rs index 3f1c658546..0206c6bc2c 100644 --- a/crates/ui-egui/src/hotbar.rs +++ b/crates/ui-egui/src/hotbar.rs @@ -1,13 +1,16 @@ //! The toolbar: a tool rail in the dock, with a searchable drawer that edits which commands sit on it. -use craft::behavior::DockSide; +use craft::behavior::{DockSide, IconId}; use craft::keymap::CommandRef; use craft::theme::Srgba; +use craft::ui::buttons::IconButton; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Show}; +use craft::ui::contract::{Bind, Entry, Props as _, Show}; use craft::ui::docking::PanelSpec; +use craft::ui::form::SliderField; use craft::ui::pickers::Select; use craft::ui::rails::{DrawerGroup, DrawerKind, LastUsed, RailTool, SlotId, ToolRail, ToolSlot, ToolbarDrawer, apply_toolbar_edit}; -use craft::ui::text::NumberField; +use craft::ui::runtime::env::UnitKind; +use craft::ui::value_drag::SliderScale; use pdfcraft_engine::commands::{COMMANDS, command}; use pdfcraft_engine::{Edit, Rgb}; use serde::{Deserialize, Serialize}; @@ -260,31 +263,55 @@ fn footer_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp) { } } +/// The colour of new Fill & Sign text, and of the selected text. +fn set_fill_text_colour(app: &mut PdfCraftApp, ctx: &egui::Context, color: Rgb) { + app.fill_text_color = color; + if let Some((page, index)) = selected_fill_text(app) { + app.apply_edit(ctx, Edit::StyleAnnotation { page, index, color: Some(color), opacity: None, width: None, endings: None }); + } +} + /// Fill & Sign's text controls: its colour, font size and border, for the selected text, or for new text when none -/// is selected. +/// is selected. Each opens a popover from the bar, as the comment tools' controls do. fn fill_text_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp) { let picked = selected_fill_text(app); - let well = Swatch::new(tl!("Text colour").to_string(), to_srgba(app.fill_text_color)).picker("hotbar.fill-text-colour").well().show(ui); - if let Some(request) = well.pick_color { + let mut colour = comments::colours::PalettePick::default(); + let current = app.fill_text_color; + comments::popover_from( + ui, + tl!("Colour"), + |ui| Swatch::new(tl!("Colour").to_string(), to_srgba(current)).show(ui).response, + |ui| { + colour = comments::palette(ui, tl!("Colour"), Some(current), "hotbar.fill-text-colour", &app.recent_colours); + colour.picked.is_some() + }, + ); + if let Some(color) = colour.picked { + set_fill_text_colour(app, ui.ctx(), color); + } + if let Some(request) = colour.request { open_picker(app, request, move |app: &mut PdfCraftApp, ctx: &egui::Context, picked_colour: Srgba| { - let color = from_srgba(picked_colour); - app.fill_text_color = color; - if let Some((page, index)) = selected_fill_text(app) { - app.apply_edit(ctx, Edit::StyleAnnotation { page, index, color: Some(color), opacity: None, width: None, endings: None }); - } + set_fill_text_colour(app, ctx, from_srgba(picked_colour)); }); } let (min, max) = (f64::from(crate::fill_sign::MIN_TEXT_SIZE), f64::from(crate::fill_sign::MAX_TEXT_SIZE)); - let mut size = Some(app.fill_text_size); - let field = NumberField::new(tl!("Font size").to_string(), Bind::bound(&mut size)).range(min..=max).popup_slider(min..=max).unit("pt").show(ui); + let mut size = app.fill_text_size; // #1274: the size also applies to the Fill & Sign text that is selected, once per committed change (a typed // value, or the end of a drag), so a drag adds one undo step and not one per frame. - let committed = field.edit.events.committed().is_some(); - if let Some(value) = size { - app.fill_text_size = value; - } - let size = app.fill_text_size; + let mut committed = false; + comments::popover_from( + ui, + tl!("Font size"), + |ui| IconButton::new(IconId::new("a-large-small")).label(tl!("Font size")).show(ui).response, + |ui| { + let field = + SliderField::new(tl!("Font size"), Bind::bound(&mut size), min..=max).scale(SliderScale::Log).unit_kind(UnitKind::Points).show(ui); + committed = field.edit.events.committed().is_some(); + false + }, + ); + app.fill_text_size = size; if committed && let Some((page, index)) = picked && app @@ -323,11 +350,14 @@ fn fill_text_border_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, picked: O } // The border's own colour (the text's unless picked). if was.width > 0.0 { - let well = Swatch::new(tl!("Border colour").to_string(), to_srgba(was.color.unwrap_or(app.fill_text_color))) - .picker("hotbar.fill-border-colour") - .well() - .show(ui); - if let Some(request) = well.pick_color { + let text_colour = selected + .and_then(|(page, index, _)| app.active_ids().and_then(|(_, id)| app.session.get(id))?.comment_props(page, index)?.color) + .unwrap_or(app.fill_text_color); + let pick = border_colour_control(ui, was.color, text_colour, "hotbar.fill-border-colour", &app.recent_colours); + if let Some(color) = pick.choice { + border.color = color; + } + if let Some(request) = pick.request { let target = selected.map(|(page, index, _)| (page, index)); open_picker(app, request, move |app: &mut PdfCraftApp, ctx: &egui::Context, picked_colour: Srgba| { let color = from_srgba(picked_colour); @@ -360,6 +390,9 @@ fn fill_text_border_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, picked: O if border.width != was.width { edits.push(Edit::StyleAnnotation { page, index, color: None, opacity: None, width: Some(border.width), endings: None }); } + if border.color != was.color { + edits.push(Edit::BorderColorAnnotation { page, index, color: border.color }); + } if border.shape != was.shape { edits.push(Edit::BorderShapeAnnotation { page, index, shape: border.shape }); } @@ -371,11 +404,35 @@ fn fill_text_border_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, picked: O } None => { app.fill_text_border = border.width; + app.fill_text_border_color = border.color; app.fill_text_border_shape = border.shape; } } } +/// The Border colour control: a swatch of the border as drawn (`own`, else the text's colour `text`) that opens +/// "Same as text" over the palette. `choice` is `Some(None)` for Same as text, `Some(Some(c))` for a colour; a choice +/// closes the popover. +fn border_colour_control( + ui: &mut egui::Ui, + own: Option, + text: Rgb, + key: &str, + recent: &comments::RecentColours, +) -> comments::colours::ColourChoice { + let mut pick = comments::colours::ColourChoice::default(); + comments::popover_from( + ui, + tl!("Border colour"), + |ui| Swatch::new(tl!("Border colour").to_string(), to_srgba(own.unwrap_or(text))).show(ui).response, + |ui| { + pick = comments::border_choice(ui, own, key, recent); + pick.choice.is_some() + }, + ); + pick +} + /// The controls of the active comment tool: its border colour (text boxes and callouts), and the quick bar's. fn comment_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, tool: comments::CommentTool) { // Text boxes and callouts: the border's own colour, for new ones and the selected one this tool made (not a @@ -390,13 +447,18 @@ fn comment_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, tool: comments::Co && doc.info.annotations.iter().any(|a| a.page == page && a.index == annotation && !a.locked && comments::made_by(a, tool)); made.then(|| (page, annotation, doc.comment_props(page, annotation))) }); - let shown = match selected.as_ref().and_then(|(.., p)| p.as_ref()) { - Some(p) => p.border_color, - None => style.border_color, + let (own, text) = match selected.as_ref().and_then(|(.., p)| p.as_ref()) { + Some(p) => (p.border_color, p.color.unwrap_or(style.color)), + None => (style.border_color, style.color), + }; + let pick = border_colour_control(ui, own, text, "hotbar.comment-border-colour", &app.recent_colours); + if let Some(color) = pick.choice { + app.comment_prefs.set_border_color(tool, color); + if let Some((page, annotation, _)) = &selected { + app.apply_edit(ui.ctx(), Edit::BorderColorAnnotation { page: *page, index: *annotation, color }); + } } - .unwrap_or(style.color); - let well = Swatch::new(tl!("Border colour").to_string(), to_srgba(shown)).picker("hotbar.comment-border-colour").well().show(ui); - if let Some(request) = well.pick_color { + if let Some(request) = pick.request { let target = selected.map(|(page, annotation, _)| (page, annotation)); open_picker(app, request, move |app: &mut PdfCraftApp, ctx: &egui::Context, picked_colour: Srgba| { let color = from_srgba(picked_colour); diff --git a/crates/ui-egui/src/panels/side_panels.rs b/crates/ui-egui/src/panels/side_panels.rs index cd3d12be58..1215de56af 100644 --- a/crates/ui-egui/src/panels/side_panels.rs +++ b/crates/ui-egui/src/panels/side_panels.rs @@ -301,10 +301,17 @@ impl DockPanels for Panels<'_> { match panel.side() { Some(side) => PanelSpec::new(side_label(side)).icon(IconSpec::svg(IconId::new(side_icon(side)))).command(command), None if self.app.left == LeftPanel::CalculationOrder => PanelSpec::new(crate::i18n::t("Calculation order").to_owned()).command(command), + None if super::tools::has_footer(self.app) => PanelSpec::new(crate::i18n::t("Tools").to_owned()).command(command).footer(), None => PanelSpec::new(crate::i18n::t("Tools").to_owned()).command(command), } } + fn footer(&mut self, panel: &PanelId, ui: &mut Ui, _cx: &mut BodyCx<'_>) { + if *panel == PanelId::Tools { + super::tools::footer(self.app, ui); + } + } + fn permissions(&self, panel: &PanelId) -> Permissions { permissions(panel) } diff --git a/crates/ui-egui/src/panels/tools.rs b/crates/ui-egui/src/panels/tools.rs index e3026df410..ed29d7a746 100644 --- a/crates/ui-egui/src/panels/tools.rs +++ b/crates/ui-egui/src/panels/tools.rs @@ -187,10 +187,6 @@ fn tool_detail(app: &mut PdfCraftApp, ui: &mut egui::Ui, g: &'static ToolGroup) } } let mut run = None; - // Redact a PDF has Acrobat's footer: Clear all / Redact all. - let footer = g.id == "redact"; - let marks = if footer { app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks()) } else { 0 }; - let mut lines = Vec::new(); for s in g.sections { lines.push(Line::Heading(s.title)); @@ -239,20 +235,36 @@ fn tool_detail(app: &mut PdfCraftApp, ui: &mut egui::Ui, g: &'static ToolGroup) // menu over the page, where it was easy to miss (#2149). Checkbox::new(Bind::bound(&mut app.flatten_fill_sign_on_save)).label(tl!("Lock into the page when saving").to_owned()).show(ui); } - if footer { - if marks > 0 { - caption_row( - ui, - &if marks == 1 { crate::i18n::fmt(tl!("1 mark"), &[]) } else { crate::i18n::fmt(tl!("{n} marks"), &[("n", &marks.to_string())]) }, - false, - ); - } - if Button::new(tl!("Clear all").to_owned()).enabled(marks > 0).show(ui).clicked() { - run = Some("redact.clear"); - } - if Button::new(tl!("Redact all").to_owned()).enabled(marks > 0).show(ui).clicked() { - run = Some("redact.apply"); - } + if let Some(cmd) = run { + app.run_command(ui.ctx(), cmd); + } +} + +/// Whether the Tools panel shows a tool whose actions sit in a footer pinned under the body: Redact a PDF's. +pub(crate) fn has_footer(app: &PdfCraftApp) -> bool { + app.left == LeftPanel::Tool("redact") && !(app.active.is_some() && crate::organize_panel::showing(app)) +} + +/// The Tools panel's pinned footer: Redact a PDF's mark count, Clear all and Redact all, in view while the body +/// scrolls, as production pinned them. +pub(crate) fn footer(app: &mut PdfCraftApp, ui: &mut egui::Ui) { + if !has_footer(app) { + return; + } + let marks = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks()); + if marks > 0 { + caption_row( + ui, + &if marks == 1 { crate::i18n::fmt(tl!("1 mark"), &[]) } else { crate::i18n::fmt(tl!("{n} marks"), &[("n", &marks.to_string())]) }, + false, + ); + } + let mut run = None; + if Button::new(tl!("Clear all").to_owned()).enabled(marks > 0).show(ui).clicked() { + run = Some("redact.clear"); + } + if Button::new(tl!("Redact all").to_owned()).enabled(marks > 0).show(ui).clicked() { + run = Some("redact.apply"); } if let Some(cmd) = run { app.run_command(ui.ctx(), cmd); diff --git a/crates/ui-egui/src/tools/camera_ui.rs b/crates/ui-egui/src/tools/camera_ui.rs index 83a9c8bb2d..5fda328ad9 100644 --- a/crates/ui-egui/src/tools/camera_ui.rs +++ b/crates/ui-egui/src/tools/camera_ui.rs @@ -5,7 +5,7 @@ // PLAN: `craft-draw`, `craft-pages` and `craft-behavior` must be dependencies of pdfcraft-ui-egui (Cargo.toml is not in this set's files). use craft::behavior::kurbo::{Point, Rect as DocRect}; use craft::behavior::overlay::Align; -use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId}; +use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId, PressState}; use craft::draw::ui::PerspectiveCropQuad; use craft::pages::ui::view::{PageBody, PlacedPage}; use craft_ui::buttons::{Button, IconButton}; @@ -176,7 +176,8 @@ pub(crate) fn bar(ui: &mut Ui, body: &PageBody<'_>, session: &mut PageSession, a pub(crate) struct CameraTool<'a> { allowed: bool, pages: &'a [PlacedPage], - /// The page the press in progress went down on. + /// The page the press in progress went down on, read from this pass's press: the press and its release come in + /// different passes. pressed: Option, /// The press moved past slop: it is a drag from its page, not a click. dragged: bool, @@ -184,9 +185,10 @@ pub(crate) struct CameraTool<'a> { } impl<'a> CameraTool<'a> { - /// The tool over the pages on screen; with `allowed` off it only refuses. - pub(crate) fn new(allowed: bool, pages: &'a [PlacedPage]) -> Self { - CameraTool { allowed, pages, pressed: None, dragged: false, moved_to: None } + /// The tool over the pages on screen, in a pass whose press is `press`; with `allowed` off it only refuses. + pub(crate) fn new(allowed: bool, pages: &'a [PlacedPage], press: &PressState) -> Self { + let pressed = press.phase.start().and_then(|start| pages.iter().find(|p| p.rect.contains(start.origin))).map(|p| p.page); + CameraTool { allowed, pages, pressed: pressed.filter(|_| allowed), dragged: false, moved_to: None } } /// The page the quadrilateral moves to, once a press asked for it. diff --git a/crates/ui-egui/src/tools/comments.rs b/crates/ui-egui/src/tools/comments.rs index 6ffa809b4d..bcb6168940 100644 --- a/crates/ui-egui/src/tools/comments.rs +++ b/crates/ui-egui/src/tools/comments.rs @@ -50,7 +50,7 @@ pub(crate) use geometry::page_rotation; pub(crate) use geometry::snapped_caret; pub use geometry::{drawn_text_box_rect, snug_text_box_rect, text_box_rect}; pub use menu::CanvasAction; -pub(crate) use menu::{CommentMenuCx, MenuRights, QuickBarPick, attachment_items, context_rows, quick_bar_controls}; +pub(crate) use menu::{CommentMenuCx, MenuRights, QuickBarPick, attachment_items, context_rows, popover_from, quick_bar_controls}; pub(crate) use overlay::{Hover, show}; pub(crate) use popups::note_popups; pub(crate) use state::PageCx; diff --git a/crates/ui-egui/src/tools/comments/bridge.rs b/crates/ui-egui/src/tools/comments/bridge.rs index 1e2688a97c..94136c7fd3 100644 --- a/crates/ui-egui/src/tools/comments/bridge.rs +++ b/crates/ui-egui/src/tools/comments/bridge.rs @@ -380,7 +380,8 @@ pub(crate) fn tips(info: &DocInfo, prefs: &CommentPrefs, tool: QuickTool) -> Vec /// The one part for the comment under the screen point `pointer`, as `pick_at` finds it (so overlapping comments /// never meet the arena's nearest-centre rule). `tolerance` and `icon_side` are page units ([`PageMap::doc_len`] of -/// the tool host's slop and icon side). Registers only under Select. +/// the tool host's slop and icon side). Registers only under Select. With `on_link` (a link lies under the pointer) a +/// highlight there takes only its right-click: a click on it follows the link, as production's did. // PLAN: `pointer` is a screen point (the sheet says `Option`): `page_at` finds its page. #[allow(clippy::too_many_arguments)] pub(crate) fn parts( @@ -392,6 +393,7 @@ pub(crate) fn parts( annotate: &AnnotateTool, tolerance: f64, icon_side: f64, + on_link: bool, ) -> Vec { let Some(screen) = pointer else { return Vec::new() }; let (Some(page), at) = (map.page_at(screen), ()) else { return Vec::new() }; @@ -413,12 +415,18 @@ pub(crate) fn parts( Cursor::System(icon) => icon, _ => CursorIcon::Default, }; + let index = key_of(id).1; + let owner = Owner::Comment { index }; + if on_link && tool == QuickTool::Select && engine(info, page, index).is_some_and(|a| a.subtype == "Highlight") { + // The link's hand and tip show there. + return screen_shapes.into_iter().map(|shape| PagePart::new(owner, page, shape, PageLayer::Comment).context_only()).collect(); + } let tip = tips(info, prefs, tool).into_iter().find(|(t, _)| *t == id).map(|(_, tip)| tip); // A part has one shape: a markup's lines are one part each, which a press resolves to the same comment. screen_shapes .into_iter() .map(|shape| { - let part = PagePart::new(Owner::Comment { index: key_of(id).1 }, page, shape, PageLayer::Comment).passes_drag().cursor(icon); + let part = PagePart::new(owner, page, shape, PageLayer::Comment).passes_drag().cursor(icon); match &tip { Some(tip) => part.tip(tip.clone()), None => part, diff --git a/crates/ui-egui/src/tools/comments/menu.rs b/crates/ui-egui/src/tools/comments/menu.rs index 2fad31b882..efe361c4e4 100644 --- a/crates/ui-egui/src/tools/comments/menu.rs +++ b/crates/ui-egui/src/tools/comments/menu.rs @@ -224,20 +224,29 @@ pub(crate) struct QuickBarPick { } /// A control that opens a popover under it: `opener` draws the control, a click on it opens and closes the -/// popover, and `body` fills it. The popover's open flag is the opener's own, kept in the UI's memory. -fn popover_from(ui: &mut egui::Ui, label: &str, opener: impl FnOnce(&mut egui::Ui) -> egui::Response, body: impl FnOnce(&mut egui::Ui)) { +/// popover, and `body` fills it; a body that reports it is done (a choice that ends the popover's use) closes it. The +/// popover's open flag is the opener's own, kept in the UI's memory. +pub(crate) fn popover_from( + ui: &mut egui::Ui, + label: &str, + opener: impl FnOnce(&mut egui::Ui) -> egui::Response, + body: impl FnOnce(&mut egui::Ui) -> bool, +) { let resp = opener(ui); let key = resp.id.with("popover-open"); let mut open = ui.memory(|m| m.data.get_temp::(key)).unwrap_or(false); - if resp.clicked() { + // A click by the pointer or by keyboard activation. + if craft::ui::contract::clicked(&resp) { open = !open; } let mut body = Some(body); + let mut done = false; Popover::new(label.to_string(), Bind::bound(&mut open)).opened_by(&resp).show(ui, |ui, _| { if let Some(body) = body.take() { - body(ui); + done = body(ui); } }); + open &= !done; ui.memory_mut(|m| m.data.insert_temp(key, open)); } @@ -259,6 +268,7 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &m out.colour = Some(c); } out.request = pick.request; + false }, ); if tool.has_fill() { @@ -274,6 +284,7 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &m if pick.request.is_some() { out.request = pick.request; } + false }, ); } @@ -290,6 +301,7 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &m prefs.set_opacity(tool, percent / 100.0); prefs.set_part_opacity(tool, None, None); } + false }, ); if tool.has_width() { @@ -303,6 +315,7 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &m if w != style.width { prefs.set_width(tool, w); } + false }, ); } diff --git a/crates/ui-egui/src/tools/comments/tests.rs b/crates/ui-egui/src/tools/comments/tests.rs index 5b6440349b..2373fc3daf 100644 --- a/crates/ui-egui/src/tools/comments/tests.rs +++ b/crates/ui-egui/src/tools/comments/tests.rs @@ -567,7 +567,7 @@ fn the_hover_outline_goes_round_what_a_press_would_take() { // PLAN: the outline shape itself is the overlay's `HoverOutline` (pdf-comments-w8); a request to w8 for an `overlay` helper // the test can compare against the part's annotation. The part registered at the pointer is asserted here. let parts = - |view: &DocView, pointer| bridge::parts(&info, &map, &prefs, QuickTool::Select, pointer, &view.session.comments.tool, tolerance, side); + |view: &DocView, pointer| bridge::parts(&info, &map, &prefs, QuickTool::Select, pointer, &view.session.comments.tool, tolerance, side, false); assert_eq!(parts(&view, Some(over)).len(), 1, "one part for the comment under the pointer"); assert!(parts(&view, None).is_empty(), "no pointer, no part"); assert!(parts(&view, Some(Point::new(5.0, 5.0))).is_empty(), "nor where nothing would take the press"); diff --git a/crates/ui-egui/src/tools/comments/tool.rs b/crates/ui-egui/src/tools/comments/tool.rs index cc614e24bf..6ecfef2775 100644 --- a/crates/ui-egui/src/tools/comments/tool.rs +++ b/crates/ui-egui/src/tools/comments/tool.rs @@ -242,11 +242,13 @@ impl CanvasTool for CommentsTool<'_> { let action = self.annotate.press(pointer, cx); *self.pressed = action != ToolAction::Ignored; // A press on no comment passes through to the text (`EmptyPress::PassThrough`): it leaves the comments - // selected only while Shift or Cmd adds to the selection. + // selected only while Shift or Cmd adds to the selection. A press that began off the pages is no page's and + // leaves them selected. if action == ToolAction::Ignored && self.annotate.tool == AnnotationTool::Select && pointer.button == PointerButton::Primary && !(pointer.mods.shift || pointer.mods.cmd) + && self.page_under(pointer.pos).is_some() { self.annotate.selected.clear(); } diff --git a/crates/ui-egui/src/tools/fill_sign.rs b/crates/ui-egui/src/tools/fill_sign.rs index 072ae41a7a..fb1612af64 100644 --- a/crates/ui-egui/src/tools/fill_sign.rs +++ b/crates/ui-egui/src/tools/fill_sign.rs @@ -5,12 +5,12 @@ use base64::Engine as _; use craft::behavior::selection::Selection; -use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId, keyed}; +use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId, PressState, keyed}; use craft::keymap::CommandRef; use craft::review::ui::signature::{SignatureSettings, paint_signature}; use craft::review::{SavedSignature, SignatureImage as SavedImage}; use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; -use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, SelectMode, Show as _, ShowCollection as _}; +use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, Sizing}; use craft::ui::list::ThumbAspect; use craft::ui::primitives::Draw; use craft::ui::style::DataColor; @@ -342,14 +342,16 @@ pub(crate) struct FillSignTool<'a> { info: &'a DocInfo, xforms: Vec<(usize, PageXform)>, outcome: &'a mut Option, - dragged: bool, + /// This pass's press: its release is a click only when it never moved past the click distance, which the press + /// itself records (the press and its release come in different passes). + press: PressState, } impl<'a> FillSignTool<'a> { - pub(crate) fn new(cx: &PageToolCx<'a>, input: FillInput<'a>, outcome: &'a mut Option) -> Self { + pub(crate) fn new(cx: &PageToolCx<'a>, input: FillInput<'a>, outcome: &'a mut Option, press: PressState) -> Self { let size = |page: usize| cx.sizes.get(page).copied().unwrap_or_default(); let xforms = cx.pages.iter().map(|placed| (placed.page, PageXform::of(placed, cx.rotation, size(placed.page)))).collect(); - FillSignTool { input, info: cx.info, xforms, outcome, dragged: false } + FillSignTool { input, info: cx.info, xforms, outcome, press } } /// The page under `pos` and its transform. @@ -418,17 +420,14 @@ impl<'a> FillSignTool<'a> { impl CanvasTool for FillSignTool<'_> { fn press(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) -> ToolAction { - self.dragged = false; if self.page_at(pointer.pos).is_some() { ToolAction::Claimed } else { ToolAction::Ignored } } - fn drag(&mut self, _pointer: &ToolPointer, _cx: &mut ToolContext<'_>) { - // The host calls `drag` only past the click distance, so a drag never places anything. - self.dragged = true; - } + fn drag(&mut self, _pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {} + /// A drag never places anything: only a click does. fn release(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) { - if std::mem::take(&mut self.dragged) { + if !self.press.phase.is_click() { return; } if let Some((page, xf)) = self.page_at(pointer.pos) { @@ -436,9 +435,7 @@ impl CanvasTool for FillSignTool<'_> { } } - fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) { - self.dragged = false; - } + fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) {} /// Escape steps back one thing per press, as a comment tool's does: the open type box, then the tool, so the Text /// tool does not open a box at every click with no way out by the keyboard. @@ -505,8 +502,11 @@ pub(crate) fn signature_entries(ui: &mut egui::Ui, app: &mut crate::PdfCraftApp) let keys: Vec = (0..shown.len()).collect(); let source = keyed(&keys, |k: &usize| *k); let ctx_less_label = &label; - // The grid places the actions of every tile; a tile never sets it. + // The grid places the actions of every tile; a tile never sets it. Two cards at most, in a panel body that + // scrolls: the grid is as tall as its cards and owns no scroll. let out = TileGrid::new(tl!("Saved signatures")) + .sizing(Sizing::Content) + .natural_height(true) .select(SelectMode::Single) .activate(ActivateOn::Click) .action_place(TileActionPlace::Band) diff --git a/crates/ui-egui/src/tools/prepare/tool.rs b/crates/ui-egui/src/tools/prepare/tool.rs index 2ad1bce03e..da2aa2f39b 100644 --- a/crates/ui-egui/src/tools/prepare/tool.rs +++ b/crates/ui-egui/src/tools/prepare/tool.rs @@ -44,12 +44,22 @@ fn transform_of(xforms: &[(usize, PageXform)], page: usize) -> Option /// moves it. The caller asks only while preparing with no field tool armed, because a field tool draws /// anywhere and fields are then not pressable. // The parts read nothing from the session; the page body hands it over so every owner's `page_parts` has one shape. -pub(crate) fn page_parts(out: &mut Vec, _session: &PageSession, form: &[FormField], info: &DocInfo, pages: &[PlacedPage], rotation: u16) { +pub(crate) fn page_parts( + out: &mut Vec, + _session: &PageSession, + form: &[FormField], + info: &DocInfo, + pages: &[PlacedPage], + rotation: u16, + field_tool: bool, +) { for (page, xf) in transforms(pages, info, rotation) { for (field, f) in form.iter().enumerate() { for (widget, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) { let rect = screen_rect(&xf, info, page, w.rect); - out.push(PagePart::new(Owner::PrepareField { field, widget }, page, rect, PageLayer::Placed).cursor(CursorIcon::Move).passes_drag()); + let part = PagePart::new(Owner::PrepareField { field, widget }, page, rect, PageLayer::Placed); + // A field tool draws new fields over the existing ones; a right-click still reaches them. + out.push(if field_tool { part.context_only() } else { part.cursor(CursorIcon::Move).passes_drag() }); } } } diff --git a/crates/ui-egui/src/workflows/files.rs b/crates/ui-egui/src/workflows/files.rs index 1ebdcf6788..152990d752 100644 --- a/crates/ui-egui/src/workflows/files.rs +++ b/crates/ui-egui/src/workflows/files.rs @@ -740,7 +740,7 @@ fn document_folder(path: Option<&str>) -> Option { impl PdfCraftApp { /// The files a pick answered, read: paths through the host's file service, browser contents /// as they are. A file that can't be read gives its name and why. - fn read_picked(&self, picked: Picked) -> Result)>, (String, String)> { + pub(crate) fn read_picked(&self, picked: Picked) -> Result)>, (String, String)> { match picked { Picked::Paths(paths) => paths .iter() diff --git a/crates/ui-egui/tests/it/date_format.rs b/crates/ui-egui/tests/it/date_format.rs index df4095ed4c..f153a260e3 100644 --- a/crates/ui-egui/tests/it/date_format.rs +++ b/crates/ui-egui/tests/it/date_format.rs @@ -25,6 +25,13 @@ fn pattern(h: &Harness<'static, PdfCraftApp>) -> Option { h.get_by_role_and_label(Role::TextInput, "Pattern").value() } +/// Opens the Preferences page `page`: its entry in the dialog's list, the first thing the dialog names so (the +/// window's own "Fill & Sign" names another thing, and the open page its heading). +fn preferences_page(h: &mut Harness<'static, PdfCraftApp>, page: &str) { + h.get_by_role(Role::Dialog).query_all_by_label(page).next().expect("the page's entry").click(); + h.run_steps(3); +} + fn retype(h: &mut Harness<'static, PdfCraftApp>, text: &str) { // The preferences scroll; bring the field into view before clicking it. h.get_by_role_and_label(Role::TextInput, "Pattern").scroll_to_me(); @@ -55,15 +62,13 @@ fn fill_and_sign_dates_follow_the_date_format_preference_and_it_is_remembered() fn reopen(h: &mut Harness<'static, PdfCraftApp>) { h.state_mut().open_preferences(); h.run_steps(4); - h.get_by_label("Fill & Sign").click(); - h.run_steps(3); + preferences_page(h, "Fill & Sign"); } fn ok(h: &mut Harness<'static, PdfCraftApp>) { h.get_by_label("OK").click(); h.run_steps(3); } - h.get_by_label("Fill & Sign").click(); - h.run_steps(3); + preferences_page(&mut h, "Fill & Sign"); // A valid pattern shows a preview of today while it's typed and applies on OK. retype(&mut h, "d \\de mmmm yyyy"); assert_eq!(h.state().session.date_format(), "m/d/yyyy", "typing edits the draft, not the session"); diff --git a/crates/ui-egui/tests/it/open_action.rs b/crates/ui-egui/tests/it/open_action.rs index 03e2863288..77d1387c04 100644 --- a/crates/ui-egui/tests/it/open_action.rs +++ b/crates/ui-egui/tests/it/open_action.rs @@ -325,7 +325,8 @@ fn open_parameters_wait_with_their_file_behind_a_password_prompt_and_a_full_queu } }); h.run_steps(4); - h.get_by_label("Password required"); + // The dialog, named by its heading. + h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Password required"); // The password goes into the dialog's field and OK is pressed. // PLAN: the password field is found by its role; the OK button is the dialog's own (the last "Open" button) let field = h.get_by(|n| n.role() == egui::accesskit::Role::PasswordInput); diff --git a/crates/ui-egui/tests/it/pickers.rs b/crates/ui-egui/tests/it/pickers.rs index 041d8e5225..48113a4aa6 100644 --- a/crates/ui-egui/tests/it/pickers.rs +++ b/crates/ui-egui/tests/it/pickers.rs @@ -419,7 +419,9 @@ fn extract_pages_saves_under_the_file_name_typed_in_the_dialog() { confirm_extract(&mut h); h.answer(Picked::Paths(vec![dir.clone()])); assert!(written(&h, "March_ 2026_receipt.pdf")); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 5, "nothing written outside those names"); + // The writes go through the host's file service, not to disk. + let names: std::collections::BTreeSet<_> = h.files.written().into_iter().filter(|p| p.starts_with(&dir)).collect(); + assert_eq!(names.len(), 5, "nothing written outside those names: {names:?}"); // Into a new tab: the tab, and so Save As, has the typed name. open_extract(&mut h, Extract { name: Some("Chapter 2"), ..Default::default() }); confirm_extract(&mut h); @@ -500,8 +502,8 @@ fn import_comments_takes_the_comments_of_another_pdf() { review.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); let dir = scratch("import-pdf-comments"); let path = dir.join("review.pdf"); - std::fs::write(&path, review).unwrap(); - let mut h = harness(&[1]); + // The import reads the picked file through the host's file service. + let mut h = rig(&[1], ScriptedFiles::held().with_file(&path, review)); assert!(h.execute("comment.import")); h.steps(2); h.answer(Picked::Paths(vec![path])); @@ -565,9 +567,9 @@ fn a_close_prompt_still_means_its_own_document_after_a_pending_save_closes_anoth fn a_watermark_file_from_browse_lands_only_in_the_dialog_that_asked() { let dir = scratch("browse"); let file = dir.join("mark.pdf"); - std::fs::write(&file, fixture(1)).unwrap(); for keep_open in [true, false] { - let mut h = harness(&[1]); + // The dialog reads the picked file through the host's file service. + let mut h = rig(&[1], ScriptedFiles::held().with_file(&file, fixture(1))); assert!(h.execute("edit.watermark")); h.steps(2); h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "File").click(); @@ -1028,14 +1030,11 @@ fn a_saved_attachment_carries_the_documents_zone() { } } -/// Every file under `dir`, recursively, sorted. -fn files_under(dir: &std::path::Path) -> Vec { - let mut out = Vec::new(); - for entry in std::fs::read_dir(dir).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { out.extend(files_under(&path)) } else { out.push(path) } - } +/// Every file the host's file service wrote anywhere, once each, sorted: the writes go through it, not to disk. +fn files_written(h: &Rig) -> Vec { + let mut out = h.files.written(); out.sort(); + out.dedup(); out } @@ -1058,7 +1057,7 @@ fn files_written_from_an_attachment_tab_stay_inside_the_chosen_folder() { let ctx_h = h.ctx.clone(); h.state_mut().split_active(&ctx_h, &pdfcraft_ui_egui::SplitPlan::By(pdfcraft_engine::SplitBy::PageCount(1))); h.answer(Picked::Paths(vec![out.clone()])); - let written = files_under(&dir.0); + let written = files_written(&h); assert_eq!(written.len(), 2, "{name}: two split parts, got {written:?}"); assert!(written.iter().all(|p| p.parent() == Some(out.as_path())), "{name}: {written:?}"); // Extract writes page 1 under the name Split gave it. @@ -1066,7 +1065,7 @@ fn files_written_from_an_attachment_tab_stay_inside_the_chosen_folder() { confirm_extract(&mut h); h.answer(Picked::Paths(vec![out.clone()])); assert!(support::shown_notice(&mut h).is_some(), "{name}: Extract reports what it wrote"); - assert_eq!(files_under(&dir.0), written, "{name}"); + assert_eq!(files_written(&h), written, "{name}"); std::fs::remove_dir_all(dir.0.join("a")).unwrap(); } } diff --git a/crates/ui-egui/tests/it/split_view.rs b/crates/ui-egui/tests/it/split_view.rs index 25254bd783..5910eb6614 100644 --- a/crates/ui-egui/tests/it/split_view.rs +++ b/crates/ui-egui/tests/it/split_view.rs @@ -300,7 +300,7 @@ fn the_pane_last_clicked_is_the_one_menus_and_keys_act_on() { h.run_steps(2); assert!(h.state().session.get(rid).unwrap().dirty); // The main strip still marks the tab its pane shows, and the window title names it. - assert_eq!(h.get_by_role_and_label(Role::Tab, "left.pdf (edited)").accesskit_node().is_selected(), Some(true)); + assert_eq!(h.get_by_role_and_label(Role::Tab, "left.pdf, modified").accesskit_node().is_selected(), Some(true)); assert!(h.state().window_title.starts_with("left.pdf"), "{}", h.state().window_title); }