From 8ad5f0d029ecd07c0139b7c24163df5fe72ee77e Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:21:04 -0500 Subject: [PATCH 01/27] deny: ignore RUSTSEC-2026-0543, chrono unmaintained (#7647) (#7649) RUSTSEC-2026-0543 marks every chrono version unmaintained and has no release to move to. It fails cargo deny on every gate run. It is a maintenance notice, not a vulnerability. Add the advisory to [advisories].ignore in deny.toml with justification, the same way other unmaintained advisories are handled. Replacing chrono is not a fix for this repository alone: house rules require time to go through chrono, and craft-libs depend on it. Revisit the ignore when a successor is chosen in craft-contrib. Fixes #7647 --- deny.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/deny.toml b/deny.toml index 8266e6bf34..bb867c14b9 100644 --- a/deny.toml +++ b/deny.toml @@ -62,6 +62,11 @@ ignore = [ { id = "RUSTSEC-2026-0370", reason = "zvariant unmaintained; Linux a11y stack via accesskit_unix" }, { id = "RUSTSEC-2026-0371", reason = "zbus_names unmaintained; Linux a11y stack via accesskit_unix" }, { id = "RUSTSEC-2026-0372", reason = "zvariant_derive unmaintained; Linux a11y stack via accesskit_unix" }, + # chrono is unmaintained (no vulnerability, every version affected, no release to move to). + # The Rust house rules require time to go through chrono, and craft-libs (craft-pdf, + # craft-pkcs7, craft-mime, craft-update) depend on it, so a successor is chosen in + # craft-contrib's standards/house-rules-rust.md first. Revisit when that names one (#7647). + { id = "RUSTSEC-2026-0543", reason = "chrono unmaintained; required by the Rust house rules and craft-libs (#7647)" }, ] # egui's default UI fonts (Ubuntu-Light, Hack, emoji-icon-font): font licences on the AGENTS.md From bd0a21c2de008d945a38eecf26aefaa1ea3520bd Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:00:42 +0800 Subject: [PATCH 02/27] M3: full screen fills the screen or keeps the page display, and Esc closes the find bar before leaving (#576, #4273, #5302) (#5325) Full screen can fill the screen edge to edge, fixing the fake full screen in #379, or keep the normal page display, via a preference. The forms bar is hidden in full screen. Up-arrow and wheel no longer jump back a page, and Esc closes one thing at a time (the find bar before leaving full screen). Bundles #576, #4273 and #5302. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/control.rs | 14 ++ crates/ui-egui/src/app/keys.rs | 14 +- crates/ui-egui/src/app/prefs.rs | 19 +- crates/ui-egui/src/app/window.rs | 1 + crates/ui-egui/src/canvas.rs | 45 +++-- crates/ui-egui/src/canvas/bars.rs | 7 +- crates/ui-egui/src/canvas/navigation.rs | 41 +++- crates/ui-egui/src/canvas/presenter.rs | 4 +- crates/ui-egui/src/canvas/tests.rs | 100 +++++++++- crates/ui-egui/src/canvas/zoom.rs | 104 ++++++++-- crates/ui-egui/src/dialogs/preferences.rs | 4 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/tests/it/view.rs | 222 ++++++++++++++++++++++ parity/acrobat-features.toml | 6 +- 15 files changed, 529 insertions(+), 56 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6e4a52ccea..3e75cbb5a6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -110,6 +110,7 @@ impl PdfCraftApp { scroll_speed: scroll_speed::ScrollSpeed::default(), invert_middle_drag: false, animation_effects: motion::AnimationEffects::default(), + full_screen_escape_exits: true, motion: motion::Motion::default(), language: i18n::AUTO.to_string(), ui_scale: None, diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index a545b4165a..9c416a5c9d 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -191,6 +191,20 @@ impl PdfCraftApp { }; self.set_active_page_gaps(show); } + ("full-screen-escape", _) => { + self.full_screen_escape_exits = match value { + "on" => true, + "off" => false, + _ => return Err("full-screen-escape must be on or off".into()), + }; + } + ("full-screen-fill", _) => { + self.view_defaults.full_screen_fill = match value { + "on" => true, + "off" => false, + _ => return Err("full-screen-fill must be on or off".into()), + }; + } ("default-page-gaps", _) => { self.view_defaults.show_page_gaps = match value { "on" => true, diff --git a/crates/ui-egui/src/app/keys.rs b/crates/ui-egui/src/app/keys.rs index 7471c2f69f..d854709512 100644 --- a/crates/ui-egui/src/app/keys.rs +++ b/crates/ui-egui/src/app/keys.rs @@ -46,8 +46,18 @@ impl PdfCraftApp { if chords { self.registry_shortcuts(ctx); } - // (Esc closes a Combine file shown large first.) - if self.full_screen && self.combine_tab.preview.is_none() && self.page_keys.pressed(ctx, Key::Escape) { + // Esc closes one thing at a time: a Combine file shown large, an open menu, or the camera, + // a selection or the find bar on the page go first, and full screen stays (#5302). With + // the Esc leaves full screen preference off, only ⌘L / Ctrl+L leaves it. + let page_takes_escape = + egui::Popup::is_any_open(ctx) || self.active.and_then(|i| self.views.get(i)).is_some_and(|v| v.escape_closes_something()); + if self.full_screen + && self.full_screen_escape_exits + && self.combine_tab.preview.is_none() + && !page_takes_escape + // Taken: the Esc that leaves full screen closes nothing on the page as well. + && self.page_keys.take(ctx, Key::Escape) + { self.set_full_screen(ctx, false); } if let Some(i) = self.active { diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 9546857d41..618c3e0178 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -173,6 +173,8 @@ impl PdfCraftApp { v["default_page_gaps"] = serde_json::Value::Bool(self.view_defaults.show_page_gaps); v["recent_limit"] = serde_json::json!(self.recent_limit); v["fill_text_color"] = serde_json::json!(self.fill_text_color); + v["full_screen_fill"] = serde_json::Value::Bool(self.view_defaults.full_screen_fill); + v["full_screen_escape_exits"] = serde_json::Value::Bool(self.full_screen_escape_exits); v["redact_prefs"] = self.redact_defaults.to_json(); v["pinned_tools"] = serde_json::json!(self.pinned_tools); // Set outside json! above, which is at serde_json's macro recursion limit. @@ -308,6 +310,19 @@ impl PdfCraftApp { } } + /// The page gaps and full screen's switches: fill the screen, and whether Esc leaves it. + fn restore_page_display_prefs(&mut self, v: &serde_json::Value) { + if let Some(show) = v["default_page_gaps"].as_bool() { + self.view_defaults.show_page_gaps = show; + } + if let Some(fill) = v["full_screen_fill"].as_bool() { + self.view_defaults.full_screen_fill = fill; + } + if let Some(exits) = v["full_screen_escape_exits"].as_bool() { + self.full_screen_escape_exits = exits; + } + } + /// The Print dialog's papers, each printer's setup and the choices it keeps (#2001). fn restore_print_prefs(&mut self, v: &serde_json::Value) { // The Print dialog's own paper sizes; settings are untrusted, so each custom paper is @@ -384,9 +399,7 @@ impl PdfCraftApp { /// Switches for reopening, window chrome and file watching. fn restore_behavior_prefs(&mut self, v: &serde_json::Value) { - if let Some(show) = v["default_page_gaps"].as_bool() { - self.view_defaults.show_page_gaps = show; - } + self.restore_page_display_prefs(v); if let Ok(units) = serde_json::from_value::(v["units"].clone()) { self.units = units; } diff --git a/crates/ui-egui/src/app/window.rs b/crates/ui-egui/src/app/window.rs index e7035b5000..cc3d83e8bc 100644 --- a/crates/ui-egui/src/app/window.rs +++ b/crates/ui-egui/src/app/window.rs @@ -44,6 +44,7 @@ impl PdfCraftApp { self.full_screen = on; for view in &mut self.views { if on { + view.full_screen_fill = self.view_defaults.full_screen_fill; view.enter_presentation(); } else { view.leave_presentation(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5ef59e76aa..686f7b6798 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -344,12 +344,23 @@ pub struct ViewDefaults { /// Highlight existing fields: a preference in Acrobat, so it carries over to the next /// document and the next session. On for new settings; a stored choice wins. pub highlight_fields: bool, + /// Full screen fills the screen with one page (or spread) at a time, edge to edge; off, it + /// keeps the page display it is entered from (continuous scrolling, say: #4273). + pub full_screen_fill: bool, } impl Default for ViewDefaults { fn default() -> Self { // Single page, scrolling continuously at fit width: the earlier "continuous" default. - Self { layout: PageLayout::Single, continuous: true, show_page_gaps: true, fit: Fit::Width, zoom: 1.0, highlight_fields: true } + Self { + layout: PageLayout::Single, + continuous: true, + show_page_gaps: true, + fit: Fit::Width, + zoom: 1.0, + highlight_fields: true, + full_screen_fill: true, + } } } @@ -553,6 +564,10 @@ pub struct DocView { /// Full screen (Acrobat's Full Screen Mode): the display saved on entering it, while the view /// shows one page or spread at a time, fitted to the screen. `None` outside full screen. presentation: Option, + /// Full screen fills the screen with one page (or spread) at a time, edge to edge (the + /// default); off, it keeps the page display it was entered from. Set from the app's + /// preference before full screen is entered. + pub full_screen_fill: bool, /// Full screen's transitions, display times and pointer (see [`presenter`]). pub(crate) presenter: presenter::Presenter, pages: HashMap, @@ -1078,6 +1093,7 @@ impl DocView { compare_marks: Vec::new(), interface: Default::default(), presentation: None, + full_screen_fill: defaults.full_screen_fill, presenter: Default::default(), pages: HashMap::new(), errors: HashMap::new(), @@ -1272,6 +1288,7 @@ impl DocView { fresh.interface = self.interface; // Still presenting, with the display to go back to on leaving. fresh.presentation = self.presentation.take(); + fresh.full_screen_fill = self.full_screen_fill; // A new document: none of the old one's transition, page or timer carries over. fresh.presenter = Default::default(); fresh.back = std::mem::take(&mut self.back); @@ -1314,6 +1331,7 @@ impl DocView { v.highlight_fields = self.highlight_fields; v.notice_dismissed = self.notice_dismissed; v.scripts_off_noted = self.scripts_off_noted; + v.full_screen_fill = self.full_screen_fill; v.goto = Some((self.current, 0.0)); v } @@ -1578,8 +1596,9 @@ fn paint_page_surface(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFra let visible = frame.visible; let info = frame.env.info; let painter = ui.painter(); - // Shadows would darken the preceding page when pages touch. - if view.show_page_gaps && frame.env.show_page_edge_shadows { + // Shadows would darken the preceding page when pages touch; full screen filling the screen + // shows the page alone on black (#576). + if view.show_page_gaps && frame.env.show_page_edge_shadows && !view.fills_screen() { painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO)); } painter.rect_filled(r, CornerRadius::ZERO, paper); @@ -2295,7 +2314,7 @@ fn anchor_zoom_change(view: &mut DocView, avail: Vec2, old_zoom: f32) { } else if let Some((page, fy, rel_y)) = anchor { view.zoom_anchor = Some((page, 0.5, fy, vec2(avail_width / 2.0, rel_y))); } else { - view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail_width / 2.0, MARGIN))); + view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail_width / 2.0, view.margin()))); } } } @@ -2775,11 +2794,12 @@ fn page_scroll_area(ui: &egui::Ui, view: &mut DocView, geometry: &ScrollGeometry // The page counts with its side gutters, which keep its edge clear of the floating // quick-action bar as the layout does. let (x, w) = (view.last_scroll.x, avail.width()); - let (left, right) = (r.left() - SIDE, r.right() + SIDE); + let gutter = view.side(); + let (left, right) = (r.left() - gutter, r.right() + gutter); // Turned by → / ← at an edge (`goto_side`): a page or spread wider than the window starts at // the edge the reader comes from. let row = shown_row(view, rects).iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union).unwrap_or(r); - let (row_left, row_right) = (row.left() - SIDE, row.right() + SIDE); + let (row_left, row_right) = (row.left() - gutter, row.right() + gutter); let target = match side { Some(from_right) if row_right - row_left > w => { if from_right { @@ -3192,16 +3212,17 @@ fn refine_goto_point(mut scroll: egui::ScrollArea, view: &mut DocView, geometry: /// Where the `shown` pages sit in the scroll content, as how far the content starts into the /// layout and how tall it is. Scrolling continuously every page scrolls; otherwise only the -/// current row does, the content being its bounding box plus margins. Pages that fit a view +/// current row does, the content being its bounding box plus `margin` (none while full screen +/// fills the screen). Pages that fit a view /// `view_height` tall sit in its middle, the spare height shared above and below (#5708): the /// content fills the view, so there is nothing to scroll, and starts on a whole physical pixel /// as the layout's pages do, or their edges would blur and the seams between them open. -fn vertical_placement(continuous: bool, rects: &[Rect], shown: &[usize], view_height: f32, pixels_per_point: f32) -> (f32, f32) { +fn vertical_placement(continuous: bool, rects: &[Rect], shown: &[usize], view_height: f32, margin: f32, pixels_per_point: f32) -> (f32, f32) { let Some(r) = shown.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) else { return (0.0, 0.0) }; if fits_height(r, view_height, pixels_per_point) { return (((r.center().y - view_height / 2.0) * pixels_per_point).round() / pixels_per_point, view_height); } - if continuous { (0.0, r.bottom() + MARGIN) } else { (r.top() - MARGIN, r.height() + 2.0 * MARGIN) } + if continuous { (0.0, r.bottom() + margin) } else { (r.top() - margin, r.height() + 2.0 * margin) } } /// Whether the pages in `r` show whole in a view `view_height` tall, without their margins. @@ -3345,7 +3366,8 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward. let row = shown_row(view, &rects); let visible_pages: Vec = if view.continuous { (0..rects.len()).collect() } else { row.clone() }; - let (y_shift, content_h) = vertical_placement(view.continuous, &rects, &visible_pages, avail.height(), ui.ctx().pixels_per_point()); + let (y_shift, content_h) = + vertical_placement(view.continuous, &rects, &visible_pages, avail.height(), view.margin(), ui.ctx().pixels_per_point()); let mut scroll = page_scroll_area( ui, @@ -3520,7 +3542,8 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { // below the window's top). Within a point, as for wheel paging, so layout rounding // can't hide an edge. let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0); - (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0) + // Going to a page clamps at 0, which is where a page sits with no margin (full screen). + (page, out.state.clamped_offset().y <= (view.margin() - view.page_gap()).max(0.0) + 1.0, out.state.clamped_offset().y >= max_y - 1.0) }); // Within a point, as above: at an edge of the scrolled content, or of the current page or // spread shown whole that way (in continuous view the content is as wide as the widest page, diff --git a/crates/ui-egui/src/canvas/bars.rs b/crates/ui-egui/src/canvas/bars.rs index 85807e28fe..17ca392463 100644 --- a/crates/ui-egui/src/canvas/bars.rs +++ b/crates/ui-egui/src/canvas/bars.rs @@ -63,7 +63,7 @@ pub(super) enum Notice { /// The notice bar above the pages: a file changed on disk first, then what a historical /// snapshot is, then pages cut at the renderer's limits, then the offer to lock a signature just /// placed, then the signature status bar, a form's scripts having been turned off, security, -/// forms and warnings. +/// forms and warnings. None in full screen. #[allow(clippy::too_many_arguments)] pub(super) fn notices( view: &mut DocView, @@ -75,6 +75,11 @@ pub(super) fn notices( ui: &mut egui::Ui, t: &Tokens, ) -> Option { + // Full screen shows the page and nothing else (#1459), so the notice bar above the pages waits + // until it is left; filling the screen, a bar would push the page past its bottom (#576). + if view.presentation.is_some() { + return None; + } let info = &doc.info; let xfa = doc.xfa.as_ref(); // The file changed on disk while this document has unsaved changes (#431): ask before diff --git a/crates/ui-egui/src/canvas/navigation.rs b/crates/ui-egui/src/canvas/navigation.rs index 1dfadf0963..de72da2564 100644 --- a/crates/ui-egui/src/canvas/navigation.rs +++ b/crates/ui-egui/src/canvas/navigation.rs @@ -207,6 +207,21 @@ impl DocView { } } + /// Whether Esc has something on the page to close: the camera, a form field being filled (its + /// editor closes it), a selection or the find bar ([`shortcuts`] closes the others in that + /// order). Esc closes one thing at a time, so full screen leaves only on an Esc that finds none + /// of them (#5302): from a field, "Esc (press twice)" leaves (*Adobe Acrobat Help*, 2019, + /// p. 248). A search shown in the Search panel isn't on the page: full screen hides the panel, + /// and keeps its search. + pub fn escape_closes_something(&self) -> bool { + self.camera.is_some() + || self.camera_done.is_some() + || self.forms.focus.is_some() + || self.selection.is_some() + || self.all_text + || self.find.as_ref().is_some_and(|f| !f.in_panel) + } + /// Next page (`true`) or previous page. In two-page view this moves a whole spread: the other /// page of the spread is already on screen, so stepping to it wouldn't move the view (#70). pub fn step_page(&mut self, forward: bool) { @@ -383,6 +398,23 @@ fn zoom_shortcuts(view: &mut DocView, pressed: &impl Fn(egui::KeyboardShortcut) } } +/// Esc on the page closes one thing: the camera, then a form field being filled, then a +/// selection, then the find bar ([`DocView::escape_closes_something`] says whether there is one). +fn escape_closes_one(view: &mut DocView) { + if view.camera.is_some() || view.camera_done.is_some() { + view.pending_action = Some(ViewAction::CancelCamera); + } else if view.forms.focus.is_some() { + // A form field being filled takes this Esc: its editor closes it, and nothing else on + // the page closes with it (a selection stays for the next Esc). + } else if view.selection.is_some() || view.all_text { + view.selection = None; + view.all_text = false; + } else if view.presentation.is_none() || view.find.as_ref().is_some_and(|f| !f.in_panel) { + // Full screen hides the Search panel: its search stays for when the panel is back. + view.find = None; + } +} + /// The view's keys: its chords, then its plain keys. `chords`: no menu of the menu bar has the /// keyboard and nothing covers the pages, so chords may run (they wait for a menu, as the /// registered commands' do). An open form field keeps the paging and scrolling keys for itself. @@ -462,14 +494,7 @@ fn view_keys( // An open menu takes Escape first and closes; the selection stays for the next one (#3535). // So does an open field, whose list closes. if key(Key::Escape) && !egui::Popup::is_any_open(ctx) && !field_open { - if view.camera.is_some() || view.camera_done.is_some() { - view.pending_action = Some(ViewAction::CancelCamera); - } else if view.selection.is_some() || view.all_text { - view.selection = None; - view.all_text = false; - } else { - view.find = None; - } + escape_closes_one(view); } // The open field's keys leave the page under it where it is. if field_open { diff --git a/crates/ui-egui/src/canvas/presenter.rs b/crates/ui-egui/src/canvas/presenter.rs index d6c8461bfa..d91da789e0 100644 --- a/crates/ui-egui/src/canvas/presenter.rs +++ b/crates/ui-egui/src/canvas/presenter.rs @@ -127,7 +127,9 @@ pub(super) fn frame( let arriving = view.presenter.turn.as_ref().map(|t| t.to_page); if showing != Some(page) && arriving != Some(page) { // A new page: play its transition from the page before, when there is one to play. - let plays = animates && view.layout == PageLayout::Single && view.rotation == 0; + // Not while scrolling: full screen that keeps a continuous display (Fill screen off, + // #4273) moves between pages by scrolling, with no page to turn from. + let plays = animates && view.layout == PageLayout::Single && !view.continuous && view.rotation == 0; let turn = showing.or(arriving).filter(|_| plays).and_then(|from_page| { let (effect, seconds) = entry(info, page).and_then(effect_of)?; let from = view.pages.get(&from_page)?.tex.clone(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index ce99e2764e..c6924c30e5 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2557,22 +2557,41 @@ fn full_screen_two_page_view_fits_the_spread_it_shows() { assert!(small > windowed * 1.9, "the small spread fills the screen: {small} vs {windowed}"); v.current = 3; v.fit_zoom(&info); - assert!((v.zoom - windowed).abs() < 1e-4, "the large spread fits as before"); + // The large spread fits the screen edge to edge, without the window's margins (#576). + let edge_to_edge = (v.viewport_w - v.page_gap()) / (2.0 * 600.0 * PT); + assert!((v.zoom - edge_to_edge).abs() < 1e-4 && v.zoom > windowed, "the large spread fills the screen: {} vs {edge_to_edge}", v.zoom); v.current = 1; v.fit_zoom(&info); assert_eq!(v.zoom, small, "page 2 is in the first spread"); - // With a cover page: [0] alone, then [1, 2] (the large page decides), then [3]. + // With a cover page: [0] alone, then [1, 2], then [3]. v.cover = true; v.current = 0; v.fit_zoom(&info); assert_eq!(v.zoom, small, "the cover page alone"); + // The mixed spread [1, 2] fits its two pages' own widths side by side, 300 + 600 points, + // and not twice the wider one: here the height decides. v.current = 1; v.fit_zoom(&info); - assert!((v.zoom - windowed).abs() < 1e-4, "page 2 shares a spread with the large page 3"); + let mixed_fit = ((v.viewport_w - v.page_gap()) / (900.0 * PT)).min(v.viewport_h / (800.0 * PT)); + assert!((v.zoom - mixed_fit).abs() < 1e-4 && v.zoom > edge_to_edge, "page 2 shares a spread with the large page 3: {} vs {mixed_fit}", v.zoom); + // And the content is as wide as that spread, so the spread is centred on the screen: room for + // twice the larger page would centre it past the screen's right edge. + let content_w = v.content_width(&info, v.viewport_w); + let rects = v.layout(&info, content_w, 1.0); + let (left, right) = (rects[1].min.x, rects[2].max.x); + assert!(content_w <= v.viewport_w + 0.5, "the spread needs no scrolling: {content_w}"); + assert!(left >= -0.5 && right <= v.viewport_w + 0.5, "the spread is on the screen: {left}..{right}"); + assert!((left - (v.viewport_w - right)).abs() < 1.0, "and centred: {left}..{right}"); + // The cover alone keeps its spread's blank slot, and is on the screen too. + v.current = 0; + v.fit_zoom(&info); + let content_w = v.content_width(&info, v.viewport_w); + let cover = v.layout(&info, content_w, 1.0)[0]; + assert!(cover.min.x >= v.viewport_w / 2.0 && cover.max.x <= v.viewport_w + 0.5, "the cover sits on the right: {cover:?}"); // Scrolling while in full screen fits the document, as scrolling does in the window. (v.continuous, v.current) = (true, 0); v.fit_zoom(&info); - assert!((v.zoom - windowed).abs() < 1e-4, "continuous full screen keeps one zoom"); + assert!((v.zoom - edge_to_edge).abs() < 1e-4, "continuous full screen keeps one zoom"); v.continuous = false; // The cover page is a spread of its own even when the next page is larger. let mixed = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0), page(600.0, 800.0)], ..Default::default() }; @@ -2585,6 +2604,17 @@ fn full_screen_two_page_view_fits_the_spread_it_shows() { (v.layout, v.continuous) = (PageLayout::TwoUp, false); v.fit_zoom(&info); assert!((v.zoom - windowed).abs() < 1e-4, "in the window, one zoom for the document"); + // With Fill off, full screen keeps the window's display (#4273): two-page view keeps one zoom + // for the document, and its width, as the spreads turn. + let content_w = v.content_width(&info, v.viewport_w); + v.full_screen_fill = false; + v.enter_presentation(); + for current in [0, 1, 3] { + v.current = current; + v.fit_zoom(&info); + assert!((v.zoom - windowed).abs() < 1e-4, "fill off, page {current}: the window's zoom, {} vs {windowed}", v.zoom); + assert_eq!(v.content_width(&info, v.viewport_w), content_w, "fill off, page {current}: the window's width"); + } } #[test] @@ -2853,6 +2883,45 @@ fn a_moved_picture_is_drawn_from_the_fresh_raster_while_a_tile_is_still_stale() h.state_mut().views[0].tiles.clear(); } +/// Review on #5325: one Esc closes one thing. With a form field being filled (a check box that +/// has the focus) and text selected, the page leaves the selection for the next Esc: the field's +/// editor takes this one. +#[test] +fn esc_with_a_field_being_filled_leaves_the_selection() { + let mut v = view(3, PageLayout::Single, true); + v.all_text = true; + v.forms.focus = Some(crate::forms_ui::Focus { + name: "agree".into(), + obj: None, + widget: 0, + text: String::new(), + picked: Vec::new(), + request_focus: false, + select_all: false, + press: None, + calendar: None, + calendar_rect: None, + calendar_text: None, + list: Default::default(), + had_focus: true, + }); + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + i.events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + }); + shortcuts(&mut v, &ctx, Default::default(), true, Default::default()); + assert!(v.all_text, "the selection stays while the field takes Esc"); + v.forms.focus = None; + shortcuts(&mut v, &ctx, Default::default(), true, Default::default()); + assert!(!v.all_text, "with no field being filled, Esc clears the selection"); +} + /// Review on #4378: `FitWindow` measures the spread the view shows, its pages side by side /// and as tall as the taller one, with one page in a spread that has only one. #[test] @@ -3187,6 +3256,25 @@ fn a_transition_of_zero_or_negative_length_cuts() { } } +/// Full screen that keeps a continuous display (Fill screen off, #4273) scrolls from page to page: +/// a page's transition doesn't play over the scrolling pages. +#[test] +fn full_screen_that_keeps_scrolling_plays_no_transition() { + use pdfcraft_render::TransitionStyle; + let ctx = egui::Context::default(); + let page = pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 }; + let info = DocInfo { pages: vec![page; 3], transitions: vec![trans(1, Some(TransitionStyle::Wipe), 1.0, None)], ..Default::default() }; + let mut v = DocView::new(DocId(1), &info, ViewDefaults { layout: PageLayout::Single, continuous: true, ..Default::default() }); + v.full_screen_fill = false; + v.enter_presentation(); + assert!(v.continuous(), "Fill screen off keeps continuous scrolling"); + give_raster(&ctx, &mut v, 0); + presenter_frame(&ctx, &mut v, &info, 0.0); + turn_to(&ctx, &mut v, 1); + presenter_frame(&ctx, &mut v, &info, 0.1); + assert!(!v.presenting_a_transition(), "no Wipe over a scrolling display"); +} + /// A style the spec doesn't name is read as its default R, Replace (ISO 32000-2 Table 164: "The /// new page simply replaces the old one with no special transition effect"): the page changes at /// once, and its display time still counts. @@ -3339,10 +3427,10 @@ fn only_pixel_snapping_passes_for_fitting_the_view() { let page = |height: f32| [Rect::from_min_size(pos2(0.0, MARGIN), vec2(300.0, height))]; for ppp in [1.0, 2.0] { let slack = 0.5 / ppp; - let (_, content) = vertical_placement(false, &page(600.0 + slack), &[0], 600.0, ppp); + let (_, content) = vertical_placement(false, &page(600.0 + slack), &[0], 600.0, MARGIN, ppp); assert_eq!(content, 600.0, "at {ppp}x, snapping's half pixel still fits"); for over in [slack + 0.1, 1.0] { - let (shift, content) = vertical_placement(false, &page(600.0 + over), &[0], 600.0, ppp); + let (shift, content) = vertical_placement(false, &page(600.0 + over), &[0], 600.0, MARGIN, ppp); assert_eq!((shift, content), (0.0, 600.0 + over + 2.0 * MARGIN), "at {ppp}x, {over} pt too tall scrolls"); } } diff --git a/crates/ui-egui/src/canvas/zoom.rs b/crates/ui-egui/src/canvas/zoom.rs index e9e2eae82b..2faf836193 100644 --- a/crates/ui-egui/src/canvas/zoom.rs +++ b/crates/ui-egui/src/canvas/zoom.rs @@ -32,15 +32,23 @@ impl DocView { } self.presentation = Some(SavedDisplay { layout: self.layout, continuous: self.continuous, cover: self.cover, fit: self.fit, zoom: self.zoom }); - self.continuous = false; - self.fit = Fit::Page; self.selection = None; self.presenter = Default::default(); - self.goto = Some((self.current, 0.0)); + // Off, the Fill screen preference keeps the display full screen was entered from (#4273), + // and the reading position in it. + if self.full_screen_fill { + self.continuous = false; + self.fit = Fit::Page; + self.goto = Some((self.current, 0.0)); + } else { + self.goto = Some(self.reading_position()); + } } /// Leave full screen: the display from before it comes back, at the page reached meanwhile. + /// From a display full screen kept, at the reading position. pub fn leave_presentation(&mut self) { + let goto = if self.fills_screen() { (self.current, 0.0) } else { self.reading_position() }; let Some(saved) = self.presentation.take() else { return }; self.presenter = Default::default(); self.layout = saved.layout; @@ -48,7 +56,17 @@ impl DocView { self.cover = saved.cover; self.fit = saved.fit; self.zoom = saved.zoom; - self.goto = Some((self.current, 0.0)); + self.goto = Some(goto); + } + + /// Where the reader is, as of the last frame: the page at the top of the document area and + /// the fraction of it scrolled past, or the top of the current page when no page is there. + fn reading_position(&self) -> (usize, f32) { + let top = self.viewport_screen.top(); + self.screen_xforms + .iter() + .find(|(_, xf)| xf.rect.top() <= top && top < xf.rect.bottom() && xf.rect.height() > 0.0) + .map_or((self.current, 0.0), |(p, xf)| (*p, ((top - xf.rect.top()) / xf.rect.height()).clamp(0.0, 1.0))) } /// The display shown outside full screen: the one presenting replaced, or the current one. @@ -72,6 +90,22 @@ impl DocView { self.presentation.is_some() } + /// Whether full screen fills the screen with one page (or spread) at a time: then the page + /// takes the whole screen, with no margin around it (#576). + pub fn fills_screen(&self) -> bool { + self.presentation.is_some() && self.full_screen_fill + } + + /// The space above the first page and below the last: none while full screen fills the screen. + pub(super) fn margin(&self) -> f32 { + if self.fills_screen() { 0.0 } else { MARGIN } + } + + /// The least space beside the pages: none while full screen fills the screen. + pub(super) fn side(&self) -> f32 { + if self.fills_screen() { 0.0 } else { SIDE } + } + /// Whether full screen is playing a page transition (or holding the page before it until the /// next one has rendered). pub fn presenting_a_transition(&self) -> bool { @@ -297,37 +331,52 @@ impl DocView { if self.cover { c.saturating_sub((c + 1) % 2) } else { c - c % 2 } } + /// The display sizes of the spread full screen shows in two-page view (one spread at a time): + /// its two pages, or one alone. `None` in every other display, full screen that keeps the + /// window's display (Fill off, #4273) included: that fits the document as the window does. + fn full_screen_spread(&self, info: &DocInfo) -> Option> { + if !self.fills_screen() || self.layout != PageLayout::TwoUp || self.continuous { + return None; + } + let first = self.spread_first(self.current); + let last = if self.cover && first == 0 { 0 } else { first.saturating_add(1) }; + Some(info.pages.iter().skip(first).take(last - first + 1).map(|p| self.display_size(p)).collect()) + } + pub(super) fn fit_zoom(&mut self, info: &DocInfo) { let largest = |side: fn((f32, f32)) -> f32| info.pages.iter().map(|p| side(self.display_size(p))).fold(1.0, f32::max); let max_w = largest(|s| s.0); - // A single page shown on its own fits that page, and full screen in two-page view fits - // the spread it shows (review on #2070). Every other display (scrolling, or two-page - // view in the window) fits its largest page, so the zoom holds still while pages of - // other sizes scroll or page past. + // A single page shown on its own fits that page, and full screen filling the screen in + // two-page view fits the spread it shows (review on #2070). Every other display + // (scrolling, or two-page view in the window or in a full screen that keeps the window's + // display) fits its largest page, so the zoom holds still while pages of other sizes + // scroll or page past. A spread of two pages fits their own widths side by + // side; a page alone in a spread keeps a spread's room (a cover keeps its blank slot). + let mut spread_w = None; let (w, h) = if self.layout == PageLayout::Single && !self.continuous { info.pages.get(self.current).map_or_else(|| (max_w, largest(|s| s.1)), |p| self.display_size(p)) - } else if self.presentation.is_some() && self.layout == PageLayout::TwoUp && !self.continuous { - let first = self.spread_first(self.current); - let last = if self.cover && first == 0 { 0 } else { first.saturating_add(1) }; - let spread: Vec<(f32, f32)> = info.pages.iter().skip(first).take(last - first + 1).map(|p| self.display_size(p)).collect(); + } else if let Some(spread) = self.full_screen_spread(info) { if spread.is_empty() { (max_w, largest(|s| s.1)) } else { + if let [a, b] = spread.as_slice() { + spread_w = Some((a.0 + b.0).max(1.0)); + } (spread.iter().map(|s| s.0).fold(1.0, f32::max), spread.iter().map(|s| s.1).fold(1.0, f32::max)) } } else { (max_w, largest(|s| s.1)) }; - let avail_w = (self.viewport_w - 2.0 * SIDE).max(100.0); + let avail_w = (self.viewport_w - 2.0 * self.side()).max(100.0); let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 }; + let zw = (avail_w - self.page_gap() * (per_row - 1.0)) / (spread_w.unwrap_or(w * per_row) * PT); match self.fit { - Fit::Width => self.zoom = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row), + Fit::Width => self.zoom = zw, Fit::Page => { - let zw = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row); - let zh = (self.viewport_h - 2.0 * MARGIN) / (h * PT); + let zh = (self.viewport_h - 2.0 * self.margin()) / (h * PT); self.zoom = zw.min(zh); } - Fit::Height => self.zoom = (self.viewport_h - 2.0 * MARGIN) / (h * PT), + Fit::Height => self.zoom = (self.viewport_h - 2.0 * self.margin()) / (h * PT), Fit::None => {} } self.zoom = self.zoom.clamp(0.08, 64.0); @@ -336,11 +385,23 @@ impl DocView { /// Width of the scroll content. Single-page view sizes it to the page it shows, so a /// wider page elsewhere in the document can't push the shown one off-centre. pub(super) fn content_width(&self, info: &DocInfo, avail_w: f32) -> f32 { + // Full screen in two-page view is as wide as the spread it shows, as `fit_zoom` sized it: + // two pages side by side, or a page alone with the room of a spread (a cover keeps its + // blank slot). Room for twice the document's widest page would centre a narrower spread + // past the screen's edge. + if let Some(spread) = self.full_screen_spread(info).filter(|s| !s.is_empty()) { + let s = self.zoom * PT; + let w = match spread.as_slice() { + [a, b] => (a.0 + b.0) * s, + _ => spread.iter().map(|p| p.0).fold(0.0, f32::max) * s * 2.0, + }; + return (w + self.page_gap() + 2.0 * self.side()).max(avail_w); + } let single = (self.layout == PageLayout::Single && !self.continuous).then(|| self.current.min(info.pages.len().saturating_sub(1))); let shown = info.pages.iter().enumerate().filter(|&(i, _)| single.is_none_or(|c| c == i)); let max_w = shown.map(|(_, p)| self.display_size(p).0).fold(0.0, f32::max); let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 }; - (max_w * self.zoom * PT * per_row + 2.0 * SIDE).max(avail_w) + (max_w * self.zoom * PT * per_row + 2.0 * self.side()).max(avail_w) } /// Page rects in content coordinates (origin at the scroll content's top-left). @@ -358,12 +419,13 @@ impl DocView { } }; let mut rects = Vec::with_capacity(info.pages.len()); - let mut y = MARGIN; + let mut y = self.margin(); + let side = self.side(); match self.layout { PageLayout::Single => { for p in &info.pages { let size = page_size(p); - rects.push(Rect::from_min_size(pos2(((content_w - size.x) / 2.0).max(SIDE), y), size)); + rects.push(Rect::from_min_size(pos2(((content_w - size.x) / 2.0).max(side), y), size)); y += size.y + gap; } } @@ -378,7 +440,7 @@ impl DocView { let sizes: Vec = pair.iter().map(page_size).collect(); let row_w: f32 = sizes.iter().map(|v| v.x).sum::() + gap * (sizes.len() as f32 - 1.0); let row_h = sizes.iter().map(|v| v.y).fold(0.0, f32::max); - let mut x = if self.cover && ri == 0 { (content_w / 2.0 + gap / 2.0).max(SIDE) } else { ((content_w - row_w) / 2.0).max(SIDE) }; + let mut x = if self.cover && ri == 0 { (content_w / 2.0 + gap / 2.0).max(side) } else { ((content_w - row_w) / 2.0).max(side) }; for size in sizes { rects.push(Rect::from_min_size(pos2(x, y + (row_h - size.y) / 2.0), size)); x += size.x + gap; diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index 02384f6b58..9dd27ef7bf 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -786,6 +786,10 @@ fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, app.view_defaults.show_page_gaps = show_page_gaps; } ctx.label_secondary(ui, tl!("Hide gaps to join page edges. Margins inside the PDF remain unchanged."), t); + ctx.checkbox(ui, &mut app.view_defaults.full_screen_fill, tl!("Full screen fills the screen with one page at a time"), t); + ctx.label_secondary(ui, tl!("Turn off to keep the page display, such as continuous scrolling, in full screen."), t); + ctx.checkbox(ui, &mut app.full_screen_escape_exits, tl!("Esc leaves full screen"), t); + ctx.label_secondary(ui, tl!("Turn off so that only Ctrl+L (⌘L on macOS) leaves full screen, as for a kiosk display."), t); ui.add_space(6.0); let mut fit_changed = false; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d77c7b1eb7..35bfd447b2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -389,6 +389,9 @@ pub struct PdfCraftApp { pub invert_middle_drag: bool, /// Preferences ▸ Animation effects: on, off, or as the system's animation setting says. pub animation_effects: motion::AnimationEffects, + /// Preferences ▸ Esc leaves full screen (on by default). Off, only ⌘L / Ctrl+L leaves it, as + /// for a kiosk display; Esc still closes the find bar and the like. + pub full_screen_escape_exits: bool, /// Whether the system asked for no animations, and how the desktop app asks it. pub motion: motion::Motion, /// Interface language preference: `auto` (follow the system) or a code from [`i18n::LANGUAGES`]. diff --git a/crates/ui-egui/tests/it/view.rs b/crates/ui-egui/tests/it/view.rs index 196818e462..53c2f2d53e 100644 --- a/crates/ui-egui/tests/it/view.rs +++ b/crates/ui-egui/tests/it/view.rs @@ -2973,6 +2973,228 @@ fn a_document_press_releases_pages_keyboard_focus_without_escape() { assert!(h.state().views[0].selected.is_empty(), "Ctrl+A now belongs to the viewer, not page thumbnails"); } +/// #576: full screen fills the screen with the page: a portrait page fits the screen's height +/// edge to edge, with no margin above or below it, and sits centred across. +#[test] +fn full_screen_fills_the_screen_edge_to_edge() { + let mut h = harness(&[]); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + assert!(h.state().full_screen && h.state().views[0].fills_screen()); + let vp = h.state().views[0].viewport_rect(); + let r = rect(&h, 0).expect("page 1 on screen"); + assert!((r.height() - vp.height()).abs() <= 1.0, "the page {r:?} spans the screen's height {vp:?}"); + assert!((r.top() - vp.top()).abs() <= 1.0 && (r.bottom() - vp.bottom()).abs() <= 1.0, "no margin: {r:?} in {vp:?}"); + assert!((r.center().x - vp.center().x).abs() <= 1.0, "centred across: {r:?} in {vp:?}"); +} + +/// With the page filling the screen there is no margin above it, and ↑ and the wheel still go +/// back a page from its top, as ↓ and the wheel go forward from its bottom. +#[test] +fn full_screen_filling_the_screen_goes_back_with_up_and_the_wheel() { + let mut h = harness(&[]); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + assert!(h.state().views[0].fills_screen()); + h.key_press(Key::End); + h.run_steps(6); + assert_eq!(h.state().views[0].current, 2); + h.key_press(Key::ArrowUp); + h.run_steps(6); + assert_eq!(h.state().views[0].current, 1, "↑ goes back a page"); + let vp = h.state().views[0].viewport_rect(); + h.hover_at(vp.center()); + h.run_steps(2); + h.event(wheel(MouseWheelUnit::Line, 1.0, TouchPhase::Move)); + h.run_steps(6); + assert_eq!(h.state().views[0].current, 0, "the wheel goes back a page"); +} + +/// #4273: with the "Full screen fills the screen with one page at a time" preference off, full +/// screen keeps the page display it was entered from (continuous scrolling here), and Esc +/// brings the window's display back. +#[test] +fn full_screen_keeps_continuous_scrolling_when_fill_is_off() { + let mut h = harness(&[("layout", "continuous"), ("zoom", "50"), ("full-screen-fill", "off")]); + h.run_steps(4); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + let v = &h.state().views[0]; + assert!(h.state().full_screen && v.presenting() && !v.fills_screen()); + assert!(v.continuous(), "still scrolling continuously"); + assert!(rect(&h, 0).is_some() && rect(&h, 1).is_some(), "more than one page on screen"); + assert!((v.zoom - 0.5).abs() < 1e-3, "the zoom stays: {}", v.zoom); + h.key_press(Key::Escape); + h.run_steps(4); + assert!(!h.state().full_screen && h.state().views[0].continuous()); +} + +/// #5302: Esc closes one thing at a time. In full screen with the find bar open, the first Esc +/// closes the find bar and full screen stays; the next one leaves full screen (*Adobe Acrobat +/// Help*, 2019, p. 248: in a form field, "Esc" deselects it and "Esc (press twice)" exits Full +/// Screen mode). +#[test] +fn full_screen_esc_closes_the_find_bar_before_leaving() { + let mut h = harness(&[]); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + assert!(h.state().full_screen); + h.state_mut().views[0].open_find(); + h.run_steps(2); + assert!(h.state().views[0].find.is_some()); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().views[0].find.is_none(), "the first Esc closes the find bar"); + assert!(h.state().full_screen, "and full screen stays"); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(!h.state().full_screen, "the next Esc leaves full screen"); +} + +/// Full screen hides the Search panel, and a search shown there isn't the find bar: the first +/// Esc leaves full screen, and the panel's search is still there afterwards. +#[test] +fn full_screen_esc_leaves_and_keeps_the_search_panels_search() { + let mut h = harness(&[]); + h.state_mut().set_option("panel", "search").unwrap(); + h.state_mut().views[0].open_find(); + h.state_mut().views[0].find.as_mut().expect("find opened").in_panel = true; + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + assert!(h.state().full_screen); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(!h.state().full_screen, "the first Esc leaves full screen"); + assert!(h.state().views[0].find.is_some(), "and the Search panel's search stays"); +} + +/// When Esc doesn't leave full screen, it doesn't close the hidden Search panel's search either. +#[test] +fn full_screen_esc_that_stays_keeps_the_search_panels_search() { + let mut h = harness(&[("full-screen-escape", "off")]); + h.state_mut().set_option("panel", "search").unwrap(); + h.state_mut().views[0].open_find(); + h.state_mut().views[0].find.as_mut().expect("find opened").in_panel = true; + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().full_screen, "Esc doesn't leave full screen"); + assert!(h.state().views[0].find.is_some(), "and the Search panel's search stays"); +} + +/// With the Fill screen preference off, full screen keeps the reading position: half way down +/// page 2, it is still half way down page 2 in full screen and again after leaving. +#[test] +fn full_screen_keeps_the_reading_position_when_fill_is_off() { + let mut h = harness(&[("layout", "continuous"), ("zoom", "200"), ("full-screen-fill", "off")]); + h.run_steps(4); + h.state_mut().views[0].goto = Some((1, 0.5)); + h.run_steps(4); + let above = |h: &Harness<'static, PdfCraftApp>| { + let v = &h.state().views[0]; + v.viewport_rect().top() - rect(h, 1).expect("page 2 on screen").top() + }; + let before = above(&h); + assert!(before > 300.0, "page 2 starts well above the window's top: {before}"); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + assert!(h.state().full_screen); + let full = above(&h); + assert!((full - before).abs() < 40.0, "full screen keeps the position: {full} vs {before}"); + h.key_press(Key::Escape); + h.run_steps(6); + assert!(!h.state().full_screen); + let after = above(&h); + assert!((after - before).abs() < 40.0, "and so does leaving it: {after} vs {before}"); +} + +/// With the "Esc leaves full screen" preference off, Esc doesn't leave full screen and only +/// Ctrl+L (⌘L) does (*Adobe Acrobat Help*, 2019, "Full Screen preferences", p. 69: "Escape Key +/// Exits: Lets you exit Full-Screen mode by pressing the Esc key. If this option is not selected, +/// you can exit by pressing Ctrl+L"). +#[test] +fn full_screen_stays_on_esc_when_esc_does_not_leave_it() { + let mut h = harness(&[("full-screen-escape", "off")]); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + assert!(h.state().full_screen); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().full_screen, "Esc doesn't leave full screen"); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(4); + assert!(!h.state().full_screen, "Ctrl+L / ⌘L leaves it"); +} + +/// From a form field being filled, the first Esc closes the field and the second leaves full +/// screen: "Esc (press twice)" (*Adobe Acrobat Help*, 2019, "Options for working in forms", +/// p. 248). +#[test] +fn full_screen_esc_from_a_field_closes_the_field_first() { + const FIELD: &[u8] = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /Annots [4 0 R] >> endobj +4 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (name) /Rect [50 100 250 140] /P 3 0 R /F 4 >> endobj +trailer << /Root 1 0 R >> +%%EOF"; + let mut h = harness(&[]); + h.state_mut().open_bytes("field.pdf", None, FIELD.to_vec()).expect("opens"); + h.run_steps(8); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + let n = h.state().views.len() - 1; + // Until page 1's raster is in, full screen veils it and the click reaches no field; on a slow + // machine that takes more frames than the six above. + for _ in 0..600 { + if h.state().views[n].presentation_settled() { + break; + } + h.run_steps(1); + } + assert!(h.state().views[n].presentation_settled(), "page 1 is shown"); + let r = h.state().views[n].page_screen_rect(0).expect("page 1 on screen"); + // One page only: the click can't turn away from the field. + click_with(&mut h, egui::pos2(r.left() + r.width() * 0.5, r.top() + r.height() * (400.0 - 120.0) / 400.0), Modifiers::NONE); + assert!(h.ctx.egui_wants_keyboard_input(), "the field is open for typing"); + h.key_press(Key::Escape); + h.run_steps(4); + assert!(h.state().full_screen, "the first Esc closes the field only"); + assert!(!h.ctx.egui_wants_keyboard_input(), "the field is closed"); + h.key_press(Key::Escape); + h.run_steps(4); + assert!(!h.state().full_screen, "the second Esc leaves full screen"); +} + +/// Full screen shows no notice bar above the page (a form's "interactive form fields" notice, here), +/// so a page filling the screen is whole on it; the bar is back on leaving. +#[test] +fn full_screen_hides_the_notice_bar_and_the_page_fits_whole() { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("form.pdf", None, include_bytes!("../data/form.pdf").to_vec()).expect("opens"); + app.set_option("left", "closed").unwrap(); + app.set_option("panel", "none").unwrap(); + app + }); + h.run_steps(8); + let notice = |h: &Harness<'static, PdfCraftApp>| h.query_by_label_contains("interactive form fields").is_some(); + assert!(notice(&h), "the form notice shows in the window"); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); + h.run_steps(6); + assert!(h.state().full_screen && !notice(&h), "no notice bar in full screen"); + let vp = h.state().views[0].viewport_rect(); + let r = rect(&h, 0).expect("page 1 on screen"); + assert!(r.top() >= vp.top() - 1.0 && r.bottom() <= vp.bottom() + 1.0, "the page {r:?} is whole in {vp:?}"); + h.key_press(Key::Escape); + h.run_steps(4); + assert!(notice(&h), "the notice is back after full screen"); +} + /// Delete over the Pages panel with a menu of the menu bar open is the menu's, and the Escape that /// closes a thumbnail's context menu the menu's: no page is deleted, and the page selection stays. /// Delete deleted the selected pages, and the panel took the Escape: it dropped the selection and diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 69e78702fc..3c411d9813 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -10191,11 +10191,11 @@ title = "Preferences: full screen" area = "N" tier = "P2" milestone = "M14" -status = "planned" +status = "partial" commands = [] tools = [] -evidence = [] -notes = "" +evidence = ["crates/ui-egui/tests/it/view.rs::full_screen_fills_the_screen_edge_to_edge", "crates/ui-egui/tests/it/view.rs::full_screen_keeps_continuous_scrolling_when_fill_is_off", "crates/ui-egui/tests/it/view.rs::full_screen_stays_on_esc_when_esc_does_not_leave_it", "crates/ui-egui/tests/it/view.rs::full_screen_esc_closes_the_find_bar_before_leaving"] +notes = "Two of the full-screen preferences, in Preferences under Documents and view and saved with the others: Full screen fills the screen with one page at a time (on: the page or spread edge to edge, no margin or shadow, #576; off: full screen keeps the page display it was entered from, such as continuous scrolling, #4273) and Esc leaves full screen (off: only Ctrl+L / Cmd+L leaves it). Esc closes an open menu, the camera, a selection or the find bar before it leaves full screen (#5302). Missing: show a navigation bar, left/right click to page as an option, loop after the last page, advance every N seconds, the alert when a document asks for full screen, which monitor, background colour, mouse cursor, default transition and ignoring the document's transitions" [[feature]] id = "misc.prefs-search" From 2251a75cc85d7da786a7bf5d910fbd7e0bfa0039 Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Wed, 18 Nov 2026 12:47:55 +0800 Subject: [PATCH 03/27] fix(render): resolve TrueType glyphs across Unicode/UCS-4 cmaps, post v2.0 aliases, and truncated FontFlags (#2159) (#2980) * fix(render): resolve accented TrueType glyphs across Symbolic flags, Unicode cmaps, post v2.0, and ToUnicode (#2159, #2426) * fix(render): separate TrueType glyph selection from extraction (#2980) Restore the existing Symbolic and CFF mapping paths. Keep name-derived Unicode cmap lookup, post-name aliases, known flag bits, and explicit .notdef handling. Replace disputed expectations with synthetic glyph/extraction regressions; the original PDFs in #2159 and #2426 remain unavailable and unverified. * fix(render): check exact post v2.0 glyph name before suffix-stripped cmap lookup (#2980) * fix(render): prefer exact post v2.0 name for multi-codepoint AGL glyph names (#2980) * style: format vendor true_type.rs * fix(render): keep TrueType vendor patch in upstream style Restore unchanged upstream formatting around the glyph-mapping fix and use upstream-default formatting for its new helpers. Preserve the upstream glyph_name_to_text extraction fallback and every existing functional change. Validated workspace cargo fmt, git diff --check, and byte-identical rustfmt canonical output before and after this formatting-only change. The eight TrueType integration tests passed on the prior head in hosted CI; fresh CI will validate this follow-up. Local recompilation and optional negative controls were not attempted because build storage is exhausted. --- crates/render/tests/truetype_cmap.rs | 335 +++++++++++++++++++ vendor/README.md | 7 + vendor/hayro-interpret/src/font/true_type.rs | 183 +++++++--- 3 files changed, 481 insertions(+), 44 deletions(-) create mode 100644 crates/render/tests/truetype_cmap.rs diff --git a/crates/render/tests/truetype_cmap.rs b/crates/render/tests/truetype_cmap.rs new file mode 100644 index 0000000000..c9c12b4a43 --- /dev/null +++ b/crates/render/tests/truetype_cmap.rs @@ -0,0 +1,335 @@ +//! Synthetic regressions for embedded TrueType glyph mapping. No original files from +//! issues #2159 or #2426 are available; these do not establish that those files are fixed. + +use std::sync::Arc; + +use lopdf::{Document, Object, Stream, dictionary}; +use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind}; + +const INTER_TTF: &[u8] = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + +/// Find the byte offset of a table in a TrueType `sfnt` font. +fn find_table(ttf: &[u8], tag: &[u8; 4]) -> usize { + let num_tables = u16::from_be_bytes([ttf[4], ttf[5]]) as usize; + for i in 0..num_tables { + let rec = 12 + i * 16; + if &ttf[rec..rec + 4] == tag { + return u32::from_be_bytes([ttf[rec + 8], ttf[rec + 9], ttf[rec + 10], ttf[rec + 11]]) as usize; + } + } + panic!("missing table {:?}", std::str::from_utf8(tag)); +} + +/// Rewrite the `cmap` table of a TrueType font so its Windows `(3, 1)` / `(3, 10)` subtable +/// headers become Unicode `(0, 3)` subtable headers and its `post` table is version 3.0 (no +/// glyph names), exercising a Unicode-only cmap shape without assuming the unavailable +/// original font from issue #2159 has this structure. +fn make_macos_unicode_cmap_subset(ttf: &[u8]) -> Vec { + let mut out = ttf.to_vec(); + let cmap = find_table(&out, b"cmap"); + let num_records = u16::from_be_bytes([out[cmap + 2], out[cmap + 3]]) as usize; + let mut changed = false; + for i in 0..num_records { + let rec = cmap + 4 + i * 8; + let platform_id = u16::from_be_bytes([out[rec], out[rec + 1]]); + let encoding_id = u16::from_be_bytes([out[rec + 2], out[rec + 3]]); + if platform_id == 3 && (encoding_id == 1 || encoding_id == 10) { + out[rec..rec + 2].copy_from_slice(&0u16.to_be_bytes()); + out[rec + 2..rec + 4].copy_from_slice(&3u16.to_be_bytes()); + changed = true; + } + } + assert!(changed, "expected at least one Windows Unicode cmap record to convert"); + + // Set `post` version to 3.0 (0x00030000), which carries no PostScript glyph names. + let post = find_table(&out, b"post"); + out[post..post + 4].copy_from_slice(&0x0003_0000u32.to_be_bytes()); + out +} + +/// Build a single-byte string `codes` on a 120x80 page. +fn pdf_for_codes(font_bytes: Vec, flags: i64, encoding: Option, to_unicode: Option<&[u8]>, codes: &[u8]) -> Vec { + let mut doc = Document::with_version("1.7"); + let program = doc.add_object(Stream::new(dictionary! {}, font_bytes)); + let descriptor = doc.add_object(dictionary! { + "Type" => "FontDescriptor", + "FontName" => "ABCDEF+Inter-Regular", + "Flags" => flags, + "FontFile2" => program, + }); + let mut font = dictionary! { + "Type" => "Font", + "Subtype" => "TrueType", + "BaseFont" => "ABCDEF+Inter-Regular", + "FontDescriptor" => descriptor, + }; + if let Some(enc) = encoding { + font.set("Encoding", enc); + } + if let Some(cmap) = to_unicode { + font.set("ToUnicode", doc.add_object(Stream::new(dictionary! {}, cmap.to_vec()))); + } + let font_id = doc.add_object(font); + + let mut ops = b"BT /F1 36 Tf 1 0 0 1 15 25 Tm <".to_vec(); + for &b in codes { + ops.extend_from_slice(format!("{b:02X}").as_bytes()); + } + ops.extend_from_slice(b"> Tj ET"); + let content = doc.add_object(Stream::new(dictionary! {}, ops)); + let pages = doc.new_object_id(); + let page = doc.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages, + "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(120), Object::Integer(80)], + "Resources" => dictionary! { "Font" => dictionary! { "F1" => font_id } }, + "Contents" => content, + }); + doc.objects.insert(pages, dictionary! { "Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1 }.into()); + let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages }); + doc.trailer.set("Root", catalog); + + let mut pdf_bytes = Vec::new(); + doc.save_to(&mut pdf_bytes).expect("save synthetic PDF"); + pdf_bytes +} + +fn render_codes(font_bytes: Vec, flags: i64, encoding: Option, to_unicode: Option<&[u8]>, codes: &[u8]) -> Vec { + let pdf_bytes = pdf_for_codes(font_bytes, flags, encoding, to_unicode, codes); + let rendered = PageRenderer::new(Arc::new(pdf_bytes), RenderConfig::default()).render(RenderRequest { + page: 0, + kind: RequestKind::Pixels, + scale: 1.0, + ..Default::default() + }); + assert!(rendered.error.is_none(), "render failed: {:?}", rendered.error); + rendered.rgba.to_vec() +} + +/// Reference raster for a single glyph named `glyph_name` in `Inter-Regular.ttf`. +fn reference_glyph_rgba(glyph_name: &[u8]) -> Vec { + let encoding = Object::Dictionary(dictionary! { + "Type" => "Encoding", + "BaseEncoding" => Object::Name(b"WinAnsiEncoding".to_vec()), + "Differences" => vec![ + Object::Integer(65), + Object::Name(glyph_name.to_vec()), + ], + }); + render_codes(INTER_TTF.to_vec(), 32, Some(encoding), None, &[65]) +} + +fn assert_reference_glyph_is_not_notdef(glyph_name: &[u8], raster: &[u8]) { + let notdef = reference_glyph_rgba(b".notdef"); + assert_ne!(raster, notdef.as_slice(), "{glyph_name:?} resolved to .notdef"); +} + +#[test] +fn nonsymbolic_truetype_with_differences_renders_czech_and_slovak_carons() { + let encoding = Object::Dictionary(dictionary! { + "Type" => "Encoding", + "BaseEncoding" => Object::Name(b"WinAnsiEncoding".to_vec()), + "Differences" => vec![ + Object::Integer(190), + Object::Name(b"lcaron".to_vec()), + Object::Integer(232), + Object::Name(b"ccaron".to_vec()), + Object::Integer(236), + Object::Name(b"ecaron".to_vec()), + Object::Integer(248), + Object::Name(b"rcaron".to_vec()), + ], + }); + for (code, name) in [(190u8, &b"lcaron"[..]), (232u8, &b"ccaron"[..]), (236u8, &b"ecaron"[..]), (248u8, &b"rcaron"[..])] { + let expected = reference_glyph_rgba(name); + assert_reference_glyph_is_not_notdef(name, &expected); + let actual = render_codes(INTER_TTF.to_vec(), 32, Some(encoding.clone()), None, &[code]); + assert!(actual == expected, "Nonsymbolic TrueType font with /Differences drew wrong glyph for {}", String::from_utf8_lossy(name)); + } +} + +#[test] +fn macos_unicode_platform_cmap_renders_slovak_carons() { + // A synthetic (0, 3) cmap with post v3.0 and no Windows subtable exercises the + // name-derived Unicode fallback. The actual font from #2159 is unavailable. + let macos_ttf = make_macos_unicode_cmap_subset(INTER_TTF); + let encoding = Object::Dictionary(dictionary! { + "Type" => "Encoding", + "BaseEncoding" => Object::Name(b"WinAnsiEncoding".to_vec()), + "Differences" => vec![ + Object::Integer(190), + Object::Name(b"lcaron".to_vec()), + Object::Integer(232), + Object::Name(b"ccaron".to_vec()), + Object::Integer(236), + Object::Name(b"ecaron".to_vec()), + Object::Integer(248), + Object::Name(b"rcaron".to_vec()), + ], + }); + for (code, name) in [(190u8, &b"lcaron"[..]), (232u8, &b"ccaron"[..]), (236u8, &b"ecaron"[..]), (248u8, &b"rcaron"[..])] { + let expected = reference_glyph_rgba(name); + assert_reference_glyph_is_not_notdef(name, &expected); + let actual = render_codes(macos_ttf.clone(), 32, Some(encoding.clone()), None, &[code]); + assert!(actual == expected, "macOS (0, 3) Unicode cmap drew wrong glyph for {}", String::from_utf8_lossy(name)); + } +} + +#[test] +fn symbolic_truetype_ignores_encoding_and_differences() { + // ISO 32000-1 9.6.6.4: the Symbolic flag makes Encoding inapplicable. + let expected = reference_glyph_rgba(b"oslash"); + assert!(expected != reference_glyph_rgba(b"rcaron")); + for name in [b"rcaron".as_slice(), b".notdef"] { + let encoding = Object::Dictionary(dictionary! { + "BaseEncoding" => "WinAnsiEncoding", + "Differences" => vec![Object::Integer(248), Object::Name(name.to_vec())], + }); + for flags in [4, 4 | (1 << 20)] { + let actual = render_codes(INTER_TTF.to_vec(), flags, Some(encoding.clone()), None, &[248]); + assert!(actual == expected, "Symbolic Encoding must be ignored: {flags}, {name:?}"); + } + } +} + +#[test] +fn tounicode_does_not_select_the_drawn_glyph() { + // ToUnicode is an extraction mapping, not a glyph-selection mapping (9.10). + let to_unicode = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap \ + /CMapName /Extraction def /CMapType 2 def \ + 1 begincodespacerange <00> endcodespacerange \ + 2 beginbfchar <41> <0042> <0159> endbfchar \ + endcmap CMapName currentdict /CMap defineresource pop end end"; + for (code, name, wrong_name) in [(65, b"A".as_slice(), b"B".as_slice()), (248, b"oslash", b"rcaron")] { + for flags in [4, 32] { + for encoding in [None, Some(Object::Name(b"WinAnsiEncoding".to_vec()))] { + // Retain the existing StandardEncoding fallback for a Nonsymbolic + // font without Encoding. Standard code 248 is lslash, not oslash; + // this reader fallback differs from MuPDF's raw Unicode lookup. + let expected_name = if code == 248 && flags == 32 && encoding.is_none() { b"lslash".as_slice() } else { name }; + let expected = reference_glyph_rgba(expected_name); + assert!(expected != reference_glyph_rgba(wrong_name)); + let plain = render_codes(INTER_TTF.to_vec(), flags, encoding.clone(), None, &[code]); + assert!(plain == expected, "reference without ToUnicode: {flags}, {code}"); + let bytes = pdf_for_codes(INTER_TTF.to_vec(), flags, encoding.clone(), Some(to_unicode), &[code]); + let text = PageRenderer::new(Arc::new(bytes), RenderConfig::default()).render(RenderRequest { + page: 0, + kind: RequestKind::Text, + ..Default::default() + }); + assert_eq!(text.text.unwrap().plain_text(), if code == 65 { "B" } else { "ř" }); + let actual = render_codes(INTER_TTF.to_vec(), flags, encoding, Some(to_unicode), &[code]); + assert!(actual == expected, "ToUnicode changed glyph: {flags}, {code}"); + } + } + } +} + +#[test] +fn nonsymbolic_explicit_notdef_does_not_fall_back_to_raw_code() { + let encoding = Object::Dictionary(dictionary! { + "BaseEncoding" => "WinAnsiEncoding", + "Differences" => vec![Object::Integer(65), Object::Name(b".notdef".to_vec())], + }); + let expected = reference_glyph_rgba(b".notdef"); + assert!(expected != reference_glyph_rgba(b"A")); + let actual = render_codes(INTER_TTF.to_vec(), 32, Some(encoding), None, &[65]); + assert!(actual == expected); +} + +#[test] +fn windows_ucs4_cmap_resolves_name_derived_unicode() { + let mut ttf = INTER_TTF.to_vec(); + let cmap = find_table(&ttf, b"cmap"); + let count = u16::from_be_bytes([ttf[cmap + 2], ttf[cmap + 3]]) as usize; + let mut retained = false; + for i in 0..count { + let rec = cmap + 4 + i * 8; + let platform = u16::from_be_bytes([ttf[rec], ttf[rec + 1]]); + let encoding = u16::from_be_bytes([ttf[rec + 2], ttf[rec + 3]]); + if platform == 3 && encoding == 10 { + retained = true; + } else { + ttf[rec..rec + 2].copy_from_slice(&99u16.to_be_bytes()); + } + } + assert!(retained); + let post = find_table(&ttf, b"post"); + ttf[post..post + 4].copy_from_slice(&0x0003_0000u32.to_be_bytes()); + let encoding = Object::Dictionary(dictionary! { + "BaseEncoding" => "WinAnsiEncoding", + "Differences" => vec![Object::Integer(65), Object::Name(b"rcaron".to_vec())], + }); + let expected = reference_glyph_rgba(b"rcaron"); + assert_reference_glyph_is_not_notdef(b"rcaron", &expected); + assert!(render_codes(ttf, 32, Some(encoding), None, &[65]) == expected); +} + +#[test] +fn post_v2_uni_and_agl_glyph_names_resolve_without_unicode_cmap() { + // Strip all Unicode cmap subtables by rewriting platform_id to 99 so lookup must go through + // the TrueType `post` v2.0 glyph name table (including uniXXXX <-> AGL aliasing). + let mut post_only_ttf = INTER_TTF.to_vec(); + let cmap = find_table(&post_only_ttf, b"cmap"); + let num_records = u16::from_be_bytes([post_only_ttf[cmap + 2], post_only_ttf[cmap + 3]]) as usize; + for i in 0..num_records { + let rec = cmap + 4 + i * 8; + post_only_ttf[rec..rec + 2].copy_from_slice(&99u16.to_be_bytes()); + } + + let encoding = Object::Dictionary(dictionary! { + "Type" => "Encoding", + "BaseEncoding" => Object::Name(b"WinAnsiEncoding".to_vec()), + "Differences" => vec![ + Object::Integer(190), + Object::Name(b"uni013E".to_vec()), + Object::Integer(232), + Object::Name(b"uni010D".to_vec()), + Object::Integer(236), + Object::Name(b"ecaron.salt".to_vec()), + Object::Integer(248), + Object::Name(b"u0159".to_vec()), + ], + }); + for (code, name) in [(190u8, &b"lcaron"[..]), (232u8, &b"ccaron"[..]), (236u8, &b"ecaron"[..]), (248u8, &b"rcaron"[..])] { + let expected = reference_glyph_rgba(name); + assert_reference_glyph_is_not_notdef(name, &expected); + let actual = render_codes(post_only_ttf.clone(), 32, Some(encoding.clone()), None, &[code]); + assert!(actual == expected, "post v2.0 glyph name resolution drew wrong glyph for {}", String::from_utf8_lossy(name)); + } + + // When a font has both a Unicode cmap and an exact suffixed alternate in `post` v2.0 (`I.1`), + // `/Differences` must select the `post` v2.0 alternate (`I.1`) rather than stripping `.1` and + // drawing plain `I` from the Unicode cmap. + let alt_encoding = Object::Dictionary(dictionary! { + "Type" => "Encoding", + "BaseEncoding" => Object::Name(b"WinAnsiEncoding".to_vec()), + "Differences" => vec![ + Object::Integer(73), + Object::Name(b"I.1".to_vec()), + ], + }); + let expected_alt = render_codes(post_only_ttf, 32, Some(alt_encoding.clone()), None, &[73]); + let plain_i = reference_glyph_rgba(b"I"); + assert!(expected_alt != plain_i, "I.1 alternate in Inter must differ from plain I"); + let actual_with_cmap = render_codes(INTER_TTF.to_vec(), 32, Some(alt_encoding), None, &[73]); + assert!(actual_with_cmap == expected_alt, "exact post v2.0 alternate I.1 must win over suffix-stripped cmap lookup"); +} + +#[test] +fn font_descriptor_flags_with_extra_bits_preserve_non_symbolic() { + let encoding = Object::Dictionary(dictionary! { + "Type" => "Encoding", + "BaseEncoding" => Object::Name(b"WinAnsiEncoding".to_vec()), + "Differences" => vec![ + Object::Integer(232), + Object::Name(b"ccaron".to_vec()), + ], + }); + let expected = reference_glyph_rgba(b"ccaron"); + assert_reference_glyph_is_not_notdef(b"ccaron", &expected); + // Bit 6 (32 = NonSymbolic) plus a high producer-specific bit (1 << 20) that previously caused + // FontFlags::from_bits to return None and discard all flags. + let actual = render_codes(INTER_TTF.to_vec(), 32 | (1 << 20), Some(encoding), None, &[232]); + assert!(actual == expected); +} diff --git a/vendor/README.md b/vendor/README.md index 6db4c6dc55..56a71e0779 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -43,6 +43,13 @@ licence files unchanged. Every patch is marked `PdfCraft patch:` in the source, PdfCraft test, and should be proposed upstream. Remove the vendored copy once upstream releases the fix. Vendoring copyleft code is never allowed (plan/adr/0001). +The TrueType name lookup patch probes Unicode `(0, *)` and Windows `(3, 10)` cmap records, +recognizes post-name aliases, and retains known descriptor flags when unknown bits are present. +`crates/render/tests/truetype_cmap.rs` covers these synthetic cases and verifies that Symbolic +Encoding/Differences and ToUnicode do not override the existing glyph-selection policy. +ToUnicode still controls extraction. The CFF fallback is unchanged. No original affected PDF +from #2159 or #2426 is available, so those reported files remain unverified. + A PdfCraft patch in `hayro-syntax::Page::base_dimensions` expresses the existing one-point floor as a raw reciprocal of `/UserUnit`, rounded upward only when f32 multiplication would fall below one point. Five `pdfcraft-render` regressions with prefix `raster::tests::raw_crop_` cover the observed dimensions, origins and rotations, units 41/47, bounded vector rasters and the nearly-zero fallback, which is US Letter since patch 44. Accepted page-unit policy and licences are unchanged. In `hayro-interpret`, Type 3 glyph bounding boxes are transformed to device space before intersecting clip and shading bounds; `raster::tests::shaded_type3_glyph_draws_at_multiple_positions` covers translated glyphs (#3178). diff --git a/vendor/hayro-interpret/src/font/true_type.rs b/vendor/hayro-interpret/src/font/true_type.rs index 27e8e6b5a2..9d84e62528 100644 --- a/vendor/hayro-interpret/src/font/true_type.rs +++ b/vendor/hayro-interpret/src/font/true_type.rs @@ -2,8 +2,8 @@ use crate::font::blob::{CffFontBlob, OpenTypeFontBlob}; use crate::font::generated::{glyph_names, mac_os_roman, mac_roman, standard, win_ansi}; use crate::font::standard_font::StandardKind; use crate::font::{ - Encoding, FallbackFontQuery, FontFlags, glyph_name_to_text, glyph_name_to_unicode, read_to_unicode, - strip_subset_prefix, unicode_from_name, + Encoding, FallbackFontQuery, FontFlags, glyph_name_to_text, glyph_name_to_unicode, + normalized_glyph_name, read_to_unicode, strip_subset_prefix, unicode_from_name, }; use crate::util::OptionLog; use crate::{CMapResolverFn, CacheKey, FontResolverFn}; @@ -245,7 +245,7 @@ impl EmbeddedKind { fn new(dict: &Dict<'_>) -> Option { let descriptor = dict.get::>(FONT_DESC).unwrap_or_default(); - let font_flags = descriptor.get::(FLAGS).and_then(FontFlags::from_bits); + let font_flags = descriptor.get::(FLAGS).map(FontFlags::from_bits_truncate); let (widths, missing_width) = read_widths(dict, &descriptor)?; let (encoding, differences) = read_encoding(dict); @@ -372,6 +372,133 @@ impl EmbeddedKind { self.base_font.outline_glyph(glyph) } + fn map_unicode_in_cmap(&self, c: char) -> Option { + let cmap = self.base_font.font_ref().cmap().ok()?; + let mut glyph = None; + + for record in cmap.encoding_records() { + if record.platform_id() == PlatformId::Windows + && matches!(record.encoding_id(), 1 | 10) + && let Ok(subtable) = record.subtable(cmap.offset_data()) + { + glyph = glyph + .or_else(|| subtable.map_codepoint(c)) + .filter(|g| *g != GlyphId::NOTDEF); + } + } + + if glyph.is_none() { + for record in cmap.encoding_records() { + if record.platform_id() == PlatformId::Unicode + && let Ok(subtable) = record.subtable(cmap.offset_data()) + { + glyph = glyph + .or_else(|| subtable.map_codepoint(c)) + .filter(|g| *g != GlyphId::NOTDEF); + } + } + } + + glyph + } + + fn map_macintosh_cmap(&self, name: &str, unicode_char: Option) -> Option { + let cmap = self.base_font.font_ref().cmap().ok()?; + let mut glyph = None; + for record in cmap.encoding_records() { + if record.platform_id() == PlatformId::Macintosh + && record.encoding_id() == 0 + && let Ok(subtable) = record.subtable(cmap.offset_data()) + { + glyph = glyph.or_else(|| { + mac_os_roman::get_inverse(name) + .or_else(|| mac_roman::get_inverse(name)) + .or_else(|| { + unicode_char + .and_then(glyph_names::get_reverse) + .and_then(|agl| { + mac_os_roman::get_inverse(agl) + .or_else(|| mac_roman::get_inverse(agl)) + }) + }) + .and_then(|c| subtable.map_codepoint(c)) + .filter(|g| *g != GlyphId::NOTDEF) + }); + } + } + glyph + } + + fn map_name(&self, lookup: &str) -> Option { + let exact_name = self + .glyph_names + .get(lookup) + .copied() + .filter(|g| *g != GlyphId::NOTDEF); + let exact_unicode = glyph_names::get(lookup) + .and_then(|n| n.chars().next()) + .or_else(|| unicode_from_name(lookup)); + + let mut glyph = + if glyph_names::get(lookup).is_some_and(|name| name.chars().nth(1).is_some()) { + exact_name + .or_else(|| exact_unicode.and_then(|c| self.map_unicode_in_cmap(c))) + .or_else(|| self.map_macintosh_cmap(lookup, exact_unicode)) + } else { + exact_unicode + .and_then(|c| self.map_unicode_in_cmap(c)) + .or_else(|| self.map_macintosh_cmap(lookup, exact_unicode)) + .or_else(|| exact_name) + }; + + if glyph.is_none() { + let base_lookup = if !lookup.starts_with('.') { + lookup.split('.').next().unwrap_or(lookup) + } else { + lookup + }; + let unicode_char = exact_unicode.or_else(|| { + glyph_names::get(base_lookup) + .and_then(|n| n.chars().next()) + .or_else(|| unicode_from_name(base_lookup)) + }); + if base_lookup != lookup { + glyph = unicode_char + .and_then(|c| self.map_unicode_in_cmap(c)) + .or_else(|| self.map_macintosh_cmap(base_lookup, unicode_char)); + } + if glyph.is_none() { + glyph = self + .glyph_names + .get(base_lookup) + .copied() + .or_else(|| { + self.glyph_names + .get(normalized_glyph_name(base_lookup)) + .copied() + }) + .or_else(|| { + unicode_char + .and_then(glyph_names::get_reverse) + .and_then(|agl| self.glyph_names.get(agl).copied()) + }) + .or_else(|| { + unicode_char.and_then(|c| { + let cp = c as u32; + self.glyph_names + .get(&format!("uni{cp:04X}")) + .or_else(|| self.glyph_names.get(&format!("u{cp:04X}"))) + .copied() + }) + }) + .or_else(|| glyph_num_string(base_lookup).map(GlyphId::new)) + .filter(|g| *g != GlyphId::NOTDEF); + } + } + + glyph + } + fn map_code(&self, code: u8) -> GlyphId { if let Some(glyph) = self.cached_mappings.borrow().get(&code) { return *glyph; @@ -384,51 +511,19 @@ impl EmbeddedKind { .unwrap_or(GlyphId::NOTDEF); } + // PdfCraft patch: keep glyph selection separate from text extraction. Symbolic + // TrueType fonts ignore Encoding (ISO 32000-1 9.6.6.4); ToUnicode supplies text + // semantics (9.10), not an alternate glyph. Extend only the existing name lookup + // with Unicode cmap records and post-name aliases. Keep the raw symbolic fallback + // and the CFF path unchanged until affected source files justify a different policy. let mut glyph = None; - if self.is_non_symbolic() { let Some(lookup) = self.code_to_name(code) else { return GlyphId::NOTDEF; }; - - if let Ok(cmap) = self.base_font.font_ref().cmap() { - for record in cmap.encoding_records() { - if record.platform_id() == PlatformId::Windows - && record.encoding_id() == 1 - && let Ok(subtable) = record.subtable(cmap.offset_data()) - { - glyph = glyph.or_else(|| { - glyph_names::get(lookup) - .map(|n| n.to_string()) - .or_else(|| unicode_from_name(lookup).map(|n| n.to_string())) - .and_then(|n| n.chars().next()) - .and_then(|c| subtable.map_codepoint(c)) - .filter(|g| *g != GlyphId::NOTDEF) - }); - } - } - - for record in cmap.encoding_records() { - if record.platform_id() == PlatformId::Macintosh - && record.encoding_id() == 0 - && let Ok(subtable) = record.subtable(cmap.offset_data()) - { - glyph = glyph.or_else(|| { - mac_os_roman::get_inverse(lookup) - .or_else(|| mac_roman::get_inverse(lookup)) - .and_then(|c| subtable.map_codepoint(c)) - .filter(|g| *g != GlyphId::NOTDEF) - }); - } - } - } - - if glyph.is_none() { - if let Some(gid) = self.glyph_names.get(lookup) { - glyph = Some(*gid); - } else if let Some(gid) = glyph_num_string(lookup) { - glyph = Some(GlyphId::new(gid)); - } + // An explicit .notdef is a mapping, not permission to draw the raw code. + if lookup != ".notdef" { + glyph = self.map_name(lookup); } } else if let Ok(cmap) = self.base_font.font_ref().cmap() { // PdfCraft patch (#4156): the Windows (3, 0) subtable comes first, and the (1, 0) one @@ -658,7 +753,7 @@ pub(crate) fn read_encoding(dict: &Dict<'_>) -> (Encoding, HashMap) if let Ok(code) = code.try_into() { map.insert(code, name.as_str().to_string()); } - code += 1; + code = code.saturating_add(1); } _ => {} } From 7895411b03e80a3886273835a531b41f32422c76 Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Wed, 18 Nov 2026 14:15:31 +0800 Subject: [PATCH 04/27] fix(forms): name detected check boxes from the nearer neighbouring label (#2943) (#2953) * fix(forms): name detected check boxes from the nearer neighbouring label (#2943) * M6: bound rectangle work during form detection (#2953) Limit drawn and existing rectangle candidates before pairwise comb and checkbox work, preserve every widget overlap exclusion, and avoid cubic default-name lookup. Document partial proposals on unusually complex pages. Verified: 143 forms unit tests, strict forms clippy, wasm check, layers, assets, and format. The count-based regression fails when the pre-comb cap is removed. * Bound existing-widget overlap work during field detection Index every existing widget spatially and cap aggregate query work, rejecting unchecked proposals if adversarial geometry exhausts the budget. Retain exclusions beyond the proposal/label budget. Add synthetic 100k-widget, inverted-geometry and linear-equivalence regressions. The original linear scan fails the new work-bound negative control. All 147 forms tests, strict Clippy, formatting, wasm, layers and assets checks pass. --------- Co-authored-by: skylar taylor-barrick --- crates/engine/src/tests.rs | 36 +++- crates/forms/README.md | 8 + crates/forms/src/detect.rs | 411 ++++++++++++++++++++++++++++++++----- crates/forms/src/tests.rs | 126 ++++++++++++ 4 files changed, 519 insertions(+), 62 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index faab8af4de..669cd36786 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7442,6 +7442,17 @@ fn detecting_fields_on_a_printed_form() { let f = &d.form[0]; assert!(f.widgets[0].rect[0] > 72.0 + 20.0, "{:?}", f.widgets[0].rect); assert!(s.detect_fields(id, &[]).is_empty(), "nothing left to detect"); + + // #2943: a "label, box, label, box" line names each check box after the label before it. + let labels_pdf = paper_form_with( + 595, + 842, + "BT /F1 10 Tf 100 534 Td (Monsieur) Tj ET 146 532 11 10 re S BT /F1 10 Tf 180 534 Td (Madame) Tj ET 222 532 11 10 re S", + ); + let labels_id = s.open("labels.pdf", None, Arc::new(labels_pdf), None).unwrap(); + let found = s.detect_fields(labels_id, &[]); + let names: Vec<&str> = found.iter().map(|(_, c)| c.name.as_str()).collect(); + assert_eq!(names, ["Monsieur", "Madame"], "{found:?}"); } /// #294, #2831: a detected field sits on a line or box the page already draws, so it gets no border @@ -7466,18 +7477,11 @@ fn detected_fields_have_no_border_or_fill() { assert!(look.border.is_some() && look.fill.is_some(), "{look:?}"); } -/// A printed form, 420 × 300 pt: a title, a label with a rule to write on, a box with a small -/// label in its corner, an empty box with its label above, and two check boxes. -fn paper_form() -> Vec { - let content = "BT /F1 14 Tf 30 270 Td (Gewerbe-Ummeldung) Tj ET \ - BT /F1 10 Tf 30 230 Td (Name:) Tj ET 0.75 w 80 228 m 380 228 l S \ - 1 w 30 150 350 50 re S BT /F1 7 Tf 34 191 Td (Anschrift) Tj ET \ - BT /F1 8 Tf 30 124 Td (Telefon) Tj ET 30 90 350 30 re S \ - 30 50 10 10 re S BT /F1 9 Tf 46 51 Td (Haupt) Tj ET 150 50 10 10 re S BT /F1 9 Tf 166 51 Td (Zweig) Tj ET"; +fn paper_form_with(w: u32, h: u32, content: &str) -> Vec { let objs = [ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 420 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>").into_bytes(), format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()).into_bytes(), b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), ]; @@ -7498,6 +7502,20 @@ fn paper_form() -> Vec { out } +/// A printed form, 420 × 300 pt: a title, a label with a rule to write on, a box with a small +/// label in its corner, an empty box with its label above, and two check boxes. +fn paper_form() -> Vec { + paper_form_with( + 420, + 300, + "BT /F1 14 Tf 30 270 Td (Gewerbe-Ummeldung) Tj ET \ + BT /F1 10 Tf 30 230 Td (Name:) Tj ET 0.75 w 80 228 m 380 228 l S \ + 1 w 30 150 350 50 re S BT /F1 7 Tf 34 191 Td (Anschrift) Tj ET \ + BT /F1 8 Tf 30 124 Td (Telefon) Tj ET 30 90 350 30 re S \ + 30 50 10 10 re S BT /F1 9 Tf 46 51 Td (Haupt) Tj ET 150 50 10 10 re S BT /F1 9 Tf 166 51 Td (Zweig) Tj ET", + ) +} + /// How the paper form was scanned. #[derive(Clone, Copy, Debug)] enum Scan { diff --git a/crates/forms/README.md b/crates/forms/README.md index 73a25c503b..4d8a9b64d0 100644 --- a/crates/forms/README.md +++ b/crates/forms/README.md @@ -45,6 +45,14 @@ let cells: Vec = grid.cells_for(names)?; // "Table1_1", "Table several steps (filling, recalculating, the XFA data, the view), most with nothing changed in between, so it walks a form once (twice on a laid-out XFA form, whose data is written in between); `form_reads_on_this_thread` counts the walks, for tests. +- Automatic field detection considers the first 2,000 drawn rectangles in input order for + combs, check boxes and empty text boxes. Check-box label detection considers at most 2,000 + drawn/existing widget rectangles combined, before filtering or deduplication. Unusually + complex pages may therefore have partial proposals, returned in reading order; existing + widgets always exclude overlapping proposals, even beyond the label budget. A balanced + spatial index avoids repeated full scans, with a shared 128,000-step query budget. If + adversarial geometry exhausts it, unverified proposals are omitted, not accepted. As the input + supplies widget geometry only, any existing small square widget can reserve a nearby label. - Inheritable attributes (`/FT`, `/Ff`, `/V`, `/DV`, `/DA`, `/Q`, `/MaxLen`) are resolved down the field tree; the form's `/DA` and `/Q` are the last fallback. - Text and choice fields get new appearance streams (`/Tx BMC … EMC`): auto-size (`0 Tf`), comb diff --git a/crates/forms/src/detect.rs b/crates/forms/src/detect.rs index 99f2447c02..4859793e94 100644 --- a/crates/forms/src/detect.rs +++ b/crates/forms/src/detect.rs @@ -49,6 +49,11 @@ pub struct Candidate { /// points along its sides (#2942: a cell drawn with a midpoint on each vertical side). const MAX_RECT_POINTS: usize = 16; +/// Maximum rectangle inputs examined for combs and boxes, and maximum combined drawn/existing +/// rectangle inputs examined for check-box labels. Count inputs before filtering or deduplication: +/// repeated or irrelevant rectangles must not defeat the bound on pairwise comparisons. +pub const MAX_DETECTION_BOXES: usize = 2000; + /// Graphics states saved (`q`) and kept at once while detecting; deeper saves are counted, not kept. const MAX_SAVES: usize = 256; @@ -335,30 +340,13 @@ fn clean(label: &str) -> String { s.chars().take(40).collect::().trim().to_string() } -/// The label for a field at `rect`: the words to its left on the same line, else the words +/// The label for a text field at `rect`: the words to its left on the same line, else the words /// just above it. -fn label_for(words: &[Word], rect: [f64; 4], right_of: bool) -> String { +fn label_for(words: &[Word], rect: [f64; 4]) -> String { let h = (rect[3] - rect[1]).max(8.0); let same_line = |w: &Word| (mid(w.rect) - mid(rect)).abs() < h.max(10.0) * 0.7; - let mut left: Vec<&Word> = if right_of { - words.iter().filter(|w| same_line(w) && w.rect[0] >= rect[2] - 1.0 && w.rect[0] - rect[2] < 200.0).collect() - } else { - words.iter().filter(|w| same_line(w) && w.rect[2] <= rect[0] + 1.0 && rect[0] - w.rect[2] < 250.0).collect() - }; + let mut left: Vec<&Word> = words.iter().filter(|w| same_line(w) && w.rect[2] <= rect[0] + 1.0 && rect[0] - w.rect[2] < 250.0).collect(); left.sort_by(|a, b| a.rect[0].total_cmp(&b.rect[0])); - if right_of { - // The words that follow the box, up to the next gap wider than a few spaces. - let mut picked = Vec::new(); - let mut x = rect[2]; - for w in left { - if w.rect[0] - x > 24.0 { - break; - } - picked.push(w.text.as_str()); - x = w.rect[2]; - } - return clean(&picked.join(" ")); - } // The words that end nearest the field, back to a wide gap. let mut picked: Vec<&str> = Vec::new(); let mut x = rect[0]; @@ -387,6 +375,119 @@ fn label_for(words: &[Word], rect: [f64; 4], right_of: bool) -> String { clean(&on.iter().map(|w| w.text.as_str()).collect::>().join(" ")) } +/// Sort items into reading order: top to bottom (rows within 8 pt of the row's first), left to right. +fn sort_reading_order(mut items: Vec, rect_of: impl Fn(&T) -> [f64; 4]) -> Vec { + items.sort_by(|a, b| mid(rect_of(b)).total_cmp(&mid(rect_of(a)))); + let mut rows = Vec::with_capacity(items.len()); + let (mut row, mut start) = (0usize, f64::INFINITY); + for item in &items { + if start - mid(rect_of(item)) > 8.0 { + row += 1; + start = mid(rect_of(item)); + } + rows.push(row); + } + let mut keyed: Vec<(usize, T)> = rows.into_iter().zip(items).collect(); + keyed.sort_by(|a, b| a.0.cmp(&b.0).then(rect_of(&a.1)[0].total_cmp(&rect_of(&b.1)[0]))); + keyed.into_iter().map(|(_, item)| item).collect() +} + +/// The label for a check box at `rect`: the nearer unclaimed phrase on the same line (to its +/// right or to its left), without crossing or stealing a phrase that sits closer to an adjacent +/// check box on the line. +fn checkbox_label(words: &[Word], rect: [f64; 4], boxes: &[[f64; 4]], used: &mut std::collections::HashSet) -> String { + let h = (rect[3] - rect[1]).max(8.0); + let same_line_word = |r: [f64; 4]| (mid(r) - mid(rect)).abs() < h.max(10.0) * 0.7; + let same_line_box = |b: [f64; 4]| { + #[cfg(test)] + work_bound_tests::record_comparison(); + (mid(b) - mid(rect)).abs() < h.max(b[3] - b[1]).max(10.0) * 0.7 + }; + let has_content = |w: &Word| !clean(&w.text).is_empty(); + let prev_box_x2 = + boxes.iter().copied().filter(|b| *b != rect && same_line_box(*b) && b[2] <= rect[0] + 1.0).map(|b| b[2]).fold(f64::NEG_INFINITY, f64::max); + let next_box_x0 = + boxes.iter().copied().filter(|b| *b != rect && same_line_box(*b) && b[0] >= rect[2] - 1.0).map(|b| b[0]).fold(f64::INFINITY, f64::min); + + let mut left_words: Vec<(usize, &Word)> = words + .iter() + .enumerate() + .filter(|(i, w)| { + !used.contains(i) && same_line_word(w.rect) && w.rect[2] <= rect[0] + 1.0 && rect[0] - w.rect[2] < 200.0 && w.rect[0] >= prev_box_x2 - 1.0 + }) + .collect(); + left_words.sort_by(|a, b| a.1.rect[0].total_cmp(&b.1.rect[0])); + let mut left_picked: Vec<(usize, &Word)> = Vec::new(); + let mut x = rect[0]; + let mut has_word = false; + for (i, w) in left_words.into_iter().rev() { + if x - w.rect[2] > 24.0 || w.text.chars().all(|c| c == '_') || (has_word && w.text.trim_end().ends_with(':')) { + break; + } + has_word |= has_content(w); + left_picked.push((i, w)); + x = w.rect[0]; + } + left_picked.reverse(); + let left_candidate = match (left_picked.iter().find(|(_, w)| has_content(w)), left_picked.iter().rev().find(|(_, w)| has_content(w))) { + (Some((_, first)), Some((_, last))) => { + let text = clean(&left_picked.iter().map(|(_, w)| w.text.as_str()).collect::>().join(" ")); + let gap = (rect[0] - last.rect[2]).max(0.0); + let prev_gap = (first.rect[0] - prev_box_x2).max(0.0); + let colon = left_picked.last().is_some_and(|(_, w)| w.text.trim_end().ends_with(':')) || last.text.trim_end().ends_with(':'); + (!text.is_empty() && gap <= prev_gap).then_some((text, gap, colon, left_picked)) + } + _ => None, + }; + + let mut right_words: Vec<(usize, &Word)> = words + .iter() + .enumerate() + .filter(|(i, w)| { + !used.contains(i) && same_line_word(w.rect) && w.rect[0] >= rect[2] - 1.0 && w.rect[0] - rect[2] < 200.0 && w.rect[2] <= next_box_x0 + 1.0 + }) + .collect(); + right_words.sort_by(|a, b| a.1.rect[0].total_cmp(&b.1.rect[0])); + let mut right_picked: Vec<(usize, &Word)> = Vec::new(); + let mut x = rect[2]; + let mut has_word = false; + for (i, w) in right_words { + if w.rect[0] - x > 24.0 || w.text.chars().all(|c| c == '_') || (has_word && (next_box_x0 - w.rect[2]).max(0.0) < w.rect[0] - x) { + break; + } + has_word |= has_content(w); + right_picked.push((i, w)); + x = w.rect[2]; + } + let right_candidate = match (right_picked.iter().find(|(_, w)| has_content(w)), right_picked.iter().rev().find(|(_, w)| has_content(w))) { + (Some((_, first)), Some((_, last))) => { + let text = clean(&right_picked.iter().map(|(_, w)| w.text.as_str()).collect::>().join(" ")); + let gap = (first.rect[0] - rect[2]).max(0.0); + let next_gap = (next_box_x0 - last.rect[2]).max(0.0); + (!text.is_empty() && gap <= next_gap).then_some((text, gap, next_gap, right_picked)) + } + _ => None, + }; + + let chosen = match (left_candidate, right_candidate) { + (Some((lt, l_gap, colon, l_words)), Some((rt, r_gap, next_gap, r_words))) => { + let pick_left = !colon && (l_gap < r_gap || (next_gap <= 24.0 && l_gap <= r_gap)); + if pick_left { Some((lt, l_words)) } else { Some((rt, r_words)) } + } + (Some((lt, _, _, l_words)), None) => Some((lt, l_words)), + (None, Some((rt, _, _, r_words))) => Some((rt, r_words)), + (None, None) => None, + }; + if let Some((text, picked)) = chosen { + for (i, _) in picked { + used.insert(i); + } + text + } else { + String::new() + } +} + /// Rows of two or more touching cells of one size, as (the row's rect, cell count). Two is /// enough: dates split into day and month groups of two cells. Cells are square or taller /// than wide; an empty table of wider cells is not a comb. @@ -404,6 +505,8 @@ fn combs(boxes: &[[f64; 4]]) -> Vec<([f64; 4], usize)> { .collect(); // `b` comes right after `a` in a row: same size, its left edge on a's right edge. let follows = |a: &[f64; 4], b: &[f64; 4]| { + #[cfg(test)] + work_bound_tests::record_comparison(); (b[0] - a[2]).abs() <= 1.0 && (b[1] - a[1]).abs() <= 0.5 && (b[3] - a[3]).abs() <= 0.5 && ((b[2] - b[0]) - (a[2] - a[0])).abs() <= 0.5 }; let mut out = Vec::new(); @@ -426,13 +529,95 @@ fn combs(boxes: &[[f64; 4]]) -> Vec<([f64; 4], usize)> { out } +/// A balanced bounding-volume tree indexes *all* existing widgets, independently of the +/// proposal/label budget. Far-away widgets can be excluded together instead of rescanning +/// the entire page for each proposal. Construction is O(n log n), with logarithmic depth. +struct WidgetIndex { + bounds: [f64; 4], + contents: WidgetContents, +} + +enum WidgetContents { + Leaf(Box<[[f64; 4]]>), + Branch(Box, Box), +} + +fn rectangles_overlap(a: [f64; 4], b: [f64; 4]) -> bool { + #[cfg(test)] + work_bound_tests::record_comparison(); + a[0] < b[2] - 1.0 && b[0] < a[2] - 1.0 && a[1] < b[3] - 1.0 && b[1] < a[3] - 1.0 +} + +impl WidgetIndex { + fn new(rects: &[[f64; 4]]) -> Option { + // A NaN makes the exact overlap predicate false. Infinities and inverted boxes are + // retained: pruning uses normalized bounds, but leaves preserve original geometry. + let mut rects: Vec<_> = rects.iter().copied().filter(|r| !r.iter().any(|x| x.is_nan())).collect(); + Self::build(&mut rects, 0) + } + + fn build(rects: &mut [[f64; 4]], depth: usize) -> Option { + let first = rects.first()?; + let mut bounds = [first[0].min(first[2]), first[1].min(first[3]), first[0].max(first[2]), first[1].max(first[3])]; + for r in rects.iter().skip(1) { + bounds = [bounds[0].min(r[0]).min(r[2]), bounds[1].min(r[1]).min(r[3]), bounds[2].max(r[0]).max(r[2]), bounds[3].max(r[1]).max(r[3])]; + } + let contents = if rects.len() <= 8 { + WidgetContents::Leaf(rects.to_vec().into_boxed_slice()) + } else { + let axis = depth % 2; + let mid = rects.len() / 2; + rects.select_nth_unstable_by(mid, |a, b| a[axis].total_cmp(&b[axis])); + let (left, right) = rects.split_at_mut(mid); + WidgetContents::Branch(Box::new(Self::build(left, depth + 1)?), Box::new(Self::build(right, depth + 1)?)) + }; + Some(Self { bounds, contents }) + } + + fn overlaps(&self, rect: [f64; 4], remaining: &mut usize) -> bool { + // Spatial indexes can degenerate on adversarial geometry. Exhaustion suppresses + // the unverified proposal, rather than overlooking any existing widget exclusion. + if *remaining == 0 { + return true; + } + *remaining -= 1; + #[cfg(test)] + work_bound_tests::record_index_visit(); + if !rectangles_overlap(self.bounds, rect) { + return false; + } + match &self.contents { + WidgetContents::Leaf(rects) => rects.iter().any(|r| { + if *remaining == 0 { + return true; + } + *remaining -= 1; + rectangles_overlap(*r, rect) + }), + WidgetContents::Branch(left, right) => left.overlaps(rect, remaining) || right.overlaps(rect, remaining), + } + } +} + /// Propose fields for a page. `existing` are the page's widget rectangles (no candidate /// overlaps them); names are unique against `taken`. +/// +/// Box detection considers only the first [`MAX_DETECTION_BOXES`] drawn rectangles in input +/// order, and check-box labelling considers at most that many drawn/existing rectangles combined. +/// Limits apply before pairwise comb/overlap/label work, not just to accepted candidates. This +/// heuristic can return a partial set on unusually complex pages, like raster shape detection; +/// the retained candidates are still returned in reading order. Every existing widget remains +/// an overlap exclusion, even when it falls outside the label-detection budget. pub fn detect(words: &[Word], shapes: &Shapes, existing: &[[f64; 4]], taken: &[String]) -> Vec { + // Bound the comb pass too: small squares qualify as comb cells, so limiting only the new + // check-box loop would still leave quadratic work on all of a hostile page's rectangles. + let boxes = shapes.boxes.get(..shapes.boxes.len().min(MAX_DETECTION_BOXES)).unwrap_or_default(); let mut out: Vec = Vec::new(); - let overlaps = |a: [f64; 4], b: [f64; 4]| a[0] < b[2] - 1.0 && b[0] < a[2] - 1.0 && a[1] < b[3] - 1.0 && b[1] < a[3] - 1.0; - let push = |kind: Kind, rect: [f64; 4], label: String, out: &mut Vec| { - if existing.iter().chain(out.iter().map(|c| &c.rect)).any(|e| overlaps(*e, rect)) { + let overlaps = rectangles_overlap; + let existing_index = WidgetIndex::new(existing); + let mut existing_work = 64 * MAX_DETECTION_BOXES; + let mut push = |kind: Kind, rect: [f64; 4], label: String, out: &mut Vec| { + if existing_index.as_ref().is_some_and(|index| index.overlaps(rect, &mut existing_work)) || out.iter().any(|c| overlaps(c.rect, rect)) { return; } out.push(Candidate { kind, rect, name: label }); @@ -443,33 +628,45 @@ pub fn detect(words: &[Word], shapes: &Shapes, existing: &[[f64; 4]], taken: &[S for b in blanks { let h = (b.rect[3] - b.rect[1]).max(10.0); let rect = [b.rect[0], b.rect[1], b.rect[2], b.rect[1] + (h * 1.4).clamp(12.0, 22.0)]; - let l = label_for(&labels, rect, false); + let l = label_for(&labels, rect); push(Kind::Text, rect, l, &mut out); } // Comb boxes (postcodes, dates, IBANs): one text field per row of cells, found before // check boxes so the cells don't each become one. - for (rect, cells) in combs(&shapes.boxes) { + for (rect, cells) in combs(boxes) { if labels.iter().any(|x| overlaps(x.rect, rect)) { continue; } - let l = label_for(&labels, rect, false); + let l = label_for(&labels, rect); push(Kind::Comb { cells }, rect, l, &mut out); } - // Small squares: check boxes, labelled by the text to their right. - for r in &shapes.boxes { + // Small squares: check boxes, labelled by the nearer text to their right or left. + // `existing` contains geometry only: a small square widget of any type reserves its label. + // Cap examined inputs, not accepted boxes, so duplicates cannot keep this pass running. + let mut checkboxes: Vec<[f64; 4]> = Vec::new(); + for r in boxes.iter().chain(existing.iter()).take(MAX_DETECTION_BOXES) { let (w, h) = (r[2] - r[0], r[3] - r[1]); - if (5.0..=20.0).contains(&w) && (5.0..=20.0).contains(&h) && (w / h - 1.0).abs() < 0.25 { - let l = label_for(&labels, *r, true); - push(Kind::CheckBox, *r, l, &mut out); + if (5.0..=20.0).contains(&w) + && (5.0..=20.0).contains(&h) + && (w / h - 1.0).abs() < 0.25 + && !out.iter().map(|c| &c.rect).chain(checkboxes.iter()).any(|e| overlaps(*e, *r)) + { + checkboxes.push(*r); } } + let checkboxes = sort_reading_order(checkboxes, |r| *r); + let mut used_words = std::collections::HashSet::new(); + for r in &checkboxes { + let l = checkbox_label(&labels, *r, &checkboxes, &mut used_words); + push(Kind::CheckBox, *r, l, &mut out); + } // Empty boxes big enough to write in: text fields inside them. - for r in &shapes.boxes { + for r in boxes { let (w, h) = (r[2] - r[0], r[3] - r[1]); let has_text = labels.iter().any(|x| overlaps(x.rect, *r)); if w >= 40.0 && (12.0..=60.0).contains(&h) && !has_text { let inner = [r[0] + 1.0, r[1] + 1.0, r[2] - 1.0, r[3] - 1.0]; - let l = label_for(&labels, *r, false); + let l = label_for(&labels, *r); push(Kind::Text, inner, l, &mut out); } } @@ -484,26 +681,14 @@ pub fn detect(words: &[Word], shapes: &Shapes, existing: &[[f64; 4]], taken: &[S if labels.iter().any(|x| overlaps(x.rect, rect)) { continue; } - let l = label_for(&labels, rect, false); + let l = label_for(&labels, rect); push(Kind::Text, rect, l, &mut out); } - // Reading order: top to bottom, left to right. - // Rows: fields whose middles are within 8 pt of the row's first. - out.sort_by(|a, b| mid(b.rect).total_cmp(&mid(a.rect))); - let mut rows = Vec::with_capacity(out.len()); - let (mut row, mut start) = (0usize, f64::INFINITY); - for c in &out { - if start - mid(c.rect) > 8.0 { - row += 1; - start = mid(c.rect); - } - rows.push(row); - } - let mut keyed: Vec<(usize, Candidate)> = rows.into_iter().zip(out).collect(); - keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.rect[0].total_cmp(&b.1.rect[0]))); - let mut out: Vec = keyed.into_iter().map(|(_, c)| c).collect(); + let mut out = sort_reading_order(out, |c| c.rect); // Unique names (Acrobat numbers repeats); unlabelled fields get Text1, Check Box1, … - let mut used: Vec = taken.to_vec(); + // A linear membership scan inside each suffix retry makes a page of unnamed squares + // cubic even after bounding the geometric passes. + let mut used: std::collections::HashSet = taken.iter().cloned().collect(); for c in &mut out { let base = if c.name.is_empty() { match c.kind { @@ -519,15 +704,135 @@ pub fn detect(words: &[Word], shapes: &Shapes, existing: &[[f64; 4]], taken: &[S n += 1; name = format!("{base}{n}"); } - used.push(name.clone()); + used.insert(name.clone()); c.name = name; } out } #[cfg(test)] -mod comb_tests { - use super::combs; +mod work_bound_tests { + use super::*; + use std::cell::Cell; + + // Per-thread so the other detection tests can run concurrently. Count work rather than + // wall time: appending more hostile rectangles must not add pairwise comparisons. + thread_local! { + static COMPARISONS: Cell = const { Cell::new(0) }; + static INDEX_VISITS: Cell = const { Cell::new(0) }; + } + + pub(super) fn record_comparison() { + COMPARISONS.set(COMPARISONS.get() + 1); + } + + pub(super) fn record_index_visit() { + INDEX_VISITS.set(INDEX_VISITS.get() + 1); + } + + #[test] + fn rectangle_budget_bounds_comparisons_before_filtering() { + for duplicates in [false, true] { + for existing_only in [false, true] { + let boxes = (0..MAX_DETECTION_BOXES) + .map(|i| { + let x = if duplicates { 0.0 } else { i as f64 * 30.0 }; + [x, 0.0, x + 10.0, 10.0] + }) + .collect(); + let mut shapes = Shapes { boxes, rules: Vec::new() }; + let run = |shapes: &Shapes| { + if existing_only { detect(&[], &Shapes::default(), &shapes.boxes, &[]) } else { detect(&[], shapes, &[], &[]) } + }; + COMPARISONS.set(0); + let expected = run(&shapes); + let bounded = COMPARISONS.get(); + assert!(bounded > 0 && bounded <= 5 * MAX_DETECTION_BOXES * MAX_DETECTION_BOXES); + shapes.boxes.extend_from_within(..); + COMPARISONS.set(0); + assert_eq!(run(&shapes), expected); + if existing_only { + // Existing widgets are never discarded: doubling them may add tree levels, + // but must not restore the full pairwise scan. + assert!(COMPARISONS.get() <= bounded + 16 * MAX_DETECTION_BOXES); + } else { + assert_eq!(COMPARISONS.get(), bounded, "discarded inputs add no pairwise work"); + } + } + } + } + + #[test] + fn many_existing_widgets_do_not_multiply_proposal_work() { + let mut existing: Vec<_> = (0..100_000) + .map(|i| { + let x = i as f64 * 30.0; + [x, 100.0, x + 10.0, 110.0] + }) + .collect(); + let shapes = Shapes { + boxes: (0..MAX_DETECTION_BOXES) + .map(|i| { + let x = i as f64 * 30.0; + [x, 0.0, x + 10.0, 10.0] + }) + .collect(), + rules: Vec::new(), + }; + // An exclusion beyond both budgets must still suppress the last drawn candidate. + let exclusion = [59_970.0, 0.0, 59_980.0, 10.0]; + existing.push(exclusion); + COMPARISONS.set(0); + let expected = detect(&[], &shapes, &[exclusion], &[]); + let baseline_work = COMPARISONS.get(); + COMPARISONS.set(0); + INDEX_VISITS.set(0); + let candidates = detect(&[], &shapes, &existing, &[]); + assert_eq!(candidates.len(), MAX_DETECTION_BOXES - 1); + assert_eq!(candidates, expected); + assert!(!candidates.iter().any(|c| c.rect == [59_970.0, 0.0, 59_980.0, 10.0])); + assert!(COMPARISONS.get() <= baseline_work + 64 * MAX_DETECTION_BOXES, "existing-widget comparisons must not be candidates times widgets"); + assert!(INDEX_VISITS.get() < 100 * MAX_DETECTION_BOXES); + } + + #[test] + fn widget_index_matches_linear_overlap_semantics() { + let mut rects = + vec![[0.0, 0.0, 10.0, 10.0], [30.0, 20.0, 20.0, 10.0], [f64::NEG_INFINITY, 50.0, f64::INFINITY, 60.0], [f64::NAN, 0.0, 10.0, 10.0]]; + rects.extend((0..500).map(|i| { + let x = (i % 25) as f64 * 3.0; + let y = (i / 25) as f64 * 4.0; + [x, y, x + 2.0, y + 2.0] + })); + let index = WidgetIndex::new(&rects).expect("nonempty index"); + for x in -5..40 { + for y in -5..70 { + let query = [x as f64, y as f64, x as f64 + 12.0, y as f64 + 12.0]; + let mut remaining = usize::MAX; + assert_eq!(index.overlaps(query, &mut remaining), rects.iter().any(|r| rectangles_overlap(*r, query))); + } + } + } + + #[test] + fn adversarial_widget_geometry_exhausts_budget_without_accepting_unchecked_fields() { + let existing = vec![[1e9, 1e9, -1e9, -1e9]; 100_000]; + let shapes = Shapes { + boxes: (0..MAX_DETECTION_BOXES) + .map(|i| { + let x = i as f64 * 30.0; + [x, 0.0, x + 10.0, 10.0] + }) + .collect(), + rules: Vec::new(), + }; + COMPARISONS.set(0); + INDEX_VISITS.set(0); + let candidates = detect(&[], &shapes, &existing, &[]); + assert!(candidates.is_empty(), "an exhausted search cannot verify any proposal"); + assert!(INDEX_VISITS.get() <= 64 * MAX_DETECTION_BOXES); + assert!(COMPARISONS.get() < 5 * MAX_DETECTION_BOXES * MAX_DETECTION_BOXES); + } #[test] fn repeated_boxes_do_not_change_or_multiply_a_comb() { diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index 1e6a18582c..036ec94892 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -4316,6 +4316,132 @@ fn document_scripts_read_each_name_tree_node_once() { assert_eq!(document_scripts_named(&doc), [("init".to_string(), "var ready = true;".to_string())]); } +#[test] +fn detection_names_check_boxes_from_the_nearer_neighbouring_label() { + use crate::detect::*; + let w = |t: &str, x0: f64, y0: f64, x1: f64| Word { text: t.into(), rect: [x0, y0, x1, y0 + 10.0] }; + let names_of = |words: &[Word], boxes: &[[f64; 4]]| -> Vec { + detect(words, &Shapes { boxes: boxes.to_vec(), rules: Vec::new() }, &[], &[]) + .into_iter() + .map(|c| { + assert_eq!(c.kind, Kind::CheckBox); + c.name + }) + .collect() + }; + + // #2943: "Monsieur [box] Madame [box]" — each label ends ~4-5 pt before its box, while + // the next label begins 23 pt after the first box. Drawing order does not change the names. + let french_words = [w("Monsieur", 100.0, 532.0, 141.0), w("Madame", 180.0, 532.0, 218.0)]; + let french_boxes = [[146.0, 532.0, 157.0, 542.0], [222.0, 532.0, 233.0, 542.0]]; + assert_eq!(names_of(&french_words, &french_boxes), ["Monsieur", "Madame"]); + assert_eq!(names_of(&french_words, &[french_boxes[1], french_boxes[0]]), ["Monsieur", "Madame"]); + + // Two filers on the same form ("Monsieur [ ] Madame [ ]" repeated) number the second pair. + let two_filers_words = + [w("Monsieur", 100.0, 532.0, 141.0), w("Madame", 180.0, 532.0, 218.0), w("Monsieur", 320.0, 532.0, 361.0), w("Madame", 400.0, 532.0, 438.0)]; + let two_filers_boxes = [[146.0, 532.0, 157.0, 542.0], [222.0, 532.0, 233.0, 542.0], [366.0, 532.0, 377.0, 542.0], [442.0, 532.0, 453.0, 542.0]]; + assert_eq!(names_of(&two_filers_words, &two_filers_boxes), ["Monsieur", "Madame", "Monsieur2", "Madame2"]); + + // Even with equal 5 pt gaps ("Label [ ] Label [ ]" vs "[ ] Label [ ] Label"), each box pairs + // with its own neighbour rather than leaving an outer box or label orphaned. + let tight_left_words = [w("Monsieur", 100.0, 400.0, 140.0), w("Madame", 160.0, 400.0, 200.0)]; + let tight_left_boxes = [[145.0, 400.0, 155.0, 410.0], [205.0, 400.0, 215.0, 410.0]]; + assert_eq!(names_of(&tight_left_words, &tight_left_boxes), ["Monsieur", "Madame"]); + + let tight_right_words = [w("Monsieur", 115.0, 400.0, 155.0), w("Madame", 175.0, 400.0, 215.0)]; + let tight_right_boxes = [[100.0, 400.0, 110.0, 410.0], [160.0, 400.0, 170.0, 410.0]]; + assert_eq!(names_of(&tight_right_words, &tight_right_boxes), ["Monsieur", "Madame"]); + + // An unlabelled box does not steal a label that sits closer to the adjacent box. + assert_eq!(names_of(&[w("Madame", 180.0, 532.0, 218.0)], &french_boxes), ["Check Box1", "Madame"]); + assert_eq!( + names_of(&[w("Monsieur", 115.0, 400.0, 155.0)], &[[100.0, 400.0, 110.0, 410.0], [178.0, 400.0, 188.0, 410.0]]), + ["Monsieur", "Check Box1"] + ); + + // Deliberate ambiguity: "[ ] 4pt Yes 3pt [ ] No" gives Yes to the closer box. + assert_eq!( + names_of(&[w("Yes", 114.0, 400.0, 134.0), w("No", 151.0, 400.0, 166.0)], &[[100.0, 400.0, 110.0, 410.0], [137.0, 400.0, 147.0, 410.0]]), + ["Check Box1", "Yes"] + ); + + // A row heading ending with a colon ("Status: [ ] Single [ ] Married" or French + // "Civilité : Monsieur [ ] Madame [ ]") does not beat or merge into the option label, + // while a standalone "Married: [ ]" or "Date of birth : [ ]" still uses its prompt. + let prompt_words = [w("Status:", 50.0, 300.0, 96.0), w("Single", 115.0, 300.0, 145.0), w("Married", 185.0, 300.0, 225.0)]; + let prompt_boxes = [[100.0, 300.0, 110.0, 310.0], [170.0, 300.0, 180.0, 310.0]]; + assert_eq!(names_of(&prompt_words, &prompt_boxes), ["Single", "Married"]); + let civilite_words = + [w("Civilité", 30.0, 532.0, 72.0), w(":", 75.0, 532.0, 78.0), w("Monsieur", 100.0, 532.0, 141.0), w("Madame", 180.0, 532.0, 218.0)]; + assert_eq!(names_of(&civilite_words, &french_boxes), ["Monsieur", "Madame"]); + assert_eq!(names_of(&[w("Married:", 50.0, 300.0, 95.0)], &[[100.0, 300.0, 110.0, 310.0]]), ["Married"]); + assert_eq!( + names_of( + &[w("Date", 30.0, 300.0, 52.0), w("of", 55.0, 300.0, 65.0), w("birth", 68.0, 300.0, 90.0), w(":", 92.0, 300.0, 95.0)], + &[[100.0, 300.0, 110.0, 310.0]] + ), + ["Date of birth"] + ); + + // "[ ] Oui Non [ ]" with an 18 pt gap between "Oui" and "Non" splits the two labels + // between their respective boxes instead of merging "Oui Non". + let mixed_words = [w("Oui", 115.0, 300.0, 135.0), w("Non", 153.0, 300.0, 175.0)]; + let mixed_boxes = [[100.0, 300.0, 110.0, 310.0], [180.0, 300.0, 190.0, 310.0]]; + assert_eq!(names_of(&mixed_words, &mixed_boxes), ["Oui", "Non"]); + + // An existing check-box widget still claims its own label so a neighbouring unlabelled box + // does not steal it. + let existing = [[100.0, 400.0, 110.0, 410.0]]; + let remaining = + detect(&[w("Monsieur", 115.0, 400.0, 155.0)], &Shapes { boxes: vec![[178.0, 400.0, 188.0, 410.0]], rules: Vec::new() }, &existing, &[]); + assert_eq!(remaining.iter().map(|c| c.name.as_str()).collect::>(), ["Check Box1"]); + + // A stray punctuation token right after the first box does not pull the next box's label in. + assert_eq!(names_of(&[w(".", 158.0, 532.0, 160.0), w("Madame", 180.0, 532.0, 218.0)], &french_boxes), ["Check Box1", "Madame"]); +} + +/// A hostile vector page can contain arbitrarily many small squares; detection must not run +/// pairwise comb/overlap/neighbor work on all of them, nor cubic default-name lookup. +#[test] +fn detection_bounds_many_small_squares_before_pairwise_work() { + use crate::detect::*; + let boxes = (0..MAX_DETECTION_BOXES * 50) + .map(|i| { + let x = (i % 100) as f64 * 30.0; + let y = (i / 100) as f64 * 30.0; + [x, y, x + 10.0, y + 10.0] + }) + .collect(); + let shapes = Shapes { boxes, rules: Vec::new() }; + let found = detect(&[], &shapes, &[], &["Check Box1".into(), "Check Box3".into()]); + assert_eq!(found.len(), MAX_DETECTION_BOXES); + assert!(found.iter().all(|c| c.kind == Kind::CheckBox)); + assert_eq!(found.first().unwrap().name, "Check Box2"); + assert_eq!(found.get(1).unwrap().name, "Check Box4"); + assert_eq!(found.last().unwrap().name, format!("Check Box{}", MAX_DETECTION_BOXES + 2)); + assert_eq!(found.iter().map(|c| &c.name).collect::>().len(), found.len()); + let prefix = Shapes { boxes: shapes.boxes.iter().take(MAX_DETECTION_BOXES).copied().collect(), rules: Vec::new() }; + assert_eq!(found, detect(&[], &prefix, &[], &["Check Box1".into(), "Check Box3".into()])); +} + +#[test] +fn detection_box_budget_counts_rejected_inputs_and_keeps_existing_exclusions() { + use crate::detect::*; + let first = [0.0, 0.0, 10.0, 10.0]; + let last = [30.0, 0.0, 40.0, 10.0]; + // The final input at the limit is included; the next is not, even if earlier inputs are + // duplicates. A later input higher on the page stays outside the budget despite reading first. + let mut boxes = vec![first; MAX_DETECTION_BOXES - 1]; + boxes.push(last); + boxes.push([60.0, 30.0, 70.0, 40.0]); + let shapes = Shapes { boxes, rules: Vec::new() }; + assert_eq!(detect(&[], &shapes, &[], &[]).iter().map(|c| c.rect).collect::>(), [first, last]); + let mut existing = vec![[90.0, 0.0, 100.0, 10.0]; MAX_DETECTION_BOXES]; + existing.push(last); + assert_eq!(detect(&[], &shapes, &existing, &[]).iter().map(|c| c.rect).collect::>(), [first]); +} + #[test] fn name_tree_nodes_sharing_one_long_kids_array_queue_it_a_bounded_number_of_times() { // 10,000 nodes share one /Kids array of 210,001 entries: the leaf, every node, and the leaf From c4e174675e2e4d976c0498b548e36d15d439a26b Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Wed, 18 Nov 2026 07:24:31 +0100 Subject: [PATCH 05/27] Bookmarks from text styles open at the heading top on turned pages (#7443) * Style bookmarks go to the displayed heading top on turned pages Co-Authored-By: Claude Sonnet 5.5 * Read and join style-bookmark headings in displayed order on turned pages Co-Authored-By: Claude Sonnet 5.5 * Read page rotations once per document for style bookmarks Co-Authored-By: Claude Sonnet 5.5 * Test style bookmarks on cropped turned pages and after save and reopen Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/edit/run.rs | 2 +- crates/engine/src/tests.rs | 159 ++++++++++++++++++++++ crates/engine/src/text_style_bookmarks.rs | 44 ++++-- crates/organize/src/lib.rs | 6 + crates/organize/src/outline.rs | 10 +- crates/organize/src/tests.rs | 4 +- 6 files changed, 207 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index 79a99a5684..a6603d91e3 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -581,7 +581,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E Edit::BookmarksFromStructure => { let entries: Vec<_> = pdfcraft_a11y::headings(doc) .into_iter() - .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, top: None }) + .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }) .collect(); pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?; } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 669cd36786..34f43b7374 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2472,6 +2472,165 @@ fn headings_in_two_columns_are_two_bookmarks() { assert_eq!(outline_titles(&s.get(id).unwrap().info.outline), ["Untitled→0[Left heading→1,Right heading→1]"]); } +/// #7415: a heading's bookmark goes to the top of the heading as displayed. The same heading is +/// shown at the same place on four pages turned 0, 90, 180 and 270 degrees; on a quarter turn the +/// displayed top is a user-space x, so it is the destination's `left` and `top` stays unspecified. +#[test] +fn style_bookmarks_go_to_the_displayed_heading_top_on_turned_pages() { + // (rotation, media box, text matrix): each shows "Birch Survey" at 90 pt from the left and + // 130 pt (baseline) from the top of a 400 x 600 displayed page. + let pages = [ + (0, "0 0 400 600", "1 0 0 1 90 470"), + (90, "0 0 600 400", "0 1 -1 0 130 90"), + (180, "0 0 400 600", "-1 0 0 -1 310 130"), + (270, "0 0 600 400", "0 -1 1 0 470 310"), + ]; + let mut pdf = + pdfcraft_testkit::Pdf::new().obj("<< /Type /Catalog /Pages 2 0 R >>").obj("<< /Type /Pages /Kids [3 0 R 5 0 R 7 0 R 9 0 R] /Count 4 >>"); + for (i, (rotate, media, tm)) in pages.iter().enumerate() { + let content = format!("BT /F1 20 Tf {tm} Tm (Birch Survey) Tj ET"); + pdf = pdf + .obj(format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [{media}] /Rotate {rotate} /Resources << /Font << /F1 11 0 R >> >> /Contents {} 0 R >>", + 4 + 2 * i + )) + .stream("", &content); + } + let bytes = pdf.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>").build(); + let mut s = Session::new(); + let id = s.open("turned.pdf", None, Arc::new(bytes), None).unwrap(); + let style = s.get(id).unwrap().text_styles()[0].style.clone(); + s.apply(id, Edit::BookmarksFromTextStyles { levels: vec![style] }).unwrap(); + let doc = s.get(id).unwrap(); + let kids = &doc.info.outline[0].children; + assert_eq!(kids.len(), 4); + // The displayed top of the heading, from the upright page. + let top_of_heading = { + let cos = pdfcraft_cos::Document::open(doc.bytes.clone()).unwrap(); + let line = &pdfcraft_edit::text_lines(&cos, 0).unwrap()[0]; + 600.0 - line.rect[1].max(line.rect[3]) as f32 + }; + assert!((110.0..115.0).contains(&top_of_heading), "{top_of_heading}"); + for (i, kid) in kids.iter().enumerate() { + let page = &doc.info.pages[i]; + assert_eq!(page.rotation, pages[i].0); + let [want_left, want_top] = page.xyz_for_view(None, Some(top_of_heading)); + match kid.view { + pdfcraft_render::DestView::Xyz { left, top, zoom: None } => { + let near = |got: Option, want: Option| match (got, want) { + (None, None) => true, + (Some(g), Some(w)) => (g - w).abs() < 1.0, + _ => false, + }; + assert!(near(left, want_left) && near(top, want_top), "rotate {}: got {left:?} {top:?}, want {want_left:?} {want_top:?}", pages[i].0); + } + ref v => panic!("{v:?}"), + } + } +} + +/// #7415: on a turned page the headings are read in displayed order (top to bottom), a heading +/// set on two lines is one bookmark, and each goes to the top of its first displayed line. One +/// layout (two headings and a two-line heading, written to the file out of order) on pages turned +/// 0, 90, 180 and 270 degrees must give the same bookmarks at the same displayed tops, with and +/// without a crop box whose origin is not the page's. +#[test] +fn style_bookmarks_read_and_join_headings_as_displayed_on_turned_pages() { + for cropped in [false, true] { + let (mut s, id) = turned_headings_session(cropped); + let style = s.get(id).unwrap().text_styles()[0].style.clone(); + s.apply(id, Edit::BookmarksFromTextStyles { levels: vec![style] }).unwrap(); + check_turned_headings(&s, id, cropped); + // The destinations survive a save and reopen (`/XYZ left null` on the quarter turns). + let bytes = s.save_bytes(id).unwrap(); + let mut s2 = Session::new(); + let id2 = s2.open("saved.pdf", None, bytes, None).unwrap(); + check_turned_headings(&s2, id2, cropped); + } +} + +/// A document of four pages turned 0, 90, 180 and 270, each showing the same three headings at the +/// same displayed places on a displayed page of 400 x 600 (or 600 x 600 with `cropped`, where +/// the crop box does not start at the page's origin), written in an order that is not reading order. +fn turned_headings_session(cropped: bool) -> (Session, DocId) { + // Displayed baselines (x, y from the top). + let lines = [("Gamma Three", 50.0, 450.0), ("Beta Cont", 50.0, 274.0), ("Alpha One", 50.0, 100.0), ("Beta Two", 50.0, 250.0)]; + // (rotation, page boxes, text matrix prefix, user position of a displayed (x, y)). + type Place = fn(f64, f64) -> (f64, f64); + let plain: [(i32, &str, &str, Place); 4] = [ + (0, "/MediaBox [0 0 400 600]", "1 0 0 1", |x, y| (x, 600.0 - y)), + (90, "/MediaBox [0 0 600 400]", "0 1 -1 0", |x, y| (y, x)), + (180, "/MediaBox [0 0 400 600]", "-1 0 0 -1", |x, y| (400.0 - x, y)), + (270, "/MediaBox [0 0 600 400]", "0 -1 1 0", |x, y| (600.0 - y, 400.0 - x)), + ]; + let boxes = "/MediaBox [0 0 700 700] /CropBox [50 40 650 640]"; + let crop: [(i32, &str, &str, Place); 4] = [ + (0, boxes, "1 0 0 1", |x, y| (50.0 + x, 640.0 - y)), + (90, boxes, "0 1 -1 0", |x, y| (50.0 + y, 40.0 + x)), + (180, boxes, "-1 0 0 -1", |x, y| (650.0 - x, 40.0 + y)), + (270, boxes, "0 -1 1 0", |x, y| (650.0 - y, 640.0 - x)), + ]; + let mut pdf = + pdfcraft_testkit::Pdf::new().obj("<< /Type /Catalog /Pages 2 0 R >>").obj("<< /Type /Pages /Kids [3 0 R 5 0 R 7 0 R 9 0 R] /Count 4 >>"); + for (i, (rotate, boxes, prefix, place)) in (if cropped { crop } else { plain }).iter().enumerate() { + let content: String = lines + .iter() + .map(|(text, x, y)| { + let (ux, uy) = place(*x, *y); + format!("BT /F1 20 Tf {prefix} {ux} {uy} Tm ({text}) Tj ET\n") + }) + .collect(); + pdf = pdf + .obj(format!( + "<< /Type /Page /Parent 2 0 R {boxes} /Rotate {rotate} /Resources << /Font << /F1 11 0 R >> >> /Contents {} 0 R >>", + 4 + 2 * i + )) + .stream("", &content); + } + let bytes = pdf.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>").build(); + let mut s = Session::new(); + let id = s.open("turned.pdf", None, Arc::new(bytes), None).unwrap(); + (s, id) +} + +/// The bookmarks of [`turned_headings_session`] after "from text styles": displayed order, the +/// two-line heading joined, each at the displayed top of its first line. +fn check_turned_headings(s: &Session, id: DocId, cropped: bool) { + let doc = s.get(id).unwrap(); + let kids = &doc.info.outline[0].children; + let titles: Vec<_> = kids.iter().map(|k| k.title.as_str()).collect(); + let per_page = ["Alpha One", "Beta Two Beta Cont", "Gamma Three"]; + assert_eq!(titles, per_page.repeat(4), "displayed order, the two-line heading joined (cropped: {cropped})"); + // The displayed tops of the three headings, from the text of the upright page. + let cos = pdfcraft_cos::Document::open(doc.bytes.clone()).unwrap(); + let upright = &doc.info.pages[0]; + let mut found: Vec<_> = + pdfcraft_edit::text_lines(&cos, 0).unwrap().into_iter().map(|l| upright.user_to_view(0.0, l.rect[3].max(l.rect[1]) as f32)[1]).collect(); + found.sort_by(f32::total_cmp); + // Alpha, Beta Two (the upper line of its heading), Gamma: three of the four lines. + let tops = [found[0], found[1], found[3]]; + for (i, kid) in kids.iter().enumerate() { + let (page, n) = (&doc.info.pages[i / 3], i % 3); + let [want_left, want_top] = page.xyz_for_view(None, Some(tops[n])); + let near = |got: Option, want: Option| match (got, want) { + (None, None) => true, + (Some(g), Some(w)) => (g - w).abs() < 1.0, + _ => false, + }; + match kid.view { + pdfcraft_render::DestView::Xyz { left, top, .. } => { + assert!( + near(left, want_left) && near(top, want_top), + "rotate {} {} (cropped: {cropped}): got {left:?} {top:?}, want {want_left:?} {want_top:?}", + page.rotation, + kid.title + ) + } + ref v => panic!("{v:?}"), + } + } +} + /// `style` at another size. fn pdfcraft_engine_style(style: &text_style_bookmarks::TextStyle, size: f64) -> text_style_bookmarks::TextStyle { text_style_bookmarks::TextStyle { size, ..style.clone() } diff --git a/crates/engine/src/text_style_bookmarks.rs b/crates/engine/src/text_style_bookmarks.rs index 5969188d67..05ca9223f0 100644 --- a/crates/engine/src/text_style_bookmarks.rs +++ b/crates/engine/src/text_style_bookmarks.rs @@ -60,11 +60,30 @@ struct Line { page: usize, text: String, style: TextStyle, - /// Top, bottom, left and right of its box in user space. + /// Top, bottom, left and right of its box as displayed (after the page's `/Rotate`, y up), so + /// reading order and the join of a heading's lines are right on a turned page. Only + /// differences between these values are used: they are offset from points on the page. top: f64, bottom: f64, left: f64, right: f64, + /// The `/XYZ` position `[left, top]` (user space) that puts the top of the line as displayed + /// at the top of the window. The box edge displayed on top depends on the rotation: the top + /// edge, the left edge (90), the bottom edge (180) or the right edge (270). On a page turned + /// a quarter it is a user-space x, so it is `left`, and `top` stays unspecified. + anchor: [Option; 2], +} + +/// A box in user space `[x0, y0, x1, y1]` on a page turned `rotation` degrees clockwise → its +/// displayed top, bottom, left and right (y up), and the `/XYZ` anchor of its displayed top. +fn displayed(rotation: i64, [x0, y0, x1, y1]: [f64; 4]) -> ([f64; 4], [Option; 2]) { + let (xl, xh, yl, yh) = (x0.min(x1), x0.max(x1), y0.min(y1), y0.max(y1)); + match rotation { + 90 => ([-xl, -xh, yl, yh], [Some(xl), None]), + 180 => ([-yl, -yh, -xh, -xl], [None, Some(yl)]), + 270 => ([xh, xl, -yh, -yl], [Some(xh), None]), + _ => ([yh, yl, xl, xh], [None, Some(yh)]), + } } /// `name` without a subset tag: six capital letters and a `+` (ISO 32000-2 §9.9.2). @@ -79,8 +98,10 @@ fn without_subset_tag(name: &str) -> &str { /// is only whitespace, or whose size can't be read, is left out. fn lines(doc: &Document) -> Vec { let pages = pdfcraft_organize::page_count(doc).unwrap_or(0).min(MAX_PAGES); + let rotations = pdfcraft_organize::page_rotations(doc).unwrap_or_default(); let mut out = Vec::new(); for page in 0..pages { + let rotation = rotations.get(page).copied().unwrap_or(0); let Ok(found) = pdfcraft_edit::text_lines(doc, page) else { continue }; let mut on_page: Vec = found .into_iter() @@ -91,6 +112,7 @@ fn lines(doc: &Document) -> Vec { let size = l.size; let [x0, y0, x1, y1] = l.rect; let ok = !text.is_empty() && size.is_finite() && size > 0.0 && [x0, y0, x1, y1].iter().all(|v| v.is_finite()); + let ([top, bottom, left, right], anchor) = displayed(rotation, l.rect); ok.then(|| Line { page, text, @@ -100,10 +122,11 @@ fn lines(doc: &Document) -> Vec { bold: l.bold, italic: l.italic, }, - top: y0.max(y1), - bottom: y0.min(y1), - left: x0.min(x1), - right: x0.max(x1), + top, + bottom, + left, + right, + anchor, }) }) .collect(); @@ -157,7 +180,7 @@ pub fn styles(doc: &Document) -> Vec { /// The bookmarks for the lines in `levels`' styles: a line in `levels[0]`'s style is a level-1 /// bookmark, `levels[1]`'s a level-2 one under the level-1 bookmark before it, and so on. A /// heading set on several lines (one after another in the same style, close below each other) -/// is one bookmark. Each goes to the top of its heading. +/// is one bookmark. Each goes to the top of its heading as displayed, also on a turned page. pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec { let mut entries: Vec = Vec::new(); // The heading the previous line belonged to: its level, and the top, bottom, left and right @@ -191,13 +214,8 @@ pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec { // The level counts from 1; the position in `levels` is at most its length, which a // caller keeps small (a few levels), so it fits a u8. let level = u8::try_from(level.saturating_add(1)).unwrap_or(u8::MAX); - entries.push(OutlineEntry { - level, - title: line.text.chars().take(MAX_TITLE_CHARS).collect(), - page: line.page, - element: None, - top: Some(line.top), - }); + let [left, top] = line.anchor; + entries.push(OutlineEntry { level, title: line.text.chars().take(MAX_TITLE_CHARS).collect(), page: line.page, element: None, left, top }); } open = Some((level, line.top, line.bottom, line.left, line.right)); } diff --git a/crates/organize/src/lib.rs b/crates/organize/src/lib.rs index 7996ee8ea6..aa498b76a2 100644 --- a/crates/organize/src/lib.rs +++ b/crates/organize/src/lib.rs @@ -160,6 +160,12 @@ pub fn page_rotation(doc: &Document, index: usize) -> Result Ok(resolved_rotation(doc, attrs).rem_euclid(360)) } +/// Effective inherited rotation of every leaf page, clockwise in degrees, from one walk of the +/// page tree (what [`page_rotation`] gives per page). +pub fn page_rotations(doc: &Document) -> Result, OrganizeError> { + Ok(walk(doc)?.iter().map(|(_, attrs)| resolved_rotation(doc, attrs).rem_euclid(360)).collect()) +} + pub fn page_count(doc: &Document) -> Result { Ok(walk(doc)?.len()) } diff --git a/crates/organize/src/outline.rs b/crates/organize/src/outline.rs index e9e20bd9fc..cb54c7b8f1 100644 --- a/crates/organize/src/outline.rs +++ b/crates/organize/src/outline.rs @@ -584,8 +584,12 @@ pub struct OutlineEntry { pub page: usize, /// The structure element it stands for (`/SE`). pub element: Option, - /// Where on the page it goes: this height (user space) at the top of the window, at the - /// reader's zoom. `None` goes to the page, keeping the reader's position. + /// Where on the page it goes: this x (user space) at the left of the window, at the reader's + /// zoom. `None` keeps the reader's horizontal position. + pub left: Option, + /// This height (user space) at the top of the window. `None` keeps the reader's vertical + /// position. A bookmark to the top of what is displayed on a page turned a quarter gives + /// `left`, not `top`. pub top: Option, } @@ -610,7 +614,7 @@ pub fn add_bookmark_tree(doc: &mut Document, parent_title: &str, entries: &[Outl for (e, page) in entries.iter().zip(targets) { let mut d = Dict::new(); d.set(b"Title".to_vec(), Object::String(PdfString::text(&e.title))); - d.set(b"Dest".to_vec(), go_to_at(page, None, e.top)); + d.set(b"Dest".to_vec(), go_to_at(page, e.left, e.top)); if let Some(se) = e.element { d.set(b"SE".to_vec(), Object::Ref(se)); } diff --git a/crates/organize/src/tests.rs b/crates/organize/src/tests.rs index fa240f777f..95c40566b9 100644 --- a/crates/organize/src/tests.rs +++ b/crates/organize/src/tests.rs @@ -14,6 +14,8 @@ fn page_rotation_resolves_inheritance_overrides_and_missing_pages() { assert_eq!(page_rotation(&doc, 1).unwrap(), 270); assert_eq!(page_rotation(&doc, 0).unwrap(), 90); assert_eq!(page_rotation(&doc, 3), Err(OrganizeError::NoSuchPage(3))); + // One walk gives each page's rotation, as the per-page call does. + assert_eq!(crate::page_rotations(&doc).unwrap(), [90, 270, 90]); } #[test] @@ -2000,7 +2002,7 @@ fn bookmarks_add_rename_move_delete() { fn a_bookmark_tree_nests_entries_by_level_under_a_new_first_bookmark() { let mut d = doc_a(); crate::add_bookmark(&mut d, &[], 0, "Existing", 0).unwrap(); - let e = |level, title: &str, page, element| crate::OutlineEntry { level, title: title.into(), page, element, top: None }; + let e = |level, title: &str, page, element| crate::OutlineEntry { level, title: title.into(), page, element, left: None, top: None }; let se = ObjRef::new(4242, 0); let entries = [e(1, "One", 0, Some(se)), e(3, "Deep", 1, None), e(2, "Two", 1, None), e(1, "Next", 2, None)]; assert_eq!(crate::add_bookmark_tree(&mut d, "Untitled", &entries).unwrap(), vec![0]); From df3f58d8b83260742336d7692a82ebbe23cd26c7 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Wed, 18 Nov 2026 07:31:36 +0100 Subject: [PATCH 06/27] Set Page Boxes crops the margin you type on UserUnit pages (#7445) * Convert Set Page Boxes margins by the page UserUnit The dialog's margins are physical (pt, in, mm, cm) but were written as user-space units, so a UserUnit 2 page cropped twice the requested margin. Co-Authored-By: Claude Sonnet 5.5 * Say that page_set_box margins are user-space units Co-Authored-By: Claude Sonnet 5.5 * Print readiness reads page boxes in points; Set Page Boxes batch keeps its wording Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/automation/src/tools.rs | 2 +- crates/engine/src/document.rs | 11 +++ crates/engine/src/printcheck.rs | 29 ++++-- crates/model/src/lib.rs | 5 ++ crates/organize/src/boxes.rs | 3 +- crates/ui-egui/src/dialogs.rs | 3 +- crates/ui-egui/src/dialogs/pageboxes.rs | 114 +++++++++++++++++++++--- crates/ui-egui/src/editing.rs | 2 + 8 files changed, 147 insertions(+), 22 deletions(-) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index e4301f2f23..f0700b735e 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1207,7 +1207,7 @@ pub fn tools() -> Vec { t( "page_set_box", "Set page boxes / crop", - "Set a page box (crop by default; also trim, bleed, art, media) on pages: either margins in points from the media box [left, bottom, right, top], or an absolute rect in points from the top-left of the displayed page. Omit both to reset the box to its default. Undoable.", + "Set a page box (crop by default; also trim, bleed, art, media) on pages: either margins from the media box [left, bottom, right, top] in default user-space units of the unrotated page (not points when the page has /UserUnit), or an absolute rect in points from the top-left of the displayed page. Omit both to reset the box to its default. Undoable.", ) .cmd("page.boxes") .with(schema( diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 8a166330b9..644ca4d54e 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -728,6 +728,17 @@ impl Document { self.editor.as_ref().and_then(|e| pdfcraft_organize::page_boxes(&e.cos).ok()).unwrap_or_default() } + /// Every page's `/UserUnit`: points per user-space unit, read as Acrobat reads it (1 when absent or invalid). + pub fn page_user_units(&self) -> Vec { + self.editor.as_ref().map(|e| pdfcraft_model::pages(&e.cos).iter().map(|p| p.user_unit(&e.cos)).collect()).unwrap_or_default() + } + + /// Page `page`'s `/UserUnit` (see [`Self::page_user_units`]); 1 when there is no such page. + pub fn page_user_unit(&self, page: usize) -> f64 { + let Some(e) = self.editor.as_ref() else { return 1.0 }; + pdfcraft_model::page_at(&e.cos, page).map_or(1.0, |p| p.user_unit(&e.cos)) + } + /// Current value of a document-information entry (Title, Author, …). pub fn info_value(&self, key: &str) -> Option { self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key)) diff --git a/crates/engine/src/printcheck.rs b/crates/engine/src/printcheck.rs index 744e52d4e4..f236370b42 100644 --- a/crates/engine/src/printcheck.rs +++ b/crates/engine/src/printcheck.rs @@ -256,15 +256,18 @@ fn page_reports(doc: &Document, pages: &[pdfcraft_model::Page]) -> Vec Vec { PageTree::new(doc).collect() } +/// Leaf page `index` (0-based), walking the page tree only as far as it. +pub fn page_at(doc: &Document, index: usize) -> Option { + PageTree::new(doc).nth(index) +} + /// Approximate bytes of inherited values copied into leaf dictionaries by one page walk. pub const MAX_INHERITED_COPIES: usize = 1 << 30; diff --git a/crates/organize/src/boxes.rs b/crates/organize/src/boxes.rs index ff56c73f67..f947d2abee 100644 --- a/crates/organize/src/boxes.rs +++ b/crates/organize/src/boxes.rs @@ -48,7 +48,8 @@ pub enum BoxSpec { Remove, /// An absolute rectangle in default user space. Rect([f64; 4]), - /// Margins inward from the media box: left, bottom, right, top (points). + /// Margins inward from the media box: left, bottom, right, top (default user-space units of the + /// unrotated page; points only on a page without `/UserUnit`). Margins([f64; 4]), } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index be9b295ae7..0d98079bc2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2169,7 +2169,8 @@ fn finish_edits(app: &mut PdfCraftApp, dialog: Dialog, req: &mut Pending) { && let Some((i, id)) = app.active_ids() { let count = app.session.get(id).map(|d| d.info.pages.len()).unwrap_or(0); - let edit = app.boxes_draft.edit(app.views[i].current, count); + let units = app.session.get(id).map(|d| d.page_user_units()).unwrap_or_default(); + let edit = app.boxes_draft.edit(app.views[i].current, count, &units); app.apply_edit(edit); app.boxes_draft.seeded = None; } diff --git a/crates/ui-egui/src/dialogs/pageboxes.rs b/crates/ui-egui/src/dialogs/pageboxes.rs index 57b5edc911..b9733e6d5d 100644 --- a/crates/ui-egui/src/dialogs/pageboxes.rs +++ b/crates/ui-egui/src/dialogs/pageboxes.rs @@ -19,7 +19,8 @@ pub enum Range { Pages(usize, usize), } -/// Dialog state. Margins are kept in points: left, bottom, right, top. +/// Dialog state. Margins are kept in physical points (1/72 in): left, bottom, right, top. A page with +/// `/UserUnit` counts each user-space unit as that many points, so they are converted per page. #[derive(Clone, Debug, PartialEq)] pub struct BoxesDraft { pub which: PageBox, @@ -46,13 +47,46 @@ impl BoxesDraft { } } - pub fn edit(&self, current: usize, count: usize) -> Edit { - let spec = - if self.margins.iter().all(|m| *m == 0.0) && self.which != PageBox::Media { BoxSpec::Remove } else { BoxSpec::Margins(self.margins) }; - Edit::SetPageBox { pages: self.pages(current, count), which: self.which, spec } + /// The edit for the draft. `user_units` is each page's `/UserUnit` (points per user-space unit): + /// the margins are physical, the page box is written in user space, so pages with different + /// units get their own margins in one undo step. + pub fn edit(&self, current: usize, count: usize, user_units: &[f64]) -> Edit { + let pages = self.pages(current, count); + if self.margins.iter().all(|m| *m == 0.0) && self.which != PageBox::Media { + return Edit::SetPageBox { pages, which: self.which, spec: BoxSpec::Remove }; + } + let unit_of = |p: usize| user_units.get(p).copied().filter(|u| *u > 0.0).unwrap_or(1.0); + let mut groups: Vec<(f64, Vec)> = Vec::new(); + for p in pages { + let u = unit_of(p); + match groups.iter_mut().find(|(g, _)| *g == u) { + Some((_, v)) => v.push(p), + None => groups.push((u, vec![p])), + } + } + let mut edits: Vec = groups + .into_iter() + .map(|(u, pages)| Edit::SetPageBox { pages, which: self.which, spec: BoxSpec::Margins(self.margins.map(|m| m / u)) }) + .collect(); + if edits.len() == 1 { + return edits.remove(0); + } + // Worded as the single edit is (`Edit::label`), so one undo step reads the same either way. + let label = if self.which == PageBox::Crop { "Crop pages" } else { "Set page boxes" }; + Edit::Batch { label: label.into(), edits } } } +/// The margins (left, bottom, right, top) of `which` inside the media box, in physical points: the +/// page's user-space differences times its `/UserUnit`, so the dialog shows what is written back. +fn margins_of(b: &[[f64; 4]; 5], which: PageBox, user_unit: f64) -> [f64; 4] { + let (m, x) = (b[0], b[box_index(which)]); + if which == PageBox::Media { + return [0.0; 4]; + } + [x[0] - m[0], x[1] - m[1], m[2] - x[2], m[3] - x[3]].map(|v| (v.max(0.0) * user_unit * 100.0).round() / 100.0) +} + fn box_index(b: PageBox) -> usize { match b { PageBox::Media => 0, @@ -69,6 +103,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo let current = app.views[i].current; let Some(doc) = app.session.get(id) else { return (false, true) }; let boxes = doc.page_boxes(); + let page_unit = doc.page_user_unit(current); let count = boxes.len().max(1); let units = app.units; let d = &mut app.boxes_draft; @@ -80,12 +115,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo if d.seeded != Some((current, d.which)) && let Some(b) = boxes.get(current) { - let (m, x) = (b[0], b[box_index(d.which)]); - d.margins = if d.which == PageBox::Media { - [0.0; 4] - } else { - [x[0] - m[0], x[1] - m[1], m[2] - x[2], m[3] - x[3]].map(|v| (v.max(0.0) * 100.0).round() / 100.0) - }; + d.margins = margins_of(b, d.which, page_unit); d.seeded = Some((current, d.which)); } ui.label(egui::RichText::new(tl!("Set Page Boxes")).font(theme::semibold(18.0))); @@ -172,7 +202,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo let page = Rect::from_center_size(r.center(), vec2(w as f32 * s, h as f32 * s)); ui.painter().rect_filled(page, CornerRadius::ZERO, Color32::WHITE); ui.painter().rect_stroke(page, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside); - let [l, bo, ri, to] = d.margins.map(|v| v as f32 * s); + let [l, bo, ri, to] = d.margins.map(|v| (v / page_unit) as f32 * s); let inner = Rect::from_min_max(pos2(page.left() + l, page.top() + to), pos2(page.right() - ri, page.bottom() - bo)); if inner.is_positive() { ui.painter().rect_stroke(inner, CornerRadius::ZERO, Stroke::new(1.5, t.accent), egui::StrokeKind::Middle); @@ -211,8 +241,64 @@ mod tests { assert_eq!(d.pages(2, 5), [2]); d.range = Range::Pages(2, 9); assert_eq!(d.pages(0, 5), [1, 2, 3, 4]); - assert!(matches!(d.edit(0, 5), Edit::SetPageBox { spec: BoxSpec::Remove, .. })); + assert!(matches!(d.edit(0, 5, &[]), Edit::SetPageBox { spec: BoxSpec::Remove, .. })); d.margins = [72.0, 0.0, 0.0, 0.0]; - assert!(matches!(d.edit(0, 5), Edit::SetPageBox { spec: BoxSpec::Margins(_), which: PageBox::Crop, .. })); + assert!(matches!(d.edit(0, 5, &[]), Edit::SetPageBox { spec: BoxSpec::Margins(_), which: PageBox::Crop, .. })); + } + + /// Two pages of 432 x 360 points, the first with `/UserUnit` 1 and the second with 2, opened in a session. + fn session_with_user_units() -> (pdfcraft_engine::Session, pdfcraft_engine::DocId) { + use pdfcraft_cos::{Document as Cos, Object, SaveOptions, write_full}; + let mut session = pdfcraft_engine::Session::new(); + let blank = session.create_blank(432.0, 360.0, 2).unwrap(); + let mut cos = Cos::open(blank).unwrap(); + let second = pdfcraft_model::pages(&cos)[1].obj; + cos.update_dict(second, |d| d.set(b"UserUnit".to_vec(), Object::Int(2))).unwrap(); + let bytes = write_full(&cos, &SaveOptions::default()).unwrap(); + let id = session.open_new("units.pdf", std::sync::Arc::new(bytes)).unwrap(); + (session, id) + } + + /// #7414: half an inch is 36 physical points, whatever the page's `/UserUnit`. + #[test] + fn physical_margins_are_converted_by_each_pages_user_unit() { + let (mut session, id) = session_with_user_units(); + let units = session.get(id).unwrap().page_user_units(); + assert_eq!(units, [1.0, 2.0]); + let mut d = BoxesDraft { which: PageBox::Crop, margins: [36.0; 4], range: Range::Current, ..Default::default() }; + session.apply(id, d.edit(1, 2, &units)).unwrap(); + let b = session.get(id).unwrap().page_boxes(); + assert_eq!(b[1][1], [18.0, 18.0, 414.0, 342.0], "UserUnit 2: 36 points are 18 user units"); + assert_eq!(b[0][1], [0.0, 0.0, 432.0, 360.0], "the page outside the range is untouched"); + d.range = Range::Pages(1, 1); + session.apply(id, d.edit(0, 2, &units)).unwrap(); + assert_eq!(session.get(id).unwrap().page_boxes()[0][1], [36.0, 36.0, 396.0, 324.0], "UserUnit 1 keeps the margin as typed"); + } + + #[test] + fn pages_with_different_user_units_get_their_own_margins_in_one_step() { + let (mut session, id) = session_with_user_units(); + let units = session.get(id).unwrap().page_user_units(); + let d = BoxesDraft { which: PageBox::Crop, margins: [36.0; 4], range: Range::All, ..Default::default() }; + session.apply(id, d.edit(0, 2, &units)).unwrap(); + let doc = session.get(id).unwrap(); + let b = doc.page_boxes(); + assert_eq!(b[0][1], [36.0, 36.0, 396.0, 324.0]); + assert_eq!(b[1][1], [18.0, 18.0, 414.0, 342.0]); + assert_eq!(doc.can_undo(), Some("Crop pages")); + session.undo(id).unwrap(); + let b = session.get(id).unwrap().page_boxes(); + assert_eq!(b[0][1], [0.0, 0.0, 432.0, 360.0], "one undo restores page 1"); + assert_eq!(b[1][1], [0.0, 0.0, 432.0, 360.0], "and page 2"); + } + + #[test] + fn the_dialog_shows_the_saved_margins_in_physical_points() { + let (session, id) = session_with_user_units(); + let doc = session.get(id).unwrap(); + let mut boxes = doc.page_boxes()[1]; + boxes[1] = [18.0, 18.0, 414.0, 342.0]; + assert_eq!(margins_of(&boxes, PageBox::Crop, 2.0), [36.0; 4], "18 user units on a UserUnit 2 page are half an inch"); + assert_eq!(margins_of(&boxes, PageBox::Media, 2.0), [0.0; 4]); } } diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index cd61e82e43..3b641e8e3f 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -115,6 +115,8 @@ fn select_after_edit( // A group moved together stays selected (its positions don't change), so it // can be moved or copied again; anything else in a batch clears the selection. Edit::Batch { edits, .. } if edits.iter().all(|e| matches!(e, Edit::MoveAnnotation { .. })) => {} + // Set Page Boxes over pages with different /UserUnit is a batch too; like one SetPageBox it keeps the selection. + Edit::Batch { edits, .. } if edits.iter().all(|e| matches!(e, Edit::SetPageBox { .. })) => {} Edit::Batch { .. } => view.comments.clear_selection(), // The copies the paste added (and nothing that was there before): select them all. Edit::PasteComments { page, .. } => { From 9db6c9d95cdb9191e143a918e97d733c6384184a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 01:55:16 -0500 Subject: [PATCH 07/27] fix(xfdf): bound field text, look up names, guard tab cells, protect fields (#5937) * fix(xfdf): bound field text, look up names, guard tab cells, protect fields XFDF import built every full field name from its parent's with no total; it is held to 64 MiB of names and values. FDF field arrays charge each decoded value before keeping it instead of after decoding all of them. merge_csv, XFDF field export and apply_values looked names up by linear scan per field; they use maps, keeping first-match behaviour. Tab-delimited export guards formula-like cells with a leading ' as CSV does, and import takes it off. A same-name comment import no longer replaces a widget whose subtype is a reference or whose /FT is inherited from its parent, existing annotations are borrowed instead of deep-copied per import, and an imported redaction mark's /Rect is grown to hold its /QuadPoints so nothing is removed outside its review outline. * address review: follow /Parent 64 levels in is_field --- crates/xfdf/src/common.rs | 43 +++++++++++--- crates/xfdf/src/fdf.rs | 25 +++++--- crates/xfdf/src/lib.rs | 20 +++++-- crates/xfdf/src/tests.rs | 121 ++++++++++++++++++++++++++++++++++++++ crates/xfdf/src/xfdf.rs | 63 ++++++++++++++++---- 5 files changed, 243 insertions(+), 29 deletions(-) diff --git a/crates/xfdf/src/common.rs b/crates/xfdf/src/common.rs index 904ea4f3fc..87559b5c16 100644 --- a/crates/xfdf/src/common.rs +++ b/crates/xfdf/src/common.rs @@ -8,6 +8,9 @@ use super::{DataError, Dict, Document, Object}; const MAX_NODES: u32 = 2_000_000; pub(crate) const MAX_DEPTH: usize = 64; +/// Most bytes of full field names and values one XFDF import expands to: a long parent name is +/// written into every descendant's full name, so a small file can name far more than it holds. +pub(crate) const MAX_XFDF_TEXT: usize = 64 << 20; /// The deepest element nesting accepted before the text reaches the XML parser. /// @@ -253,26 +256,52 @@ pub(crate) fn xml_name(name: &str) -> String { s } -pub(crate) fn walk_xfdf(node: &craft_xml::El, prefix: &str, out: &mut Vec<(String, Vec)>, depth: usize) -> Result<(), DataError> { +pub(crate) fn walk_xfdf( + node: &craft_xml::El, + prefix: &str, + out: &mut Vec<(String, Vec)>, + depth: usize, + bytes: &mut usize, +) -> Result<(), DataError> { if depth > MAX_DEPTH { return Err(DataError::Malformed(format!("XFDF fields nest more than {MAX_DEPTH} deep"))); } for f in node.children(craft_xml::Local("field")) { let Some(name) = f.attr("name") else { continue }; + // Charge temporary parent names too, before allocation/recursion can amplify them. + let full_len = if prefix.is_empty() { name.len() } else { prefix.len().saturating_add(1).saturating_add(name.len()) }; + charge_xfdf_text(bytes, full_len)?; let full = if prefix.is_empty() { name.to_string() } else { format!("{prefix}.{name}") }; - let vals: Vec = f - .children(craft_xml::Local("value")) - // Comments and processing instructions can split a value into several text nodes. - .map(el_text) - .collect(); + let mut vals = Vec::new(); + for value in f.children(craft_xml::Local("value")) { + let len = value + .children + .iter() + .filter_map(|n| match n { + craft_xml::Node::Text(t) => Some(t.len()), + _ => None, + }) + .fold(0, usize::saturating_add); + charge_xfdf_text(bytes, len)?; + vals.push(el_text(value)); + } // A leaf with no `` is an empty field (the export writes one that way), so it // clears the field like FDF's `/V ()`; a field with kids only names their parent. A // leaf holding only `` is not read yet, so it leaves the field alone. let names_kids_or_rich = f.elements().any(|c| matches!(c.local(), "field" | "value-richtext")); if !vals.is_empty() || !names_kids_or_rich { + charge_xfdf_text(bytes, full.len())?; // The emitted name is a second owned copy. out.push((full.clone(), vals)); } - walk_xfdf(f, &full, out, depth + 1)?; + walk_xfdf(f, &full, out, depth + 1, bytes)?; + } + Ok(()) +} + +fn charge_xfdf_text(bytes: &mut usize, amount: usize) -> Result<(), DataError> { + *bytes = bytes.saturating_add(amount); + if *bytes > MAX_XFDF_TEXT { + return Err(DataError::Malformed(format!("the file expands to more than {} MiB of field names and values", MAX_XFDF_TEXT >> 20))); } Ok(()) } diff --git a/crates/xfdf/src/fdf.rs b/crates/xfdf/src/fdf.rs index 6c2f169931..28d79b3c0b 100644 --- a/crates/xfdf/src/fdf.rs +++ b/crates/xfdf/src/fdf.rs @@ -476,16 +476,27 @@ pub(crate) fn walk_fdf( let full = if prefix.is_empty() { t } else { format!("{prefix}.{t}") }; budget.spend(0, full.len())?; if let Some(v) = d.get(b"V").map(|v| fdf.resolve(v)) { - let vals: Vec = match &*v { - Object::String(s) => vec![s.to_text()], - Object::Name(n) => vec![pdfcraft_forms::name_text(n)], + // Each value is charged as it is decoded, before the next: an array of references to + // one long string is not decoded whole and then refused. + let mut vals: Vec = Vec::new(); + let keep = |vals: &mut Vec, s: String, budget: &mut ImportBudget| -> Result<(), DataError> { + budget.spend(1, s.len())?; + vals.push(s); + Ok(()) + }; + match &*v { + Object::String(s) => keep(&mut vals, s.to_text(), budget)?, + Object::Name(n) => keep(&mut vals, pdfcraft_forms::name_text(n), budget)?, Object::Array(a) => { budget.spend(a.len(), 0)?; - a.iter().filter_map(|x| fdf.resolve(x).as_string().map(|s| s.to_text())).collect() + for x in a { + if let Some(s) = fdf.resolve(x).as_string() { + keep(&mut vals, s.to_text(), budget)?; + } + } } - _ => Vec::new(), - }; - budget.spend(vals.len(), vals.iter().map(String::len).fold(0, usize::saturating_add))?; + _ => {} + } out.push((full.clone(), vals)); } if let Some(kids) = d.get(b"Kids").map(|k| fdf.resolve(k)) diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index a3c600c220..fc6d77ac43 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -138,7 +138,11 @@ pub fn export_data(doc: &Document, format: Format) -> String { ) } _ => { - let clean = |s: &str| s.replace(['\t', '\n', '\r'], " "); + // A formula-like cell gets a leading `'`, as in CSV; `tab_delimited` takes it off. + let clean = |s: &str| { + let s = if csv_guarded(s) { format!("'{s}") } else { s.to_string() }; + s.replace(['\t', '\n', '\r'], " ") + }; format!( "{}\n{}\n", fields.iter().map(|f| clean(&f.0)).collect::>().join("\t"), @@ -184,7 +188,7 @@ pub fn data_values(bytes: &[u8]) -> Result)>, DataError } let mut values = Vec::new(); if let Some(fields) = root.child(craft_xml::Local("fields")) { - walk_xfdf(fields, "", &mut values, 0)?; + walk_xfdf(fields, "", &mut values, 0, &mut 0)?; } Ok(values) } @@ -197,9 +201,10 @@ pub fn data_values(bytes: &[u8]) -> Result)>, DataError /// is written with a leading `'`, which keeps it text; a plain number such as `-12.5` is not. pub fn merge_csv(files: &[Vec<(String, Vec)>]) -> String { let mut columns: Vec<&str> = Vec::new(); + let mut known: HashSet<&str> = HashSet::new(); for f in files { for (k, _) in f { - if !columns.contains(&k.as_str()) { + if known.insert(k.as_str()) { columns.push(k); } } @@ -218,7 +223,12 @@ pub fn merge_csv(files: &[Vec<(String, Vec)>]) -> String { let mut out = columns.iter().map(|c| q(c)).collect::>().join(","); out.push('\n'); for f in files { - let row: Vec = columns.iter().map(|c| f.iter().find(|(k, _)| k == c).map_or(String::new(), |(_, v)| q(&v.join(", ")))).collect(); + // The first value of a name repeated in one file wins, as the scan it replaces found it. + let mut by_name: HashMap<&str, &Vec> = HashMap::new(); + for (k, v) in f { + by_name.entry(k.as_str()).or_insert(v); + } + let row: Vec = columns.iter().map(|c| by_name.get(c).map_or(String::new(), |v| q(&v.join(", ")))).collect(); out.push_str(&row.join(",")); out.push('\n'); } @@ -342,7 +352,7 @@ fn import_table(doc: &mut Document, text: &str) -> Result { fn tab_delimited(t: &str) -> Result)>, DataError> { let mut lines = t.lines(); let (Some(head), Some(row)) = (lines.next(), lines.next()) else { return Err(DataError::UnknownFormat) }; - Ok(head.split('\t').map(str::to_string).zip(row.split('\t')).map(|(k, v)| (k, vec![v.to_string()])).collect()) + Ok(head.split('\t').map(|k| csv_text(k.to_string())).zip(row.split('\t')).map(|(k, v)| (k, vec![csv_text(v.to_string())])).collect()) } /// Import comments and/or field values from XFDF, FDF, XML, CSV or tab-delimited text diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs index 401849afcf..f9e97cf3bf 100644 --- a/crates/xfdf/src/tests.rs +++ b/crates/xfdf/src/tests.rs @@ -2267,6 +2267,100 @@ fn an_fdf_comment_popup_without_a_rect_is_dropped() { assert_eq!(popups, 0); } +/// Tab-delimited export guards a formula-like cell as CSV does, and the import takes the guard +/// off, so a spreadsheet never runs form data and the value survives the round trip. +#[test] +fn tab_delimited_export_guards_formula_cells_and_round_trips() { + let mut doc = blank(); + set_value(&mut doc, "Name", &FieldValue::Text("=SUM(A1:A9)".into())).unwrap(); + let text = export_data(&doc, Format::Txt); + let row = text.lines().nth(1).unwrap(); + assert!(row.starts_with("'=SUM(A1:A9)"), "{row:?}"); + let mut again = blank(); + import(&mut again, text.as_bytes()).unwrap(); + assert_eq!(values(&again).iter().find(|(k, _)| k == "Name").map(|(_, v)| v.clone()), Some(vec!["=SUM(A1:A9)".to_string()])); +} + +/// Merging many files with many distinct names stays linear: every column once, in first-seen +/// order, and a row looks its names up rather than scanning them. +#[test] +fn merge_csv_lists_each_column_once_in_order() { + let files: Vec)>> = + (0..3).map(|f| (0..4).map(|i| (format!("c{}", (i + f) % 5), vec![format!("{f}-{i}")])).collect()).collect(); + let csv = merge_csv(&files); + let mut lines = csv.lines(); + assert_eq!(lines.next(), Some("c0,c1,c2,c3,c4")); + assert_eq!(lines.next(), Some("0-0,0-1,0-2,0-3,")); + assert_eq!(lines.next(), Some(",1-0,1-1,1-2,1-3")); + assert_eq!(lines.next(), Some("2-3,,2-0,2-1,2-2")); +} + +/// A long parent name is written into every descendant's full name: past the import's text +/// bound the file is refused rather than expanded. +#[test] +fn xfdf_field_names_past_the_text_bound_are_refused() { + let parent = "p".repeat(1 << 20); + let kids: String = (0..100).map(|i| format!("v")).collect(); + let xfdf = + format!("{kids}"); + let mut doc = blank(); + match import(&mut doc, xfdf.as_bytes()) { + Err(DataError::Malformed(m)) => assert!(m.contains("64 MiB"), "{m}"), + other => panic!("{other:?}"), + } +} + +/// A same-name import never replaces a widget whose field type is inherited, or whose subtype is +/// written as a reference: the field keeps its dictionary and the import goes beside it. +#[test] +fn same_name_import_keeps_a_widget_with_an_inherited_field_type() { + let mut doc = blank(); + let page = pdfcraft_model::pages(&doc)[0].obj; + // A field with one widget kid: /FT on the field, the widget names it as /Parent. + let mut field = Dict::new(); + field.set(b"FT".to_vec(), Object::name("Tx")); + field.set(b"T".to_vec(), Object::String(PdfString::text("inherited"))); + let field = doc.add(field); + let subtype = doc.add(Object::name("Widget")); + let mut widget = Dict::new(); + widget.set(b"Type".to_vec(), Object::name("Annot")); + widget.set(b"Subtype".to_vec(), Object::Ref(subtype)); + widget.set(b"Rect".to_vec(), arr(&[10.0, 10.0, 60.0, 30.0])); + widget.set(b"NM".to_vec(), Object::String(PdfString::text("w1"))); + widget.set(b"Parent".to_vec(), Object::Ref(field)); + let widget = doc.add(widget); + doc.update_dict(field, |d| d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(widget)]))).unwrap(); + doc.update_dict(page, |p| p.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(widget)]))).unwrap(); + let mut note = Dict::new(); + note.set(b"Type".to_vec(), Object::name("Annot")); + note.set(b"Subtype".to_vec(), Object::name("Text")); + note.set(b"Rect".to_vec(), arr(&[10.0, 10.0, 30.0, 30.0])); + note.set(b"NM".to_vec(), Object::String(PdfString::text("w1"))); + let added = xfdf::place(&mut doc, page, note).unwrap(); + assert_ne!(added, widget); + assert_eq!(doc.get(widget).as_dict().unwrap().name(b"Type"), Some(b"Annot".as_slice())); + assert!(doc.get(widget).as_dict().unwrap().reference(b"Parent").is_some(), "the widget was replaced"); + let annots = doc.get(page).as_dict().unwrap().get(b"Annots").unwrap().as_array().unwrap().len(); + assert_eq!(annots, 2); +} + +#[test] +fn a_field_type_up_to_64_parents_away_protects_the_annotation() { + // the forms crate follows /Parent 64 levels: so does the import's protection check + let mut doc = blank(); + let mut top = Dict::new(); + top.set(b"FT".to_vec(), Object::name("Tx")); + let mut parent = doc.add(Object::Dict(top)); + for _ in 0..40 { + let mut d = Dict::new(); + d.set(b"Parent".to_vec(), Object::Ref(parent)); + parent = doc.add(Object::Dict(d)); + } + let mut annot = Dict::new(); + annot.set(b"Parent".to_vec(), Object::Ref(parent)); + assert!(crate::xfdf::is_field(&doc, &annot)); +} + /// A check box field whose two kids have the on states `A` and `B`. fn check_box_kids() -> Document { let objs = [ @@ -2641,3 +2735,30 @@ fn copies_keep_their_intent_cloud_and_pdfcraft_keys() { assert_eq!(got[0].name(b"Subtype"), Some(b"Square".as_slice()), "not taken from the attribute"); assert!(got[0].get(b"PCRef").is_none() && got[1].get(b"PCAngle").is_none(), "{got:?}"); } + +#[test] +fn xfdf_charges_non_emitted_parent_names_before_recursing() { + let fields = common::parse_form_xml("").unwrap(); + let mut out = Vec::new(); + let mut bytes = common::MAX_XFDF_TEXT - 5; + assert!(walk_xfdf(&fields, "", &mut out, 0, &mut bytes).is_err()); + assert!(out.is_empty()); + let mut bytes = common::MAX_XFDF_TEXT - 6; + walk_xfdf(&fields, "", &mut out, 0, &mut bytes).unwrap(); + assert_eq!(bytes, common::MAX_XFDF_TEXT); +} + +#[test] +fn xfdf_charges_split_text_before_copying_values() { + let fields = common::parse_form_xml("abc").unwrap(); + let mut out = Vec::new(); + let mut bytes = common::MAX_XFDF_TEXT - 3; + assert!(walk_xfdf(&fields, "", &mut out, 0, &mut bytes).is_err()); + assert!(out.is_empty()); +} + +#[test] +fn merge_csv_keeps_first_repeated_value() { + let rows = vec![("Name".into(), vec!["first".into()]), ("Name".into(), vec!["second".into()])]; + assert_eq!(merge_csv(&[rows]), "Name\nfirst\n"); +} diff --git a/crates/xfdf/src/xfdf.rs b/crates/xfdf/src/xfdf.rs index 720e5bb9be..77bc92e60c 100644 --- a/crates/xfdf/src/xfdf.rs +++ b/crates/xfdf/src/xfdf.rs @@ -562,6 +562,8 @@ fn xfdf_fields(doc: &Document, out: &mut String) { struct Node { values: Vec, kids: Vec<(String, Node)>, + /// Each child's place in `kids`, by name: a wide level is not scanned per field. + index: std::collections::HashMap, } let mut root = Node::default(); for f in pdfcraft_forms::fields(doc) { @@ -576,10 +578,11 @@ fn xfdf_fields(doc: &Document, out: &mut String) { // the last level stay together in the deepest element's name, and the import joins them // back with periods into the same full name. for part in f.name.splitn(MAX_DEPTH, '.') { - let i = match node.kids.iter().position(|(k, _)| k == part) { - Some(i) => i, + let i = match node.index.get(part) { + Some(&i) => i, None => { node.kids.push((part.to_string(), Node::default())); + node.index.insert(part.to_string(), node.kids.len() - 1); node.kids.len() - 1 } }; @@ -846,8 +849,13 @@ pub fn export_xfdf(doc: &Document, comments: bool, fields: bool, file: &str) -> /// Set the values of fields named in `values` (full names), counting what took. pub(crate) fn apply_values(doc: &mut Document, values: &[(String, Vec)], report: &mut Report) { let all = pdfcraft_forms::fields(doc); + // The first field of a name, as the scan it replaces found it. + let mut by_name: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for (i, f) in all.iter().enumerate() { + by_name.entry(f.name.as_str()).or_insert(i); + } for (name, vals) in values { - let Some(f) = all.iter().find(|f| &f.name == name) else { continue }; + let Some(f) = by_name.get(name.as_str()).and_then(|&i| all.get(i)) else { continue }; let first = vals.first().cloned().unwrap_or_default(); let v = match f.kind { FieldKind::Text => FieldValue::Text(first), @@ -1065,7 +1073,27 @@ pub(crate) const LOCKED: i64 = 128; /// widget or field (replacing it would set the field's value and policy around the form setter). fn import_protected(doc: &Document, x: &Dict) -> bool { let flags = x.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0); - flags & LOCKED != 0 || matches!(x.name(b"Subtype"), Some(b"Redact" | b"Widget")) || x.contains(b"FT") + let subtype = x.get(b"Subtype").map(|s| doc.resolve(s)); + flags & LOCKED != 0 || matches!(subtype.as_deref().and_then(Object::as_name), Some(b"Redact" | b"Widget")) || is_field(doc, x) +} + +/// Whether `x` is a form field or a widget of one: it has `/FT`, or a `/Parent` up the field +/// tree does (a widget inherits its field's type). +pub(crate) fn is_field(doc: &Document, x: &Dict) -> bool { + if x.contains(b"FT") { + return true; + } + let mut parent = x.reference(b"Parent"); + let mut seen = std::collections::HashSet::new(); + while let Some(r) = parent.filter(|r| seen.len() < 64 && seen.insert(*r)) { + let o = doc.get(r); + let Some(d) = o.as_dict() else { return false }; + if d.contains(b"FT") { + return true; + } + parent = d.reference(b"Parent"); + } + false } pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result { @@ -1090,7 +1118,19 @@ pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result let (quads, rest) = v.as_chunks::<8>(); v.len() == q.len() && rest.is_empty() && !quads.is_empty() && quads.iter().all(quad_has_area) }); - if !quads_drawable { + if quads_drawable { + // The rectangle holds all the mark removes: its review outline is clipped to the + // rectangle, so a quad outside it would be removed unseen. + let v: Vec = d.get(b"QuadPoints").and_then(Object::as_array).into_iter().flatten().filter_map(Object::as_f64).collect(); + let mut r = rect_strict(doc, d.get(b"Rect")) + .map_or([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |[x0, y0, x1, y1]| { + [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)] + }); + for [x, y] in v.as_chunks::<2>().0 { + r = [r[0].min(*x), r[1].min(*y), r[2].max(*x), r[3].max(*y)]; + } + d.set(b"Rect".to_vec(), arr(&r)); + } else { // Quads the outline can't draw, or any quad that encloses no area, are replaced by the // /Rect's, or dropped when there is no usable /Rect either; such a mark then removes // nothing. @@ -1144,9 +1184,11 @@ pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result // and add the imported dict beside it under no name of its own. let mut clash = false; for a in annots { - let existing = a.as_ref().and_then(|r| doc.get(r).as_dict().cloned()); - let same = nm.is_some() && existing.as_ref().and_then(|x| x.get(b"NM").and_then(|n| doc.resolve(n).as_string().map(|s| s.to_text()))) == nm; - if same && existing.as_ref().is_some_and(|x| import_protected(doc, x)) { + // Borrowed: the page's annotations are read once per imported one, never copied. + let held = a.as_ref().map(|r| doc.get(r)); + let existing = held.as_deref().and_then(Object::as_dict); + let same = nm.is_some() && existing.and_then(|x| x.get(b"NM").and_then(|n| doc.resolve(n).as_string().map(|s| s.to_text()))) == nm; + if same && existing.is_some_and(|x| import_protected(doc, x)) { clash = true; kept.push(a); } else if same { @@ -1160,7 +1202,8 @@ pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result } // The replaced note's pop-up goes with it; otherwise it stays on the page pointing at a note that is no longer there. kept.retain(|a| { - let Some(x) = a.as_ref().map(|r| doc.get(r)).and_then(|o| o.as_dict().cloned()) else { return true }; + let Some(held) = a.as_ref().map(|r| doc.get(r)) else { return true }; + let Some(x) = held.as_dict() else { return true }; x.name(b"Subtype") != Some(b"Popup".as_slice()) || x.reference(b"Parent").is_none_or(|p| !removed.contains(&p)) }); // Keep the replaced comment's identity: replies and review statuses not included in a @@ -1347,7 +1390,7 @@ pub(crate) fn import_xfdf_with( // Fields. if let Some(fields) = root.child(craft_xml::Local("fields")) { let mut values = Vec::new(); - walk_xfdf(fields, "", &mut values, 0)?; + walk_xfdf(fields, "", &mut values, 0, &mut 0)?; apply_values(doc, &values, &mut report); } Ok(report) From 4448ee940b27735634c3073a2a8d44866f3049cd Mon Sep 17 00:00:00 2001 From: Yousef <48837178+Yousef-Dev921@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:27:08 +0300 Subject: [PATCH 08/27] fix(ui): mirror the macOS title bar when the traffic lights are on the right (RTL system languages) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this changes On macOS with a **right-to-left system language** (Arabic, Hebrew, Persian, …) AppKit lays the traffic lights out from the **right** end of the title bar. That happens even though PdfCraft has no right-to-left localization, and whatever PdfCraft's own interface language is (I checked 0.8.0 in English on an Arabic system: same result). The integrated tab strip (#789 / #1055) always kept its clearance on the left. So: - the lights covered the **theme** and **keyboard-shortcuts** buttons and crowded **Discord**, so they couldn't be clicked; - Home sat beside an empty 70 pt gap where the lights would have been. Before (0.8.0, Arabic system language): | | Strip | |---|---| | Expected left-to-right design | `[● ● ●] [Home] [tabs…] [+ Open] ……… [Discord] [?] [theme]` | | 0.8.0, RTL system | `[ 70 pt gap ] [Home] [+ Open] ……… [Discord] [?][theme] under [● ● ●]` | | This PR, RTL system | `[theme] [?] [Discord] ……… [Open +] [tabs…] [Home] [● ● ●]` | The fix: 1. **Ask the window which side the lights are on** instead of guessing from a language: `NSWindow.windowTitlebarLayoutDirection`, which Apple documents for apps that use `titlebarAppearsTransparent` and put controls under the title bar ("the layout direction may be RTL even in applications that do not have a RTL language localization"). Safe `objc2-app-kit` calls only (same approach as `drag_pointer.rs`), on the main thread, cached in `PdfCraftApp::titlebar_lights_right` once a window has answered. The new features (`NSApplication`, `NSResponder`, `NSWindow`, `NSUserInterfaceLayout`) are already in the tree through winit/rfd, except the empty `NSUserInterfaceLayout` feature. 2. **Mirror the strip** when they are on the right, so the existing design holds with the lights at the other end: Home beside the lights, the tabs reading from the right (the first tab beside Home), then Open; Discord, shortcuts and theme at the far end, in mirrored order. The scroll arrows keep their visual sides. - egui's `ScrollArea` only scrolls content that grows to the right, so mirrored, the tabs keep a left-to-right scroll area inside a box exactly their width (`tabs_shown_width`), set beside Home. - Tab dragging (#1537) reads the slots in reading order with x flipped (`reading_order`), so `drop_index` and `drop_marker` serve both directions unchanged. - The Combine files tab block moved into `combine_tab()` (unchanged behaviour) so it can be drawn first when mirrored and still read last. Left-to-right systems, Windows, Linux (including the GNOME header bar) and the web are unchanged: everything new hangs off `mirrored`, which is only true on macOS with the integrated title bar and lights on the right. ## How you verified it - [x] `cargo fmt --check` - [x] `cargo clippy -p pdfcraft-ui-egui --all-targets -- -D warnings`: clean. With Rust 1.95, `main` itself trips `clippy::collapsible_match` in `crates/edit/src/images.rs` and `clippy::nonminimal_bool` in `crates/ui-egui/src/compare_ui.rs`, files this PR doesn't touch, so the run allowed those two lints; a separate pass with them as warnings finds them only there. - [x] `cargo test -p pdfcraft-ui-egui --no-fail-fast`: 2,911 passed, 0 failed, after the rebase on `main` (`d749fd80`, 2026-11-12) on Windows 11; `pdfcraft-cli` + `pdfcraft`: 198 passed. The rebase moved the mirrored drag into `main`'s new `tab_drag`, which split view's strips share: the main strip passes `mirrored`, the second pane's strip does not. The macOS tests below run only on macOS; on Windows I ran them with the macOS gate lifted locally (not committed): they pass, and with the scrolling fix switched off its test fails. - [x] `cargo xtask layers` and `cargo xtask assets` New tests (macOS, `crates/ui-egui/tests/ui.rs`): - `the_integrated_title_bar_mirrors_with_traffic_lights_at_the_right`: everything stays in the 28 pt band and clear of the lights; Home is beside the lights, the tabs read from the right, then Open; theme, shortcuts and Discord are at the far left in mirrored order. - `dragging_a_tab_in_the_mirrored_title_bar_follows_its_reading_order`: dragging left moves a tab later in the order, and dragging right moves it earlier. Unit tests in `chrome.rs`: `mirrored_tabs_drop_in_their_reading_order`, `shown_tabs_take_their_capped_widths_and_the_gaps`. **Seen failing before the fix:** with mirroring switched off, both UI tests fail. With only the x-flip removed, the drag test fails and the layout test passes, so each test pins its own part. Checked by eye on macOS with an Arabic system language: the real app (dev build, portable mode, three sample PDFs) shows `[theme][?][Discord] … [فتح +][third][second][first][Home][● ● ●]`, with nothing under the lights. ## Never-crash - [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests - [x] No indexing with input-derived positions (the tab loop indexes `app.views` with indices from `0..len`, as before) - [x] No `unsafe`: the AppKit calls are safe methods in `objc2-app-kit` 0.3; `MainThreadMarker::new()` returns `None` off the main thread, and a missing window returns `None` (then the strip stays as it was and asks again next frame) - [x] No crash fixed here ## Provenance - [x] No asset from an Adobe product - [x] No font files - [x] No GPL/AGPL code - [x] Behaviour from Apple's public AppKit documentation and black-box observation of PdfCraft itself - [x] No new assets ## Security - [x] `--root` confinement untouched - [x] MCP and the control channel untouched - [x] No network access ## Parity and reach - [ ] `parity/`: not applicable (a layout fix, not a feature) - [ ] `automation` tool: not applicable (window chrome) - [x] Docs: no documented behaviour changes ## Anything a reviewer should look at first - **Mirroring follows the lights, not the interface language.** The rest of the app isn't mirrored for RTL languages, so mirroring only the title bar could look like a partial RTL mode. But the title bar's order is anchored to the lights (Home beside them is the #789 design), and AppKit picks their side from the system language, not ours. Tying it to `windowTitlebarLayoutDirection` also covers an English UI on an Arabic system. - **Overflowing tabs when mirrored:** the scroll area still starts at offset 0, its left end, which holds the last tabs. The active tab is scrolled into view on every change (as before), so it's always visible, but at startup with many tabs the first ones (beside Home) may start out of view. Starting it scrolled to the right end would need the content width before the first frame; I left that out to keep this small. Happy to add it. - **A flaky test I saw locally:** `files_and_quit_from_the_operating_system` failed 3 times in ~40 full `--test ui` runs while the machine was also building and running the app, then 0/20 on a quiet machine, both with and without this change. It opens a file on the open worker and waits a fixed 4 frames, so it looks timing-sensitive under load rather than related to this change. - Also adds my own entry to `contributors/people.toml` (separate commit, `sync_github_name = true`). --- contributors/people.toml | 3 + crates/ui-egui/Cargo.toml | 7 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/chrome.rs | 255 +++++++++++++++++++++++++++------- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/tests/it/ui.rs | 107 ++++++++++++++ 6 files changed, 325 insertions(+), 51 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 06c98f6464..a150fe5276 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -194,3 +194,6 @@ sync_github_name = false [people.enriquemelzer-bit] sync_github_name = true + +[people.Yousef-Dev921] +sync_github_name = true diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index cca968360b..d77cd62188 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -68,10 +68,11 @@ pollster = "1.0" fontconfig-parser = "0.5.8" [target.'cfg(target_os = "macos")'.dependencies] -# Safe AppKit calls for drag coordinates and repairing an existing per-file PDFCraft binding. -# The Objective-C wrappers and block support are already in the tree through arboard and rfd. +# Safe AppKit calls for drag coordinates, which end of the title bar the traffic lights are at, and +# repairing an existing per-file PDFCraft binding. The Objective-C wrappers and block support are +# already in the tree through arboard and rfd. objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSEvent", "NSScreen", "NSWorkspace", "block2"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSEvent", "NSResponder", "NSScreen", "NSUserInterfaceLayout", "NSWindow", "NSWorkspace", "block2"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry", "NSBundle", "NSURL", "NSString", "NSError"] } block2 = "0.6" plist = "1.10" diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 3e75cbb5a6..aa6f2224e1 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -188,6 +188,7 @@ impl PdfCraftApp { script_messages_dropped: 0, toast_dropped: 0, integrated_titlebar: false, + titlebar_lights_right: None, window_controls: None, system_title_bar: false, app_frame_shown: None, diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 4cc264e7dc..4c632d39e7 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -22,13 +22,33 @@ const MAC_LIGHT: f32 = 12.0; const MAC_LIGHT_PITCH: f32 = 20.0; const MAC_LIGHTS_LEFT: f32 = 10.0; /// Where the strip's content starts to the right of the traffic lights: the end of the three -/// lights plus the same gap the lights keep from the top of the window. +/// lights plus the same gap the lights keep from the top of the window. Mirrored, it is where the +/// content ends when the lights are at the right. pub const MAC_CONTENT_LEFT: f32 = MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT + (MAC_TITLE_BAR - MAC_LIGHT) / 2.0; + /// The strip and its controls everywhere else. const TAB_STRIP: f32 = 38.0; const TAB_HEIGHT: f32 = 30.0; const STRIP_BUTTON: f32 = 28.0; +/// Whether AppKit lays the traffic lights out from the right end of the title bar, or `None` when +/// no window can say yet. It does when the system language is right-to-left, whatever PdfCraft's +/// own interface language is, so the window is asked rather than the interface language +/// (Apple: `NSWindow.windowTitlebarLayoutDirection`, for apps with controls under the title bar). +#[cfg(target_os = "macos")] +fn mac_lights_on_right() -> Option { + use objc2_app_kit::{NSApplication, NSUserInterfaceLayoutDirection}; + // AppKit's window list is only for the main thread (where egui runs). + let mtm = objc2::MainThreadMarker::new()?; + let window = NSApplication::sharedApplication(mtm).windows().firstObject()?; + Some(window.windowTitlebarLayoutDirection() == NSUserInterfaceLayoutDirection::RightToLeft) +} + +#[cfg(not(target_os = "macos"))] +fn mac_lights_on_right() -> Option { + None +} + /// Draw the window's tab strip: home and open controls, shrinkable and scrollable document tabs with drag /// reordering, and platform window controls. pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { @@ -36,11 +56,27 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { // macOS: the strip is the 28 pt title bar, so the traffic lights are centred in it; tabs and // buttons shrink to keep a margin above and below. let mac = cfg!(target_os = "macos") && app.integrated_titlebar; - let left = if mac { MAC_CONTENT_LEFT as i8 } else { 8 }; + if mac && app.titlebar_lights_right.is_none() { + app.titlebar_lights_right = mac_lights_on_right(); + } + // With the lights at the right (a right-to-left system language), the strip is the mirror + // image of the usual one: Home beside the lights, the tabs and Open after it, and the + // Discord, shortcuts and theme buttons at the far end. + let mirrored = mac && app.titlebar_lights_right == Some(true); + let (left, right) = match (mac, mirrored) { + (true, false) => (MAC_CONTENT_LEFT as i8, 10), + (true, true) => (10, MAC_CONTENT_LEFT as i8), + (false, _) => (8, 10), + }; + let (row, far_end) = if mirrored { + (Layout::right_to_left(Align::Center), Layout::left_to_right(Align::Center)) + } else { + (Layout::left_to_right(Align::Center), Layout::right_to_left(Align::Center)) + }; let (tab_h, button) = if mac { (MAC_TITLE_BAR - 2.0, 24.0) } else { (TAB_HEIGHT, STRIP_BUTTON) }; egui::Panel::top("tab_strip") .exact_size(if mac { MAC_TITLE_BAR } else { TAB_STRIP }) - .frame(egui::Frame::NONE.fill(t.titlebar).inner_margin(egui::Margin { left, right: 10, top: 0, bottom: 0 })) + .frame(egui::Frame::NONE.fill(t.titlebar).inner_margin(egui::Margin { left, right, top: 0, bottom: 0 })) .show(ui, |ui| { let full = ui.max_rect(); app.panes.main_strip = Some(full); @@ -59,7 +95,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { .clone() .filter(|_| app.draws_window_frame() && !fullscreen) .unwrap_or_else(|| window_controls::Layout { left: Vec::new(), right: Vec::new() }); - ui.horizontal_centered(|ui| { + ui.allocate_ui_with_layout(ui.available_size_before_wrap(), row, |ui| { ui.spacing_mut().item_spacing.x = 4.0; if !controls.left.is_empty() { ui.scope(|ui| { @@ -101,9 +137,14 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { // Where the tabs were scrolled to last frame, and how far they can go. let scroll_id = ui.scope_id().with("tab_scroll"); let (offset, max_offset) = ui.data(|d| d.get_temp::<(f32, f32)>(scroll_id)).unwrap_or((0.0, 0.0)); - let mut scroll_to = None; - if overflow && arrow(ui, "chevron-left", offset > 0.5, tl!("Scroll tabs left")) { - scroll_to = Some((offset - (TAB_MIN_WIDTH + gap)).max(0.0)); + let scroll_left = |ui: &mut egui::Ui| overflow && arrow(ui, "chevron-left", offset > 0.5, tl!("Scroll tabs left")); + let scroll_right = |ui: &mut egui::Ui| overflow && arrow(ui, "chevron-right", offset < max_offset - 0.5, tl!("Scroll tabs right")); + // The arrows keep their sides: the one laid out first is at the row's start. + let (mut left_clicked, mut right_clicked) = (false, false); + if mirrored { + right_clicked = scroll_right(ui); + } else { + left_clicked = scroll_left(ui); } // Keyed by document, not index: a tab dragged past the active one moves it without // the strip jumping to it. @@ -114,14 +155,20 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { data.insert_temp(id, state); changed }); + // Mirrored, the tabs' reading start is the scroll area's far end: the strip goes + // there once when it starts to scroll, and the active tab is brought back in view. + let start_id = scroll_id.with("reading_start"); + let (start, started) = mirrored_start(mirrored, max_offset, ui.data(|d| d.get_temp::(start_id)).unwrap_or(false)); + ui.data_mut(|d| d.insert_temp(start_id, started)); + let changed = changed || start.is_some(); let mut action = None; let mut close = None; // The pointer's x while a tab is dragged, for scrolling at the strip's edges. let mut drag_x = None; - ui.scope(|ui| { + let show_tabs = |ui: &mut egui::Ui| { ui.style_mut().always_scroll_the_only_direction = true; let mut area = egui::ScrollArea::horizontal().id_salt("document_tabs").max_width(tabs_width).auto_shrink([true, true]); - if let Some(x) = ui.data_mut(|d| d.remove_temp::(scroll_id.with("to"))) { + if let Some(x) = ui.data_mut(|d| d.remove_temp::(scroll_id.with("to"))).or(start) { area = area.horizontal_scroll_offset(x); } let out = area.show(ui, |ui| { @@ -130,7 +177,13 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { // (with whether it was just released). let mut slots = Vec::with_capacity(app.views.len()); let mut dragged = None; - for i in app.tabs_in(Place::Main) { + // Mirrored, the tabs read from the right: the first is beside Home. + let mut order = app.tabs_in(Place::Main); + if mirrored { + order.reverse(); + combine_tab(app, ui, &t, cap, tab_h, changed); + } + for i in order { let Some(doc) = app.session.get(app.views[i].id) else { continue }; let Some(name) = crate::canvas::tab_label(app, i) else { continue }; let dirty = doc.dirty; @@ -170,7 +223,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { close = Some(i); } } - drag_x = tab_drag(app, ui, &slots, dragged, Place::Main, close.is_some() || action.is_some()); + drag_x = tab_drag(app, ui, &slots, dragged, Place::Main, close.is_some() || action.is_some(), mirrored); if let Some(i) = close && let Some(view) = app.views.get(i) { @@ -179,40 +232,17 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { if let Some(action) = action { app.tab_action(action); } - if app.combine_tab.open { - // After the document tabs; its index can't clash with theirs. - let mut close = None; - let response = tab( - ui, - TabSpec { - id: ui.scope_id().with("combine-tab"), - theme: &t, - icon: "files", - name: tl!("Combine files"), - file: None, - dirty: false, - active: app.combine_showing(), - index: usize::MAX, - cap, - height: tab_h, - draggable: false, - }, - &mut close, - ); - if changed && app.combine_showing() { - response.scroll_to_me(Some(Align::Center)); - } - if response.clicked() { - app.open_combine_tab(); - } - if close.is_some() || response.middle_clicked() { - app.close_combine_tab(); - } + if !mirrored { + combine_tab(app, ui, &t, cap, tab_h, changed); } }); }); let max = (out.content_size.x - out.inner_rect.width()).max(0.0); ui.data_mut(|d| d.insert_temp(scroll_id, (out.state.clamped_offset().x, max))); + // The strip just started to scroll: the next frame takes it to its reading start. + if mirrored_start(mirrored, max, started).0.is_some() { + ui.ctx().request_repaint(); + } // A tab dragged to either edge of a strip that scrolls brings the hidden tabs in. if let Some(x) = drag_x && max > 0.0 @@ -229,8 +259,25 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { ui.ctx().request_repaint(); } } - }); - if overflow && arrow(ui, "chevron-right", offset < max_offset - 0.5, tl!("Scroll tabs right")) { + }; + if mirrored { + // egui scrolls only content that runs left to right, so mirrored the tabs sit in + // a box that runs that way, exactly as wide as they are, beside Home. + let width = tabs_shown_width(&natural, cap, gap).min(tabs_width); + ui.allocate_ui_with_layout(vec2(width, ui.available_height()), Layout::left_to_right(Align::Center), show_tabs); + } else { + ui.scope(show_tabs); + } + if mirrored { + left_clicked = scroll_left(ui); + } else { + right_clicked = scroll_right(ui); + } + let mut scroll_to = None; + if left_clicked { + scroll_to = Some((offset - (TAB_MIN_WIDTH + gap)).max(0.0)); + } + if right_clicked { scroll_to = Some((offset + TAB_MIN_WIDTH + gap).min(max_offset)); } if let Some(x) = scroll_to { @@ -242,7 +289,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { if widgets::ghost_button_sized(ui, "plus", tl!("Open"), tab_h).on_hover_text(tip).clicked() { app.open_dialog(); } - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.with_layout(far_end, |ui| { if !controls.right.is_empty() { // Laid out left to right inside the right-to-left run, so they read in // the desktop's order. @@ -284,6 +331,42 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { }); } +/// The Combine files tab, when it is open: after the document tabs in reading order (drawn first +/// when they read from the right). Its index can't clash with theirs. +fn combine_tab(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, cap: Option, height: f32, changed: bool) { + if !app.combine_tab.open { + return; + } + let mut close = None; + let response = tab( + ui, + TabSpec { + id: ui.scope_id().with("combine-tab"), + theme: t, + icon: "files", + name: tl!("Combine files"), + file: None, + dirty: false, + active: app.combine_showing(), + index: usize::MAX, + cap, + height, + draggable: false, + }, + &mut close, + ); + if changed && app.combine_showing() { + response.scroll_to_me(Some(Align::Center)); + } + if response.clicked() { + app.open_combine_tab(); + } + // A middle click closes it too, as it does a document tab (#1853). + if close.is_some() || response.middle_clicked() { + app.close_combine_tab(); + } +} + /// The right-click menu on the title bar's theme button. fn appearance_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) { if ui.button(tl!("Appearance settings…")).clicked() { @@ -329,21 +412,32 @@ fn tab_menu(app: &PdfCraftApp, ui: &mut egui::Ui, index: usize, action: &mut Opt /// over split view's other pane, a hint shows where it would go instead, and letting go puts it /// there (`crate::panes`). `busy` is a close or menu choice this frame, which wins. Returns the /// pointer's x while the tab moves along the strip, for scrolling at the strip's edges. -fn tab_drag(app: &mut PdfCraftApp, ui: &egui::Ui, slots: &[(usize, Rect)], dragged: Option<(usize, bool)>, place: Place, busy: bool) -> Option { +fn tab_drag( + app: &mut PdfCraftApp, + ui: &egui::Ui, + slots: &[(usize, Rect)], + dragged: Option<(usize, bool)>, + place: Place, + busy: bool, + mirrored: bool, +) -> Option { let (from, released) = dragged?; let pos = ui.ctx().pointer_latest_pos()?; match app.drop_target(pos, place) { TabDrop::Strip => { let x = pos.x; - let to = drop_index(slots, from, x); + // Reading order, with x flipped when the tabs read from the right. + let slots = reading_order(slots, mirrored); + let flip = |x: f32| if mirrored { -x } else { x }; + let to = drop_index(&slots, from, flip(x)); if released { if !busy { - app.move_tab_in_strip(from, slots, to); + app.move_tab_in_strip(from, &slots, to); } return None; } ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - if let Some(marker) = drop_marker(slots, from, to, ui.spacing().item_spacing.x) { + if let Some(marker) = drop_marker(&slots, from, to, ui.spacing().item_spacing.x).map(flip) { let t = Tokens::get(ui.ctx()); let span = slots.first().map_or(ui.max_rect().y_range(), |(_, r)| r.y_range()); // In front of the first tab the gap lies outside the scroll area's clip rect @@ -418,7 +512,7 @@ pub(crate) fn pane_tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, strip: Re close = Some(i); } } - tab_drag(app, &row, &slots, dragged, place, close.is_some() || action.is_some()); + tab_drag(app, &row, &slots, dragged, place, close.is_some() || action.is_some(), false); if let Some(i) = close && let Some(view) = app.views.get(i) { @@ -465,6 +559,32 @@ fn drop_marker(slots: &[(usize, Rect)], from: usize, to: usize, gap: f32) -> Opt } } +/// The tabs' slots in reading order, in a space where reading runs left to right: when the tabs +/// read from the right (`mirrored`), their order is reversed and x flipped, so `drop_index` and +/// `drop_marker` serve both directions. +fn reading_order(slots: &[(usize, Rect)], mirrored: bool) -> Vec<(usize, Rect)> { + if !mirrored { + return slots.to_vec(); + } + slots.iter().rev().map(|(i, r)| (*i, Rect::from_x_y_ranges(-r.right()..=-r.left(), r.y_range()))).collect() +} + +/// Where a mirrored strip that has just started to scroll goes (`max_offset`, the far end of a +/// scroll area that runs left to right, is where its tabs start to read), and whether it has gone +/// there. Once only, so the user's own scrolling stands; a strip that stops scrolling starts again. +fn mirrored_start(mirrored: bool, max_offset: f32, started: bool) -> (Option, bool) { + if !mirrored || max_offset.is_nan() || max_offset <= 0.5 { + return (None, false); + } + if started { (None, true) } else { (Some(max_offset), true) } +} + +/// How wide tabs of `natural` widths, each at most `cap`, are laid out `gap` apart. +fn tabs_shown_width(natural: &[f32], cap: Option, gap: f32) -> f32 { + let tabs: f32 = natural.iter().map(|w| cap.map_or(*w, |cap| w.min(cap))).sum(); + tabs + gap * natural.len().saturating_sub(1) as f32 +} + /// A scroll arrow beside the tabs; dimmed (and inert) at its end. True when clicked. fn arrow(ui: &mut egui::Ui, icon: &str, enabled: bool, tip: &str) -> bool { ui.add_enabled_ui(enabled, |ui| icons::button(ui, icon, TAB_ARROW, false, tip)).inner.clicked() @@ -1043,6 +1163,45 @@ mod tab_widths { assert_eq!(drop_marker(&[], 0, 1, 4.0), None); } + /// Mirrored, the slots come back in reading order with x flipped, so the drop helpers read + /// the tabs from the right. + #[test] + fn mirrored_tabs_drop_in_their_reading_order() { + use super::{drop_index, drop_marker, reading_order}; + // Drawn right to left: tab 0 at the right, tab 2 at the left. + let drawn: Vec<_> = three_slots().into_iter().map(|(k, r)| (2 - k, r)).collect(); + let slots = reading_order(&drawn, true); + assert_eq!(slots.iter().map(|(i, _)| *i).collect::>(), [0, 1, 2]); + // Tab 0 (drawn at 208..308, beside Home) dragged to the far left lands at the end. + assert_eq!(drop_index(&slots, 0, -10.0), 2); + // Its drop line, flipped back, sits left of the leftmost tab. + assert_eq!(drop_marker(&slots, 0, 2, 4.0).map(|x| -x), Some(-2.0)); + // Unmirrored, nothing changes. + assert_eq!(reading_order(&three_slots(), false), three_slots()); + assert!(reading_order(&[], true).is_empty()); + } + + /// A mirrored strip goes to its reading start (the far end) once when it starts to scroll, + /// then leaves the offset to the user until it no longer scrolls. + #[test] + fn a_mirrored_strip_starts_at_its_reading_start_once() { + use super::mirrored_start; + assert_eq!(mirrored_start(true, 0.0, false), (None, false), "nothing to scroll"); + assert_eq!(mirrored_start(true, 240.0, false), (Some(240.0), true), "it just started to scroll"); + assert_eq!(mirrored_start(true, 240.0, true), (None, true), "once only"); + assert_eq!(mirrored_start(true, 0.0, true), (None, false), "it stopped scrolling: next time starts again"); + assert_eq!(mirrored_start(false, 240.0, false), (None, false), "unmirrored, the start is offset 0"); + assert_eq!(mirrored_start(true, f32::NAN, false), (None, false)); + } + + #[test] + fn shown_tabs_take_their_capped_widths_and_the_gaps() { + use super::tabs_shown_width; + assert_eq!(tabs_shown_width(&[100.0, 200.0], None, 4.0), 304.0); + assert_eq!(tabs_shown_width(&[100.0, 200.0], Some(150.0), 4.0), 254.0); + assert_eq!(tabs_shown_width(&[], None, 4.0), 0.0); + } + #[test] fn the_mac_title_bar_centres_and_clears_the_traffic_lights() { // The lights are centred in the bar, and content keeps the same gap after them (#789). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 35bfd447b2..6a6062093e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -542,6 +542,9 @@ pub struct PdfCraftApp { pub toast_dropped: u64, /// Whether the macOS title bar is drawn by us (traffic lights over our tab strip). pub integrated_titlebar: bool, + /// Whether AppKit put those traffic lights at the right end of the title bar, as it does when + /// the system language is right-to-left (`None` until a window has said). + pub titlebar_lights_right: Option, /// Set when the desktop leaves the window frame to the app (GNOME on Wayland): the tab strip /// carries these window buttons and the window's edges resize it. pub window_controls: Option, diff --git a/crates/ui-egui/tests/it/ui.rs b/crates/ui-egui/tests/it/ui.rs index 9363737413..05b56706e8 100644 --- a/crates/ui-egui/tests/it/ui.rs +++ b/crates/ui-egui/tests/it/ui.rs @@ -751,6 +751,113 @@ fn the_integrated_title_bar_is_the_traffic_light_band() { assert!(home.left() >= 62.0 + 4.0, "Home {home:?} clears the traffic lights"); } +/// macOS with a right-to-left system language: AppKit mirrors the traffic lights to the right end +/// of the title bar, and the strip mirrors with them. Home sits beside the lights, the tabs read +/// from the right after it, then Open; Discord, shortcuts, theme and Preferences move to the far +/// left end. +#[cfg(target_os = "macos")] +fn mirrored_title_bar(names: &[&'static str]) -> Harness<'static, PdfCraftApp> { + let names = names.to_vec(); + harness(move |app| { + app.integrated_titlebar = true; + app.titlebar_lights_right = Some(true); + for name in names { + app.open_bytes(name, None, FIXTURE.to_vec()).unwrap(); + } + }) +} + +#[cfg(target_os = "macos")] +#[test] +fn the_integrated_title_bar_mirrors_with_traffic_lights_at_the_right() { + let (width, band, lights) = (1400.0, 28.0, 62.0); + let h = mirrored_title_bar(&["first.pdf", "last.pdf"]); + let rect = |label: &str| h.get_by_label(label).rect(); + let theme = h.get_by_label_contains("Display theme:").rect(); + for (label, r) in [ + ("Home", rect("Home")), + ("first.pdf", rect("first.pdf")), + ("Open", rect("Open")), + ("Discord", rect("Discord")), + ("Display theme", theme), + ("Preferences", rect("Preferences")), + ] { + assert!(r.top() >= 0.0 && r.bottom() <= band, "{label}: {r:?} inside the {band} pt title bar"); + assert!(r.right() <= width - lights - 4.0, "{label}: {r:?} clears the traffic lights"); + } + // Home is the first thing after the lights, as it is on the left in a left-to-right system. + let home = rect("Home"); + assert!(home.right() >= width - lights - 16.0, "Home {home:?} sits beside the lights"); + // Then the tabs, read from the right, then Open. + assert!(rect("first.pdf").right() <= home.left(), "the first tab follows Home"); + assert!(rect("last.pdf").right() <= rect("first.pdf").left(), "the tabs read from the right"); + assert!(rect("first.pdf").right() >= home.left() - 12.0, "the tabs stay beside Home"); + assert!(rect("Open").right() <= rect("last.pdf").left(), "Open follows the tabs"); + // The other end: Preferences, theme, shortcuts and Discord, mirroring their order at the right. + let (preferences, help, discord) = (rect("Preferences"), rect("Keyboard shortcuts"), rect("Discord")); + assert!(preferences.left() < 20.0, "Preferences {preferences:?} at the far end"); + assert!( + preferences.right() <= theme.left() && theme.right() <= help.left() && help.right() <= discord.left(), + "Preferences, theme, shortcuts, Discord" + ); + assert!(discord.right() < rect("Open").left(), "Discord stays clear of Open"); +} + +/// Mirrored, a tab dragged to the left moves later in the order, as it reads from the right. +#[cfg(target_os = "macos")] +#[test] +fn dragging_a_tab_in_the_mirrored_title_bar_follows_its_reading_order() { + use egui::accesskit::Role; + let mut h = mirrored_title_bar(&["first.pdf", "middle.pdf", "last.pdf"]); + let ids: Vec<_> = h.state().views.iter().map(|view| view.id).collect(); + let tab = |h: &Harness<'static, PdfCraftApp>, name: &str| h.get_by_role_and_label(Role::Tab, name).rect(); + // first.pdf past the end, which is the left. + let to = tab(&h, "last.pdf").left_center() - egui::vec2(20.0, 0.0); + drag_named_tab(&mut h, "first.pdf", to, true); + assert_eq!(h.state().views.iter().map(|view| view.id).collect::>(), [ids[1], ids[2], ids[0]]); + assert!(tab(&h, "first.pdf").right() < tab(&h, "last.pdf").left(), "the strip draws the new order"); + // last.pdf, now in the middle, to the front, which is the right. + let to = tab(&h, "middle.pdf").right_center() + egui::vec2(10.0, 0.0); + drag_named_tab(&mut h, "last.pdf", to, true); + assert_eq!(h.state().views.iter().map(|view| view.id).collect::>(), [ids[2], ids[1], ids[0]]); +} + +/// A mirrored strip that starts to scroll (here Home shows and the window narrows) shows its +/// reading start: the first tab beside Home, as the unmirrored strip does at its left end. It goes +/// there once, so a step the user scrolls stands. +#[cfg(target_os = "macos")] +#[test] +fn a_mirrored_strip_that_starts_to_scroll_shows_the_first_tab_beside_home() { + let mut h = mirrored_title_bar(&["first.pdf", "second.pdf", "third.pdf", "last.pdf"]); + h.state_mut().active = None; + h.run_steps(4); + assert!(h.query_by_label("Scroll tabs left").is_none(), "wide, the tabs don't scroll yet"); + h.set_size(egui::vec2(700.0, 600.0)); + h.run_steps(6); + let home = h.get_by_label("Home").rect(); + let first = h.get_by_label("first.pdf").rect(); + assert!(first.right() <= home.left() && first.right() >= home.left() - 50.0, "first.pdf {first:?} beside Home {home:?}"); + h.get_by_label("Scroll tabs left").click(); + h.run_steps(6); + let scrolled = h.get_by_label("first.pdf").rect(); + assert!(scrolled.left() > first.left() + 1.0, "the step stands: {first:?} -> {scrolled:?}"); +} + +/// Going to the reading start never hides the active tab: a document shown while the strip starts +/// to scroll stays in view. +#[cfg(target_os = "macos")] +#[test] +fn a_mirrored_strip_that_starts_to_scroll_keeps_the_active_tab_in_view() { + let mut h = mirrored_title_bar(&["first.pdf", "second.pdf", "third.pdf", "last.pdf"]); + h.run_steps(4); + assert_eq!(h.state().active, Some(3)); + h.set_size(egui::vec2(700.0, 600.0)); + h.run_steps(6); + let (home, open) = (h.get_by_label("Home").rect(), h.get_by_label("Open").rect()); + let last = h.get_by_label("last.pdf").rect(); + assert!(last.left() >= open.right() && last.right() <= home.left(), "last.pdf {last:?} between Open {open:?} and Home {home:?}"); +} + #[test] fn narrow_tab_strips_accept_vertical_wheel_scrolling() { for width in [600.0, 900.0] { From 4f9d93c173d425a6a067a57719f1bbc363cc25cd Mon Sep 17 00:00:00 2001 From: Cristi Radu Date: Wed, 18 Nov 2026 11:28:05 +0200 Subject: [PATCH 09/27] =?UTF-8?q?fix(ui):=20Edit=20=E2=96=B8=20Copy=20and?= =?UTF-8?q?=20Paste=20are=20enabled=20for=20selected=20comments=20(#7123)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #7123 ## What this changes With a drawn annotation (or any comment) selected, Edit ▸ Copy is now enabled, and Edit ▸ Paste is enabled once comments have been copied, matching ⌘C / ⌘V. **Root cause.** `run_menu_command` already sends the clipboard items as their keys (`menus.rs:561`: Copy pushes `Event::Copy`, Paste requests a paste), and `clipboard_keys` handles those by copying the selected comments when no text is selected and by pasting copied XFDF onto the canvas. Only the enabled state was out of sync. `menu_state` enabled Copy for selected text, a picked image, Edit-a-PDF objects or Organize, and Paste only for objects or pages, so both stayed greyed out with a comment selected. **Fix.** There are two new arms in `menu_state` (`crates/ui-egui/src/menus.rs`), placed after the existing image, object and page arms so those still take precedence: - Copy follows `comment.copy` when a comment is selected and no text is. Selected text is what ⌘C copies first, so it is left to the existing text rule. - Paste follows `comment.paste` when the comment clipboard holds something, outside Organize and Prepare Form, where the canvas does not take pastes. ## How you verified it - [x] `cargo fmt --check` - [x] clippy with `-D warnings` on `pdfcraft-ui-egui` (the only warning is in vendored `hayro-interpret`, which was already there) - [x] tests pass on `pdfcraft-ui-egui`, except for failures that also happen on `main` on my machine (Windows, MSVC): `comments::the_selection_bar_stays_inside_the_pages_area` fails every time, and `print::printing_landscape_sheets_tells_cups_to_turn_them` and `print::each_printer_keeps_what_it_last_printed_with_across_a_restart` fail some runs and not others **Test.** `comments::edit_copy_and_paste_are_enabled_for_a_selected_comment` draws a square, selects it, and checks that Edit ▸ Copy is enabled. It then runs Edit ▸ Copy through `run_menu_command` and checks that the comment was copied and that Paste is now enabled. Finally it deselects the comment and checks that Copy is greyed out again. It fails on `main` (`Edit ▸ Copy is enabled with a comment selected`) and passes with the fix. ## Never-crash - [x] No new `unwrap`/`expect`/`panic!` outside tests, no indexing, no `unsafe` ## Anything a reviewer should look at first - **Paste is enabled from app state, without reading the clipboard.** After copying a comment, if another app later puts plain text on the system clipboard, Edit ▸ Paste looks enabled but pastes nothing, as ⌘V already does in that case. I did not read the clipboard just to draw the menu (see #6169 / #6379). - **Copy follows `comment.copy`, which needs only an open document.** So Edit ▸ Copy is now enabled for a selected comment on a document that forbids copying. The same was already true of ⌘C and Edit ▸ Copy comments, so this is not a new way to copy. Whether copy-restricted documents should block copying comments at all is a separate question, and this PR leaves it alone. - **The command palette is unchanged.** `edit.copy` run from the palette (`command_enabled` / `execute`) still covers only text; this PR fixes the menus the issue reports. --- crates/ui-egui/src/menus.rs | 11 ++++++ crates/ui-egui/tests/it/comments.rs | 56 +++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b697cd6cf7..ca3eeca908 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -497,6 +497,17 @@ impl PdfCraftApp { doc.is_some_and(|d| d.allows_copying() && (command.id != CUT || d.allows_modification())) } PASTE if edit_objects && self.object_clipboard.is_some() => doc.is_some_and(pdfcraft_engine::Document::allows_modification), + // Selected comments are what ⌘C copies when no text is selected, and ⌘V pastes + // copied ones onto the pages (#7123); the menu items send those same events. + // Selected text is ⌘C's first, and Prepare Form takes neither key (`clipboard_keys`). + "edit.copy" + if !organize + && !self.is_preparing() + && view.is_some_and(|v| v.comments.selected.is_some() && v.selected_text().is_none_or(|t| t.is_empty())) => + { + enabled_id("comment.copy") + } + PASTE if !organize && !self.is_preparing() && self.comment_clipboard.is_some() => enabled_id("comment.paste"), CUT => organize && enabled_id("page.cut"), PASTE => organize && self.page_clipboard.is_some() && enabled_id("page.paste"), SELECT_ALL | DELETE => has_doc, diff --git a/crates/ui-egui/tests/it/comments.rs b/crates/ui-egui/tests/it/comments.rs index 0f88020674..9cf0294ec1 100644 --- a/crates/ui-egui/tests/it/comments.rs +++ b/crates/ui-egui/tests/it/comments.rs @@ -5587,6 +5587,62 @@ fn edit_delete_with_a_popup_open_removes_the_selected_comment() { assert!(comments(&h).is_empty(), "Edit ▸ Delete removed the comment"); } +/// Edit ▸ Copy and Paste take a selected drawn comment as ⌘C and ⌘V do (#7123). Both were +/// greyed out, as the menu only counted selected text, pictures and objects. +#[test] +fn edit_copy_and_paste_are_enabled_for_a_selected_comment() { + let mut h = selected_square(); + let state = |h: &Harness<'static, PdfCraftApp>, id: &str| h.state().menu_state(&h.ctx, &craft_menu::CommandRef::new(id)).enabled; + assert!(state(&h, "edit.copy"), "Edit ▸ Copy is enabled with a comment selected"); + assert!(!state(&h, "edit.paste"), "nothing is copied yet"); + + let ctx = h.ctx.clone(); + h.state_mut().run_menu_command(&ctx, &craft_menu::CommandRef::new("edit.copy")); + h.run_steps(4); + assert!(h.state().comment_clipboard.is_some(), "Edit ▸ Copy copied the comment"); + assert!(state(&h, "edit.paste"), "Edit ▸ Paste is enabled with a comment copied"); + + // Edit ▸ Paste asks the platform for the clipboard; its answer, the XFDF Copy put there, + // arrives as a paste (the harness has no platform, so the test delivers it). The copy hangs + // on the pointer, as with ⌘V, and a click places it there. + let id = h.state().views[0].id; + let annotations = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(id).unwrap().info.annotations.clone(); + let before = annotations(&h).len(); + let xfdf = h.state().comment_clipboard.as_ref().map(|c| c.xfdf.clone()).expect("copied"); + h.state_mut().run_menu_command(&ctx, &craft_menu::CommandRef::new("edit.paste")); + h.step(); + assert!(crate::support::asked_for_the_clipboard(&h), "Edit ▸ Paste asked the platform for the clipboard"); + h.step(); + h.event(egui::Event::Paste(xfdf)); + h.run_steps(2); + assert!(h.state().views[0].comments.gesture.is_some(), "Edit ▸ Paste waits for a click to place the copy"); + let at = (200.0, 160.0); + click_pt(&mut h, at); + let after = annotations(&h); + assert_eq!(after.len(), before + 1, "Edit ▸ Paste placed one copy: {after:?}"); + let placed = after.iter().max_by_key(|a| a.index).map(|a| a.rect).expect("placed"); + assert!(((placed[0] + placed[2]) / 2.0 - at.0).abs() < 1.0, "centred on the click: {placed:?}"); + assert!(h.state().views[0].comments.gesture.is_none(), "the copy is placed"); + assert!(h.state().views[0].comments.selected.is_some(), "the copy is selected"); + + h.state_mut().views[0].comments.selected = None; + h.run_steps(2); + assert!(!state(&h, "edit.copy"), "with nothing selected, Copy is greyed out again"); +} + +/// Prepare Form keeps ⌘C off the selected comments, so Edit ▸ Copy, which sends the same Copy, +/// is greyed out there too rather than enabled and doing nothing (#7123). +#[test] +fn edit_copy_is_off_for_a_selected_comment_while_preparing_a_form() { + let mut h = selected_square(); + assert!(h.state_mut().execute("form.prepare")); + h.run_steps(2); + assert!(h.state().is_preparing()); + assert!(h.state().views[0].comments.selected.is_some(), "the comment stays selected"); + let copy = h.state().menu_state(&h.ctx, &craft_menu::CommandRef::new("edit.copy")); + assert!(!copy.enabled, "Edit ▸ Copy is greyed out while preparing a form"); +} + /// A native menu's click never reaches the window, so Edit ▸ Delete closes the Hotbar tools window, /// as it closes egui's popups, and removes the selected comment. The window held the Delete. #[test] From 35165085891931461743cb7bd5f86bde7ad99a03 Mon Sep 17 00:00:00 2001 From: regendorf-ux Date: Wed, 18 Nov 2026 04:29:06 -0500 Subject: [PATCH 10/27] Edit text: space between paragraphs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this changes `edit.line-paragraph-spacing` was partial: line spacing existed, the space between paragraphs did not. Now a line break in the edited text starts a paragraph, and the paragraphs are set apart: - `BlockStyle.paragraph_spacing: Option` (points, beyond the line spacing). `rewrite_block` splits the text at line breaks, wraps and justifies each paragraph on its own (the last line of each paragraph is never stretched), and steps down by the line spacing plus the gap before a paragraph's first line; underlines follow. `None` is half the font size when the text has several paragraphs, so a plain Enter already reads as a paragraph; a non-finite value is refused. - The row-model rewrite (`text_regions`) keeps the rows a line break started apart from wrapped ones: the gap goes before those, and a row the page already had sits where it was, shifted by the spacing added above it. - Format text panel: a Paragraph spacing field (points) next to the line spacing; the tool `text_edit` takes `paragraph_spacing`. - Rows for the two labels in all 21 languages; `parity/acrobat-features.toml` `edit.line-paragraph-spacing` → shipped (notes: space before and after as separate values are still missing). ## How you verified it Re-run on 2026-10-15 after merging `main` into the branch (41809cf7, then afa8e184). The merge needed the language catalogs (upstream's rows and this PR's kept), ATTRIBUTION.toml's checksums and the tests both sides had appended at the same place; the new Vietnamese catalog got this PR's 2 labels (written by an AI model, like the other languages' rows, so a native speaker's review is welcome). Reconciled with #1486 (line breaks kept when editing a multi-line paragraph): the default gap between paragraphs applies to upright text only; turned text keeps its rows where they were unless a spacing is set. #1539 merged without conflict. A needless borrow clippy found on Windows is fixed. Full run on Windows (Rust 1.98) at the branch merged with `main` 41809cf7; after `main` afa8e184 was merged, re-checked on macOS (this PR's tests, the `i18n` tests, `cargo clippy --all-targets -- -D warnings` on the changed crates and their dependents (automation, edit, engine, ui-egui, audit, redact, the apps), `cargo xtask assets`): - [x] `cargo fmt --all --check`, `cargo xtask assets`, `cargo xtask layers`, doctests: exit 0 - [x] `cargo clippy --workspace --all-targets -- -D warnings`: clean on Windows; on macOS the only warnings are `main`'s own (`crates/ui-egui/tests/view.rs`: two helpers used only by a non-macOS test) - [x] This PR's tests pass: `paragraph_breaks_get_their_own_spacing`, `the_format_panel_has_a_paragraph_spacing_field`, and `main`'s `turned_paragraph_keeps_its_line_breaks_when_a_word_is_added` - [ ] `cargo nextest run --workspace`: 3422 of 3433 passed on Windows. The 11 failures fail the same way on `main` without this change: the parity file's duplicate keys (also `cargo xtask parity`; #2419 / #2473), the zh-hant duplicates and the Vietnamese coverage tests in `i18n` (none lists this PR's labels), `signing_with_translated_labels_through_tools` (#2429), `canvas::tests::explicit_search_jumps_record_history_and_keep_match_destination`, `view::single_page_swipe_that_reaches_the_edge_does_not_turn_but_a_fresh_one_does`, `editing::files_dropped_beside_the_pages_panel_still_open_as_documents` (intermittent) **Tests.** `paragraph_breaks_get_their_own_spacing` (edit): a one-line source rewritten as "First one\nSecond one" gets the row step alone (15 pt for a 10 pt one-liner), 35 pt with a 20 pt spacing, 15 pt with 0, and a wrapped single paragraph keeps the ordinary 12 pt step. `the_format_panel_has_a_paragraph_spacing_field` (ui-egui): the field is in the panel while a paragraph is being edited. ## Anything a reviewer should look at first - The labels in the 20 non-English language files were written by an AI model from the English wording; a native speaker's review of those rows would be welcome. - Justification now stops at each paragraph's last line (before, only the block's last line was left unstretched); with a single paragraph nothing changes. - **Overlap with #1487** ("M7: line and paragraph spacing", opened the day before this one): it adds the same `BlockStyle.paragraph_spacing`, a spacing field in the Format panel and the `text_edit` argument. On top of that, this PR stops justification at each paragraph's last line, adds a UI test beside the edit-crate test, and carries the label in all 21 catalogs. Whichever you prefer is fine: if #1487 lands first I'll rebase this down to what it adds on top of it, or close it. - **Fits #2249** ("lay out Format text as Acrobat's panel"): that redesign shows paragraph spacing disabled as *Planned* and replaces `edit_text_ui::extras_panel`, where this PR's field lives. This PR supplies what the control would drive (`BlockStyle.paragraph_spacing` applied by `text_regions.rs`); if #2249 lands first I'll move the field into its panel and enable it there. ## Never-crash - [x] No new `unwrap`/`expect`/`panic!` outside tests - [x] The spacing is validated (finite, clamped to 0–14 400 pt); rows are indexed with `get` - [x] No `unsafe` ## Provenance - [x] No asset added; no code from another implementation ## Security - [x] No network access ## Parity and reach - [x] `parity/acrobat-features.toml` updated with what is still missing - [x] Headless through `text_edit` (`paragraph_spacing`) - [x] No documented behaviour changed (`docs/` has no entry for it) - **Merged with main dc41044b** (2026-10-15): #2510's Vietnamese and Lithuanian catalogs added rows beside this branch's in `vi.tsv` and `lt.tsv` (and `ATTRIBUTION.toml`'s sha256 lines), nothing else. Main's rows kept, this branch's rows main lacks after them, hashes recomputed. Re-checked after the merge: `cargo xtask assets` ok, `i18n::tests` 117/117. - **Merged with main 5fdd820b** (2026-10-15): #1895's catalog rows conflicted with this branch's in `es.tsv` and `vi.tsv` (and `ATTRIBUTION.toml`'s sha256 lines), nothing else. Main's rows kept, this branch's rows main lacks after them, hashes recomputed. Re-checked after the merge: `cargo xtask assets` ok, clippy -D warnings on this branch's crates ok, `i18n::tests` 117/117. - **Merged with main bc7a12b9** (2026-10-17): only the translation catalogs' new rows and `ATTRIBUTION.toml`'s hashes met this branch (both sides kept, hashes recomputed). Re-checked on macOS: `cargo check --workspace --all-targets`, `cargo xtask assets`, `i18n::tests` 115/115. - **Merged with main 3f5a784c** (2026-10-17): tests and docs both sides added kept (upstream's first), translation rows and `ATTRIBUTION.toml`'s hashes by key. Re-checked on macOS: `cargo check --workspace --all-targets`, `cargo xtask assets`, `i18n::tests` 115/115. - **Merged with main dab31491** (2026-10-18, in two steps: 932bf9c6, then dab31491 without conflicts): main and this branch both added tests at the end of `crates/edit/src/tests.rs` and `crates/ui-egui/tests/editing.rs`; both kept, each with its own closing brace (this branch's first), no test lost: the `#[test]` count is main's plus this branch's; and `ATTRIBUTION.toml`'s sha256 lines (main's file kept, every hash recomputed from the merged tree). Re-checked after the merge: `cargo check --workspace --all-targets` ok, `cargo xtask assets` ok, `i18n::tests` 119/119, this branch's tests 2/2. - **CodeRabbit fixes** (2026-10-21): choosing a font family no longer spreads rows apart when no spacing is set, and applying a spacing replaces the gap a paragraph already had instead of adding to it, so repeating it gives the same result. Each has a test in its own file that fails without the fix. - **Merged with main 6dec57bf** (2026-10-21): upstream rebuilt the Format text panel and deleted the function this PR's Paragraph spacing row lived in, so the row moved into the new panel, replacing its disabled placeholder; upstream already had the "Paragraph spacing" label in every catalog, so this PR's duplicate rows were dropped, and ATTRIBUTION.toml took main's copy with the hashes recomputed. - **Merged with main 6898094e** (2026-10-21): only the translation-catalog hashes in ATTRIBUTION.toml met this branch. - **Round-2 CodeRabbit fixes** (2026-10-21): the draft's line breaks are matched to the source rows by where they came from instead of by position, so a break inserted inside a source row puts the spacing before the new paragraph and later rows keep their source steps. Each has a test in its own file. - **Merged with main dbc7130b** (2026-10-21): only the translation-catalog hashes in ATTRIBUTION.toml met this branch. - **Merged with main ffaf3123** (2026-10-21): only the translation-catalog hashes in ATTRIBUTION.toml met this branch. - **Merged with main adea2c90** (2026-10-23): the parity row both sides changed keeps upstream's evidence with this PR's entries on top; this PR's test moved into upstream's new tests/it layout. - **Merged with main 57e531cc** (2026-10-23): only the translation-catalog hashes in ATTRIBUTION.toml met this branch. - **Merged with main a2ec27b4** (2026-10-23): upstream's changes met this PR in pdfcraft-automation, pdfcraft-edit, pdfcraft-ui-egui; checked. - **Merged with main 6718f1f3** (2026-10-24): upstream's changes met this PR in pdfcraft-automation, pdfcraft-edit, pdfcraft-ui-egui; checked. - **Merged with main 418ac6a2** (2026-10-25): upstream's changes met this PR in pdfcraft-automation, pdfcraft-edit, pdfcraft-ui-egui; checked. - **Merged with main 1dd2737b4** (2026-10-27): upstream's changes met this PR in pdfcraft-automation, pdfcraft-edit, pdfcraft-ui-egui; checked. - **Merged with main 0cba87ae** (2026-11-01): upstream's changes met this PR in pdfcraft-automation, pdfcraft-edit, pdfcraft-ui-egui; checked. - **Merged with main 3936f93a** (2026-11-02): upstream's changes met this PR in pdfcraft-automation, pdfcraft-edit, pdfcraft-ui-egui; checked. --- crates/automation/src/dispatch.rs | 1 + crates/automation/src/tools.rs | 1 + crates/edit/src/lib.rs | 4 + .../edit/src/paragraph_spacing_break_tests.rs | 176 +++++++++++ crates/edit/src/paragraph_spacing_tests.rs | 88 ++++++ crates/edit/src/tests.rs | 41 ++- crates/edit/src/text.rs | 2 +- crates/edit/src/text/blocks.rs | 8 + crates/edit/src/text/rewrite.rs | 124 +++++++- crates/edit/src/text_regions.rs | 2 +- crates/edit/src/text_regions/styled.rs | 289 ++++++++++++++++-- crates/ui-egui/src/panels/format_text_ui.rs | 58 ++-- crates/ui-egui/src/tools/edit_text_ui.rs | 6 +- crates/ui-egui/tests/it/content.rs | 13 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/paragraph_spacing.rs | 79 +++++ parity/acrobat-features.toml | 6 +- 17 files changed, 819 insertions(+), 80 deletions(-) create mode 100644 crates/edit/src/paragraph_spacing_break_tests.rs create mode 100644 crates/edit/src/paragraph_spacing_tests.rs create mode 100644 crates/ui-egui/tests/it/paragraph_spacing.rs diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index f79f585a31..6439a12d1d 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -614,6 +614,7 @@ impl Automation { size: a.opt_num("size")?, underline: a.opt_bool("underline")?, line_spacing: a.opt_num("line_spacing")?, + paragraph_spacing: a.opt_num("paragraph_spacing")?, char_spacing: a.opt_num("char_spacing")?, scale: a.opt_num("scale")?, width, diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index f0700b735e..481ded19b9 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1755,6 +1755,7 @@ pub fn tools() -> Vec { "aligns": { "type": "array", "maxItems": 4096, "items": { "type": "string", "enum": ["left", "center", "right", "justify", "inherit"] }, "description": "Each paragraph's (line's) own alignment, by index; inherit (or legacy null) follows align." }, "underline": { "type": "boolean" }, "line_spacing": { "type": "number", "description": "Multiple of the font size (1.2 is ordinary)." }, + "paragraph_spacing": { "type": "number", "description": "Points between paragraphs (a line break in text starts one), beyond the line spacing; unset, half the size for a paragraph the page did not have (rows it had keep their space); 0 is none." }, "dx": { "type": "number", "description": "Paragraph only: move right by this many points (negative: left)." }, "dy": { "type": "number", "description": "Paragraph only: move up by this many points (negative: down)." }, "width": { "type": "number", "description": "Paragraph only: rewrap to this width in points (dragging the box's edge)." }, diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index f02930a8e5..886bfc3522 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -99,4 +99,8 @@ mod find_replace_rows_tests; #[cfg(test)] mod marked_isolation_tests; #[cfg(test)] +mod paragraph_spacing_break_tests; +#[cfg(test)] +mod paragraph_spacing_tests; +#[cfg(test)] mod tests; diff --git a/crates/edit/src/paragraph_spacing_break_tests.rs b/crates/edit/src/paragraph_spacing_break_tests.rs new file mode 100644 index 0000000000..cc50030b6f --- /dev/null +++ b/crates/edit/src/paragraph_spacing_break_tests.rs @@ -0,0 +1,176 @@ +//! The paragraph spacing goes before a row whose line break the edit inserted, and the rows +//! below it keep their own source steps. + +use crate::paragraph_spacing_tests::{close, page, steps}; +use crate::text; + +/// Source rows `One`, `TwoThree` and `Four` of 10 pt text at baselines 700, 688 and 676: a +/// 12 pt row step and no paragraph gap. The draft breaks `TwoThree` into `Two` and `Three` and +/// sets a 10 pt spacing. `Three` starts the only new paragraph: it goes 12 + 10 below `Two`, +/// at 688 - 22 = 666, and `Four` keeps its 12 pt step below it, at 654. Steps 12, 22, 12. +/// Before, draft rows were paired with source rows by position: `Three` took `Four`'s row +/// (676, no gap there), and `Four`, past the source's rows, got the spacing: 12, 12, 22. +#[test] +fn spacing_goes_before_an_inserted_break() { + let mut doc = page("BT /F1 10 Tf 72 700 Td (One) Tj 0 -12 Td (TwoThree) Tj 0 -12 Td (Four) Tj ET"); + let style = text::BlockStyle { paragraph_spacing: Some(10.0), ..Default::default() }; + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree\nFour"), &style).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 22.0, 12.0]), "{s:?}"); +} + +/// A range style takes the styled path (`text_regions`), whose rows are placed by source row. +fn styled(spacing: f64) -> text::BlockStyle { + let range = + text::RangeStyle { range: 0..3, family: None, resource: None, size: None, color: None, underline: None, char_spacing: None, scale: None }; + text::BlockStyle { paragraph_spacing: Some(spacing), ranges: vec![range], ..Default::default() } +} + +/// The styled path: `TwoThree` is split into `Two` and `Three`. `Three` starts the new paragraph, +/// 12 + 10 below `Two`, and `Four` keeps its 12 pt step below it: 12, 22, 12. The source's own +/// breaks, with no extra space above them, get none. +#[test] +fn styled_rows_take_the_spacing_before_an_inserted_break() { + let source = "BT /F1 10 Tf 72 700 Td (One) Tj 0 -12 Td (TwoThree) Tj 0 -12 Td (Four) Tj ET"; + let mut doc = page(source); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree\nFour"), &styled(10.0)).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 22.0, 12.0]), "{s:?}"); + let mut doc = page(source); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwoThree\nFour"), &styled(10.0)).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 12.0]), "{s:?}"); +} + +/// The styled path: a source row set apart by a 4 pt gap (step 16) has that gap replaced by a +/// 10 pt spacing (step 22), and the row below keeps its step. +#[test] +fn styled_rows_replace_the_gap_a_row_already_had() { + let mut doc = page("BT /F1 10 Tf 72 700 Td (One) Tj 0 -12 Td (Two) Tj 0 -16 Td (Three) Tj ET"); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &styled(10.0)).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 22.0]), "{s:?}"); +} + +fn rows(names: &[&str]) -> String { + let body: String = + names.iter().enumerate().map(|(i, n)| format!("{}({n}) Tj ", if i == 0 { "".to_string() } else { "0 -12 Td ".to_string() })).collect(); + format!("BT /F1 10 Tf 72 700 Td {body}ET") +} + +fn steps_after(source: &[&str], draft: &str) -> Vec { + let mut doc = page(&rows(source)); + text::rewrite_block(&mut doc, 0, 0, Some(draft), &styled(10.0)).unwrap(); + steps(&doc) +} + +/// The styled path: a whole row inserted exactly between two source rows takes the spacing, +/// not the row after it. Source `One`, `Two`, `Three`; the draft adds `New` after `Two`. +/// Aligned by character prefix and suffix the added line could not be told from the break +/// after `Two` and the spacing went before `Three`: 12, 12, 22. +#[test] +fn styled_spacing_goes_before_a_row_inserted_at_a_row_boundary() { + let s = steps_after(&["One", "Two", "Three"], "One\nTwo\nNew\nThree"); + assert!(close(&s, &[12.0, 22.0, 12.0]), "{s:?}"); +} + +/// A row inserted after the last row, and one before the first. +#[test] +fn styled_spacing_for_a_row_inserted_at_the_end_and_at_the_start() { + let s = steps_after(&["One", "Two", "Three"], "One\nTwo\nThree\nNew"); + assert!(close(&s, &[12.0, 12.0, 22.0]), "{s:?}"); + let s = steps_after(&["One", "Two", "Three"], "New\nOne\nTwo\nThree"); + assert!(close(&s, &[22.0, 12.0, 12.0]), "{s:?}"); +} + +/// Rows that repeat: a third `B` among `A`, `B`, `B`, `C` is one more paragraph, set apart once, +/// and the rows below it keep their steps. +#[test] +fn styled_spacing_for_a_row_inserted_among_identical_rows() { + let s = steps_after(&["A", "B", "B", "C"], "A\nB\nB\nB\nC"); + assert!(close(&s, &[12.0, 12.0, 22.0, 12.0]), "{s:?}"); + // Only one paragraph is added, whichever of the identical rows is the new one. + let total: f64 = s.iter().sum(); + assert!((total - 58.0).abs() < 0.5, "{s:?}"); +} + +/// The default is half the size, for a paragraph the page did not have: a 10 pt row broken in two +/// is a 12 pt row step and 5 pt apart, 17. Rows the page already had stay one 12 pt step apart +/// whatever the draft does around them (below). +#[test] +fn a_new_styled_paragraph_gets_half_the_size_when_no_spacing_is_set() { + let range = + text::RangeStyle { range: 0..3, family: None, resource: None, size: None, color: None, underline: None, char_spacing: None, scale: None }; + let style = text::BlockStyle { ranges: vec![range], ..Default::default() }; + let mut doc = page(&rows(&["One", "Three"])); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &style).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[17.0, 12.0]), "{s:?}"); + // Asking for none takes it away again. + let none = text::BlockStyle { paragraph_spacing: Some(0.0), ..style }; + let mut doc = page(&rows(&["One", "Three"])); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &none).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 12.0]), "{s:?}"); +} + +/// Rows the page had keep their steps when no spacing is set: two paragraphs of 10 pt text stay +/// one 12 pt row step apart. +#[test] +fn styled_source_rows_keep_their_steps_when_no_spacing_is_set() { + let range = + text::RangeStyle { range: 0..3, family: None, resource: None, size: None, color: None, underline: None, char_spacing: None, scale: None }; + let style = text::BlockStyle { ranges: vec![range], ..Default::default() }; + let mut doc = page(&rows(&["One", "Two"])); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo"), &style).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0]), "{s:?}"); +} + +/// Choosing a family takes the single-style path, which lays every row out afresh. +fn single(spacing: Option) -> text::BlockStyle { + text::BlockStyle { family: Some((crate::Family::Times, false, false)), paragraph_spacing: spacing, ..Default::default() } +} + +/// The single-style path, like the styled one: unset, a paragraph the draft's break adds gets half +/// the size (a 12 pt step and 5 pt apart, 17), and asking for none takes it away again. +#[test] +fn a_new_single_style_paragraph_gets_half_the_size_when_no_spacing_is_set() { + let mut doc = page(&rows(&["One", "Three"])); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &single(None)).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[17.0, 12.0]), "{s:?}"); + let mut doc = page(&rows(&["One", "Three"])); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &single(Some(0.0))).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 12.0]), "{s:?}"); +} + +/// Rows the page had keep their steps when no spacing is set, whichever way the draft breaks +/// around them, and a gap a source row already had is kept, not added to. +#[test] +fn single_style_source_rows_keep_their_steps_when_no_spacing_is_set() { + let mut doc = page(&rows(&["One", "Two"])); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo"), &single(None)).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0]), "{s:?}"); + // `Three` sits 16 pt below `Two`: a 4 pt gap, kept. + let mut doc = page("BT /F1 10 Tf 72 700 Td (One) Tj 0 -12 Td (Two) Tj 0 -16 Td (Three) Tj ET"); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &single(None)).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 16.0]), "{s:?}"); + // A row added at the end is the only one set apart. + let mut doc = page(&rows(&["One", "Two"])); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nNew"), &single(None)).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 17.0]), "{s:?}"); +} + +/// A set spacing replaces the gap a single-style row already had (never adds to it). +#[test] +fn single_style_spacing_that_is_set_replaces_the_gap_a_row_had() { + let mut doc = page("BT /F1 10 Tf 72 700 Td (One) Tj 0 -12 Td (Two) Tj 0 -16 Td (Three) Tj ET"); + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &single(Some(10.0))).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[22.0, 22.0]), "{s:?}"); +} diff --git a/crates/edit/src/paragraph_spacing_tests.rs b/crates/edit/src/paragraph_spacing_tests.rs new file mode 100644 index 0000000000..a59d7dbde4 --- /dev/null +++ b/crates/edit/src/paragraph_spacing_tests.rs @@ -0,0 +1,88 @@ +//! The paragraph spacing: no default space between source rows, and a set spacing that +//! replaces the space a paragraph already had instead of adding to it. + +use std::sync::Arc; + +use pdfcraft_cos::{Document, SaveOptions, write_incremental}; + +use super::*; + +/// One page drawing `content` with Helvetica as /F1. +pub(crate) fn page(content: &str) -> Document { + let objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(), + format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offs = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offs.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let x = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offs { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes()); + Document::open(Arc::new(out)).unwrap() +} + +fn reopen(doc: &Document) -> Document { + let bytes = write_incremental(doc, &SaveOptions::default()).unwrap(); + Document::open(Arc::new(bytes)).unwrap() +} + +/// The steps from each row down to the next, in points. +pub(crate) fn steps(doc: &Document) -> Vec { + let b: Vec = text::text_lines(&reopen(doc), 0).unwrap().iter().map(|l| l.rect[1]).collect(); + b.windows(2).map(|w| w[0] - w[1]).collect() +} + +pub(crate) fn close(got: &[f64], want: &[f64]) -> bool { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() < 0.5) +} + +/// Choosing a family takes the single-style path. Three rows of 10 pt text 12 pt apart (the +/// default 1.2 line step) stay 12 pt apart: no spacing is set, so none is added. Half the size +/// before every row, as before, made the steps 17 and 17. +#[test] +fn choosing_a_family_keeps_row_steps() { + let mut doc = page("BT /F1 10 Tf 72 700 Td (One) Tj 0 -12 Td (Two) Tj 0 -12 Td (Three) Tj ET"); + let style = text::BlockStyle { family: Some((Family::Times, false, false)), ..Default::default() }; + text::rewrite_block(&mut doc, 0, 0, Some("One\nTwo\nThree"), &style).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 12.0]), "{s:?}"); +} + +/// Rows of 10 pt text at baselines 700, 688, 672 and 660: a 12 pt row step, and a 4 pt gap +/// before the third row (step 16, still one paragraph: a gap of 1.5 rows is the next one). A +/// 10 pt spacing replaces that gap: the third row moves +/// down 6 pt to 666 and the fourth with it to 654, so the steps are 12, 22, 12. Applied again +/// to the result the gap is already 10, so nothing moves. Before, the spacing was added on top +/// of the gap and before every row: 22, 30, 22 the first time, and growing each time after. +/// A 0 pt spacing takes the gap away: 12, 12, 12. +#[test] +fn reapplying_paragraph_spacing_replaces_the_gap() { + let source = "BT /F1 10 Tf 72 700 Td (One) Tj 0 -12 Td (Two) Tj 0 -16 Td (Three) Tj 0 -12 Td (Four) Tj ET"; + let draft = Some("One\nTwo\nThree\nFour"); + let ten = text::BlockStyle { paragraph_spacing: Some(10.0), ..Default::default() }; + let mut doc = page(source); + text::rewrite_block(&mut doc, 0, 0, draft, &ten).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 22.0, 12.0]), "first time: {s:?}"); + // The 22 pt step is wider than a row step and a half, so the reopened page reads the third + // row as the next paragraph: the spacing applied again to the first one changes nothing. + let mut doc = reopen(&doc); + let first = text::text_blocks(&doc, 0).unwrap()[0].editor_text.clone(); + text::rewrite_block(&mut doc, 0, 0, Some(&first), &ten).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 22.0, 12.0]), "again: {s:?}"); + let mut doc = page(source); + text::rewrite_block(&mut doc, 0, 0, draft, &text::BlockStyle { paragraph_spacing: Some(0.0), ..Default::default() }).unwrap(); + let s = steps(&doc); + assert!(close(&s, &[12.0, 12.0, 12.0]), "none: {s:?}"); +} diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 7a59a238a1..974f298fb2 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -3826,7 +3826,8 @@ fn growing_into_a_blank_line_keeps_the_neighbour_after_save() { let bases: Vec = lines.iter().map(|l| l.origin_baseline()).collect(); assert_eq!(bases.len(), 4, "{bases:?}"); let grown = bases[2] - bases[3]; - assert!((grown - tl).abs() < 0.05, "the new row is {grown} pt above the neighbour, not one leading"); + // The new paragraph takes half the size (6 pt) of the blank line's room: no spacing is set. + assert!((grown - (tl - 6.0)).abs() < 0.05, "the new row is {grown} pt above the neighbour, not one leading less half the size"); assert!(grown < tl * 1.5, "this gap is outside the join window, so the test would pass without the marker"); let texts = |doc: &Document| text::text_blocks(doc, 0).unwrap().into_iter().map(|b| b.text).collect::>(); assert_eq!(texts(&doc), ["One Two Three", "Neighbour"]); @@ -4197,7 +4198,8 @@ fn resizing_a_grown_paragraph_keeps_the_neighbour() { let lines = text::text_lines(&doc, 0).unwrap(); let added = lines.iter().find(|l| l.text.contains("Alpha next row.")).unwrap(); let neighbour = lines.iter().find(|l| l.text.contains("Neighbor")).unwrap(); - assert!((added.origin_baseline() - neighbour.origin_baseline()).abs() < 0.5, "the new row is not on the neighbour"); + // The two rows the edit added are new paragraphs, half the size (6 pt) each below the blank line. + assert!((neighbour.origin_baseline() - added.origin_baseline() - 12.0).abs() < 0.5, "the new row is not 12 pt below the neighbour"); let width = text::text_blocks(&doc, 0).unwrap()[0].rect[2] - text::text_blocks(&doc, 0).unwrap()[0].rect[0]; for factor in [0.6_f64, 1.6] { let mut copy = doc.clone(); @@ -9909,6 +9911,41 @@ fn removing_marks_strips_wrappers_that_closed_open_state() { assert_eq!(streams(&doc, 0), ["q 2 0 0 2 0 0 cm"]); } +/// A line break in the edited text keeps a row of its own (the editor's rows); with a paragraph +/// spacing set, that much more space goes before it, and unset, half the size does. A row the +/// page already had stays where it was, shifted by the spacing added above it. +#[test] +fn paragraph_breaks_get_their_own_spacing() { + let baselines = |doc: &Document| -> Vec { text::text_lines(&reopen(doc), 0).unwrap().iter().map(|l| l.rect[1]).collect() }; + let gap_after_first = |b: &[f64]| b[0] - b[1]; + // A one-line source has no row step of its own: 1.5 × the size stands in. + let mut doc = text_page("BT /F1 10 Tf 72 700 Td (The quick brown fox) Tj ET"); + text::rewrite_block(&mut doc, 0, 0, Some("First one\nSecond one"), &text::BlockStyle::default()).unwrap(); + let b = baselines(&doc); + assert_eq!(b.len(), 2, "{b:?}"); + assert!((gap_after_first(&b) - 20.0).abs() < 0.5, "the row step and half the size: {b:?}"); + let mut doc = text_page("BT /F1 10 Tf 72 700 Td (The quick brown fox) Tj ET"); + text::rewrite_block(&mut doc, 0, 0, Some("First one\nSecond one"), &text::BlockStyle { paragraph_spacing: Some(20.0), ..Default::default() }) + .unwrap(); + assert!((gap_after_first(&baselines(&doc)) - 35.0).abs() < 0.5, "{:?}", baselines(&doc)); + let mut doc = text_page("BT /F1 10 Tf 72 700 Td (The quick brown fox) Tj ET"); + text::rewrite_block(&mut doc, 0, 0, Some("First one\nSecond one"), &text::BlockStyle { paragraph_spacing: Some(0.0), ..Default::default() }) + .unwrap(); + assert!((gap_after_first(&baselines(&doc)) - 15.0).abs() < 0.5); + // Without a break, nothing changes: one paragraph, the ordinary line step. + let mut doc = text_page("BT /F1 10 Tf 72 700 Td (The quick brown fox) Tj ET"); + text::rewrite_block( + &mut doc, + 0, + 0, + Some("First one Second one and then some more words to wrap"), + &text::BlockStyle { width: Some(90.0), ..Default::default() }, + ) + .unwrap(); + let b = baselines(&doc); + assert!(b.len() >= 2 && (gap_after_first(&b) - 12.0).abs() < 0.5, "{b:?}"); +} + /// Printer marks: drawn outside the trim box as a removable page mark; the page /// is widened to make room when asked and the trim box stays; running again replaces them. #[test] diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs index f55cea4866..7f8013c00c 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -26,7 +26,7 @@ mod regions; #[path = "text_session.rs"] mod session; pub use fallback::strip_subset_tag; -use regions::{alignment_frame, group_blocks, is_centred, rewrite_changed_words, rewrite_styled_block}; +use regions::{alignment_frame, existing_gap, group_blocks, is_centred, rewrite_changed_words, rewrite_styled_block, row_sources, source_row_step}; pub use session::TextSession; mod blocks; diff --git a/crates/edit/src/text/blocks.rs b/crates/edit/src/text/blocks.rs index db4fa4f2db..9593b184c7 100644 --- a/crates/edit/src/text/blocks.rs +++ b/crates/edit/src/text/blocks.rs @@ -517,6 +517,14 @@ pub struct BlockStyle { pub underline: Option, /// Line spacing as a multiple of the font size (1.2 is ordinary). pub line_spacing: Option, + /// Space between paragraphs, in points, beyond the line spacing; `Some(0.0)` is none. Unset, a + /// paragraph the page did not have (a line break the edit inserted) gets half the size and a + /// row the page had keeps the space it had above it, on both paths. Where the text keeps the + /// page's rows in place (styled), a line break starts a paragraph only on a new row or on a + /// row the page had already set apart, and a set spacing replaces the space it had. Where the + /// text is laid out afresh (a chosen family or weight), a set spacing goes before every line + /// break, replacing what was there. + pub paragraph_spacing: Option, /// Character spacing (points) and horizontal scaling (percent). pub char_spacing: Option, pub scale: Option, diff --git a/crates/edit/src/text/rewrite.rs b/crates/edit/src/text/rewrite.rs index 68699e4a4f..baea82d429 100644 --- a/crates/edit/src/text/rewrite.rs +++ b/crates/edit/src/text/rewrite.rs @@ -10,8 +10,8 @@ use super::lines::{ text_lines, }; use super::{ - Dict, Document, EditError, HashMap, HashSet, Matrix, Metrics, Object, Op, PdfString, TextLine, TextSession, alignment_frame, group_blocks, - is_centred, parse, rewrite_changed_words, rewrite_styled_block, + Dict, Document, EditError, HashMap, HashSet, Matrix, Metrics, Object, Op, PdfString, TextLine, TextSession, alignment_frame, existing_gap, + group_blocks, is_centred, parse, rewrite_changed_words, rewrite_styled_block, row_sources, source_row_step, }; /// What replacing a line did. @@ -377,7 +377,8 @@ fn choose_rewrite_path( /// The paragraph's text for writing back: explicit line breaks stay (#1443), and so does each typed /// U+0020 space: a run of them is not folded into one (#4199, #3797). Every [`row_break`] is a break -/// too; other white space is written as one space. +/// too; other white space is written as one space. A line break also starts a paragraph, with the +/// paragraph spacing before it. fn paragraph_text(text: &str) -> String { text.replace("\r\n", "\n") .chars() @@ -389,6 +390,68 @@ fn paragraph_text(text: &str) -> String { .collect() } +/// The wrapped lines, and for each the paragraph it starts (see [`wrap_paragraphs`]). +type Wrapped = (Vec<(String, bool, usize)>, Vec>); + +/// Every paragraph (text between line breaks) wrapped on its own, with, per line, the number of +/// the paragraph it starts when it is a paragraph's first line after the first paragraph. +fn wrap_paragraphs(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Wrapped { + let (mut wrapped, mut starts) = (Vec::new(), Vec::new()); + for (paragraph, text) in text.split('\n').enumerate() { + for (line, wrapped_line) in wrap(text, width, &advance).into_iter().enumerate() { + wrapped.push(wrapped_line); + starts.push((paragraph > 0 && line == 0).then_some(paragraph)); + } + } + (wrapped, starts) +} + +/// The gap before each wrapped line, in text space, beyond the line step: none except before the +/// first line of a paragraph after the first (`starts` says which paragraph that is). +/// +/// A spacing that is set (`Some(0.0)` is none) goes before every such line: every line is laid out +/// afresh, and it replaces whatever space the page had there. Unset, the paragraphs follow the same +/// rule as the styled path (`RowSpacing`): a paragraph the draft's line break started anew gets +/// half the size, and one the page already had keeps the space it had above it, so choosing a +/// family or applying the draft again moves no source row. Which paragraph is which comes from +/// aligning the draft to the source's rows ([`row_sources`]). +fn paragraph_gaps( + (b, lines): (&TextBlock, &[TextLine]), + text: &str, + starts: &[Option], + style: &BlockStyle, + (k, size): (f64, f64), +) -> Result, EditError> { + match style.paragraph_spacing { + Some(p) if p.is_finite() => { + let gap = (p / k).clamp(0.0, 14_400.0); + return Ok(starts.iter().map(|s| if s.is_some() { gap } else { 0.0 }).collect()); + } + Some(_) => return Err(EditError::Invalid("the paragraph spacing must be a number".into())), + None => {} + } + let mut at = 0; + let ranges: Vec> = text + .split('\n') + .map(|paragraph| { + let range = at..at + paragraph.chars().count(); + at = range.end + 1; + range + }) + .collect(); + let explicit: Vec = (0..ranges.len()).map(|i| i > 0).collect(); + let sources = row_sources(b, text, &ranges, &explicit); + let row_step = source_row_step(b, lines, size * k * 1.5); + Ok(starts + .iter() + .map(|s| match s.and_then(|paragraph| sources.get(paragraph)) { + Some(Some(source)) => existing_gap(b, lines, row_step, *source) / k, + Some(None) => size / 2.0, + None => 0.0, + }) + .collect()) +} + /// Where a paragraph sits on its page, for choosing the width it is laid out in. struct ParaGeometry { rect: [f64; 4], @@ -683,9 +746,21 @@ struct LineWriter<'a> { lead: f64, } +/// Where a wrapped line stands in its paragraph. +#[derive(Clone, Copy)] +struct LineRow { + /// The last line of the text (not justified). + last: bool, + /// The gap before the line, beyond the line step: set only on a paragraph's first line after + /// the first (see [`paragraph_gaps`]). + gap: f64, +} + /// What carries over from one line to the next. struct LineCursor { x: f64, + /// How far the lines have moved down from the first, in text space. + y: f64, tw_set: f64, shown_font: String, } @@ -731,7 +806,7 @@ impl LineWriter<'_> { index: usize, line: &str, wrap: (usize, bool, usize), - last: bool, + pos: LineRow, cursor: &mut LineCursor, ops: &mut Vec, ) -> Result<(f64, f64, f64), EditError> { @@ -740,9 +815,11 @@ impl LineWriter<'_> { let line_align = self.align_of(row); let body = line.trim_matches(' '); let interior = body.matches(' ').count(); - let tw = self.stretch(body, last, line_align == Some(crate::added::Align::Justify)); + let tw = self.stretch(body, pos.last, line_align == Some(crate::added::Align::Justify)); let (shown, visible) = self.shown(line, body, tw); let dx = if tw > 0.0 { 0.0 } else { self.alignment.offset(visible, line_align) }; + // The line step, plus the gap before a paragraph's first line. + let step = if index > 0 { self.lead + pos.gap } else { 0.0 }; if index > 0 { // Inside this text object, so the marker starts and ends here. `/PCHard` is a newline // that was already in the text. `/PCSoft` rejoins when the box widens, with `/N` the @@ -759,9 +836,10 @@ impl LineWriter<'_> { ops.push(Op::new("EMC", vec![])); } if index > 0 || dx != 0.0 { - ops.push(Op::new("Td", vec![n(dx - cursor.x), n(if index > 0 { -self.lead } else { 0.0 })])); + ops.push(Op::new("Td", vec![n(dx - cursor.x), n(-step)])); } cursor.x = dx; + cursor.y -= step; // Word spacing reaches only single-byte code 32 (ISO 32000-1 §9.3.3), so where a space is // shown with another code (a composite font, a generated Type 3 font, a subset without a // space) the extra space follows each space as a TJ adjustment instead. @@ -790,7 +868,7 @@ impl LineWriter<'_> { let tw = tw + stretch; // Underlined to the line's last word, over its stretched gaps. let w = (visible + tw * interior as f64 * self.scale * self.k) / self.k; - Ok((dx, dx + w, -(index as f64) * self.lead - self.size * 0.12)) + Ok((dx, dx + w, cursor.y - self.size * 0.12)) } fn show_piece(&self, piece: &str, line: &str, tw: f64, cursor: &mut LineCursor, ops: &mut Vec) -> Result<(), EditError> { @@ -825,7 +903,13 @@ impl LineWriter<'_> { } /// Writes every wrapped line, returning their underlines. - fn write_all(&self, wrapped: &[(String, bool, usize)], cursor: &mut LineCursor, ops: &mut Vec) -> Result, EditError> { + fn write_all( + &self, + wrapped: &[(String, bool, usize)], + gaps: &[f64], + cursor: &mut LineCursor, + ops: &mut Vec, + ) -> Result, EditError> { let mut row = 0usize; wrapped .iter() @@ -834,7 +918,11 @@ impl LineWriter<'_> { if i > 0 && !soft { row = row.saturating_add(1); } - self.write_line(i, line, (row, *soft, *gap), i + 1 == wrapped.len(), cursor, ops) + // Every line but the last is justified: a line break in the draft separates the rows + // of one paragraph, as the paragraph editor sends them, not paragraphs. + let last = i + 1 >= wrapped.len(); + let pos = LineRow { last, gap: gaps.get(i).copied().unwrap_or(0.0) }; + self.write_line(i, line, (row, *soft, *gap), pos, cursor, ops) }) .collect() } @@ -855,7 +943,13 @@ struct BlockPlan<'a> { underline: bool, } -fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[(String, bool, usize)], show_font: String) -> Result, EditError> { +fn block_ops( + plan: &BlockPlan<'_>, + writer: &LineWriter<'_>, + wrapped: &[(String, bool, usize)], + gaps: &[f64], + show_font: String, +) -> Result, EditError> { let n = pdfcraft_content::num; let mut ops = vec![Op::new("q", vec![])]; ops.extend(reveal_ops(plan.block, plan.lines, plan.style, plan.emit.ctm)?); @@ -871,14 +965,14 @@ fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[(String, let mut state = plan.state.clone(); state.word_spacing = 0.0; // The font the next run is shown in: the one the BT sets, until a run of another fallback subset. - let mut cursor = LineCursor { x: 0.0, tw_set: 0.0, shown_font: show_font.clone() }; + let mut cursor = LineCursor { x: 0.0, y: 0.0, tw_set: 0.0, shown_font: show_font.clone() }; state.font = Some((show_font, plan.size)); if let Some([r, g, bl]) = plan.style.color { state.fill = vec![Op::new("rg", vec![n(r), n(g), n(bl)])]; } ops.extend(state.ops()); ops.push(Op::new("Tm", plan.tm.iter().map(|v| n(*v)).collect())); - let underlines = writer.write_all(wrapped, &mut cursor, &mut ops)?; + let underlines = writer.write_all(wrapped, gaps, &mut cursor, &mut ops)?; ops.push(Op::new("ET", vec![])); if plan.underline { ops.extend(underline_ops(&state.fill, &plan.tm, plan.size, &underlines)); @@ -1085,7 +1179,8 @@ pub(crate) fn rewrite_block_from( width }; let right_edge = if anchored_right { right_edge } else { width }; - let wrapped = wrap(&text, width + 0.5, |s| advance.of(s)); + // Every paragraph wrapped on its own; `starts` marks a paragraph's first line (but the first's). + let (wrapped, starts) = wrap_paragraphs(&text, width + 0.5, |s| advance.of(s)); let font = choose_font( &FontInputs { source: source_metrics, @@ -1101,6 +1196,7 @@ pub(crate) fn rewrite_block_from( &mut fonts_res, )?; let lead = line_lead(&b, &lines, style, &LeadScale { k, size, old_size, leading: o_state.leading }); + let gaps = paragraph_gaps((&b, &lines), &text, &starts, style, (k, size))?; let start = last.ops.first().copied().unwrap_or(emit.bt_op); let split = shows_before_paragraph(&ops, emit.bt_op, start, &dropped); // What the text after the paragraph expects, and what is in force where the paragraph is @@ -1149,7 +1245,7 @@ pub(crate) fn rewrite_block_from( size, underline: style.underline == Some(true), }; - let mut block_ops = block_ops(&plan, &writer, &wrapped, font.show_font.clone())?; + let mut block_ops = block_ops(&plan, &writer, &wrapped, &gaps, font.show_font.clone())?; let on_top = crate::lift_on_top(over, &mut block_ops); block_ops.extend(after.ops().into_iter().filter(|op| !op.is("Tf") || after.font.is_some())); if split { diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rs index ee808a8dec..c879cb1d92 100644 --- a/crates/edit/src/text_regions.rs +++ b/crates/edit/src/text_regions.rs @@ -17,4 +17,4 @@ mod styled; pub(super) use grouping::{alignment_frame, group_blocks, group_reading_blocks, is_centred}; pub(super) use ocr_words::rewrite_changed_words; -pub(super) use styled::rewrite_styled_block; +pub(super) use styled::{existing_gap, rewrite_styled_block, row_sources, source_row_step}; diff --git a/crates/edit/src/text_regions/styled.rs b/crates/edit/src/text_regions/styled.rs index a1beb291f9..63d32c4755 100644 --- a/crates/edit/src/text_regions/styled.rs +++ b/crates/edit/src/text_regions/styled.rs @@ -370,6 +370,8 @@ fn styled_run_end(items: &[StyledChar], start: usize) -> usize { type StyledRows = Vec>; type RowRanges = Vec>; +/// Which rows a line break in the draft started, as against wrapping. +type ExplicitRows = Vec; enum ShapedFont { Existing(Vec<(String, Vec)>), Program { bytes: Vec, family: String }, @@ -672,7 +674,10 @@ fn page_font_metrics( } fn paragraph_geometry(doc: &Document, page: &pdfcraft_model::Page, block: &TextBlock, style: &BlockStyle) -> Result<(f64, f64, f64), EditError> { - if [style.size, style.line_spacing, style.char_spacing, style.scale, style.width].iter().flatten().any(|value| !value.is_finite()) + if [style.size, style.line_spacing, style.paragraph_spacing, style.char_spacing, style.scale, style.width] + .iter() + .flatten() + .any(|value| !value.is_finite()) || style.color.is_some_and(|color| color.iter().any(|value| !value.is_finite())) { return Err(EditError::Invalid("the paragraph's formatting must use finite numbers".into())); @@ -699,7 +704,7 @@ fn row_step(style: &BlockStyle, size: f64, source_leading: f64) -> f64 { } } -type WrappedStyledRows = (StyledRows, RowRanges, Vec, Vec, Vec); +type WrappedStyledRows = (StyledRows, RowRanges, Vec, Vec, Vec, ExplicitRows); /// For each of `chars`, whether a row may end just before it inside a run of non-space characters /// (Chinese, Japanese and Thai), worked out once per run: Thai words need the whole run, not just @@ -743,6 +748,9 @@ fn wrap_styled_rows( let mut row_lines: Vec = Vec::new(); let mut draft_line = 0usize; let mut row_start = 0; + // Which rows a line break in the draft started, as against wrapping: the paragraph spacing, + // when one is set, goes before those. + let mut explicit: ExplicitRows = vec![false]; let mut row = Vec::new(); let mut row_width = 0.0; let mut at = 0; @@ -761,6 +769,7 @@ fn wrap_styled_rows( row_lines.push(draft_line); draft_line = draft_line.saturating_add(1); rows.push(std::mem::take(&mut row)); + explicit.push(true); row_width = 0.0; at += 1; row_start = at; @@ -788,6 +797,7 @@ fn wrap_styled_rows( row_ranges.push(row_start..row_start + row.len()); row_lines.push(draft_line); rows.push(std::mem::take(&mut row)); + explicit.push(false); row_width = 0.0; row_start = at; } @@ -802,7 +812,7 @@ fn wrap_styled_rows( row_lines.push(draft_line); rows.push(row); } - Ok((rows, row_ranges, row_lines, row_soft, row_gap)) + Ok((rows, row_ranges, row_lines, row_soft, row_gap, explicit)) } fn apply_range_styles<'a>( @@ -1282,23 +1292,104 @@ fn shape_source(doc: &Document, fonts: &Dict, thai: &ThaiShaping, name: &str, te ))) } +/// Where a paragraph spacing puts each row. The space before a paragraph, when a paragraph +/// spacing is set: the draft breaks every source row, so a break starts a paragraph only where +/// the edit inserted it, or at a source break whose row was already set apart from the row above +/// by more than the ordinary row step; there the set spacing replaces the space it had. A row +/// that starts a source row keeps that row's step from the row drawn above it, so the rows below +/// an inserted break or spacing move down with it instead of being drawn over it. +struct RowSpacing<'a> { + block: &'a TextBlock, + lines: &'a [TextLine], + first: &'a TextLine, + gap: f64, + /// Whether the spacing was asked for. Unset, the default gap goes only before a paragraph the + /// page did not have: a row it already had, whether set apart or not, keeps where it was, so + /// choosing a family or applying the draft again moves no source row. + set: bool, + row_step: f64, + /// The source row each output row starts, if any. + sources: Vec>, + explicit: ExplicitRows, + /// Rows keep their source baselines unless the size or the line spacing is changed. + follow_source: bool, + /// The baseline the row above was drawn on. + previous: Option, +} + +impl<'a> RowSpacing<'a> { + fn new( + block: &'a TextBlock, + lines: &'a [TextLine], + first: &'a TextLine, + style: &BlockStyle, + row_ranges: &[std::ops::Range], + draft: &str, + explicit: ExplicitRows, + ) -> Result { + let (gap, set) = match style.paragraph_spacing { + Some(p) if p.is_finite() => (p.clamp(0.0, 14_400.0), true), + Some(_) => return Err(EditError::Invalid("the paragraph spacing must be a number".into())), + // Half the size, for a paragraph the page did not have (see `set`). + None => (style.size.unwrap_or(first.size) / 2.0, false), + }; + let row_step = source_row_step(block, lines, first.size * 1.5); + let sources = row_sources(block, draft, row_ranges, &explicit); + Ok(Self { + block, + lines, + first, + gap, + set, + row_step, + sources, + explicit, + follow_source: style.line_spacing.is_none() && style.size.is_none(), + previous: None, + }) + } + + fn run_of(&self, row: usize) -> Option<&'a TextLine> { + self.block.rows.get(row).and_then(|r| r.first()).and_then(|i| self.lines.get(*i)) + } + + /// The baseline of output row `row_index`, given the one the row above ended on (`baseline`), + /// and the source run the row is styled from. + fn place(&mut self, row_index: usize, mut baseline: f64) -> (f64, &'a TextLine) { + let source_row = self.sources.get(row_index).copied().flatten(); + let anchor = source_row.and_then(|j| self.run_of(j)); + // The baseline of the source row above the source row this row starts. + let above = source_row.and_then(|j| self.run_of(j.checked_sub(1)?)).map(|l| l.origin.baseline); + // The space this row already had above it, beyond the ordinary row step. + let existing = source_row.map_or(0.0, |j| existing_gap(self.block, self.lines, self.row_step, j)); + let starts_paragraph = + row_index > 0 && self.explicit.get(row_index).copied().unwrap_or(false) && (anchor.is_none() || (self.set && existing > 0.5)); + let paragraph = starts_paragraph.then_some(self.gap); + if self.follow_source { + match (anchor, above, self.previous) { + // The source's step down from the row above, kept from where that row was drawn; + // written `here - (above - previous)` so a row below unmoved rows lands exactly + // on its source baseline. + (Some(a), Some(above), Some(previous)) => { + baseline = a.origin.baseline - (above - previous) - paragraph.map_or(0.0, |gap| gap - existing); + } + (Some(a), _, None) => baseline = a.origin.baseline, + _ => baseline -= paragraph.unwrap_or(0.0), + } + } else { + baseline -= paragraph.unwrap_or(0.0); + } + self.previous = Some(baseline); + (baseline, anchor.or_else(|| self.run_of(row_index)).unwrap_or(self.first)) + } +} + /// For each output row (a range of the draft's characters), whether it is exactly the source row /// at the same position: the same characters, none of them inserted or changed by the edit. fn untouched_rows(block: &TextBlock, draft: &str, rows: &[std::ops::Range]) -> Vec { let old: Vec = block.editor_text.chars().collect(); let new: Vec = draft.chars().collect(); - let prefix = old.iter().zip(&new).take_while(|(a, b)| a == b).count(); - let suffix = old.iter().rev().zip(new.iter().rev()).take(old.len().min(new.len()).saturating_sub(prefix)).take_while(|(a, b)| a == b).count(); - // The source character a draft character is, if the edit left it alone. - let origin = |i: usize| { - if i < prefix { - Some(i) - } else if i >= new.len().saturating_sub(suffix) { - (old.len() + i).checked_sub(new.len()) - } else { - None - } - }; + let origins = Origins::new(&old, &new); let mut source_rows = Vec::new(); let mut start = 0; for (i, ch) in old.iter().enumerate() { @@ -1316,7 +1407,7 @@ fn untouched_rows(block: &TextBlock, draft: &str, rows: &[std::ops::Range .enumerate() .map(|(r, range)| { source_rows.get(r).is_some_and(|source| { - !range.is_empty() && range.len() == source.len() && range.clone().zip(source.clone()).all(|(i, j)| origin(i) == Some(j)) + !range.is_empty() && range.len() == source.len() && range.clone().zip(source.clone()).all(|(i, j)| origins.of(i) == Some(j)) }) }) .collect() @@ -1514,6 +1605,159 @@ fn rewrite_anchor<'a>( RewriteAnchor { lead, drop, start, split } } +/// Which source character each draft character is, where the edit left it alone. The text is +/// aligned a line at a time first: the lines the source and the draft share at their start and +/// at their end are the same lines, so a whole line inserted exactly at a line boundary is +/// attributed to the lines between them, whatever the characters around it are (a character +/// prefix and suffix cannot tell `Two\nNew\nThree` from `Two\nThree` where the break is). Between +/// them, what is left of each is aligned by its common character prefix and suffix. +struct Origins { + of: Vec>, +} + +/// The lines of `text` as character ranges, each with its line break (the last has none). +fn line_ranges(text: &[char]) -> Vec> { + let mut lines = Vec::new(); + let mut start = 0; + for (i, ch) in text.iter().enumerate() { + if *ch == '\n' { + lines.push(start..i + 1); + start = i + 1; + } + } + lines.push(start..text.len()); + lines +} + +impl Origins { + fn new(old: &[char], new: &[char]) -> Self { + let (old_lines, new_lines) = (line_ranges(old), line_ranges(new)); + // A line's text without its break, and whether it has one: lines are the same when the + // text is, and a break is shared only when both have it. + let text = |chars: &'_ [char], r: &std::ops::Range| -> (usize, usize) { + let end = if r.end > r.start && chars[r.end - 1] == '\n' { r.end - 1 } else { r.end }; + (r.start, end) + }; + let same = |o: &std::ops::Range, n: &std::ops::Range| { + let ((os, oe), (ns, ne)) = (text(old, o), text(new, n)); + old[os..oe] == new[ns..ne] + }; + let mut of = vec![None; new.len()]; + let mut pair = |o: &std::ops::Range, n: &std::ops::Range, with_break: bool| { + let ((os, oe), (ns, ne)) = (text(old, o), text(new, n)); + for k in 0..oe - os { + of[ns + k] = Some(os + k); + } + if with_break && o.end > oe && n.end > ne { + of[ne] = Some(oe); + } + }; + let (ol, nl) = (old_lines.len(), new_lines.len()); + let limit = ol.min(nl); + let head = (0..limit).take_while(|&k| same(&old_lines[k], &new_lines[k])).count(); + let tail = (0..limit - head).take_while(|&k| same(&old_lines[ol - 1 - k], &new_lines[nl - 1 - k])).count(); + let (old_gap, new_gap) = (ol - head - tail, nl - head - tail); + for k in 0..head { + // The break after the last of them is the source's only when nothing lies between. + let last = k + 1 == head; + pair(&old_lines[k], &new_lines[k], !last || (old_gap == 0 && new_gap == 0)); + } + for k in 1..=tail { + pair(&old_lines[ol - k], &new_lines[nl - k], true); + } + let from_here = |lines: &[std::ops::Range], at: usize, len: usize| lines.get(at).map_or(len, |r| r.start); + if old_gap > 0 && new_gap > 0 { + // Lines the edit changed: aligned by the characters they share at their start and + // at their end, from the break before them to the break after. + let before = |lines: &[std::ops::Range]| if head > 0 { lines[head - 1].end - 1 } else { 0 }; + let old_mid = before(&old_lines)..from_here(&old_lines, ol - tail, old.len()); + let new_mid = before(&new_lines)..from_here(&new_lines, nl - tail, new.len()); + let (om, nm) = (&old[old_mid.clone()], &new[new_mid.clone()]); + let prefix = om.iter().zip(nm).take_while(|(a, b)| a == b).count(); + let suffix = om.iter().rev().zip(nm.iter().rev()).take(om.len().min(nm.len()) - prefix).take_while(|(a, b)| a == b).count(); + for k in 0..prefix { + of[new_mid.start + k] = Some(old_mid.start + k); + } + for k in 1..=suffix { + of[new_mid.end - k] = Some(old_mid.end - k); + } + // The same number of lines on both sides: each is the line at its own position, so + // the breaks between them are the source's (an edited row is still that row). + if old_gap == new_gap { + for k in 0..old_gap { + let (o, n) = (&old_lines[head + k], &new_lines[head + k]); + if old[o.end - 1] == '\n' && new[n.end - 1] == '\n' { + of[n.end - 1] = Some(o.end - 1); + } + } + } + } else if tail > 0 { + // A whole line (or lines) inserted or removed: the break before the first line that + // follows is the same break in both, and no other break in between is the source's. + if let (Some(n), Some(o)) = (new_lines[nl - tail].start.checked_sub(1), old_lines[ol - tail].start.checked_sub(1)) { + of[n] = Some(o); + } + } + Self { of } + } + + /// The source character the draft character `i` is, if the edit left it alone. + fn of(&self, i: usize) -> Option { + self.of.get(i).copied().flatten() + } +} + +/// The baseline of source row `row`'s first run. +fn source_baseline(block: &TextBlock, lines: &[TextLine], row: usize) -> Option { + block.rows.get(row).and_then(|r| r.first()).and_then(|i| lines.get(*i)).map(|l| l.origin.baseline) +} + +/// The ordinary step between the block's source rows: the smallest, or `fallback` for one row. +pub(crate) fn source_row_step(block: &TextBlock, lines: &[TextLine], fallback: f64) -> f64 { + (1..block.rows.len()) + .filter_map(|r| Some(source_baseline(block, lines, r - 1)? - source_baseline(block, lines, r)?)) + .filter(|v| *v > 0.0) + .fold(None, |min: Option, v| Some(min.map_or(v, |m| m.min(v)))) + .unwrap_or(fallback) +} + +/// The space source row `row` already had above it, beyond the ordinary `row_step`. +pub(crate) fn existing_gap(block: &TextBlock, lines: &[TextLine], row_step: f64, row: usize) -> f64 { + match (source_baseline(block, lines, row), row.checked_sub(1).and_then(|r| source_baseline(block, lines, r))) { + (Some(here), Some(above)) => (above - here - row_step).max(0.0), + _ => 0.0, + } +} + +/// For each output row (a range of the draft's characters), the source row it starts: row 0 +/// starts row 0, and a row the draft's line break started (`explicit`) starts the source row +/// after that break when the break is one of the source's, left alone by the edit. A wrapped +/// row, or one after a break the edit inserted, starts none. When the source rows can't be told +/// apart by their line breaks, each row is paired with the source row at its own position. +pub(crate) fn row_sources(block: &TextBlock, draft: &str, rows: &[std::ops::Range], explicit: &[bool]) -> Vec> { + let old: Vec = block.editor_text.chars().collect(); + let breaks: Vec = old.iter().enumerate().filter(|(_, c)| **c == '\n').map(|(i, _)| i).collect(); + if breaks.len().saturating_add(1) != block.rows.len() { + return (0..rows.len()).map(Some).collect(); + } + let new: Vec = draft.chars().collect(); + let origins = Origins::new(&old, &new); + rows.iter() + .enumerate() + .map(|(r, range)| { + if r == 0 { + return Some(0); + } + if !explicit.get(r).copied().unwrap_or(false) { + return None; + } + // The draft's line break is the character just before the row. + let source = origins.of(range.start.checked_sub(1)?)?; + breaks.binary_search(&source).ok().map(|k| k + 1) + }) + .collect() +} + /// Open (`op` is `"BMC"`) or close (`"EMC"`) the `/P` marker that wraps the whole rewrite when /// `marked` (every row is in this rewrite, see [`rewrite_styled_block`]), so the paragraph /// cannot be mistaken for a neighbour by geometry alone (#2517). @@ -1722,7 +1966,7 @@ pub(crate) fn rewrite_styled_block( } Ok(width) }; - let (mut rows, row_ranges, row_lines, row_soft, row_gap) = wrap_styled_rows(&chars, width, measure)?; + let (mut rows, row_ranges, row_lines, row_soft, row_gap, explicit) = wrap_styled_rows(&chars, width, measure)?; let space_styles: Vec<_> = rows.iter_mut().map(|row| assign_subset_space_fonts(row, &metrics)).collect(); let streams = content_streams(doc, &p.dict)?; let pieces = crate::text::joined(&streams); @@ -1783,6 +2027,7 @@ pub(crate) fn rewrite_styled_block( }) .rfind(|v| *v > 0.0) .unwrap_or(first.size * 1.5); + let mut spacing = RowSpacing::new(block, lines, first, style, &row_ranges, draft, explicit)?; // Revealed OCR text that something is painted over goes on top of the page, where it starts // from the initial state. let largest = @@ -1798,14 +2043,8 @@ pub(crate) fn rewrite_styled_block( let drawn_from = if over { &initial } else { after }; let mut baseline = first.origin.baseline; for (row_index, row) in rows.iter().enumerate() { - let anchor = block.rows.get(row_index).and_then(|r| r.first()).and_then(|i| lines.get(*i)); - if style.line_spacing.is_none() - && style.size.is_none() - && let Some(anchor) = anchor - { - baseline = anchor.origin.baseline; - } - let anchor = anchor.unwrap_or(first); + let anchor; + (baseline, anchor) = spacing.place(row_index, baseline); if kept.get(row_index).copied().unwrap_or(false) { // Kept rows only occur without spacing or size changes, so this is the step below. baseline -= source_leading; diff --git a/crates/ui-egui/src/panels/format_text_ui.rs b/crates/ui-egui/src/panels/format_text_ui.rs index 412563b026..09e08bad64 100644 --- a/crates/ui-egui/src/panels/format_text_ui.rs +++ b/crates/ui-egui/src/panels/format_text_ui.rs @@ -3,7 +3,7 @@ //! horizontal scale and character spacing. One panel serves a paragraph being edited (with the //! fonts already on its page and the spacing controls) and added text (the standard families, //! size, colour, style, alignment and character spacing). What PdfCraft can't apply yet (lists, -//! paragraph spacing, or line spacing and scale for added text) is shown +//! or line and paragraph spacing and scale for added text) is shown //! disabled and says so. //! //! The icons are Lucide's (AGENTS.md §1); only the arrangement follows Acrobat. @@ -97,6 +97,7 @@ const SIZES: [f64; 16] = [4.0, 6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0 const LINE_SPACINGS: [f64; 7] = [1.0, 1.15, 1.2, 1.5, 2.0, 2.5, 3.0]; const SCALES: [f64; 8] = [50.0, 75.0, 90.0, 100.0, 110.0, 125.0, 150.0, 200.0]; const CHAR_SPACINGS: [f64; 8] = [-1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0, 5.0]; +const PARAGRAPH_SPACINGS: [f64; 5] = [0.0, 6.0, 12.0, 18.0, 24.0]; /// A row's height: the tallest control in it (the 30 pt icon buttons). Every control is centred /// on the row, whatever its own height, so lists, swatches and buttons line up (#3037). const ROW: f32 = 30.0; @@ -127,6 +128,7 @@ pub(crate) const MIN_ROW: f32 = { /// What can be typed: horizontal scale in percent, character spacing in points. const SCALE_RANGE: std::ops::RangeInclusive = 10.0..=400.0; const CHAR_SPACING_RANGE: std::ops::RangeInclusive = -5.0..=50.0; +const PARAGRAPH_SPACING_RANGE: std::ops::RangeInclusive = 0.0..=72.0; /// A number as the lists show it: no trailing zeros ("1.2", "100", "-0.5"). fn number(v: f64) -> String { @@ -374,19 +376,10 @@ pub(crate) fn panel( spacing_resp.on_hover_text(&shown); }); ui.add_space(8.0); - ui.add_enabled_ui(false, |ui| { - let label = labelled_icon(ui, t, "pilcrow", tl!("Paragraph spacing")); - let tip = format!("{} — {}", tl!("Paragraph spacing"), tl!("Planned")); - let _ = outlined(ui, |ui| { - craft_ui::ComboBox::from_id_salt("format-paragraph-spacing") - .selected_text(centred(ui, "0")) - .width(half) - .show_ui(ui, |_| {}) - .response - .labelled_by(label.id) - .on_disabled_hover_text(tip) - }); - }); + let label = labelled_icon(ui, t, "pilcrow", tl!("Paragraph spacing")); + let spacing = Number { value: &mut e.paragraph_spacing, range: PARAGRAPH_SPACING_RANGE, speed: 0.5, suffix: " pt" }; + number_with_presets(ui, spacing, &PARAGRAPH_SPACINGS, half, (label.id, tl!("Paragraph spacing"))) + .on_hover_text(tl!("Between paragraphs: press Enter in the box to start one")); }); }); // Any value the engine takes can be typed; the lists hold the common ones. Added text has @@ -494,28 +487,34 @@ fn preset_arrow(ui: &mut egui::Ui, label: &str) -> egui::Response { } /// One box round a value and its arrow, like a list's, so the pair reads as a single control. -fn boxed(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { +fn boxed(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { let t = Tokens::get(ui.ctx()); let edge = if ui.is_enabled() { t.border } else { t.border.gamma_multiply(0.5) }; - egui::Frame::new().fill(t.field).stroke(Stroke::new(1.0, edge)).corner_radius(CornerRadius::same(4)).show(ui, |ui| { - let w = &mut ui.visuals_mut().widgets; - for state in [&mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open] { - state.bg_stroke = Stroke::NONE; - } - w.inactive.weak_bg_fill = Color32::TRANSPARENT; - ui.spacing_mut().item_spacing.x = 0.0; - ui.spacing_mut().button_padding.x = 2.0; - add(ui); - }); + egui::Frame::new() + .fill(t.field) + .stroke(Stroke::new(1.0, edge)) + .corner_radius(CornerRadius::same(4)) + .show(ui, |ui| { + let w = &mut ui.visuals_mut().widgets; + for state in [&mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open] { + state.bg_stroke = Stroke::NONE; + } + w.inactive.weak_bg_fill = Color32::TRANSPARENT; + ui.spacing_mut().item_spacing.x = 0.0; + ui.spacing_mut().button_padding.x = 2.0; + add(ui) + }) + .inner } /// A number field with an arrow beside it that lists common values, in `width` all told: type any /// value in its range, or pick one. Both are named by `label`: the icon before them and its text. -fn number_with_presets(ui: &mut egui::Ui, n: Number<'_>, presets: &[f64], width: f32, label: (egui::Id, &str)) { +/// Returns the field. +fn number_with_presets(ui: &mut egui::Ui, n: Number<'_>, presets: &[f64], width: f32, label: (egui::Id, &str)) -> egui::Response { boxed(ui, |ui| { let field = egui::DragValue::new(&mut *n.value).range(n.range).speed(n.speed).max_decimals(2).suffix(n.suffix); - let drag_resp = ui.add_sized([(width - PRESET_LIST - 2.0).max(30.0), 26.0], field).labelled_by(label.0); - drag_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, ui.is_enabled(), label.1)); + let field = ui.add_sized([(width - PRESET_LIST - 2.0).max(30.0), 26.0], field).labelled_by(label.0); + field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, ui.is_enabled(), label.1)); let list = preset_arrow(ui, label.1); egui::Popup::menu(&list).show(|ui| { for &v in presets { @@ -525,7 +524,8 @@ fn number_with_presets(ui: &mut egui::Ui, n: Number<'_>, presets: &[f64], width: } } }); - }); + field + }) } /// The text colour as a square swatch that opens the palette. diff --git a/crates/ui-egui/src/tools/edit_text_ui.rs b/crates/ui-egui/src/tools/edit_text_ui.rs index 4f5b1642db..822dffd886 100644 --- a/crates/ui-egui/src/tools/edit_text_ui.rs +++ b/crates/ui-egui/src/tools/edit_text_ui.rs @@ -225,13 +225,16 @@ pub(crate) fn reselect(ctx: &egui::Context, id: egui::Id, text: &str, range: &st pub struct Extras { pub underline: bool, pub line_spacing: f64, + /// Space between paragraphs in points (a line break in the box starts one); 0 = unset (a + /// new paragraph gets half the size; rows the page had keep their space). + pub paragraph_spacing: f64, pub char_spacing: f64, pub scale: f64, } impl Default for Extras { fn default() -> Self { - Extras { underline: false, line_spacing: 0.0, char_spacing: 0.0, scale: 100.0 } + Extras { underline: false, line_spacing: 0.0, paragraph_spacing: 0.0, char_spacing: 0.0, scale: 100.0 } } } @@ -299,6 +302,7 @@ impl LineEditor { underline: (self.extras.underline != self.extras0.underline).then_some(self.extras.underline), line_spacing: (self.extras.line_spacing != self.extras0.line_spacing && self.extras.line_spacing > 0.0) .then_some(self.extras.line_spacing), + paragraph_spacing: (self.extras.paragraph_spacing != self.extras0.paragraph_spacing).then_some(self.extras.paragraph_spacing), char_spacing: (self.extras.char_spacing != self.extras0.char_spacing).then_some(self.extras.char_spacing), scale: (self.extras.scale != self.extras0.scale).then_some(self.extras.scale), ..Default::default() diff --git a/crates/ui-egui/tests/it/content.rs b/crates/ui-egui/tests/it/content.rs index 76d8d68d0a..6cfec4e1ef 100644 --- a/crates/ui-egui/tests/it/content.rs +++ b/crates/ui-egui/tests/it/content.rs @@ -704,9 +704,13 @@ fn format_text_rows_line_up_and_fit_the_panel() { assert!((middle(size) - middle(other)).abs() < 0.5, "the size list ({size:?}) is centred with {label} ({other:?})"); } assert_eq!(size.height(), font.height(), "the font and size lists are the same height"); - // Line and paragraph spacing; scale and character spacing with their lists. - let line = [combo(&h, "Auto"), combo(&h, "0")]; - assert!((middle(line[0]) - middle(line[1])).abs() < 0.5, "{line:?}"); + // Line spacing, and paragraph spacing, scale and character spacing with their lists. + let line = combo(&h, "Auto"); + let paragraph: Vec = h.query_all_by_label("Paragraph spacing").map(|n| n.rect()).collect(); + assert_eq!(paragraph.len(), 2, "the paragraph spacing field and its arrow: {paragraph:?}"); + for r in ¶graph { + assert!((middle(line) - middle(*r)).abs() < 0.5, "{line:?} {paragraph:?}"); + } // Each: its number field and the arrow that lists common values. let scale_row: Vec = ["Horizontal scale", "Character spacing"].iter().flat_map(|l| h.query_all_by_label(l).map(|n| n.rect())).collect(); @@ -714,7 +718,8 @@ fn format_text_rows_line_up_and_fit_the_panel() { for r in &scale_row { assert!((middle(*r) - middle(scale_row[0])).abs() < 0.5, "{scale_row:?}"); } - for r in h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).chain(scale_row).chain([size, h.get_by_label("Font size").rect()]) { + for r in h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).chain(scale_row).chain(paragraph).chain([size, h.get_by_label("Font size").rect()]) + { assert!(r.right() <= font.right() + 0.5, "{r:?} reaches past the panel ({font:?})"); } } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 03d673abfa..a5716e6493 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -62,6 +62,7 @@ mod open_action; mod organize_drag; mod pageboxes; mod panel_snapshots; +mod paragraph_spacing; mod paste_ownership; mod pdf_links; mod pickers; diff --git a/crates/ui-egui/tests/it/paragraph_spacing.rs b/crates/ui-egui/tests/it/paragraph_spacing.rs new file mode 100644 index 0000000000..010da0a308 --- /dev/null +++ b/crates/ui-egui/tests/it/paragraph_spacing.rs @@ -0,0 +1,79 @@ +//! Format text's Paragraph spacing row edits the open paragraph's spacing. + +use egui::Key; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use pdfcraft_ui_egui::PdfCraftApp; + +/// A one-page document showing "Page 1". +fn fixture() -> Vec { + let body = "BT /F1 24 Tf 20 150 Td (Page 1) Tj ET"; + let objs = [ + "<< /Type /Catalog /Pages 2 0 R >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_string(), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(), + "<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << /Font << /F1 3 0 R >> >> >>".to_string(), + format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +/// The document open in Edit text with its paragraph in the editor. +fn editing() -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("doc.pdf", None, fixture()).expect("fixture opens"); + app + }); + h.run_steps(4); + assert!(h.state_mut().execute("edit.edit_text")); + h.run_steps(2); + let r = h.state().views[0].page_screen_rect(0).expect("on screen"); + let at = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height()); + h.hover_at(at); + h.run_steps(1); + h.drag_at(at); + h.run_steps(1); + h.drop_at(at); + h.run_steps(3); + assert!(h.state().views[0].line_editor.is_some()); + h +} + +fn paragraph_spacing(h: &Harness<'static, PdfCraftApp>) -> Option { + h.state().views[0].line_editor.as_ref().map(|e| e.extras.paragraph_spacing) +} + +/// The row is a working field, not a placeholder: a value typed in it becomes the paragraph's +/// spacing and is applied as an edit. +#[test] +fn the_paragraph_spacing_field_edits_the_paragraph() { + let mut h = editing(); + h.get_by_label("FORMAT TEXT"); + let field = h.get_by_role_and_label(Role::SpinButton, "Paragraph spacing"); + assert!(!field.accesskit_node().is_disabled()); + assert_eq!(paragraph_spacing(&h), Some(0.0)); + field.click(); + h.run_steps(2); + h.event(egui::Event::Text("12".into())); + h.run_steps(1); + h.key_press(Key::Enter); + h.run_steps(4); + assert_eq!(paragraph_spacing(&h), Some(12.0)); + let s = h.state(); + assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Edit text")); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 3c411d9813..2eadbefd62 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2020,11 +2020,11 @@ title = "Line and paragraph spacing" area = "C" tier = "P1" milestone = "M7" -status = "partial" +status = "shipped" commands = ["edit.edit_text"] tools = ["text_edit"] -evidence = ["crates/edit/src/tests.rs::justify_underline_and_spacing", "crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited"] -notes = "line spacing (1, 1.15, 1.5, 2 × size or any multiple); space between paragraphs is not adjustable yet" +evidence = ["crates/edit/src/tests.rs::justify_underline_and_spacing", "crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited", "crates/edit/src/tests.rs::paragraph_breaks_get_their_own_spacing", "crates/edit/src/paragraph_spacing_break_tests.rs::styled_rows_take_the_spacing_before_an_inserted_break", "crates/edit/src/paragraph_spacing_break_tests.rs::styled_rows_replace_the_gap_a_row_already_had", "crates/edit/src/paragraph_spacing_break_tests.rs::a_new_single_style_paragraph_gets_half_the_size_when_no_spacing_is_set", "crates/edit/src/paragraph_spacing_break_tests.rs::single_style_source_rows_keep_their_steps_when_no_spacing_is_set", "crates/ui-egui/tests/it/paragraph_spacing.rs::the_paragraph_spacing_field_edits_the_paragraph"] +notes = "line spacing (1, 1.15, 1.5, 2 × size or any multiple); space between paragraphs: a line break in the edited text starts a paragraph, set apart by the Paragraph spacing value (points, beyond the line step; unset, a new paragraph gets half the size, in styled and single-style text alike, and a row the page had keeps where it was; a set value replaces the space a paragraph already had), each paragraph wrapped and justified on its own, a kept row shifted by the spacing added above it; the panel's Paragraph spacing field, text_edit's paragraph_spacing. Still missing against Acrobat: space before and after as separate values." [[feature]] id = "edit.char-spacing-scale" From d4da4b94bb3de846c0047877a7b0fc3b4cb79bae Mon Sep 17 00:00:00 2001 From: amoisttowe1 Date: Wed, 18 Nov 2026 01:29:46 -0800 Subject: [PATCH 11/27] M5.1: structural round-trip, property and never-crash tests for crates/annot (tests only) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this adds Structural round-trip, property and never-crash evidence for `crates/annot`, which had no `tests/` directory — every prior test checked an in-memory object and never crossed the writer. 50 new tests take the crate from 42 to **92 passing / 0 failed**, with nothing ignored and no existing test weakened: - `tests/round_trip.rs` (25) — annotations survive save and reopen across all three writer paths: geometry, contents text, flag bits, opacity, identifying names, pop-up back-references, link targets/URIs/dash structure, per-page order and ownership. - `tests/properties.rs` (10) — proptest invariants over generated geometry, opacity and flags. - `tests/malformed.rs` (15) — damaged input must never panic; each case documents the *measured* behaviour as defined degradation, not endorsed output. - `tests/support/{bytes.rs,fixture.rs}` — a raw-byte reader and PDF skeletons, so claims can be made about the saved file rather than only about parsed objects. `proptest = { workspace = true }` as a dev-dependency (same declaration as `cos`; style differs from the dotted form in crypt/filters). proptest 1.11.0 is already locked in the workspace, so `Cargo.lock` gains one edge and no new package. **No product code is changed.** This pins current behaviour, including three questionable behaviours it surfaced (below), and leaves every fix to a follow-up. ## Appearance is deliberately out of scope Nothing here asserts what an appearance stream draws, so this stays clear of #2345, #2137, #2066, #1775 and #1513 (all open, all rewriting appearance generation). Structural fidelity — where a mark sits, what it says, which rules apply — is behaviour none of them intends to alter. ## Evidence quality: mutation-tested, with credit split honestly Ten single-site guard/arithmetic/key-rename mutants were run against `crates/annot/src/lib.rs` by two independent reviewers plus the author. All ten were caught, and they split **five and five**: - Killed by pre-existing inline tests in `crates/annot/src/tests.rs` as well: `lib.rs:857` inverted, `:1030` inverted (six inline tests), `:1930` inverted, `:2161` tie-break swapped, `:1241` `/Parent` renamed. - Killed **only** by tests added here: `:1030` clamp deleted, `:857` clamp deleted, opacity clamp removed at `:1024`, colour clamp in `rgb()` removed at `:824`, and a clamp introduced on the read path at `:2238`. `lib.rs:857` and `:1030` appear on both sides deliberately — inverting either trips inline tests, deleting them trips nothing outside this branch. Confusing those two mutation families is easy enough to produce a false refutation, so the distinction is recorded in `round_trip.rs` rather than left to whoever re-runs them. A build failure was never counted as a kill in any pass. The mutants were run at `crates/annot/src/lib.rs` as of base `99941daa`. Main has since split that file into modules (`5ce4d244`); the anchor statements are byte-identical at their new homes (the `/Parent` site apart, locals renamed), but main also grew the inline suite from 42 to 74 tests — so the five-and-five split describes the base tree, and the battery was not re-run at the merge head `3122ebad`. ## Three defects found while writing this — reported, not fixed 1. **Large finite numbers are written unvalidated and become unreadable downstream.** The only style guard on the create path (`lib.rs:1018`) is `!finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite()`; the `abs() < 1e7` cap inside `finite()` (`:827-829`) applies to **colour alone**, so `width` carries no magnitude limit at all. Measured: `width = 1e9` and `1e299` are accepted and written verbatim to `/BS /W`. qpdf (`pikepdf.Job(["--check", …])`, pikepdf 9.11 / libqpdf 12.2) exits **3** — its *warning* status, printed with "operation succeeded with warnings" (0 = clean and silent here) — reporting `overflow/underflow converting <301 digits> to 64-bit integer`, and `/Annots[0]` resolves to `null` (still null after a qpdf re-save) while `pikepdf.open()` reports success. Our own `repair_log()` stays empty, which conflicts with CLAUDE.md's "never silently drop or repair data". 2. **Fill colour is accepted on create and refused on edit.** Create never screens `fill` (it is clamped component-wise by `rgb()` at `:823-825`), while `set_fill` refuses the identical value with `Invalid("invalid fill colour")` at `:2010`. Pinned by `malformed::the_same_huge_fill_is_accepted_on_create_and_refused_on_edit`. 3. **One unparseable token in a page's `/Annots` loses the whole page, silently.** For `[4 0 R notanumber]`, `page_refs()` returns `Ok([])` with `/Pages` still showing the page — so the page object itself fails to parse, every annotation on it disappears, and `repair_log()` records nothing. qpdf keeps the page and warns: `(object 3 0, offset 191): unknown token while reading object; treating as string`. Anchors in this section read against `crates/annot/src/lib.rs` at base `99941daa`; main has since split that file (`5ce4d244`). The same code at merge head `3122ebad`: `:1018` → `create.rs:416`, `:827-829` → `create.rs:17-19`, `:823-825` → `create.rs:13-15`, `:2010` → `modify.rs:626-627`. All three described behaviours re-verified unchanged at this head. These need a policy decision rather than a patch, so they are described here and will be filed as separate issues; nothing in this PR fixes them. ## CI status and base note This branch was opened at `afa8e18` (then current `main`) and rebased onto `99941da`. Two jobs were red on the original base — `test (ubuntu-latest)`, `test (windows-latest)` and the FreeBSD job, all failing in `crates/automation/tests/automation.rs` at `:354` (`signing_with_translated_labels_through_tools`, which passed a 7-character password against an 8-character minimum) and at `:359` (`a_save_that_does_not_reopen_leaves_the_file_as_it_was`), `173 passed; 2 failed`. Those were upstream failures reproduced on that commit's own CI run (**38703572296**, plus the FreeBSD run **38703573428**) in a crate this change never touches; they have since been fixed on `main` by #2420 (the signing password now meets the minimum) and #2484 (save/search regression expectations updated), which is why `main`'s latest CI run is green and why this branch was rebased. The rebase is a no-op for our code: `crates/annot/src/lib.rs` at both commits is byte-identical (`fb491e19…`), so every line number cited below still resolves as written. Since then `main` was merged in (`dc943eeb`, merge commit `3122ebad`) to clear the FreeBSD job per the CI triage on this PR: the `files_and_quit_from_the_operating_system` race was fixed on main by `12fcc641` (#2812). The merge probe was clean (zero conflicts; `Cargo.lock` the only overlapping path). Main split `crates/annot/src/lib.rs` into modules and reshaped `set_style` to take a `StyleChange`; the merge commit carries three tests-only adaptations (two `SaveOptions` literals gain `drop_unlinked: false`, the writer's default; one `set_style` call re-shaped; citations re-derived to the new file layout). No crate source diverges from main's: `git diff --stat upstream/main HEAD -- crates/annot/src/` is empty. Inline-suite counts at this head: 74 (main grew it from 42); the 42 → 92 figures above describe base `99941daa`. proptest on main's lock is now 1.12.0; one edge added, no new package. ## Where the proof stops - The first CI run on this branch was at our original base and showed the inherited failures described above; results cited here are local macOS runs (we have no Poppler locally, so qpdf cross-checks ran through pikepdf in a workspace virtualenv). - The probe PDFs used for qpdf measurements are **not** committed, because AGENTS.md §1 requires an `ATTRIBUTION.toml` entry per sample document — so CI cannot re-measure them. Each measurement carries a regenerate recipe and sha256 in the test comments (`malformed.rs`). - All oracle figures are tied to one machine's build: pikepdf 9.11 over libqpdf 12.2 (`__libqpdf_version__`; the Job API rejects `--version`, so no raw qpdf version string). Poppler comparisons would need CI, as `pdftoppm` is unavailable locally. - Mutation evidence covers single-site guard/arithmetic/key-rename mutants only — no multi-site, data-flow or off-by-one classes were attempted. - We did not measure what any viewer displays to a user after these failures; the listed-but-null entry was observed, not rendered behaviour. ## Question for maintainers CLAUDE.md asks new tests to be registered in `ROADMAP.md` and `parity/acrobat-features.toml`, but several open PRs above are editing both files right now, so we left them untouched to avoid collisions. Tell us where you would like these registered and we will add the lines here, or open a follow-up. Credit: `contributors/people.toml` deliberately carries no new entry in this PR — ours is already queued on #2073. --- Cargo.lock | 1 + crates/annot/Cargo.toml | 5 + .../tests/malformed.proptest-regressions | 6 + crates/annot/tests/malformed.rs | 859 +++++++++++++ .../tests/properties.proptest-regressions | 6 + crates/annot/tests/properties.rs | 417 +++++++ crates/annot/tests/round_trip.rs | 1086 +++++++++++++++++ crates/annot/tests/support/bytes.rs | 336 +++++ crates/annot/tests/support/fixture.rs | 207 ++++ 9 files changed, 2923 insertions(+) create mode 100644 crates/annot/tests/malformed.proptest-regressions create mode 100644 crates/annot/tests/malformed.rs create mode 100644 crates/annot/tests/properties.proptest-regressions create mode 100644 crates/annot/tests/properties.rs create mode 100644 crates/annot/tests/round_trip.rs create mode 100644 crates/annot/tests/support/bytes.rs create mode 100644 crates/annot/tests/support/fixture.rs diff --git a/Cargo.lock b/Cargo.lock index 7230c7db39..20d3f9a16a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4640,6 +4640,7 @@ dependencies = [ "pdfcraft-fonts", "pdfcraft-geom", "pdfcraft-model", + "proptest", "thiserror 2.0.21", ] diff --git a/crates/annot/Cargo.toml b/crates/annot/Cargo.toml index e91c9ed896..1d09f0f8bc 100644 --- a/crates/annot/Cargo.toml +++ b/crates/annot/Cargo.toml @@ -18,3 +18,8 @@ thiserror = { workspace = true } [dev-dependencies] hayro-syntax = { workspace = true } +# Property tests over generated annotation geometry and metadata (`tests/properties.rs`). Same +# workspace dependency the sibling test suites already carry: `crates/cos/Cargo.toml` declares it as +# `proptest = { workspace = true }`, and `crates/crypt`/`crates/filters` use the dotted form +# `proptest.workspace = true`. Nothing new enters the dependency graph. +proptest = { workspace = true } diff --git a/crates/annot/tests/malformed.proptest-regressions b/crates/annot/tests/malformed.proptest-regressions new file mode 100644 index 0000000000..341ba3ff3d --- /dev/null +++ b/crates/annot/tests/malformed.proptest-regressions @@ -0,0 +1,6 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. diff --git a/crates/annot/tests/malformed.rs b/crates/annot/tests/malformed.rs new file mode 100644 index 0000000000..64fc241baf --- /dev/null +++ b/crates/annot/tests/malformed.rs @@ -0,0 +1,859 @@ +//! Damaged annotation dictionaries: what the reader does, and what it must never do. +//! +//! **These are never-crash tests.** They assert that a stranger's broken annotation data produces an +//! error or a defined degradation instead of a panic. Where the current behaviour is questionable, +//! that is said out loud and pinned as it is: an expected value below is *what PdfCraft does today*, +//! not a claim that it is right. Each such place carries a `NOTE` comment naming the alternative a +//! reader could reasonably choose, so a later fix shows up as a changed expectation here rather than a +//! silent edit. (`AGENTS.md` §4 and `CLAUDE.md` Fidelity: no crash, and never repair silently.) +//! +//! The shapes come from two directions: bytes written by hand (a file we did not make, including +//! tokens our typed API cannot even express — a three-number quadrilateral or an unknown keyword), and +//! values handed to the builder (`add_annotation` with NaN in a style or geometry). + +mod support { + pub mod bytes; + pub mod fixture; +} + +use pdfcraft_annot::{ + AnnotError, AttachIcon, Meta, NewAnnotation, NoteIcon, Shape, Style, add_annotation, delete_annotation, has_visible_fill_sign, links, page_refs, + picture_rotation, props, set_annots, signature_image, summaries, +}; +use pdfcraft_cos::{Dict, Document, ObjRef, Object}; +use proptest::prelude::*; +use std::sync::Arc; + +use support::bytes; +use support::fixture::{Save, annot_entries, blank, dict_of, name_of, nums, page_object_numbers, pdf, save_and_reopen}; + +/// Open a hand-written file that must parse well enough to be examined. +fn open(objs: &[&[u8]]) -> Document { + Document::open(Arc::new(pdf(objs))).expect("a damaged file still opens") +} + +/// A one-page file whose single annotation is `body`. +fn one_annot(body: &[u8]) -> Document { + open(&[ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>", + body, + ]) +} + +/// Run every annotation reader over a document. The point is that none of them panics; the counts +/// are checked by the callers, which know what the damage was. +fn read_everything(doc: &Document) { + let listed = summaries(doc); + let pages = page_refs(doc).map(|p| p.len()).unwrap_or(0); + for page in 0..pages { + let entries = annot_entries(doc, page); + for index in 0..entries.len() + 2 { + let _ = props(doc, page, index); + } + } + let _ = links::list(doc); + let _ = has_visible_fill_sign(doc); + for page in 0..pages { + let entries = annot_entries(doc, page); + for index in 0..entries.len() { + let _ = signature_image(doc, page, index); + let _ = picture_rotation(doc, page, index); + } + } + let _ = listed; +} + +// ── wrong-shaped numbers ─────────────────────────────────────────────────────────────────────── + +/// A `/Rect` that is not four numbers cannot place a comment. Today it reads as the empty rectangle +/// at the origin and the comment is still listed, so a viewer would draw it in the page corner. +/// NOTE: refusing the entry, or listing it at no position, are both defensible; pinning whichever +/// is chosen keeps the change honest. The invariant held here is "listed, with a finite rect, no +/// panic" — not that the position is meaningful. +#[test] +fn a_malformed_rectangle_reads_as_the_origin_instead_of_panicking() { + let bodies: Vec<&[u8]> = vec![ + b"<< /Type /Annot /Subtype /Square /Rect [10 20] >>", + b"<< /Type /Annot /Subtype /Square /Rect [1 2 3] >>", + b"<< /Type /Annot /Subtype /Square /Rect [1 2 3 4 5] >>", + b"<< /Type /Annot /Subtype /Square /Rect [/a /b /c /d] >>", + b"<< /Type /Annot /Subtype /Square /Rect (a string) >>", + b"<< /Type /Annot /Subtype /Square /Rect null >>", + // Colour components outside [0,1]: clamped on read rather than refused. + b"<< /Type /Annot /Subtype /Square /Rect [10 20 30 40] /IC [0.5 2 -0.5] >>", + ]; + for (n, body) in bodies.into_iter().enumerate() { + let doc = one_annot(body); + read_everything(&doc); + let listed = summaries(&doc); + assert_eq!(listed.len(), 1, "case {n}: the comment is still listed ({body:?})"); + assert!(listed[0].rect.iter().all(|v| v.is_finite()), "case {n}: a finite rectangle, got {:?}", listed[0].rect); + assert_eq!( + name_of(&doc, &dict_of(&doc, &annot_entries(&doc, 0)[0]).expect("a dictionary"), b"Subtype").as_deref(), + Some("Square"), + "case {n}" + ); + // Save it on and the damage must not turn into a crash or a file we cannot reopen. + for path in [Save::Incremental, Save::FullTable] { + let (_, reopened) = save_and_reopen(&doc, path); + read_everything(&reopened); + assert_eq!(summaries(&reopened).len(), 1, "case {n} after {path:?}"); + } + } +} + +/// `/QuadPoints` must come in eights (§12.5.6.10). A list that does not divide evenly is truncated +/// to whole quadrilaterals: seven numbers give none, twelve give one, and the leftover numbers are +/// dropped without a word. NOTE: "drop silently" is what happens today; reporting the odd tail would +/// be kinder. What is asserted here is that the chunking never over-reads and never panics. +#[test] +fn a_quad_list_that_is_not_a_multiple_of_eight_keeps_whole_quads_only() { + let cases: Vec<(&[u8], usize)> = vec![ + (b"[1 2 3 4 5 6 7]", 0), + (b"[1 2 3 4 5 6 7 8]", 1), + (b"[1 2 3 4 5 6 7 8 9]", 1), + (b"[1 2 3 4 5 6 7 8 9 10 11 12]", 1), + (b"[16 numbers follow: this token is not a number at all]", 0), + (b"[]", 0), + ]; + for (n, (values, want_quads)) in cases.into_iter().enumerate() { + let body = format!("<< /Type /Annot /Subtype /Highlight /Rect [10 20 60 30] /QuadPoints {} >>", String::from_utf8_lossy(values)); + let doc = one_annot(body.as_bytes()); + read_everything(&doc); + if String::from_utf8_lossy(values).contains("numbers follow") { + // An unparseable token inside the array loses the whole annotation object: see the note + // on `an_unparseable_token_...` below. It is listed in /Annots but reads as nothing. + assert!(summaries(&doc).is_empty(), "case {n}"); + continue; + } + let listed = summaries(&doc); + assert_eq!(listed.len(), 1, "case {n}: the markup is still listed"); + assert_eq!(listed[0].quads.len(), want_quads, "case {n}: {}", String::from_utf8_lossy(values)); + // The stored array is preserved verbatim: reading truncates, saving must not rewrite. + let d = dict_of(&doc, &annot_entries(&doc, 0)[0]).expect("a dictionary"); + let stored = nums(&doc, &d, b"QuadPoints").unwrap_or_default(); + let written = values.iter().filter(|c| c.is_ascii_digit() || **c == b' ').count(); + assert!(stored.len() <= written, "case {n}: we read at most what is there ({} vs {written})", stored.len()); + } +} + +/// A token the object parser cannot interpret (a bare word that is not a number, name, +/// reference, string, `true`, `false` or `null`) loses the object it sits in. Inside a page's +/// `/Annots` that costs the *whole page*: `page_refs()` comes back `Ok([])` and every annotation +/// on that page disappears — with an empty repair log. Precision matters here: `/Pages` still +/// shows `Count 1, Kids [3 0 R]`, so it is not that the annotation list alone became +/// unreachable; the page object itself fails to parse, and nothing downstream sees it. +/// NOTE: this is `pdfcraft-cos` parser behaviour, reached through the annotation readers. The +/// bytes below are HAND-BUILT by this test's `open` helper — no writer path emits a bare +/// keyword there; they model damage an outside editor or a truncated edit leaves behind. +/// +/// Cross-checked against qpdf core 12.2.0 via pikepdf 9.11 on these exact bytes (sha256 +/// 582e0eb0e8a25e6975c0727d405372d7df6c8dfcb06e0289817f5b28e546b94e, 447 B — hand-built and +/// not committed; re-create it from the object bodies below, in order). Running qpdf's check, +/// `pikepdf.Job(["--check", , "/dev/null"])`, exits 3 with warnings on process stderr, +/// verbatim: +/// `WARNING: (object 3 0, offset 191): unknown token while reading object; treating as string` +/// — note `object 3 0` and the offset; there is no `/Annots` in qpdf's wording. qpdf KEEPS the +/// page, so this loss is ours alone — and qpdf's warning shows it was detectable. The word +/// 'silently' below refers only to our empty `repair_log()`, never to qpdf, which complains. +/// +/// The honest claim here is limited to: no panic, an error or an empty page list, and +/// `add_annotation` refusing cleanly rather than writing onto a page it cannot see. Fixing the +/// parser should make this test fail, and that is exactly what it is for. +#[test] +fn an_unparseable_token_inside_annots_loses_the_page_and_says_nothing() { + let doc = open(&[ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R notanumber] >>", + b"<< /Type /Annot /Subtype /Square /Rect [10 20 60 30] >>", + ]); + read_everything(&doc); + assert_eq!(page_refs(&doc).map(|p| p.len()), Ok(0), "the page object could not be read"); + assert!(doc.repair_log().is_empty(), "and nothing was recorded about losing it"); + assert!(page_object_numbers(&doc).is_empty(), "this file's own page walk agrees there is nothing to read"); + assert!(summaries(&doc).is_empty()); + + let mut try_add = doc.clone(); + let e = add_annotation( + &mut try_add, + &NewAnnotation { + page: 0, + shape: Shape::Rectangle { rect: [10.0, 10.0, 40.0, 30.0] }, + style: Style::default(), + contents: "x".into(), + author: "A".into(), + }, + &Meta { date: None, id: "i".into() }, + ) + .err(); + assert_eq!(e, Some(AnnotError::NoSuchPage(0)), "adding to the vanished page refuses rather than inventing a page"); + assert_eq!(links::list(&doc).len(), 0); +} + +// ── broken references ────────────────────────────────────────────────────────────────────────── + +/// Dangling, duplicated and wrong-typed entries in one `/Annots` array: each is skipped by the +/// readers, none panics, and deleting one leaves the others alone. A duplicated reference really is +/// listed twice — the two comments share a `Rect` because they *are* the same object. +#[test] +fn dangling_duplicate_and_wrong_typed_entries_are_skipped() { + let doc = open(&[ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [5 0 R 4 0 R 4 0 R (a string) null] >>", + b"<< /Type /Annot /Subtype /Square /Rect [10 20 60 30] >>", + b"[7 0 R]", + ]); + read_everything(&doc); + let entries = annot_entries(&doc, 0); + assert_eq!(entries.len(), 5, "the array keeps all five slots"); + let listed = summaries(&doc); + assert_eq!(listed.iter().map(|s| s.index).collect::>(), vec![1, 2], "only the two real dictionaries are comments"); + assert_eq!(listed[0].rect, listed[1].rect, "the duplicate is the same object"); + assert!(props(&doc, 0, 0).is_none(), "an entry naming an array is not a comment"); + assert!(props(&doc, 0, 3).is_none(), "a string entry is not a comment"); + assert_eq!(signature_image(&doc, 0, 1).ok().flatten(), None); + + // Deleting one of the duplicates removes **both** slots: `delete_annotation` drops every entry + // that names a doomed object, not just the index asked for (that is how it takes pop-ups and + // replies with their parent). So the shared dictionary leaves the page entirely. + let mut cut = doc.clone(); + delete_annotation(&mut cut, 0, 1).expect("deletes the comment"); + assert_eq!(annot_entries(&cut, 0).len(), 3, "both slots naming that object are gone"); + assert!(summaries(&cut).is_empty()); + let (_, reopened) = save_and_reopen(&cut, Save::FullTable); + assert!(summaries(&reopened).is_empty(), "and the file agrees"); + + // An `/Annots` that is not an array at all reads as "no annotations". + let weird = open(&[ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots (hello) >>", + ]); + read_everything(&weird); + assert!(annot_entries(&weird, 0).is_empty()); + let mut d = weird.clone(); + assert_eq!(delete_annotation(&mut d, 0, 0).err(), Some(AnnotError::NoSuchAnnotation { page: 0, index: 0 })); +} + +/// Reference loops must terminate. These are the shapes a generated or half-repaired file produces: +/// an annotation replying to itself, two replies replying to each other, and a pop-up chain whose +/// back-references point at the next annotation instead of the previous one. +#[test] +fn reference_loops_terminate_and_a_delete_takes_the_cycle_with_it() { + // Self-reference. + let self_irt = one_annot(b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /IRT 4 0 R >>"); + read_everything(&self_irt); + let mut cut = self_irt.clone(); + delete_annotation(&mut cut, 0, 0).expect("deletes the self-replying comment"); + assert!(annot_entries(&cut, 0).is_empty()); + + // Mutual references: deleting either must take both and stop. + let shared = open(&[ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R 5 0 R] >>", + b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /IRT 5 0 R >>", + b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /IRT 4 0 R >>", + ]); + read_everything(&shared); + assert_eq!(summaries(&shared).len(), 2, "both halves of the pair are listed"); + let mut cut = shared.clone(); + delete_annotation(&mut cut, 0, 0).expect("deleting one of a mutual pair returns"); + assert!(annot_entries(&cut, 0).is_empty(), "the cycle is taken out together"); + + // A pop-up whose /Parent names a third annotation, which in turn names the first. + let chained = open(&[ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R 5 0 R 6 0 R] >>", + b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /Popup 5 0 R >>", + b"<< /Type /Annot /Subtype /Popup /Rect [40 20 90 60] /Parent 6 0 R >>", + b"<< /Type /Annot /Subtype /Popup /Rect [40 20 90 60] /Parent 4 0 R >>", + ]); + read_everything(&chained); + assert_eq!(summaries(&chained).len(), 1, "only the text comment is a comment"); + let mut cut = chained.clone(); + delete_annotation(&mut cut, 0, 0).expect("deleting the owner of a pop-up chain returns"); + assert!(annot_entries(&cut, 0).is_empty(), "and the whole chain goes with it"); + + // A `/Popup` that names a missing object must not stop the comment being used. + let dangling_popup = one_annot(b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /Popup 99 0 R >>"); + read_everything(&dangling_popup); + assert_eq!(summaries(&dangling_popup).len(), 1); + let mut reply = dangling_popup.clone(); + assert!( + pdfcraft_annot::add_reply(&mut reply, 0, 0, "to you", "Ben", &Meta { date: None, id: "r".into() }).is_ok(), + "a missing pop-up does not block replying" + ); +} + +// ── wrong types where the reader wants a number or a name ───────────────────────────────────── + +/// Values of the wrong type in flag, opacity and colour entries: the reader falls back to its +/// defaults instead of panicking. NOTE on opacity: reading does **not** clamp, so `/CA 7.5` comes +/// back as 7.5 and would hand a nonsense value to a 0–1 slider; writing clamps (`add_annotation` +/// refuses non-finite and clamps the range). The asymmetry is recorded here, not endorsed. +#[test] +fn wrong_typed_flag_opacity_and_colour_entries_fall_back_without_panicking() { + let doc = one_annot(b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /CA 7.5 /F /NotAnInt /C [1 2] >>"); + read_everything(&doc); + let p = props(&doc, 0, 0).expect("still a comment"); + assert_eq!(p.opacity, 7.5, "the out-of-range opacity is passed through as written"); + assert!(!p.locked, "a name where /F belongs reads as no flags at all"); + assert_eq!(p.color, None, "/C with two components is not a colour"); + let listed = summaries(&doc); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].color, None); + + // And the other direction: /F as a real number is read by its integer value. + let flags_real = one_annot(b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /F 132.0 >>"); + let p = props(&flags_real, 0, 0).expect("still a comment"); + assert!(p.locked, "132 sets ReadOnly (bit 8) whatever the number's form"); + + // An annotation with no /Subtype at all: nothing to name, so it is not a comment and has no + // properties, but the entry survives untouched (preserve unknown data). + let no_subtype = one_annot(b"<< /Type /Annot /Rect [10 20 30 40] >>"); + read_everything(&no_subtype); + assert!(summaries(&no_subtype).is_empty()); + assert!(props(&no_subtype, 0, 0).is_none()); + assert_eq!(annot_entries(&no_subtype, 0).len(), 1); + + // A `/P` pointing at a page that does not exist is cosmetic: the comment still lists. + let bad_parent_page = one_annot(b"<< /Type /Annot /Subtype /Square /Rect [10 20 30 40] /P 77 0 R >>"); + read_everything(&bad_parent_page); + assert_eq!(summaries(&bad_parent_page).len(), 1); +} + +// ── guards that only bite on damaged data, pinned so they stay visible ──────────────────────── + +/// `move_annotation` shifts the numbers of every geometry key, but only the first four of an array +/// it treats as a rectangle (`every || i < 4`, `crates/annot/src/modify.rs:302`). A `/Rect` with +/// more than four numbers is not something PdfCraft writes, so the guard only shows up on damaged +/// data — which is precisely why it is pinned here: without this test the rule can be deleted +/// silently. What must hold is that the four rectangle numbers move together and whatever strays +/// the file carries are left exactly as they were, rather than being dragged along by half a point. +#[test] +fn moving_a_damaged_rectangle_shifts_its_four_numbers_and_leaves_the_strays_alone() { + let mut doc = one_annot(b"<< /Type /Annot /Subtype /Square /Rect [10 20 60 30] >>"); + let r = annot_entries(&doc, 0)[0].as_ref().expect("an indirect entry"); + doc.update_dict(r, |d| { + d.set( + b"Rect".to_vec(), + Object::Array(vec![ + Object::Real(10.0), + Object::Real(20.0), + Object::Real(60.0), + Object::Real(30.0), + Object::Real(9.0), + Object::Real(-9.5), + ]), + ); + }) + .expect("the entry is a dictionary"); + + pdfcraft_annot::move_annotation(&mut doc, 0, 0, 5.0, 7.0, &Meta { date: None, id: "m".into() }).expect("the comment is not locked"); + let d = dict_of(&doc, &annot_entries(&doc, 0)[0]).expect("a dictionary"); + let stored = nums(&doc, &d, b"Rect").expect("six numbers"); + assert_eq!(stored, vec![15.0, 27.0, 65.0, 37.0, 9.0, -9.5], "four shift, two strays do not"); + + // It survives a save that way, and the comment list still cannot use such a rectangle. + let (file, reopened) = save_and_reopen(&doc, Save::FullTable); + let stored_again = bytes::numbers_of(&file, "Rect"); + assert_eq!(stored_again.first(), Some(&vec![15.0, 27.0, 65.0, 37.0, 9.0, -9.5]), "the file keeps all six"); + let listed = summaries(&reopened); + assert_eq!(listed.len(), 1, "still a comment"); + assert_eq!(listed[0].rect, [0.0, 0.0, 0.0, 0.0], "and still not a usable position"); +} + +/// A link area is checked before anything is written: it needs finite corners whose span is at +/// least two points in both directions. Two different reasons, two different messages — and in +/// every case the page gains no entry. +#[test] +fn a_link_area_that_is_too_small_or_broken_is_refused_before_it_is_written() { + let cases = [ + ("one point wide", [10.0, 20.0, 11.0, 40.0], "too small"), + ("zero height", [10.0, 20.0, 50.0, 20.0], "too small"), + ("a NaN corner", [f64::NAN, 1.0, 50.0, 60.0], "finite coordinates"), + ("corners whose span overflows", [-1e308, 1.0, 1e308, 60.0], "too small or too large"), + ]; + for (label, rect, want_in_message) in cases { + let mut doc = blank(2); + let e = links::add(&mut doc, 0, rect, &links::LinkAction::Page(1), &links::LinkStyle::default()).err(); + let msg = match &e { + Some(AnnotError::Invalid(m)) => m.clone(), + other => panic!("{label}: expected Invalid, got {other:?}"), + }; + assert!(msg.contains(want_in_message), "{label}: message {msg:?} should mention {want_in_message:?}"); + assert!(annot_entries(&doc, 0).is_empty(), "{label}: nothing was written"); + assert!(links::list(&doc).is_empty(), "{label}: no link to list"); + } +} + +// ── hostile numbers handed to the builder ───────────────────────────────────────────────────── + +/// Non-finite style and geometry must be refused before anything is written: no partial object, no +/// `NaN` or exponent token in the file. (`AGENTS.md` §4: guard NaN/inf casts.) +#[test] +fn non_finite_builder_input_is_refused_and_leaves_the_document_untouched() { + let shapes = [ + ("nan rect", Shape::Rectangle { rect: [f64::NAN, 10.0, 40.0, 30.0] }), + ("infinite rect", Shape::Rectangle { rect: [f64::NEG_INFINITY, 10.0, 40.0, 30.0] }), + ("nan quad", Shape::TextMarkup { kind: pdfcraft_annot::Markup::Highlight, quads: vec![[10.0, 10.0, f64::NAN, 20.0, 10.0, 5.0, 30.0, 5.0]] }), + ("far away note", Shape::Note { at: [1e308, 2.0], icon: NoteIcon::Note }), + ("nan ink", Shape::Ink { strokes: vec![vec![[f64::NAN, 1.0], [2.0, 3.0]]] }), + ("empty ink", Shape::Ink { strokes: vec![vec![]] }), + ( + "degenerate line", + Shape::Line { from: [10.0, 10.0], to: [10.0, 10.5], start: pdfcraft_annot::LineEnding::None, end: pdfcraft_annot::LineEnding::None }, + ), + ("nan polygon", Shape::Polygon { vertices: vec![[0.0, 0.0], [f64::INFINITY, 10.0], [5.0, 5.0]], cloud: false }), + ("two point polygon", Shape::Polygon { vertices: vec![[0.0, 0.0], [10.0, 10.0]], cloud: false }), + ( + "nan callout", + Shape::Callout { + rect: [10.0, 10.0, 40.0, 30.0], + knee: [f64::NAN, 0.0], + point: [0.0, 0.0], + font_size: 12.0, + ending: pdfcraft_annot::LineEnding::None, + }, + ), + ("no quads", Shape::TextMarkup { kind: pdfcraft_annot::Markup::StrikeOut, quads: vec![] }), + ]; + for (label, shape) in shapes { + let mut doc = blank(1); + let e = add_annotation( + &mut doc, + &NewAnnotation { page: 0, shape, style: Style::default(), contents: "x".into(), author: "A".into() }, + &Meta { date: None, id: "i".into() }, + ) + .err(); + assert!(matches!(e, Some(AnnotError::Invalid(_))), "{label}: refused with Invalid, got {e:?}"); + assert!(annot_entries(&doc, 0).is_empty(), "{label}: nothing was written"); + // The refusal must not corrupt the document either: it still saves and reloads empty. + let (_, reopened) = save_and_reopen(&doc, Save::Incremental); + assert!(summaries(&reopened).is_empty(), "{label}: the file is still clean"); + } + + for (label, style) in [ + ("nan opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::NAN, width: 1.0, fill: None }), + ("infinite opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::INFINITY, width: 1.0, fill: None }), + ("nan colour", Style { color: [f64::NAN, 0.0, 0.0], opacity: 1.0, width: 1.0, fill: None }), + ("nan width", Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width: f64::NAN, fill: None }), + ] { + let mut doc = blank(1); + let e = add_annotation( + &mut doc, + &NewAnnotation { page: 0, shape: Shape::Rectangle { rect: [10.0, 10.0, 40.0, 30.0] }, style, contents: "x".into(), author: "A".into() }, + &Meta { date: None, id: "i".into() }, + ) + .err(); + assert_eq!(e.as_ref(), Some(&AnnotError::Invalid("invalid style".into())), "{label}"); + assert!(annot_entries(&doc, 0).is_empty(), "{label}: nothing was written"); + } + + // Edits take the same care: moving by a non-finite offset is refused and leaves geometry alone. + let mut doc = blank(1); + add_annotation( + &mut doc, + &NewAnnotation { + page: 0, + shape: Shape::Rectangle { rect: [10.0, 20.0, 60.0, 45.0] }, + style: Style::default(), + contents: "keep".into(), + author: "A".into(), + }, + &Meta { date: None, id: "ok".into() }, + ) + .expect("adds"); + let before = summaries(&doc)[0].rect; + assert_eq!( + pdfcraft_annot::move_annotation(&mut doc, 0, 0, f64::NAN, 1.0, &Meta { date: None, id: "m".into() }).err(), + Some(AnnotError::Invalid("invalid offset".into())) + ); + assert_eq!(summaries(&doc)[0].rect, before, "a refused move does not shift the comment"); + assert_eq!( + pdfcraft_annot::set_rect(&mut doc, 0, 0, [f64::NAN, 0.0, 1e308, 1e308], &Meta { date: None, id: "m".into() }).err().as_ref(), + Some(&AnnotError::Invalid("invalid rectangle (too small)".into())) + ); + assert_eq!(summaries(&doc)[0].rect, before, "a refused resize does not shift the comment"); +} + +/// Attachment input is checked too: a blank file name is refused with an actionable message and +/// writes nothing, so no half-built file specification is left in the document. +#[test] +fn an_attachment_needs_a_name_and_leaves_nothing_behind_when_it_has_none() { + for name in ["", " ", "\t"] { + let mut doc = blank(1); + let e = add_annotation( + &mut doc, + &NewAnnotation { + page: 0, + shape: Shape::Attachment { at: [10.0, 700.0], icon: AttachIcon::Paperclip, file: name.into(), data: b"x".to_vec() }, + style: Style::default(), + contents: String::new(), + author: "A".into(), + }, + &Meta { date: None, id: "a".into() }, + ) + .err(); + assert_eq!(e.as_ref(), Some(&AnnotError::Invalid("the attached file needs a name".into())), "{name:?}"); + assert!(annot_entries(&doc, 0).is_empty(), "no orphan file specification for {name:?}"); + } +} + +// ── fields that carry no magnitude screen (recorded, not endorsed) ──────────────────────────── + +/// This is a MAGNITUDE story, not a one-field story. `rect_for` checks the rectangle of every +/// variant but passes `Shape::CustomStamp { size }` and `Shape::TypedSignature { contours }` +/// straight into `/PCPictureSize` and `/PCOutline` (`create.rs:62-82`, `create.rs:278`, +/// `create.rs:285`) with no +/// magnitude screen whatsoever — and width gets none either. The only style guard on the create +/// path (`create.rs:416`) reads `!finite(&style.color) || !style.opacity.is_finite() +/// || !style.width.is_finite()`: `finite()` (`create.rs:17-19`, i.e. `is_finite() && abs() < 1e7`) +/// magnitude-screens `color` ALONE, while `opacity` and `width` are checked for non-finiteness +/// only. So even the one cap that exists sits at ten million, far below what a reader can turn +/// into an integer. Measured with qpdf's check (`pikepdf.Job(["--check", , "/dev/null"])`, +/// warnings on process stderr, exit code 3). Read that exit code carefully: **3 is qpdf's warning +/// status**, printed together with "operation succeeded with warnings", so the check still completes +/// and writes its output — it is not a hard failure (libqpdf: 0 = no errors or warnings, +/// 2 = errors detected, 3 = warnings detected; a clean file returns 0 with no stderr at all). +/// Every warning probe in this file returns 3 — the three overflow cases below and the +/// unknown-token probe documented at `:155-157` above — so the exit code alone does not separate +/// them from each other; the warning text does. The 9,999,999 control below is the only probe +/// that returns 0. Re-measurement trap: `Job.stderr` stays `None` even when qpdf warns, because +/// the warnings go to the inherited process stderr — redirect at shell level or you will report +/// "no warnings" from a file that produced them. Measured per field, each file written by THIS +/// crate's own writer path: +/// +/// `/BS /W` = 1e299 on an Oval: qpdf reports `object 4/0: error reading object: +/// overflow/underflow converting <1 followed by 299 digits> to 64-bit integer`. +/// +/// `/PCPictureSize` = 1e300 plus NaN: same message. File 1198 B, sha256 +/// 357946a6580e7c13fbcf3c80c396cd80f961a53e55aea9e11dff5e284f759e07, 301 digits confirmed. +/// +/// `/PCOutline` = 1e300: same message. +/// +/// `/BS /W` = 9999999: clean, exit code 0 — because that value has few enough digits for a +/// reader's 64-bit integer conversion (which tops out near 9.2e18), NOT because this crate caps +/// it: width never passes through `finite()`, so the ten-million figure plays no part here. The +/// boundary that matters is the reader's integer range, and it sits far above anything a real +/// border width could be. Measured here too: `/BS /W` = 1e9 is accepted and written verbatim as +/// `1000000000`, which is well past any sane border yet still parseable — the failure only +/// begins when the digits outrun a 64-bit conversion. +/// +/// So ANY annotation number of sufficient magnitude can make the whole object unreadable to a +/// third-party reader — width included, not just stamp payload. Two measurement notes that +/// matter when re-running: `pikepdf.open()` alone prints nothing for these files and still +/// reports `/Annots` length 1, while resolving `/Annots[0]` yields **null** and stays null after +/// qpdf re-saves — a listed-but-null entry is exactly what silent corruption looks like. qpdf +/// classifies it as a WARNING and its open still reports success; pikepdf puts `WARNING:` on a +/// line of its own, so grepping raw stderr for one combined line misses it. What we did NOT +/// measure is what any particular viewer then shows a user — the null entry was observed, not a +/// renderer's behaviour. +/// Meanwhile our own `repair_log()` stays empty, which contradicts this project's rule that +/// dropped or repaired data must be recorded (`CLAUDE.md`, Fidelity). None of these probe files +/// is committed: any sample PDF would need its own `ATTRIBUTION.toml` entry (`AGENTS.md` §1), +/// which this change avoids — regenerate them from the `file` bytes bound below and re-measure. +/// +/// How far a caller can actually get there, checked in this workspace rather than assumed: only +/// `/BS /W` is reachable through a shipped path. The automation tools read `width` as any finite +/// number (`crates/automation/src/comments.rs:427-429` assigns `style.width = w.max(0.0)` after +/// `opt_num`, whose only filter is `is_finite()` at `crates/automation/src/json.rs:112-113`), +/// and the published schema sets `"minimum": 0` with no upper bound +/// (`crates/automation/src/tools.rs:774`) — so a script or MCP agent can write a file whose +/// annotation object qpdf refuses to parse. The desktop UI caps the same value at 0.5..=12.0 +/// (`crates/ui-egui/src/dialogs/comment_props.rs:240-243`, `0.5..=12.0`, or a 0.0 floor when a +/// font size is set), and `/PCPictureSize` / `/PCOutline` are computed +/// inside the engine — `crates/engine/src/edit/run.rs:331` takes the source image's pixel size, +/// scales it to a 200 pt natural box at `:335-339` and hands that size to the stamp shape at +/// `:343`, while contour sizing lives at `crates/engine/src/fill_sign.rs:14-20` (which does reject a +/// non-positive width) — so reaching those two needs a caller using the crates directly +/// rather than an app or tool action. The defect is therefore automation-reachable today, and not +/// reachable by clicking in the desktop app. +/// +/// Non-finite values are rewritten on the way out: `write_real` (`crates/cos/src/writer.rs:48`) +/// emits a literal `0` for any non-finite REAL that reaches it, which is the mechanism for +/// `size` and contour points. Colours are a different route — `rgb()` (`create.rs:13-15`) clamps +/// each component to `0.0..=1.0` BEFORE the writer sees it, so infinity becomes `1.0`, not `0` +/// (see the create-vs-edit case below). The assertions that follow pin only what we write. +/// +/// NOTE: these tests record current behaviour so a fix becomes visible. They assert nothing about +/// the result being correct — the values are wrong on the way in and quietly rewritten on the +/// way out. +#[test] +fn unvalidated_stamp_size_and_signature_contours_are_rewritten_silently_in_the_file() { + let mut doc = blank(1); + let picture = doc.add(Object::Dict(Dict::new())); + add_annotation( + &mut doc, + &NewAnnotation { + page: 0, + shape: Shape::CustomStamp { rect: [10.0, 20.0, 60.0, 50.0], name: "Sig".into(), picture, image: true, size: (1e300, f64::NAN) }, + style: Style::default(), + contents: String::new(), + author: "A".into(), + }, + &Meta { date: None, id: "cs".into() }, + ) + .expect("the size is not validated, so the comment is accepted"); + + let (file, reopened) = save_and_reopen(&doc, Save::FullTable); + let stored = bytes::numbers_of(&file, "PCPictureSize"); + assert_eq!(stored.len(), 1, "one /PCPictureSize array in the file"); + assert_eq!(stored[0][1], 0.0, "NaN was written as 0 ({:?})", stored[0]); + assert!(stored[0][0] > 1e299, "the huge size was written rather than refused ({:?})", stored[0][0]); + assert!(doc.repair_log().is_empty() && reopened.repair_log().is_empty(), "nothing recorded about either substitution"); + // The digits are really there: 301 of them, no exponent form. + let pos = file.windows(b"/PCPictureSize".len()).position(|w| w == b"/PCPictureSize").expect("the key is in the file"); + let run = &file[pos..]; + let digits = run.iter().take(400).filter(|b| b.is_ascii_digit()).count(); + assert!(digits > 300, "a 301-digit decimal was written to the file ({digits} digits seen)"); + + let mut doc2 = blank(1); + add_annotation( + &mut doc2, + &NewAnnotation { + page: 0, + shape: Shape::TypedSignature { rect: [10.0, 20.0, 60.0, 50.0], contours: vec![vec![[f64::NAN, 1.0], [2.0, 3.0], [4.0, f64::INFINITY]]] }, + style: Style::default(), + contents: String::new(), + author: "A".into(), + }, + &Meta { date: None, id: "ts".into() }, + ) + .expect("the contours are not validated either"); + let (file2, _) = save_and_reopen(&doc2, Save::FullTable); + let outline = bytes::numbers_of(&file2, "PCOutline"); + assert_eq!(outline.as_slice(), &[vec![0.0, 1.0, 2.0, 3.0, 4.0, 0.0]], "both non-finite contour points became 0"); +} + +/// The fill colour is screened differently on the two paths. `add_annotation` magnitude-screens +/// only `style.color`, through `finite()` (`create.rs:416`; the helper at `create.rs:17-19` is +/// `is_finite() && abs() < 1e7`), gives `opacity` and `width` plain finiteness checks, and never +/// screens `fill` at all; `set_fill` refuses the same value (`modify.rs:626-627`, "invalid fill +/// colour") — and that refusal calls `finite()` too, which is why it trips on anything from ten +/// million up as well as on NaN or infinity. The accepted value is then clamped component-wise by +/// `rgb()` (`create.rs:13-15`, `clamp(0.0, 1.0)`), so what lands in the file is the top of the +/// range: NaN survives clamping as NaN and `write_real` (`crates/cos/src/writer.rs:48`) then +/// emits a literal `0`, while infinity becomes `1.0`. Measured across magnitudes +/// in `the_same_huge_fill_is_accepted_on_create_and_refused_on_edit`, which pins +/// 1e7 / 1e8 / infinity as well. Border width and stroke colour behave symmetrically on both +/// paths — width is finiteness-checked only, so a huge width gets written rather than refused (see +/// the magnitude note above), and both paths clamp it at zero — while stamp `size` and signature +/// `contours` have no edit path at all, so only create can diverge for them. Pinned as current +/// behaviour, not as desired behaviour. +#[test] +fn a_nan_fill_is_accepted_on_create_and_refused_on_edit() { + let nan = [f64::NAN, 0.0, 0.0]; + let mut doc = blank(1); + add_annotation( + &mut doc, + &NewAnnotation { + page: 0, + shape: Shape::Rectangle { rect: [10.0, 20.0, 60.0, 40.0] }, + style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(nan) }, + contents: String::new(), + author: "A".into(), + }, + &Meta { date: None, id: "nf".into() }, + ) + .expect("create does not screen the fill colour"); + let (file, reopened) = save_and_reopen(&doc, Save::FullTable); + let ic = bytes::numbers_of(&file, "IC"); + assert_eq!(ic.first(), Some(&vec![0.0, 0.0, 0.0]), "the NaN components were written as zeros"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.fill), Some([0.0, 0.0, 0.0])); + + let e = pdfcraft_annot::set_fill(&mut reopened.clone(), 0, 0, Some(nan), &Meta { date: None, id: "nf2".into() }).err(); + assert_eq!(e.as_ref(), Some(&AnnotError::Invalid("invalid fill colour".into())), "the same value is refused two lines later in the same crate"); +} + +// ── generated damage, same rule: refuse or degrade, never panic ─────────────────────────────── + +/// proptest's assert macros cannot capture local names in their format strings, so the writer path +/// is formatted here and passed in explicitly. +fn tag(path: Save) -> String { + format!("{path:?}") +} + +/// The kinds of damage a stranger's annotation data can carry. Twelve wreck the dictionary of a +/// comment PdfCraft wrote, so the file stays structurally valid around one wrong entry; the +/// duplicate-entry kind instead repeats that comment's entry in the page's `/Annots`. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum Damage { + RectTooShort, + RectWrongType, + QuadPointsOddLength, + QuadPointsWrongType, + FlagsAsName, + OpacityOutOfRange, + SubtypeMissing, + PopupDangling, + ParentToMissingObject, + IrtSelfReference, + DuplicateEntryInAnnots, + InkListWrongShape, + VerticesOddLength, +} + +const DAMAGES: [Damage; 13] = [ + Damage::RectTooShort, + Damage::RectWrongType, + Damage::QuadPointsOddLength, + Damage::QuadPointsWrongType, + Damage::FlagsAsName, + Damage::OpacityOutOfRange, + Damage::SubtypeMissing, + Damage::PopupDangling, + Damage::ParentToMissingObject, + Damage::IrtSelfReference, + Damage::DuplicateEntryInAnnots, + Damage::InkListWrongShape, + Damage::VerticesOddLength, +]; + +/// Apply one damage. Twelve of the kinds wreck the annotation dictionary at `/Annots[index]` +/// itself; the duplicate-entry kind instead lists that entry twice in the page's `/Annots`. +fn damage(doc: &mut Document, index: usize, kind: Damage) { + let entries = annot_entries(doc, 0); + let Some(r) = entries.get(index).and_then(|e| e.as_ref()) else { return }; + if kind == Damage::DuplicateEntryInAnnots { + // The damage lives on the page, not the dictionary: the same entry object appears twice in + // `/Annots`, so the page lists one annotation dictionary through two slots. Routed through + // `set_annots`, the same writer the crate itself uses, so both storage shapes (array + // inline in the page, array behind a reference) are rewritten the way mainline rewrites. + let mut list = annot_entries(doc, 0); + if let Some(slot) = list.get(index).cloned() { + list.insert(index, slot); + let page = ObjRef::new(*page_object_numbers(doc).first().expect("the page exists"), 0); + set_annots(doc, page, list).expect("the page dictionary is editable"); + } + return; + } + doc.update_dict(r, |d| match kind { + Damage::RectTooShort => d.set(b"Rect".to_vec(), Object::Array(vec![Object::Real(10.0), Object::Real(20.0)])), + Damage::RectWrongType => { + d.set(b"Rect".to_vec(), Object::Array(vec![Object::name("a"), Object::name("b"), Object::name("c"), Object::name("d")])) + } + Damage::QuadPointsOddLength => d.set(b"QuadPoints".to_vec(), Object::Array((0..7).map(|i| Object::Real(i as f64)).collect())), + Damage::QuadPointsWrongType => d.set(b"QuadPoints".to_vec(), Object::Array(vec![Object::Real(1.0), Object::name("notanumber")])), + Damage::FlagsAsName => d.set(b"F".to_vec(), Object::name("Locked")), + Damage::OpacityOutOfRange => d.set(b"CA".to_vec(), Object::Real(4.25)), + Damage::SubtypeMissing => { + d.remove(b"Subtype"); + } + Damage::PopupDangling => d.set(b"Popup".to_vec(), Object::Ref(ObjRef::new(9997, 0))), + Damage::ParentToMissingObject => d.set(b"Parent".to_vec(), Object::Ref(ObjRef::new(9998, 0))), + Damage::IrtSelfReference => d.set(b"IRT".to_vec(), Object::Ref(r)), + Damage::DuplicateEntryInAnnots => unreachable!("this damage edits the page, not the dictionary"), + Damage::InkListWrongShape => d.set(b"InkList".to_vec(), Object::Array(vec![Object::Real(5.0), Object::name("notastroke")])), + Damage::VerticesOddLength => d.set(b"Vertices".to_vec(), Object::Array(vec![Object::Real(1.0), Object::Real(2.0), Object::Real(3.0)])), + }) + .expect("the entry is an annotation dictionary"); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + /// For any single damage, and any of the three writer paths: opening, reading every annotation + /// entry point, re-saving and reopening must all complete without a panic. Alongside that the + /// test insists on something positive, so it cannot pass by reading nothing at all — an undamaged + /// second comment on the same page keeps its exact rectangle, and the damaged comment is either + /// listed or skipped but never half-parsed into a crash. + #[test] + fn damaged_annotations_never_panic(kind in prop::sample::select(DAMAGES.to_vec()), extra_annot in 0usize..=2) { + // Build a page holding one comment that will be damaged plus `extra_annot` clean ones. + let mut doc = blank(1); + for i in 0..=extra_annot { + add_annotation(&mut doc, &NewAnnotation { page: 0, shape: Shape::TextMarkup { kind: pdfcraft_annot::Markup::Highlight, quads: vec![[20.0 + 10.0 * i as f64, 500.0, 80.0 + 10.0 * i as f64, 500.0, 20.0 + 10.0 * i as f64, 486.0, 80.0 + 10.0 * i as f64, 486.0]] }, style: Style::default(), contents: format!("ok{i}"), author: "Ada".into() }, &Meta { date: None, id: format!("ok{i}") }).expect("adds"); + } + let clean_rect = summaries(&doc).iter().map(|s| s.rect).collect::>(); + damage(&mut doc, 0, kind); + + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let (_, reopened) = save_and_reopen(&doc, path); + read_everything(&reopened); + // The undamaged comments are untouched by the damage and its save. + let after = summaries(&reopened); + // A comment stops being listed only when the damage removes what makes it a comment — + // its `/Subtype` (measured, not assumed). The other damages all leave it listed; the + // duplicate-entry damage lists one comment through two slots, so it adds a listing. + let want_listed = clean_rect.len() - usize::from(kind == Damage::SubtypeMissing) + usize::from(kind == Damage::DuplicateEntryInAnnots); + prop_assert_eq!(after.len(), want_listed, "damage {k} on {p}: listed comment count", k = format!("{kind:?}"), p = tag(path)); + // Every undamaged comment keeps its exact rectangle through the damage and the rewrite. + for r in &clean_rect[1..] { + prop_assert!(after.iter().any(|s| s.rect == *r), "damage {k} on {p}: the clean comment at {r:?} is gone", k = format!("{kind:?}"), p = tag(path)); + } + // And deleting by index never panics, whatever the damage was. + let mut cut = reopened.clone(); + for i in 0..clean_rect.len() + 1 { + let _ = delete_annotation(&mut cut, 0, i); + } + } + } +} + +/// Read side, measured: a negative border width arriving from another tool is reported unchanged +/// by the public API. Our own writer clamps negatives to 0 (`create.rs:47`, `create.rs:216`), and +/// the helper `border_width_of` (`modify.rs:498-500`) does apply `.max(0.0)` — but the property +/// read path used here (`props()` -> `info.rs:227-231`) takes `/BS /W` raw for non-FreeText +/// subtypes, so a foreign file +/// declaring -3 comes back as -3.0. Pinned because the asymmetry is visible in the public API: +/// what we refuse to keep, we are willing to report. (Compare `/CA`, likewise unclamped on read.) +#[test] +fn foreign_negative_border_width_is_reported_as_written() { + let doc = open(&[ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>", + b"<< /Type /Annot /Subtype /Square /Rect [10 20 60 30] /BS << /S /S /W -3 >> >>", + ]); + let p = props(&doc, 0, 0).expect("the annotation is readable"); + assert_eq!( + p.width, + Some(-3.0), + "props() reports /BS /W as written; note border_width_of (modify.rs:498-500) does clamp at zero, so this is path-specific" + ); + assert!(doc.repair_log().is_empty(), "and that neither is recorded as a repair"); +} + +/// The create-vs-edit divergence is wider than the NaN case: the edit-side refusal begins at `1e7` +/// **in magnitude**, because `finite()` (`create.rs:17-19`, called by the edit path at `modify.rs:626`) +/// tests `abs() < 1e7`, so a component of magnitude exactly ten million is refused (positive or +/// negative) while 9,999,999 passes — what THIS test pins is the positive side (1e7, 1e8, infinity); +/// a negative-magnitude row is not pinned here, only reasoned from `abs()` (independently measured +/// in review round 5, which found `-1e7` refused on the edit path) +/// while create never screens `fill` at all, so any value whatsoever is accepted +/// there. Measured, not assumed — the +/// expected `/IC` components below are what this crate's writer actually produced on re-run +/// (clamping happens in `rgb()`, `create.rs:13-15`, so an accepted huge component lands at 1.0). +#[test] +fn the_same_huge_fill_is_accepted_on_create_and_refused_on_edit() { + let cases: [([f64; 3], &[f64; 3]); 3] = + [([1e7, 0.0, 0.0], &[1.0, 0.0, 0.0]), ([1e8, 0.0, 0.0], &[1.0, 0.0, 0.0]), ([f64::INFINITY; 3], &[1.0, 1.0, 1.0])]; + for (probe, want) in cases { + let mut doc = blank(1); + add_annotation( + &mut doc, + &NewAnnotation { + page: 0, + shape: Shape::Rectangle { rect: [10.0, 20.0, 60.0, 40.0] }, + style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(probe) }, + contents: String::new(), + author: "A".into(), + }, + &Meta { date: None, id: "huge-fill".into() }, + ) + .expect("create does not screen the fill colour"); + let (file, reopened) = save_and_reopen(&doc, Save::FullTable); + let ic = bytes::numbers_of(&file, "IC"); + assert_eq!(ic.first().map(Vec::as_slice), Some(want.as_slice()), "{probe:?}: create stores the clamped colour"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.fill), Some([want[0], want[1], want[2]]), "{probe:?}: read-back matches what was written",); + let e = pdfcraft_annot::set_fill(&mut reopened.clone(), 0, 0, Some(probe), &Meta { date: None, id: "huge-fill-2".into() }).err(); + assert_eq!(e.as_ref(), Some(&AnnotError::Invalid("invalid fill colour".into())), "{probe:?}: the same value is refused on the edit path",); + } +} diff --git a/crates/annot/tests/properties.proptest-regressions b/crates/annot/tests/properties.proptest-regressions new file mode 100644 index 0000000000..341ba3ff3d --- /dev/null +++ b/crates/annot/tests/properties.proptest-regressions @@ -0,0 +1,6 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. diff --git a/crates/annot/tests/properties.rs b/crates/annot/tests/properties.rs new file mode 100644 index 0000000000..8efb6b7046 --- /dev/null +++ b/crates/annot/tests/properties.rs @@ -0,0 +1,417 @@ +//! Property tests for annotation structural fidelity, stated over the **saved bytes**. +//! +//! What is proven here is a rule about files, not about structs: for every generated comment the +//! writer produces bytes that (a) hold the geometry as fixed-decimal number arrays, and (b) parse +//! back — with our reader *and* with vendored hayro-syntax — into dictionaries whose numbers, +//! names, flags and opacity equal values computed in this file from the input plus ISO 32000-2. +//! Two things make that more than "compare an object to itself": the expectations never read the +//! pre-save document, and the number tokens are re-parsed from raw `Vec` by `support::bytes`, +//! a strict scanner that is not `pdfcraft-cos`. +//! +//! Geometry comes from a half-point grid (`x = k / 2`, |k| ≤ 450). Every such value has an exact +//! decimal form and survives Flate, `f64` arithmetic and the writer's shortest-round-trip +//! formatting, so a mismatch means data changed shape on disk rather than drifting by an ulp. +//! Text is generated from an alphabet spanning ASCII punctuation, Latin-1 letters and CJK — the +//! cases where PDF's two string encodings disagree. +//! +//! Not covered, deliberately: appearance-stream content (the five open appearance PRs named in +//! `tests/round_trip.rs`), and the comment-list ordering rule of `summaries`, which is +//! deterministic and checked there instead. + +mod support { + pub mod bytes; + pub mod fixture; +} + +use pdfcraft_annot::{LineEnding, Markup, Meta, NewAnnotation, NoteIcon, Shape, Style, add_annotation, props, summaries}; +use pdfcraft_cos::Document; +use proptest::prelude::*; + +use support::bytes; +use support::fixture::{ + FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, Save, annot_entries, blank, dict_of, name_of, num, nums, page_object_numbers, save_and_reopen, str_of, +}; + +/// proptest's assert macros cannot capture local names inside their format strings (the message is +/// built in proptest's own expansion scope), so every message here passes what it names explicitly. +fn tag(path: Save) -> String { + format!("{path:?}") +} + +/// A coordinate on the half-point grid. +fn coord() -> impl Strategy { + any::().prop_map(|k| f64::from(k.rem_euclid(901) - 450) / 2.0) +} + +/// A rectangle as four grid coordinates, corners in any order (the writer normalises). +fn rect4() -> impl Strategy { + (coord(), coord(), coord(), coord()).prop_map(|(x0, y0, x1, y1)| [x0, y0, x1.max(x0 + 1.0), y1.max(y0 + 1.0)]) +} + +/// A quadrilateral: eight grid numbers, in Acrobat's corner order (§12.5.6.10). +fn quad8() -> impl Strategy { + prop::array::uniform8(coord()) +} + +/// Text from an alphabet where PDF's two string encodings disagree: printable ASCII (including the +/// punctuation a literal string has to escape around), Latin-1 letters beyond 0x7F, and CJK. +const TEXT_CHARS: &str = "abZq07 .,:;!?-_%$#*+=~()[]<>&@^|\n\t\u{e9}\u{fc}\u{f1}\u{df}\u{a7}\u{c0}\u{f6}\u{301}\u{65e5}\u{672c}"; + +fn text_of(max_len: usize) -> impl Strategy { + prop::collection::vec(prop::sample::select(TEXT_CHARS.chars().collect::>()), 0..=max_len).prop_map(|c| c.into_iter().collect()) +} + +/// ASCII-only identity strings: `/NM` is a thread key other readers match literally, so keep it +/// free of characters that would make a byte-level comparison ambiguous. +fn id_of(max_len: usize) -> impl Strategy { + prop::collection::vec( + prop::sample::select("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._".chars().collect::>()), + 0..=max_len, + ) + .prop_map(|c| c.into_iter().collect()) +} + +/// A grid coordinate's PDF decimal form, computed here rather than by the writer: integers without +/// a fraction, half-points with one digit (§7.3.3). +fn token(v: f64) -> String { + if v.fract() == 0.0 { format!("{}", v as i64) } else { format!("{v:.1}") } +} + +fn rect_token(r: &[f64]) -> String { + format!("/Rect [{}]", r.iter().map(|v| token(*v)).collect::>().join(" ")) +} + +/// Normalise as §12.5.4.2 requires a rectangle to be stored: lower-left then upper-right. +fn norm(r: [f64; 4]) -> Vec { + vec![r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])] +} + +/// Bounds of a point list, computed here rather than by the crate. +fn bounds_of(points: &[[f64; 2]]) -> Vec { + let mut out = [f64::MAX, f64::MAX, f64::MIN, f64::MIN]; + for p in points { + out[0] = out[0].min(p[0]); + out[1] = out[1].min(p[1]); + out[2] = out[2].max(p[0]); + out[3] = out[3].max(p[1]); + } + out.to_vec() +} + +fn meta(id: String) -> Meta { + Meta { date: Some("D:20261001120000Z".into()), id } +} + +fn comment(page: usize, shape: Shape, style: Style, contents: String, author: String) -> NewAnnotation { + NewAnnotation { page, shape, style, contents, author } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(128))] + + /// A rectangle comment's `/Rect` reaches the file as four fixed-decimal numbers equal to the + /// normalised input, and parses back to exactly those numbers on all three writer paths. The + /// raw-token claim runs where the bytes are uncompressed, so it is a claim about the file. + #[test] + fn a_rectangles_stored_rectangle_is_the_input_normalised(rect in rect4(), id in id_of(12)) { + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let mut doc = blank(1); + add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect }, Style::default(), String::new(), "Ada".into()), &meta(id.clone())) + .expect("a normalised box is at least a point wide"); + let (file, reopened) = save_and_reopen(&doc, path); + let want = norm(rect); + let entries = annot_entries(&reopened, 0); + prop_assert_eq!(entries.len(), 1, "{}: exactly the one comment", tag(path)); + let d = dict_of(&reopened, &entries[0]).expect("one annotation"); + let stored = nums(&reopened, &d, b"Rect"); + prop_assert_eq!(stored.as_deref(), Some(want.as_slice()), "{}: /Rect must be the normalised input {:?}", tag(path), rect); + if path != Save::FullStreams { + let t = rect_token(&want); + prop_assert!(file.windows(t.len()).any(|w| w == t.as_bytes()), "{}: {:?} must be written exactly as {}", tag(path), rect, t); + prop_assert!(bytes::numbers_of(&file, "Rect").contains(&want), "{}: the file itself must hold {:?}", tag(path), want); + } + } + } + + /// Markup keeps every quadrilateral, in order: `/QuadPoints` holds all 8·n numbers and `/Rect` + /// is the bounds of all of them, not just the first quad's. + #[test] + fn markup_keeps_every_quadrilateral(quads in prop::collection::vec(quad8(), 1..=3)) { + let flat: Vec = quads.concat(); + let points: Vec<[f64; 2]> = quads.iter().flat_map(|q| q.as_chunks::<2>().0.iter().copied()).collect(); + let want_rect = bounds_of(&points); + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let mut doc = blank(1); + add_annotation(&mut doc, &comment(0, Shape::TextMarkup { kind: Markup::Highlight, quads: quads.clone() }, Style::default(), String::new(), "Ada".into()), &meta("q".into())) + .expect("adds"); + let (file, reopened) = save_and_reopen(&doc, path); + let entries = annot_entries(&reopened, 0); + prop_assert_eq!(entries.len(), 1, "{}: exactly the one comment", tag(path)); + let d = dict_of(&reopened, &entries[0]).expect("one annotation"); + let stored = nums(&reopened, &d, b"QuadPoints"); + prop_assert_eq!(stored.as_deref(), Some(flat.as_slice()), "{}: all {} quad numbers, in order", tag(path), flat.len()); + let stored_rect = nums(&reopened, &d, b"Rect"); + prop_assert_eq!(stored_rect.as_deref(), Some(want_rect.as_slice()), "{}: /Rect bounds every quad", tag(path)); + prop_assert_eq!(summaries(&reopened).first().map(|s| s.quads.len()), Some(quads.len()), "{}: the comment list chunks them the same way", tag(path)); + if path != Save::FullStreams { + prop_assert!(bytes::numbers_of(&file, "QuadPoints").contains(&flat), "{}: {} numbers must be in the file", tag(path), flat.len()); + } + } + } + + /// `/CA` obeys its rule whatever the caller asked for: written only when clamped opacity is + /// below 1, and equal to the clamped value. A non-finite opacity is refused before any object + /// is created, so the file never holds a number PDF cannot write. + #[test] + fn opacity_and_flags_follow_their_rules(opacity in any::()) { + let mut doc = blank(1); + let added = add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: [10.0, 10.0, 60.0, 40.0] }, Style { color: [0.5, 0.25, 0.75], opacity, width: 1.0, fill: None }, String::new(), "Ada".into()), &meta("c".into())); + if !opacity.is_finite() { + prop_assert!(added.is_err(), "a non-finite opacity ({:?}) must be refused, not written", opacity); + return Ok(()); + } + let _ = added.expect("adds"); + let want = opacity.clamp(0.0, 1.0); + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let (file, reopened) = save_and_reopen(&doc, path); + let entries = annot_entries(&reopened, 0); + prop_assert_eq!(entries.len(), 1, "{}: exactly the one comment", tag(path)); + let d = dict_of(&reopened, &entries[0]).expect("one annotation"); + if want < 1.0 { + prop_assert_eq!(num(&reopened, &d, b"CA"), Some(want), "{}: opacity {:?} clamps to {:?}", tag(path), opacity, want); + prop_assert_eq!(props(&reopened, 0, 0).map(|p| p.opacity), Some(want), "{}: reported opacity", tag(path)); + if path != Save::FullStreams { + prop_assert_eq!(bytes::scalars_of(&file, "CA").first().copied(), Some(want), "{}: /CA must be in the file as {}", tag(path), token(want)); + } + } else { + prop_assert!(d.get(b"CA").is_none(), "{}: full opacity writes no /CA (it is the default)", tag(path)); + } + let flags = d.int(b"F").unwrap_or_default(); + prop_assert_ne!(flags & FLAG_PRINT, 0, "{}: a comment keeps its Print bit (§12.5.3)", tag(path)); + let colour = nums(&reopened, &d, b"C"); + prop_assert_eq!(colour.as_deref(), Some(&[0.5, 0.25, 0.75][..]), "{}: colours pass through unchanged", tag(path)); + } + } + + /// Text, author and id survive exactly — including the empty string. `/Contents` is stored even + /// when empty (an empty PDF string), while `/T` and `/NM` follow the crate's emptiness rule: + /// no author or id means the key is not written at all. + #[test] + fn text_author_and_id_survive_exactly(contents in text_of(40), author in text_of(16), id in id_of(12)) { + for path in [Save::Incremental, Save::FullTable] { + let mut doc = blank(1); + add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: [10.0, 20.0, 70.0, 45.0] }, Style::default(), contents.clone(), author.clone()), &meta(id.clone())) + .expect("adds"); + let (file, reopened) = save_and_reopen(&doc, path); + let entries = annot_entries(&reopened, 0); + prop_assert_eq!(entries.len(), 1, "{}: exactly the one comment", tag(path)); + let d = dict_of(&reopened, &entries[0]).expect("one annotation"); + let storedcontents = str_of(&reopened, &d, b"Contents"); + prop_assert_eq!(storedcontents.as_deref(), Some(contents.as_str()), "{}: /Contents round trip for {:?}", tag(path), contents); + let storedid = str_of(&reopened, &d, b"NM"); + if id.is_empty() { + prop_assert!(storedid.is_none(), "{}: an empty id writes no /NM, got {storedid:?}", tag(path)); + } else { + prop_assert_eq!(storedid.as_deref(), Some(id.as_str()), "{}: /NM round trip", tag(path)); + } + prop_assert!(bytes::texts_of(&file, "Contents").contains(&contents), "{:?} must appear in the file as a PDF string", contents); + if id.is_empty() { + prop_assert!(bytes::texts_of(&file, "NM").is_empty(), "{}: no /NM in the file for an empty id", tag(path)); + } else { + prop_assert!(bytes::texts_of(&file, "NM").contains(&id), "{:?} must appear in the file as a PDF string", id); + } + if author.is_empty() { + prop_assert!(d.get(b"T").is_none(), "{}: an empty author writes no /T", tag(path)); + } else { + let storedauthor = str_of(&reopened, &d, b"T"); + prop_assert_eq!(storedauthor.as_deref(), Some(author.as_str()), "{}: /T round trip for {:?}", tag(path), author); + } + } + } + + /// Several comments on one page keep their count, their order and all of their rectangles — + /// including the raw-file claim that the list of `/Rect` arrays is exactly what was added. + #[test] + fn several_rectangles_keep_count_order_and_geometry(rects in prop::collection::vec(rect4(), 1..=6), opacity_bits in any::()) { + let mut doc = blank(1); + let mut want_rects = Vec::new(); + for (i, r) in rects.iter().enumerate() { + // Two bits of the byte give opacities 1.0, 0.5, -0.5 and 0.0: written, clamped or absent. + let opacity = match opacity_bits & 3 { + 0 => 1.0, + 1 => 0.5, + 2 => -0.5, + _ => 0.0, + }; + add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: *r }, Style { color: [0.9, 0.1, 0.1], opacity, width: 2.0, fill: None }, format!("c{i}"), "Ada".into()), &meta(format!("k{i}"))) + .expect("adds"); + want_rects.push(norm(*r)); + } + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let (file, reopened) = save_and_reopen(&doc, path); + let want = want_rects.clone(); + let entries = annot_entries(&reopened, 0); + prop_assert_eq!(entries.len(), want.len(), "{}: one object per comment", tag(path)); + let got: Vec> = entries.iter().filter_map(|e| dict_of(&reopened, e)).flat_map(|d| nums(&reopened, &d, b"Rect")).collect(); + prop_assert_eq!(got, want.clone(), "{}: the same rectangles in the same order", tag(path)); + prop_assert_eq!(summaries(&reopened).len(), want.len(), "{}: every comment is listed", tag(path)); + if path != Save::FullStreams { + prop_assert_eq!(bytes::numbers_of(&file, "Rect"), want, "{}: every rectangle is in the file", tag(path)); + } + } + } + + /// Sticky notes arrive with a pop-up partner, and the pairing is two references: so that means + /// they still point at each other after a save, that the count is always two per note, and + /// that the icon box stays 20 pt square at the position asked for. + #[test] + fn notes_always_bring_a_popup_that_points_back(at in prop::array::uniform2(coord()), n in 1usize..=3) { + let at = [at[0], at[1].max(25.0)]; + let mut doc = blank(n); + for p in 0..n { + add_annotation(&mut doc, &comment(p, Shape::Note { at, icon: NoteIcon::Comment }, Style::default(), String::new(), "Ada".into()), &meta(format!("n{p}"))) + .expect("adds"); + } + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let (_, reopened) = save_and_reopen(&doc, path); + let pages = page_object_numbers(&reopened); + prop_assert_eq!(pages.len(), n, "{}", tag(path)); + for p in 0..n { + let entries = annot_entries(&reopened, p); + prop_assert_eq!(entries.len(), 2, "{}: note and pop-up on page {}", tag(path), p); + let note = dict_of(&reopened, &entries[0]).expect("note dictionary"); + let pop = dict_of(&reopened, &entries[1]).expect("pop-up dictionary"); + let notekind = name_of(&reopened, ¬e, b"Subtype"); + prop_assert_eq!(notekind.as_deref(), Some("Text"), "{}", tag(path)); + let popupkind = name_of(&reopened, &pop, b"Subtype"); + prop_assert_eq!(popupkind.as_deref(), Some("Popup"), "{}", tag(path)); + prop_assert_eq!(pop.reference(b"Parent"), entries[0].as_ref(), "{}: /Parent back-reference", tag(path)); + prop_assert_eq!(note.reference(b"Popup"), entries[1].as_ref(), "{}: /Popup forward reference", tag(path)); + let iconbox = nums(&reopened, ¬e, b"Rect"); + prop_assert_eq!(iconbox.as_deref(), Some(&[at[0], at[1] - 20.0, at[0] + 20.0, at[1]][..]), "{}: the icon box for {:?}", tag(path), at); + let flags = note.int(b"F").unwrap_or_default(); + prop_assert_ne!(flags & (FLAG_NO_ZOOM | FLAG_NO_ROTATE), 0, "{}: a note icon neither scales nor rotates", tag(path)); + } + } + } + + /// An incremental save and a garbage-collecting full rewrite must describe the same comments. + /// Their bytes differ by design; what may not differ is what a reader learns from them. + #[test] + fn every_writer_path_reports_the_same_comments(rect in rect4(), contents in text_of(20), id in id_of(8)) { + let mut doc = blank(2); + let quad = [rect[0], rect[3], rect[2], rect[3], rect[0], rect[1], rect[2], rect[1]]; + add_annotation(&mut doc, &comment(1, Shape::TextMarkup { kind: Markup::Underline, quads: vec![quad] }, Style::default(), contents, "Ada".into()), &meta(id)) + .expect("adds"); + + let (_, inc) = save_and_reopen(&doc, Save::Incremental); + let (_, full) = save_and_reopen(&doc, Save::FullTable); + let (_, packed) = save_and_reopen(&doc, Save::FullStreams); + let describe = |d: &Document| -> (Vec, Vec>, Option) { + let dicts: Vec<_> = annot_entries(d, 1).iter().filter_map(|x| dict_of(d, x)).collect(); + ( + dicts.iter().map(|x| name_of(d, x, b"Subtype").unwrap_or_default()).collect(), + dicts.iter().flat_map(|x| nums(d, x, b"QuadPoints")).collect(), + dicts.first().and_then(|x| str_of(d, x, b"Contents")), + ) + }; + prop_assert_eq!(describe(&inc), describe(&full)); + prop_assert_eq!(describe(&full), describe(&packed)); + } + + /// Border width and interior colour reach the file as given, and a `None` fill leaves no `/IC` + /// behind — "no fill" is stored as absence, not as black. + /// + /// The range includes NEGATIVE widths on purpose: `add_annotation` screens width for + /// non-finiteness only (`crates/annot/src/create.rs:416` tests `style.width.is_finite()`; the + /// `abs() < 1e7` cap inside `finite()` at `create.rs:17-19` guards `color`, never width), so + /// negatives are accepted and then clamped by `max(0.0)` on the way to `/BS /W` (`create.rs:216`). + /// Sampling `0.0..` alone left both clamps untested while this test's name implied coverage. + /// The upper end stays modest deliberately: magnitude is not screened here either, so a huge + /// width would be written verbatim — that case is pinned in `malformed.rs`, not by this + /// property, whose job is the sign clamp and the fill/absence rules. + #[test] + fn width_and_fill_are_written_as_they_were_given(width in -4.0f64..12.0, fill in prop::option::of(prop::array::uniform3(0.0f64..1.0))) { + let mut doc = blank(1); + add_annotation(&mut doc, &comment(0, Shape::Oval { rect: [5.0, 5.0, 65.0, 35.0] }, Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width, fill }, String::new(), "Ada".into()), &meta("f".into())) + .expect("adds"); + for path in [Save::Incremental, Save::FullTable] { + let (file, reopened) = save_and_reopen(&doc, path); + let entries = annot_entries(&reopened, 0); + prop_assert_eq!(entries.len(), 1, "{}: exactly the one comment", tag(path)); + let d = dict_of(&reopened, &entries[0]).expect("one annotation"); + let bs = d.get(b"BS").map(|o| reopened.resolve(o)).and_then(|o| o.as_dict().cloned()).expect("/BS"); + prop_assert_eq!(num(&reopened, &bs, b"W"), Some(width.max(0.0)), "{}: /BS /W for width {:?}", tag(path), width); + prop_assert_eq!(d.contains(b"IC"), fill.is_some(), "{}: /IC is present exactly when a fill was given", tag(path)); + prop_assert_eq!(props(&reopened, 0, 0).and_then(|p| p.width), Some(width.max(0.0)), "{}: reported width {:?}", tag(path), width); + prop_assert_eq!(props(&reopened, 0, 0).and_then(|p| p.fill), fill, "{}: /IC for {:?}", tag(path), fill); + let ic = bytes::numbers_of(&file, "IC"); + match fill { + Some(c) => prop_assert_eq!(ic.first(), Some(&vec![c[0], c[1], c[2]]), "{}: /IC must be in the file", tag(path)), + None => prop_assert!(ic.is_empty(), "{}: no /IC when unfilled, got {:?}", tag(path), ic), + } + } + } + + /// A line keeps its endpoints verbatim in `/L`, and the annotation's rectangle always spans + /// both of them — the one geometry rule a line must obey however wide its stroke or arrowheads + /// are drawn (§12.5.4.2). The padding itself lives in `appearance`, so it is not pinned here. + #[test] + fn a_line_keeps_its_endpoints_and_its_rectangle_spans_them(from in prop::array::uniform2(coord()), dx in 1.0f64..300.0, dy in -300.0f64..300.0, width in 0.5f64..8.0) { + let to = [(from[0] + dx).min(450.0), from[1] + dy]; + let mut doc = blank(1); + add_annotation(&mut doc, &comment(0, Shape::Line { from, to, start: LineEnding::None, end: LineEnding::OpenArrow }, Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width, fill: None }, String::new(), "Ada".into()), &meta("l".into())) + .expect("adds"); + let span = bounds_of(&[from, to]); + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let (file, reopened) = save_and_reopen(&doc, path); + let entries = annot_entries(&reopened, 0); + prop_assert_eq!(entries.len(), 1, "{}: exactly the one comment", tag(path)); + let d = dict_of(&reopened, &entries[0]).expect("one annotation"); + let r = nums(&reopened, &d, b"Rect").expect("/Rect"); + prop_assert!(r[0] <= span[0] && r[1] <= span[1] && r[2] >= span[2] && r[3] >= span[3], "{}: line {:?} to {:?} must lie inside {:?}", tag(path), from, to, r); + let storedline = nums(&reopened, &d, b"L"); + prop_assert_eq!(storedline.as_deref(), Some(&[from[0], from[1], to[0], to[1]][..]), "{}: /L verbatim", tag(path)); + if path != Save::FullStreams { + prop_assert!(bytes::numbers_of(&file, "L").contains(&vec![from[0], from[1], to[0], to[1]]), "{}: /L must be in the file", tag(path)); + } + } + } +} + +/// A comment is addressed as `(page, index)`, and `lib.rs` documents `index` as its position in +/// that page's `/Annots`. Fixed rather than generated, because the interesting part is not the +/// arithmetic but the interaction: a note adds its pop-up to the same array, so an index claimed +/// before a save has to still name the same comment afterwards. +#[test] +fn indices_claimed_before_a_save_still_name_the_same_comment_after_it() { + let mut doc = blank(1); + let first = add_annotation( + &mut doc, + &comment(0, Shape::Rectangle { rect: [10.0, 700.0, 90.0, 730.0] }, Style::default(), "one".into(), "A".into()), + &meta("i1".into()), + ) + .expect("adds"); + let second = add_annotation( + &mut doc, + &comment(0, Shape::Note { at: [10.0, 600.0], icon: NoteIcon::Note }, Style::default(), "two".into(), "A".into()), + &meta("i2".into()), + ) + .expect("adds"); + let third = add_annotation( + &mut doc, + &comment(0, Shape::Rectangle { rect: [10.0, 400.0, 90.0, 430.0] }, Style::default(), "three".into(), "A".into()), + &meta("i3".into()), + ) + .expect("adds"); + assert_eq!((first, second, third), (0, 1, 3), "the pop-up takes index 2"); + + for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { + let (_, reopened) = save_and_reopen(&doc, path); + for (idx, want_id) in [(first, "i1"), (second, "i2"), (third, "i3")] { + let entries = annot_entries(&reopened, 0); + let d = dict_of(&reopened, &entries[idx]).unwrap_or_else(|| panic!("{}: index {idx} exists", tag(path))); + assert_eq!(str_of(&reopened, &d, b"NM").as_deref(), Some(want_id), "{}: index {idx} is still the same comment", tag(path)); + } + } +} diff --git a/crates/annot/tests/round_trip.rs b/crates/annot/tests/round_trip.rs new file mode 100644 index 0000000000..3e60601498 --- /dev/null +++ b/crates/annot/tests/round_trip.rs @@ -0,0 +1,1086 @@ +//! Structural fidelity of annotations across save and reopen (ISO 32000-2 §12.5). +//! +//! `src/tests.rs` checks comments against the document *in memory*: it edits a comment and +//! asserts what the dictionary now holds, with `reopen` used mainly to prove the bytes parse. +//! These tests take the other half — a comment is added, the file is written and re-read from +//! scratch, and what survives is checked entry by entry against values worked out here from the +//! standard rather than read back from the crate that wrote them. +//! +//! Each test replays its assertions over all three writer paths in `support::fixture` +//! (incremental, full save with a cross-reference table, full save into compressed object +//! streams). Object numbers change on the third path, so `/P`, `/Popup`, `/IRT` and `/Dest` +//! targets have to be re-pointed rather than copied — that is where reference-carrying data +//! actually breaks. +//! +//! Scope, deliberately: **structure only**. Nothing here asserts what an appearance stream draws, +//! how wide a stamp label is, or where glyphs land. Appearance generation is being rewritten by +//! several open PRs at once (#2345 stamps, #2137 pop-up windows, #2066 Vietnamese text, #1775 +//! FreeText fonts, #1513 Turkish), and a test that pinned today's drawing would be noise for +//! them. Where stored geometry is defined in terms of an appearance measurement — a line's +//! arrowhead padding, a cloud's bulge, a callout box's re-fit — these tests assert the +//! containment and internal consistency that must hold whatever that measurement is. + +mod support { + pub mod bytes; + pub mod fixture; +} + +use pdfcraft_annot::{ + AnnotError, AttachIcon, LineEnding, Markup, Meta, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, ReviewState, Shape, StampKind, Style, + StyleChange, add_annotation, add_reply, delete_annotation, links, page_refs, props, set_locked, set_review_state, set_style, summaries, +}; +use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions}; + +use support::bytes; +use support::fixture::{ + ALL_SAVES, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, FLAG_READONLY, Save, annot_entries, blank, blank_with_indirect_annots, dict_of, name_of, + num, nums, page_object_numbers, pdf, save_and_reopen, str_of, +}; + +/// A deterministic `/M` date and `/NM` id, so nothing here depends on the clock. +fn meta(id: &str) -> Meta { + Meta { date: Some("D:20261001120000Z".into()), id: id.into() } +} + +/// A comment with plain styling unless a test asks otherwise. +fn ann(page: usize, shape: Shape, contents: &str) -> NewAnnotation { + NewAnnotation { page, shape, style: Style::default(), contents: contents.into(), author: "Ada".into() } +} + +fn styled(page: usize, shape: Shape, contents: &str, color: [f64; 3], opacity: f64, width: f64, fill: Option<[f64; 3]>) -> NewAnnotation { + NewAnnotation { page, shape, style: Style { color, opacity, width, fill }, contents: contents.into(), author: "Ada".into() } +} + +/// The dictionary of the `k`-th `/Annots` entry of a page. +fn annot_at(doc: &Document, page: usize, k: usize, path: Save) -> Dict { + let entries = annot_entries(doc, page); + let entry = entries.get(k).unwrap_or_else(|| panic!("{path:?}: page {page} has {} /Annots entries, wanted index {k}", entries.len())); + dict_of(doc, entry).unwrap_or_else(|| panic!("{path:?}: /Annots[{k}] is not a dictionary")) +} + +fn ref_at(doc: &Document, page: usize, k: usize) -> ObjRef { + annot_entries(doc, page)[k].as_ref().expect("an indirect /Annots entry") +} + +/// Comment subtypes on a page, in `/Annots` order. +fn kinds(doc: &Document, page: usize) -> Vec { + annot_entries(doc, page).iter().filter_map(|e| dict_of(doc, e)).map(|d| name_of(doc, &d, b"Subtype").unwrap_or_default()).collect() +} + +/// A `/LE`-style array of names, as strings. +fn name_array(doc: &Document, d: &Dict, key: &[u8]) -> Option> { + let a = doc.resolve(d.get(key)?).as_array()?.clone(); + // Every element must be a name; an array like [/OpenArrow 3] is not a valid /LE. + let mut out = Vec::with_capacity(a.len()); + for x in &a { + out.push(String::from_utf8_lossy(x.as_name()?).into_owned()); + } + Some(out) +} + +// ── the sticky note: geometry, text, flags and its pop-up ───────────────────────────────────── + +/// A sticky note carries more distinct data than any other comment: a position, an icon name, the +/// flag combination that keeps the icon unscaled on zoom and rotation, a closed `Open`, opacity, +/// author, text, date, id — plus a separate pop-up annotation that points back at it. +#[test] +fn sticky_note_and_its_popup_survive_every_save_path() { + let mut doc = blank(2); + // §12.5.6.4: a sticky note is a `Text` annotation; the icon's top-left sits at `at`, and + // NOTE_SIZE (20 pt) gives the box, so /Rect is [100 680 120 700]. + let i = add_annotation(&mut doc, &ann(0, Shape::Note { at: [100.0, 700.0], icon: NoteIcon::Key }, "Left margin note"), &meta("note-1")) + .expect("adds"); + assert_eq!(i, 0); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + assert_eq!(kinds(&reopened, 0), vec!["Text".to_string(), "Popup".to_string()], "{path:?}"); + let n = annot_at(&reopened, 0, 0, path); + assert_eq!(name_of(&reopened, &n, b"Type").as_deref(), Some("Annot"), "{path:?}"); + assert_eq!(nums(&reopened, &n, b"Rect").as_deref(), Some(&[100.0, 680.0, 120.0, 700.0][..]), "{path:?} /Rect"); + assert_eq!(name_of(&reopened, &n, b"Name").as_deref(), Some("Key"), "{path:?}: the icon (§12.5.6.4 Table 175)"); + assert_eq!(str_of(&reopened, &n, b"Contents").as_deref(), Some("Left margin note"), "{path:?}"); + assert_eq!(str_of(&reopened, &n, b"T").as_deref(), Some("Ada"), "{path:?}"); + assert_eq!(str_of(&reopened, &n, b"NM").as_deref(), Some("note-1"), "{path:?}"); + assert_eq!(str_of(&reopened, &n, b"M").as_deref(), Some("D:20261001120000Z"), "{path:?}"); + assert_eq!(str_of(&reopened, &n, b"Subj").as_deref(), Some("Sticky Note"), "{path:?}"); + // §12.5.3: /CA defaults to 1, so full opacity writes no /CA at all. + assert!(n.get(b"CA").is_none(), "{path:?}: /CA must be absent at full opacity"); + // Notes print, and stay unscaled under zoom and rotation: Print|NoZoom|NoRotate. + assert_eq!(n.int(b"F"), Some(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?} /F"); + assert_eq!(n.get(b"Open").map(|o| matches!(o, Object::Bool(false))), Some(true), "{path:?}: /Open false"); + assert_eq!(nums(&reopened, &n, b"C").as_deref(), Some(&[1.0, 0.82, 0.0][..]), "{path:?} /C"); + // /P names the page it belongs to — the same object, after any renumbering. + assert_eq!(n.reference(b"P").map(|r| r.num), Some(page_object_numbers(&reopened)[0]), "{path:?}: /P resolves to page 1"); + + // The pop-up names its parent and the parent names it back. + let pop = annot_at(&reopened, 0, 1, path); + assert_eq!(name_of(&reopened, &pop, b"Subtype").as_deref(), Some("Popup"), "{path:?}"); + assert_eq!(pop.reference(b"Parent"), Some(ref_at(&reopened, 0, 0)), "{path:?}: /Popup and /Parent agree both ways"); + assert_eq!(n.reference(b"Popup"), Some(ref_at(&reopened, 0, 1)), "{path:?}"); + // Acrobat's pop-up is a 200×120 pt window beside the icon, top aligned with it. + assert_eq!(nums(&reopened, &pop, b"Rect").as_deref(), Some(&[130.0, 580.0, 330.0, 700.0][..]), "{path:?}: pop-up /Rect"); + + if !matches!(path, Save::FullStreams) { + // Claims about the file's own bytes (see `support::bytes`), not via our reader. + assert_eq!(bytes::numbers_of(&file, "Rect").first(), Some(&vec![100.0, 680.0, 120.0, 700.0]), "{path:?}"); + assert!(bytes::texts_of(&file, "NM").contains(&"note-1".to_string()), "{path:?}"); + assert!(bytes::texts_of(&file, "Contents").contains(&"Left margin note".to_string()), "{path:?}"); + assert!(bytes::has_name(&file, "Key"), "{path:?}: the icon name is in the file"); + } + } +} + +/// Opacity below 1 must reach the file as `/CA`; an out-of-range value is clamped, and a clamp +/// to 1.0 means the key disappears rather than being written as `1`. +#[test] +fn opacity_is_written_only_when_it_differs_from_one() { + let cases = [(0.65, Some(0.65)), (1.0, None), (1.75, None), (0.0, Some(0.0)), (-0.25, Some(0.0))]; + for (opacity, expected) in cases { + let mut doc = blank(1); + add_annotation( + &mut doc, + &styled(0, Shape::Rectangle { rect: [10.0, 10.0, 60.0, 40.0] }, "x", [0.9, 0.1, 0.1], opacity, 2.0, None), + &meta("o"), + ) + .expect("adds"); + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let d = annot_at(&reopened, 0, 0, path); + assert_eq!(num(&reopened, &d, b"CA"), expected, "{path:?}: /CA at the given opacity {opacity}"); + assert_eq!(props(&reopened, 0, 0).map(|p| p.opacity), Some(expected.unwrap_or(1.0)), "{path:?}: reported opacity {opacity}"); + if !matches!(path, Save::FullStreams) { + assert_eq!(bytes::scalars_of(&file, "CA").first().copied(), expected, "{path:?}: /CA written at opacity {opacity}"); + } + } + } +} + +// ── text markup: quadrilaterals are the geometry (§12.5.6.10) ───────────────────────────────── + +/// The four markup kinds differ in `/Subtype` alone; each keeps its quadrilateral list and derived +/// rectangle. The two-quad case shows the array is stored whole (16 numbers) rather than +/// truncated to the first quad, and that `/Rect` spans both. +#[test] +fn markup_kinds_keep_quads_and_rectangles() { + let kinds = + [("Highlight", Markup::Highlight), ("Underline", Markup::Underline), ("StrikeOut", Markup::StrikeOut), ("Squiggly", Markup::Squiggly)]; + let q1 = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0]; + let q2 = [72.0, 692.0, 320.0, 692.0, 72.0, 680.0, 320.0, 680.0]; + let mut doc = blank(1); + for (k, name) in kinds.iter() { + add_annotation(&mut doc, &ann(0, Shape::TextMarkup { kind: *name, quads: vec![q1] }, "word"), &meta(&format!("m-{k}"))).expect("adds"); + } + // A two-quad highlight last, so the multi-array case sits at a known index. + let two = add_annotation(&mut doc, &ann(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![q1, q2] }, "two lines"), &meta("m-two")) + .expect("adds"); + assert_eq!(two, kinds.len()); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let mut want = kinds.iter().map(|(label, _)| (*label).to_string()).collect::>(); + want.push("Highlight".into()); // the two-quad comment added last + assert_eq!(kinds_of(&reopened, 0), want, "{path:?}"); + for (n, label) in kinds.iter().map(|(label, _)| *label).enumerate() { + let d = annot_at(&reopened, 0, n, path); + assert_eq!(nums(&reopened, &d, b"QuadPoints").as_deref(), Some(&q1[..]), "{path:?}: /QuadPoints verbatim"); // attribution dropped: nothing here tests any specific reader's ordering + assert_eq!(nums(&reopened, &d, b"Rect").as_deref(), Some(&[72.0, 700.0, 200.0, 712.0][..]), "{path:?}: /Rect bounds the quad"); + assert!(d.get(b"BS").is_none(), "{path:?}: markup writes no border style"); + assert_eq!(str_of(&reopened, &d, b"NM").as_deref(), Some(format!("m-{label}").as_str()), "{path:?}"); + } + let d = annot_at(&reopened, 0, two, path); + assert_eq!( + nums(&reopened, &d, b"QuadPoints").as_deref(), + Some(&[q1.to_vec(), q2.to_vec()].concat()[..]), + "{path:?}: two quads are 16 numbers" + ); + assert_eq!(nums(&reopened, &d, b"Rect").as_deref(), Some(&[72.0, 680.0, 320.0, 712.0][..]), "{path:?}: /Rect spans both quads"); + if !matches!(path, Save::FullStreams) { + let sixteen = [q1.to_vec(), q2.to_vec()].concat(); + assert_eq!(bytes::numbers_of(&file, "QuadPoints").last(), Some(&sixteen), "{path:?}: 16 fixed-decimal numbers in the file"); + } + } +} + +fn kinds_of(doc: &Document, page: usize) -> Vec { + kinds(doc, page) +} + +/// `Summary` reports quadrilaterals as 8-number chunks; the same list must chunk identically +/// after a save, and its rectangle must be the bounds those chunks imply. +#[test] +fn summary_quads_and_rect_agree_after_reopen() { + let q1 = [72.0, 300.0, 160.0, 300.0, 72.0, 286.0, 160.0, 286.0]; + let q2 = [72.0, 280.0, 500.0, 280.0, 72.0, 266.0, 500.0, 266.0]; + let mut doc = blank(1); + add_annotation(&mut doc, &ann(0, Shape::TextMarkup { kind: Markup::Squiggly, quads: vec![q1, q2] }, "s"), &meta("sq")).expect("adds"); + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + let sum = summaries(&reopened).into_iter().find(|s| s.subtype == "Squiggly").expect("the squiggly is listed"); + assert_eq!(sum.quads, vec![q1.map(|v| v as f32), q2.map(|v| v as f32)], "{path:?}"); + assert_eq!(sum.rect, [72.0f32, 266.0, 500.0, 300.0], "{path:?}"); + assert_eq!(sum.contents.as_deref(), Some("s"), "{path:?}"); + assert_eq!(sum.author.as_deref(), Some("Ada"), "{path:?}"); + } +} + +// ── shapes, lines and drawings ──────────────────────────────────────────────────────────────── + +/// Squares, ovals and stamps keep an exact `/Rect` (reversed corners normalised as §12.5.4.2 +/// requires), interior colour, border width and stamp identity. +#[test] +fn shapes_keep_rectangles_fills_borders_and_stamp_identity() { + let mut doc = blank(1); + add_annotation( + &mut doc, + &styled(0, Shape::Rectangle { rect: [300.0, 300.0, 200.0, 200.0] }, "box", [0.9, 0.1, 0.1], 1.0, 2.0, Some([0.0, 0.5, 0.0])), + &meta("sq"), + ) + .expect("adds square"); + add_annotation(&mut doc, &styled(0, Shape::Oval { rect: [50.0, 60.0, 90.0, 120.0] }, "oval", [0.0, 0.4, 0.8], 1.0, 3.0, None), &meta("ov")) + .expect("adds oval"); + add_annotation( + &mut doc, + &styled( + 0, + Shape::Stamp { rect: [40.0, 600.0, 180.0, 650.0], stamp: StampKind::Approved, by: Some("Ada".into()) }, + "stamped", + [0.13, 0.55, 0.13], + 1.0, + 2.0, + None, + ), + &meta("st"), + ) + .expect("adds stamp"); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let sq = annot_at(&reopened, 0, 0, path); + assert_eq!(name_of(&reopened, &sq, b"Subtype").as_deref(), Some("Square"), "{path:?}"); + // Corners were given as [300 300 200 200]; a rectangle is stored lower-left then upper-right. + assert_eq!(nums(&reopened, &sq, b"Rect").as_deref(), Some(&[200.0, 200.0, 300.0, 300.0][..]), "{path:?}"); + assert_eq!(nums(&reopened, &sq, b"IC").as_deref(), Some(&[0.0, 0.5, 0.0][..]), "{path:?}: /IC (§12.5.6.8)"); + assert_eq!(nums(&reopened, &sq, b"C").as_deref(), Some(&[0.9, 0.1, 0.1][..]), "{path:?}"); + let p = props(&reopened, 0, 0).expect("properties"); + assert_eq!(p.width, Some(2.0), "{path:?}: /BS /W"); + assert_eq!(p.fill, Some([0.0, 0.5, 0.0]), "{path:?}"); + assert!(p.fillable, "{path:?}: rectangles can be filled"); + + let ov = annot_at(&reopened, 0, 1, path); + assert_eq!(name_of(&reopened, &ov, b"Subtype").as_deref(), Some("Circle"), "{path:?}: an oval is /Circle (§12.5.6.9)"); + assert_eq!(nums(&reopened, &ov, b"Rect").as_deref(), Some(&[50.0, 60.0, 90.0, 120.0][..]), "{path:?}"); + assert!(ov.get(b"IC").is_none(), "{path:?}: no interior colour when unfilled"); + assert_eq!(props(&reopened, 0, 1).and_then(|q| q.width), Some(3.0), "{path:?}"); + + let st = annot_at(&reopened, 0, 2, path); + assert_eq!(name_of(&reopened, &st, b"Subtype").as_deref(), Some("Stamp"), "{path:?}"); + assert_eq!(name_of(&reopened, &st, b"Name").as_deref(), Some("Approved"), "{path:?}: a standard stamp keeps its Table 184 name"); + assert_eq!(nums(&reopened, &st, b"Rect").as_deref(), Some(&[40.0, 600.0, 180.0, 650.0][..]), "{path:?}"); + assert!(st.contains(b"PCStamp"), "{path:?}: PdfCraft's own artwork is marked as such"); + assert_eq!(str_of(&reopened, &st, b"PCByLine").as_deref(), Some("Ada"), "{path:?}"); + if !matches!(path, Save::FullStreams) { + assert_eq!(bytes::numbers_of(&file, "IC").first(), Some(&vec![0.0, 0.5, 0.0]), "{path:?}"); + assert!(bytes::has_name(&file, "Approved"), "{path:?}"); + } + } +} + +/// Lines, connected lines and polygons keep their endpoint arrays (`/L`, `/Vertices`), their +/// ending pair (`/LE`) and a cloud's intent. Their `/Rect` is grown by arrowhead and bulge +/// measurements that live in `appearance`, so this checks containment rather than exact padding. +#[test] +fn lines_and_polygons_keep_endpoints_endings_and_cloud_intent() { + let mut doc = blank(1); + add_annotation( + &mut doc, + &ann(0, Shape::Line { from: [50.0, 50.0], to: [150.0, 100.0], start: LineEnding::None, end: LineEnding::OpenArrow }, "arrow"), + &meta("l1"), + ) + .expect("adds arrow"); + add_annotation( + &mut doc, + &ann( + 0, + Shape::PolyLine { vertices: vec![[10.0, 20.0], [40.0, 60.0], [70.0, 25.0]], start: LineEnding::ClosedArrow, end: LineEnding::Butt }, + "path", + ), + &meta("pl"), + ) + .expect("adds polyline"); + add_annotation( + &mut doc, + &ann(0, Shape::Polygon { vertices: vec![[200.0, 100.0], [260.0, 110.0], [230.0, 160.0]], cloud: true }, "cloud"), + &meta("pg"), + ) + .expect("adds cloud"); + add_annotation( + &mut doc, + &ann(0, Shape::Ink { strokes: vec![vec![[0.0, 0.0], [10.0, 10.0], [20.0, 0.0]], vec![[40.0, 40.0], [50.0, 50.0]]] }, "ink"), + &meta("ink"), + ) + .expect("adds ink"); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + + let l = annot_at(&reopened, 0, 0, path); + assert_eq!(name_of(&reopened, &l, b"Subtype").as_deref(), Some("Line"), "{path:?}"); + assert_eq!(nums(&reopened, &l, b"L").as_deref(), Some(&[50.0, 50.0, 150.0, 100.0][..]), "{path:?}: /L (§12.5.6.7)"); + assert_eq!( + name_array(&reopened, &l, b"LE").as_deref(), + Some(&["None".to_string(), "OpenArrow".to_string()][..]), + "{path:?}: /LE (§12.5.6.7 Table 217)" + ); + let r = nums(&reopened, &l, b"Rect").expect("/Rect"); + assert!(r[0] <= 50.0 && r[1] <= 50.0 && r[2] >= 150.0 && r[3] >= 100.0, "{path:?}: /Rect must contain both endpoints, got {r:?}"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.endings), Some(vec![LineEnding::None, LineEnding::OpenArrow]), "{path:?}"); + + let pl = annot_at(&reopened, 0, 1, path); + assert_eq!(name_of(&reopened, &pl, b"Subtype").as_deref(), Some("PolyLine"), "{path:?}"); + assert_eq!(nums(&reopened, &pl, b"Vertices").as_deref(), Some(&[10.0, 20.0, 40.0, 60.0, 70.0, 25.0][..]), "{path:?}: /Vertices (§12.5.6.9)"); + assert_eq!(props(&reopened, 0, 1).and_then(|p| p.endings), Some(vec![LineEnding::ClosedArrow, LineEnding::Butt]), "{path:?}"); + + let pg = annot_at(&reopened, 0, 2, path); + assert_eq!(name_of(&reopened, &pg, b"Subtype").as_deref(), Some("Polygon"), "{path:?}"); + assert_eq!(name_of(&reopened, &pg, b"IT").as_deref(), Some("PolygonCloud"), "{path:?}: a cloud is `/IT /PolygonCloud` (§12.5.6.9)"); + let be = pg.get(b"BE").map(|o| reopened.resolve(o)).and_then(|o| o.as_dict().cloned()).expect("/BE"); + assert_eq!(name_of(&reopened, &be, b"S").as_deref(), Some("C"), "{path:?}: cloudy border"); + assert_eq!(be.int(b"I"), Some(1), "{path:?}"); + assert_eq!(nums(&reopened, &pg, b"Vertices").as_deref(), Some(&[200.0, 100.0, 260.0, 110.0, 230.0, 160.0][..]), "{path:?}"); + + let ink = annot_at(&reopened, 0, 3, path); + assert_eq!(name_of(&reopened, &ink, b"Subtype").as_deref(), Some("Ink"), "{path:?}"); + let strokes: Vec> = ink + .get(b"InkList") + .map(|o| reopened.resolve(o)) + .and_then(|o| o.as_array().cloned()) + .expect("/InkList") + .iter() + .map(|s| reopened.resolve(s).as_array().expect("a stroke array").iter().filter_map(|x| x.as_f64()).collect()) + .collect(); + assert_eq!(strokes, vec![vec![0.0, 0.0, 10.0, 10.0, 20.0, 0.0], vec![40.0, 40.0, 50.0, 50.0]], "{path:?}: both strokes, all their points"); + if !matches!(path, Save::FullStreams) { + assert_eq!(bytes::numbers_of(&file, "L").first(), Some(&vec![50.0, 50.0, 150.0, 100.0]), "{path:?}"); + assert_eq!(bytes::numbers_of(&file, "Vertices").first(), Some(&vec![10.0, 20.0, 40.0, 60.0, 70.0, 25.0]), "{path:?}"); + } + } +} + +// ── FreeText: the box, its font size and a callout's leader line ─────────────────────────────── + +/// A text box stores its rectangle, colour and size in `/DA`/`Q`, and typewriter text marks its +/// intent (§12.5.6.6). The stored box is the requested one: re-fitting happens on later edits, +/// not at creation. +#[test] +fn text_boxes_keep_rectangles_font_size_and_intent() { + let mut doc = blank(1); + add_annotation( + &mut doc, + &styled(0, Shape::TextBox { rect: [300.0, 600.0, 500.0, 650.0], font_size: 14.0 }, "Type here", [0.1, 0.2, 0.3], 1.0, 0.0, None), + &meta("tb"), + ) + .expect("adds text box"); + add_annotation( + &mut doc, + &styled(0, Shape::Typewriter { rect: [72.0, 100.0, 300.0, 124.0], font_size: 12.0 }, "Typed words", [0.0, 0.0, 0.0], 1.0, 0.0, None), + &meta("tw"), + ) + .expect("adds typewriter"); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let tb = annot_at(&reopened, 0, 0, path); + assert_eq!(name_of(&reopened, &tb, b"Subtype").as_deref(), Some("FreeText"), "{path:?}"); + assert_eq!(nums(&reopened, &tb, b"Rect").as_deref(), Some(&[300.0, 600.0, 500.0, 650.0][..]), "{path:?}"); + assert_eq!(str_of(&reopened, &tb, b"DA").as_deref(), Some("0.1 0.2 0.3 rg /Helv 14 Tf"), "{path:?}: /DA (§12.5.6.6, §12.7.2.3)"); + assert_eq!(tb.int(b"Q"), Some(0), "{path:?}: left aligned"); + assert!(tb.get(b"IT").is_none(), "{path:?}: a plain text box sets no intent"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.font_size), Some(14.0), "{path:?}"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.color), Some([0.1, 0.2, 0.3]), "{path:?}: FreeText colour comes from /DA"); + + let tw = annot_at(&reopened, 0, 1, path); + assert_eq!(name_of(&reopened, &tw, b"IT").as_deref(), Some("FreeTextTypeWriter"), "{path:?}"); + assert_eq!(nums(&reopened, &tw, b"Rect").as_deref(), Some(&[72.0, 100.0, 300.0, 124.0][..]), "{path:?}"); + assert_eq!(props(&reopened, 0, 1).and_then(|p| p.font_size), Some(12.0), "{path:?}"); + assert!(tw.contains(b"PCFillSign"), "{path:?}: typewriter text is a Fill & Sign item"); + if !matches!(path, Save::FullStreams) { + assert_eq!(bytes::texts_of(&file, "DA").first().map(String::as_str), Some("0.1 0.2 0.3 rg /Helv 14 Tf"), "{path:?}"); + } + } +} + +/// A callout keeps six numbers in `/CL` (arrow point, knee, box attach) plus the inset `/RD`; +/// together those must rebuild exactly the text box that was asked for. That is a consistency +/// claim, so it does not depend on how wide the arrowhead is drawn. +#[test] +fn callout_keeps_its_leader_line_and_rebuilds_the_same_text_box() { + let mut doc = blank(1); + add_annotation( + &mut doc, + &ann( + 0, + Shape::Callout { + rect: [300.0, 400.0, 420.0, 460.0], + knee: [250.0, 380.0], + point: [200.0, 350.0], + font_size: 16.0, + ending: LineEnding::OpenArrow, + }, + "why", + ), + &meta("co"), + ) + .expect("adds callout"); + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let d = annot_at(&reopened, 0, 0, path); + assert_eq!(name_of(&reopened, &d, b"IT").as_deref(), Some("FreeTextCallout"), "{path:?}"); + // The knee is left of the box, so the leader attaches at the box's left edge midpoint. + assert_eq!(nums(&reopened, &d, b"CL").as_deref(), Some(&[200.0, 350.0, 250.0, 380.0, 300.0, 430.0][..]), "{path:?}: /CL point→knee→attach"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.endings), Some(vec![LineEnding::OpenArrow]), "{path:?}"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.font_size), Some(16.0), "{path:?}"); + let rect = nums(&reopened, &d, b"Rect").expect("/Rect"); + let rd = nums(&reopened, &d, b"RD").expect("/RD"); + assert!(rd.iter().all(|v| *v >= 0.0), "{path:?}: /RD insets are non-negative (§12.5.3)"); + assert_eq!( + [rect[0] + rd[0], rect[1] + rd[1], rect[2] - rd[2], rect[3] - rd[3]], + [300.0, 400.0, 420.0, 460.0], + "{path:?}: /Rect inset by /RD is the text box" + ); + if !matches!(path, Save::FullStreams) { + assert_eq!(bytes::numbers_of(&file, "CL").first(), Some(&vec![200.0, 350.0, 250.0, 380.0, 300.0, 430.0]), "{path:?}"); + } + } +} + +// ── redaction and file attachment: payload data, not just dictionary keys ───────────────────── + +/// A redaction stores the area it will cover, the colour it will paint and its overlay text with +/// style. Applying a redaction is other crates' business; here only the data has to survive. +#[test] +fn redaction_keeps_quads_fill_and_overlay_text() { + let quads = vec![[72.0, 712.0, 300.0, 712.0, 72.0, 690.0, 300.0, 690.0], [72.0, 680.0, 240.0, 680.0, 72.0, 660.0, 240.0, 660.0]]; + let mut doc = blank(1); + add_annotation( + &mut doc, + &styled( + 0, + Shape::Redact { + quads: quads.clone(), + overlay: "SECRET".into(), + look: OverlayLook { font: OverlayFont::Courier, size: 0.0, color: [1.0, 0.0, 0.0], align: 2, repeat: true }, + }, + "remove this", + [0.89, 0.13, 0.13], + 1.0, + 1.0, + Some([0.0, 0.0, 0.0]), + ), + &meta("red"), + ) + .expect("adds redaction"); + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let d = annot_at(&reopened, 0, 0, path); + assert_eq!(name_of(&reopened, &d, b"Subtype").as_deref(), Some("Redact"), "{path:?}"); + assert_eq!(nums(&reopened, &d, b"QuadPoints").as_deref(), Some(&quads.concat()[..]), "{path:?}"); + assert_eq!(nums(&reopened, &d, b"IC").as_deref(), Some(&[0.0, 0.0, 0.0][..]), "{path:?}: /IC is the colour applied (§12.5.6.23)"); + assert_eq!(str_of(&reopened, &d, b"OverlayText").as_deref(), Some("SECRET"), "{path:?}"); + assert_eq!(str_of(&reopened, &d, b"DA").as_deref(), Some("1 0 0 rg /Cour 0 Tf"), "{path:?}: the overlay font resource"); + assert_eq!(d.int(b"Q"), Some(2), "{path:?}: right aligned"); + assert_eq!(d.get(b"Repeat").map(|o| matches!(o, Object::Bool(true))), Some(true), "{path:?}"); + assert_eq!(nums(&reopened, &d, b"Rect").as_deref(), Some(&[72.0, 660.0, 300.0, 712.0][..]), "{path:?}"); + if !matches!(path, Save::FullStreams) { + assert_eq!(bytes::texts_of(&file, "OverlayText").first().map(String::as_str), Some("SECRET"), "{path:?}"); + } + } +} + +/// An attached file is the heaviest annotation there is: a file specification, an embedded file +/// stream with its own parameters, and the bytes inside it. A full rewrite renumbers all three +/// objects and may move them into object streams, so this is the strongest reference test here. +#[test] +fn attached_file_specification_and_bytes_survive_every_save_path() { + let body = b"first line\nsecond line, 27 bytes more\n".to_vec(); + let mut doc = blank(1); + add_annotation( + &mut doc, + &ann(0, Shape::Attachment { at: [300.0, 600.0], icon: AttachIcon::Paperclip, file: "notes.txt".into(), data: body.clone() }, ""), + &meta("att"), + ) + .expect("attaches"); + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + let d = annot_at(&reopened, 0, 0, path); + assert_eq!(name_of(&reopened, &d, b"Subtype").as_deref(), Some("FileAttachment"), "{path:?}"); + assert_eq!(name_of(&reopened, &d, b"Name").as_deref(), Some("Paperclip"), "{path:?}"); + // With no comment text the file's name is shown as the contents (§12.5.6.15). + assert_eq!(str_of(&reopened, &d, b"Contents").as_deref(), Some("notes.txt"), "{path:?}"); + assert_eq!(nums(&reopened, &d, b"Rect").as_deref(), Some(&[300.0, 580.0, 320.0, 600.0][..]), "{path:?}"); + + let fs_ref = d.reference(b"FS").expect("/FS must reference a file specification"); + let fs = reopened.get(fs_ref).as_dict().cloned().expect("/FS resolves to a dictionary"); + assert_eq!(name_of(&reopened, &fs, b"Type").as_deref(), Some("Filespec"), "{path:?}"); + assert_eq!(str_of(&reopened, &fs, b"F").as_deref(), Some("notes.txt"), "{path:?}"); + let ef = fs.get(b"EF").map(|o| reopened.resolve(o)).and_then(|o| o.as_dict().cloned()).expect("/EF"); + let file_ref = ef.reference(b"F").expect("/EF /F references the embedded stream"); + let Object::Stream(s) = &*reopened.get(file_ref) else { panic!("the embedded file is a stream") }; + assert_eq!(s.decoded().expect("decodes").as_slice(), &body[..], "{path:?}: the file's bytes survive"); + let params = s.dict.get(b"Params").map(|o| reopened.resolve(o)).and_then(|o| o.as_dict().cloned()).expect("/Params"); + assert_eq!(params.int(b"Size").map(|v| v as usize), Some(body.len()), "{path:?}"); + } +} + +// ── order, indices and page ownership across several comments ───────────────────────────────── + +/// Five comments on two pages keep their per-page order, the `(page, index)` addressing documented +/// at the top of `lib.rs`, and each one's `/P`. `summaries` additionally promises page order then +/// top edge first; both are checked, because `index` refers to `/Annots` position while the list +/// order does not. +/// COVERAGE HONESTY (ten single-site mutations, run independently by two reviewers plus the +/// author; run at base 99941daa, before main split `lib.rs` into modules - the anchors below +/// are the merged layout, re-derived line by line from the split files). FIVE are also killed by pre-existing inline tests in `crates/annot/src/tests.rs`, and +/// they share a family — the clamp is INVERTED, or a key/order changed rather than removed: +/// `create.rs:47` inverted (`ink_strokes_are_smooth_curves_through_their_points`), `create.rs:216` inverted +/// (six inline tests), `modify.rs:547` inverted (`restyle_and_resize_redraw_the_appearance`), +/// `info.rs:151` tie-break swapped (`stamps_draw_their_label_and_by_line`, the same tie-break as +/// here) and `create.rs:450` `/Parent` renamed (`every_tool_creates_a_drawable_comment`). This file shares that +/// credit and claims none of it alone. The other FIVE are killed only by tests added here, and +/// they share a different family — the clamp is REMOVED outright, or introduced where the code +/// does not have one: `create.rs:216` deleted, `create.rs:47` deleted, the opacity clamp at +/// `create.rs:212` removed, the colour clamp in `rgb()` at `create.rs:14` removed (killed only by +/// `malformed::the_same_huge_fill_is_accepted_on_create_and_refused_on_edit`), and a clamp ADDED +/// to the read path at `info.rs:231`. Note that `create.rs:47` appears on both sides, and +/// deliberately so: +/// inverting that clamp trips an inline test as well, while deleting it trips nothing but +/// `a_negative_and_a_zero_border_pad_a_line_identically`. Confusing those two mutations is easy +/// enough to produce a false refutation, so the distinction is recorded here rather than left to +/// whoever re-runs them. +/// Two further notes: the stored `/Annots` order checked below goes through all three save paths, +/// which no inline test does; and `properties.rs::several_rectangles_keep_count_order_and_geometry` +/// constrains stored array order only — it does NOT exercise `summaries()` ordering. +#[test] +fn several_comments_keep_order_indices_and_page_ownership() { + let mut doc = blank(4); + add_annotation(&mut doc, &ann(0, Shape::Rectangle { rect: [10.0, 100.0, 60.0, 140.0] }, "low"), &meta("a")).expect("adds"); + add_annotation(&mut doc, &ann(0, Shape::Note { at: [10.0, 700.0], icon: NoteIcon::Note }, "high note"), &meta("b")).expect("adds"); + add_annotation( + &mut doc, + &ann(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![[10.0, 450.0, 90.0, 450.0, 10.0, 436.0, 90.0, 436.0]] }, "mid"), + &meta("c"), + ) + .expect("adds"); + add_annotation(&mut doc, &ann(2, Shape::Oval { rect: [20.0, 30.0, 80.0, 90.0] }, "p3 oval"), &meta("d")).expect("adds"); + add_annotation(&mut doc, &ann(2, Shape::Caret { rect: [300.0, 400.0, 312.0, 424.0] }, "p3 caret"), &meta("e")).expect("adds"); + + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + assert_eq!(kinds(&reopened, 0), ["Square", "Text", "Popup", "Highlight"].map(str::to_owned), "{path:?}: page 1 order"); + assert_eq!(kinds(&reopened, 2), ["Circle", "Caret"].map(str::to_owned), "{path:?}: page 3 order"); + assert_eq!(annot_entries(&reopened, 1).len(), 0, "{path:?}: page 2 stays comment-free"); + assert_eq!(annot_entries(&reopened, 3).len(), 0, "{path:?}"); + + // Every comment's /P names its own page object (pop-ups carry no /P). + let pages = page_object_numbers(&reopened); + for (page, want) in [(0usize, pages[0]), (2, pages[2])] { + for e in annot_entries(&reopened, page) { + let d = dict_of(&reopened, &e).expect("a dictionary"); + if name_of(&reopened, &d, b"Subtype").as_deref() == Some("Popup") { + continue; + } + assert_eq!(d.reference(b"P").map(|r| r.num), Some(want), "{path:?}: /P of {:?}", name_of(&reopened, &d, b"Subtype")); + } + } + + let sums = summaries(&reopened); + assert_eq!(sums.len(), 5, "{path:?}: pop-ups are not comments"); + let mut got: Vec<(usize, usize, String)> = sums.iter().map(|s| (s.page, s.index, s.subtype.clone())).collect(); + got.sort(); + assert_eq!( + got, + vec![ + (0, 0, "Square".to_string()), + (0, 1, "Text".to_string()), + (0, 3, "Highlight".to_string()), + (2, 0, "Circle".to_string()), + (2, 1, "Caret".to_string()) + ], + "{path:?}: (page, index in /Annots, subtype)" + ); + for w in sums.windows(2) { + if w[0].page == w[1].page { + assert!(w[0].rect[3] >= w[1].rect[3], "{path:?}: top edge first, got {:?} then {:?}", w[0].rect, w[1].rect); + } else { + assert!(w[0].page < w[1].page, "{path:?}: page by page"); + } + } + } +} + +/// `annot::page_refs` — the crate's own page walk, cycle guard and all — must agree with this +/// file's independent walk over the same reopened bytes. +#[test] +fn page_refs_agrees_with_an_independent_walk() { + let mut doc = blank(3); + add_annotation(&mut doc, &ann(1, Shape::Rectangle { rect: [0.0, 0.0, 20.0, 20.0] }, "x"), &meta("p")).expect("adds"); + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + let mine = page_object_numbers(&reopened); + let theirs: Vec = page_refs(&reopened).expect("a page tree").iter().map(|r| r.num).collect(); + assert_eq!(mine, theirs, "{path:?}"); + } +} + +// ── threads: replies and review states keep their edges ──────────────────────────────────────── + +/// A reply is a text annotation whose `/IRT` points at its parent; setting a status adds another +/// one. Deleting a comment takes its pop-up and its replies with it. Every edge there is a +/// reference, so a full rewrite has to re-point them all. +#[test] +fn reply_threads_and_the_delete_cascade_survive_every_save_path() { + let mut doc = blank(1); + add_annotation(&mut doc, &ann(0, Shape::Note { at: [100.0, 700.0], icon: NoteIcon::Comment }, "parent"), &meta("p1")).expect("adds parent"); + add_reply(&mut doc, 0, 0, "child one", "Ben", &meta("r1")).expect("replies"); + let status = set_review_state(&mut doc, 0, 0, ReviewState::Accepted, "Ben", &meta("r2")).expect("sets status"); + assert_eq!(status, 3); + + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + assert_eq!(kinds(&reopened, 0), vec!["Text", "Popup", "Text", "Text"], "{path:?}: parent, pop-up, reply, status reply"); + let parent = ref_at(&reopened, 0, 0); + for k in [2usize, 3] { + let d = annot_at(&reopened, 0, k, path); + assert_eq!(d.reference(b"IRT"), Some(parent), "{path:?}: /IRT points at the parent after renumbering"); + assert_eq!(str_of(&reopened, &d, b"T").as_deref(), Some("Ben"), "{path:?}"); + } + let st = annot_at(&reopened, 0, status, path); + assert_eq!(str_of(&reopened, &st, b"State").as_deref(), Some("Accepted"), "{path:?}"); + assert_eq!(str_of(&reopened, &st, b"StateModel").as_deref(), Some("Review"), "{path:?}"); + assert_eq!(str_of(&reopened, &st, b"Subj").as_deref(), Some("Status"), "{path:?}"); + // Replies are printed but keep the icon flags of a comment; no Hidden bit here. + assert_eq!(st.int(b"F"), Some(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?}"); + let listed = summaries(&reopened); + assert_eq!(listed.iter().filter(|s| s.in_reply_to.as_deref() == Some("p1")).count(), 2, "{path:?}: both replies name the parent's /NM"); + assert_eq!(listed.iter().filter(|s| s.state.as_deref() == Some("Accepted")).count(), 1, "{path:?}"); + + // Deleting the comment takes its pop-up and both replies with it. + let mut cut = reopened.clone(); + delete_annotation(&mut cut, 0, 0).expect("deletes the thread"); + assert_eq!(annot_entries(&cut, 0).len(), 0, "{path:?}: nothing of the thread is left in memory"); + let (_, cut) = save_and_reopen(&cut, path); + assert_eq!(annot_entries(&cut, 0).len(), 0, "{path:?}: and the file agrees"); + assert!(summaries(&cut).is_empty(), "{path:?}"); + } +} + +/// The Locked flag is not decoration: a comment that reads back locked must refuse the edits the +/// crate says it refuses. Checking after a save means the flag survived on disk, not merely in +/// memory that happened to still hold it. +#[test] +fn locked_flag_survives_and_still_refuses_edits_after_reopen() { + let mut doc = blank(1); + add_annotation(&mut doc, &ann(0, Shape::Rectangle { rect: [10.0, 20.0, 60.0, 50.0] }, "locked box"), &meta("lk")).expect("adds"); + set_locked(&mut doc, 0, 0, true).expect("locks"); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let d = annot_at(&reopened, 0, 0, path); + assert_eq!(d.int(b"F"), Some(FLAG_PRINT | FLAG_READONLY), "{path:?}: Print plus ReadOnly (bit 8)"); + assert_eq!(props(&reopened, 0, 0).map(|p| p.locked), Some(true), "{path:?}"); + let mut try_move = reopened.clone(); + let e = pdfcraft_annot::move_annotation(&mut try_move, 0, 0, 5.0, 5.0, &meta("nope")).err(); + assert_eq!(e, Some(AnnotError::Invalid("the comment is locked".into())), "{path:?}: moving a locked comment refuses"); + let mut try_delete = reopened.clone(); + assert!(delete_annotation(&mut try_delete, 0, 0).is_err(), "{path:?}: deleting a locked comment refuses"); + if !matches!(path, Save::FullStreams) { + assert_eq!(bytes::scalars_of(&file, "F").first(), Some(&132.0), "{path:?}: the flag value is in the file"); + } + } +} + +// ── links (§12.5.6.5) ──────────────────────────────────────────────────────────────────────── + +/// A link's action is a destination array naming a page object, or a URI action. Page targets are +/// the interesting case across a full rewrite: the link must land on the same page after every +/// object number changes. NOTE (naming): this covers link structure — `/A`, `/Dest`, `/URI` and the +/// dash pattern. It deliberately says nothing about appearance streams, which are out of scope here +/// because #2345/#2137/#2066/#1775/#1513 are rewriting appearance generation. +#[test] +fn links_keep_page_targets_uri_and_dash_structure_across_renumbering() { + let mut doc = blank(3); + add_annotation(&mut doc, &ann(0, Shape::Rectangle { rect: [10.0, 700.0, 90.0, 720.0] }, "shape"), &meta("s")).expect("adds a comment too"); + let i = links::add( + &mut doc, + 0, + [120.0, 700.0, 240.0, 720.0], + &links::LinkAction::Page(2), + &links::LinkStyle { visible: true, width: 2.0, dashed: true, ..Default::default() }, + ) + .expect("links to page 3"); + assert_eq!(i, 1); + links::add( + &mut doc, + 1, + [50.0, 600.0, 200.0, 620.0], + &links::LinkAction::Uri("https://example.com/a?b=c&d=1".into()), + &links::LinkStyle::default(), + ) + .expect("links out"); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let pages = page_object_numbers(&reopened); + let got: Vec<(usize, usize, [f64; 4], String, bool)> = links::list(&reopened) + .into_iter() + .map(|l| { + let a = match l.action { + links::LinkAction::Page(p) => format!("page {p}"), + links::LinkAction::Uri(u) => u, + links::LinkAction::Other(o) => format!("other:{o}"), + }; + (l.page, l.index, l.rect, a, l.style.visible) + }) + .collect(); + assert_eq!(got.len(), 2, "{path:?}"); + assert_eq!(got[0], (0, 1, [120.0, 700.0, 240.0, 720.0], "page 2".into(), true), "{path:?}: the target is still page 3"); + assert_eq!(got[1], (1, 0, [50.0, 600.0, 200.0, 620.0], "https://example.com/a?b=c&d=1".into(), false), "{path:?}"); + + let d = annot_at(&reopened, 0, 1, path); + let dest = d.get(b"Dest").map(|o| reopened.resolve(o)).and_then(|o| o.as_array().cloned()).expect("/Dest is an array"); + assert_eq!(dest.first().and_then(|x| x.as_ref()).map(|r| r.num), Some(pages[2]), "{path:?}: /Dest names the page object"); + assert_eq!(name_of(&reopened, &d, b"H").as_deref(), Some("I"), "{path:?}: highlight /H (invert, §12.5.3)"); + let bs = d.get(b"BS").map(|o| reopened.resolve(o)).and_then(|o| o.as_dict().cloned()).expect("/BS"); + assert_eq!(name_of(&reopened, &bs, b"S").as_deref(), Some("D"), "{path:?}: dashed"); + assert_eq!(bs.get(b"W").and_then(|w| w.as_f64()), Some(2.0), "{path:?}"); + assert_eq!(summaries(&reopened).iter().filter(|s| s.page == 0).count(), 1, "{path:?}: only the rectangle is a comment"); + if !matches!(path, Save::FullStreams) { + assert_eq!( + bytes::texts_of(&file, "URI").first().map(String::as_str), + Some("https://example.com/a?b=c&d=1"), + "{path:?}: the URI is in the file" + ); + } + } +} + +/// Removing every link leaves comments alone. Both directions are index arithmetic over one shared +/// array, so a mistake shows up as a lost comment or an orphaned link. +#[test] +fn removing_all_links_keeps_comments() { + let mut doc = blank(2); + add_annotation(&mut doc, &ann(0, Shape::Note { at: [50.0, 700.0], icon: NoteIcon::Help }, "note"), &meta("n")).expect("adds"); + links::add(&mut doc, 0, [200.0, 700.0, 300.0, 715.0], &links::LinkAction::Page(0), &links::LinkStyle::default()).expect("links"); + let removed = links::remove_all(&mut doc, None).expect("removes all links"); + assert_eq!(removed, 1); + + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + assert_eq!(kinds(&reopened, 0), vec!["Text", "Popup"], "{path:?}: the note and its pop-up stay"); + assert!(links::list(&reopened).is_empty(), "{path:?}"); + } +} + +// ── data the crate does not understand, and nothing at all ───────────────────────────────────── + +/// A stranger's file can hold inline annotation dictionaries and keys PdfCraft has never heard of. +/// Fidelity says they are preserved rather than dropped (`CLAUDE.md`: preserve unknown data). +#[test] +fn inline_annotations_and_unknown_keys_survive_every_save_path() { + let objs: Vec<&[u8]> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [<< /Type /Annot /Subtype /Square /Rect [10 10 50 50] /C [1 0 0] /OddKey (kept) /AnotherLevel << /Deep 42 >> >>] >>", + ]; + let mut doc = Document::open(std::sync::Arc::new(pdf(&objs))).expect("the stranger's file opens"); + add_annotation(&mut doc, &ann(0, Shape::Rectangle { rect: [100.0, 100.0, 150.0, 130.0] }, "ours"), &meta("mine")).expect("adds ours"); + + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + assert_eq!(kinds(&reopened, 0), vec!["Square", "Square"], "{path:?}: theirs first, ours second"); + let foreign = annot_at(&reopened, 0, 0, path); + assert_eq!(str_of(&reopened, &foreign, b"OddKey").as_deref(), Some("kept"), "{path:?}: an unknown string key"); + let deep = foreign.get(b"AnotherLevel").map(|o| reopened.resolve(o)).and_then(|o| o.as_dict().cloned()).expect("an unknown dictionary"); + assert_eq!(deep.int(b"Deep"), Some(42), "{path:?}"); + assert_eq!(nums(&reopened, &foreign, b"Rect").as_deref(), Some(&[10.0, 10.0, 50.0, 50.0][..]), "{path:?}"); + assert_eq!(str_of(&reopened, &annot_at(&reopened, 0, 1, path), b"NM").as_deref(), Some("mine"), "{path:?}: our own comment is still there"); + } +} + +/// A document with nothing on it round trips without acquiring stray keys: no `/Annots` at all, +/// and an empty comment list. Cheap to check, and it is the case where a writer bug would add +/// noise that no other assertion in this file would notice. +#[test] +fn an_empty_document_stays_empty() { + let doc = blank(2); + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let pages = page_object_numbers(&reopened); + assert_eq!(pages.len(), 2, "{path:?}"); + for (page, &number) in pages.iter().enumerate() { + assert!(annot_entries(&reopened, page).is_empty(), "{path:?}: no entries on page {}", page + 1); + let p = reopened.get(ObjRef::new(number, 0)); + assert!(p.as_dict().is_some_and(|d| !d.contains(b"Annots")), "{path:?}: page {} has no /Annots key", page + 1); + } + assert!(summaries(&reopened).is_empty(), "{path:?}"); + assert!(file.starts_with(b"%PDF-"), "{path:?}"); + } +} + +/// An empty `/Annots` array written by someone else and referenced indirectly: adding the first +/// comment must write through that shared object rather than replacing the page's reference with a +/// fresh array, or a viewer holding the old reference would still see no annotations. +#[test] +fn first_comment_into_an_indirect_annotss_array_writes_through_it() { + let mut doc = blank_with_indirect_annots(2, 1); + add_annotation(&mut doc, &ann(1, Shape::Oval { rect: [20.0, 30.0, 60.0, 70.0] }, "o"), &meta("w")).expect("adds"); + let shared = { + let pages = page_object_numbers(&doc); + doc.get(ObjRef::new(pages[1], 0)).as_dict().and_then(|d| d.reference(b"Annots")).expect("the skeleton's shared /Annots object") + }; + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + assert_eq!(kinds(&reopened, 1), vec!["Circle"], "{path:?}"); + if path == Save::Incremental { + // The original object is still the page's /Annots on an incremental save. + let pages = page_object_numbers(&reopened); + let now = reopened.get(ObjRef::new(pages[1], 0)).as_dict().and_then(|d| d.reference(b"Annots")); + assert_eq!(now, Some(shared), "{path:?}: the page still points at the same array object"); + assert_eq!(reopened.get(shared).as_array().map(|a| a.len()), Some(1), "{path:?}"); + } + } +} + +/// Text is the payload a comment exists to carry. Acrobat separates lines with CR, PDF strings may +/// hold parentheses and backslashes, and anything outside printable ASCII goes out as UTF-16BE. All +/// of it must come back identical — checked against the file's bytes, not only through our reader. +#[test] +fn awkward_comment_text_survives_to_the_bytes() { + let cases = [ + "plain", + "(parenthesised) \\backslash\\", + "line one\r\nline two", + "Annà", // non-ASCII → UTF-16BE with a BOM + "emoji: \u{1F642}", // a surrogate pair in UTF-16BE + "tabs\tand\nbreaks", + ]; + for text in cases { + let mut doc = blank(1); + add_annotation(&mut doc, &ann(0, Shape::Note { at: [10.0, 700.0], icon: NoteIcon::Note }, text), &meta("t")).expect("adds"); + for path in [Save::Incremental, Save::FullTable] { + let (file, reopened) = save_and_reopen(&doc, path); + let d = annot_at(&reopened, 0, 0, path); + assert_eq!(str_of(&reopened, &d, b"Contents").as_deref(), Some(text), "{path:?}: {text:?} through our reader"); + let found = bytes::texts_of(&file, "Contents"); + assert!(found.contains(&text.to_string()), "{path:?}: {text:?} is in the file as a PDF string, got {found:?}"); + assert_eq!(props(&reopened, 0, 0).map(|p| p.subtype), Some("Text".into()), "{path:?}"); + } + } +} + +/// Enum names reach the file as the strings the standard defines, which is what other programs +/// read. `/H`'s one-letter codes are checked through the reader instead: a bare `/P` in raw bytes +/// is ambiguous with `/Pages`, `/Parent` and every page object's `/P`. +#[test] +fn enum_names_are_written_as_the_standard_name_strings() { + let mut doc = blank(1); + add_annotation(&mut doc, &ann(0, Shape::Note { at: [10.0, 700.0], icon: NoteIcon::NewParagraph }, "n"), &meta("e1")).expect("adds"); + links::add( + &mut doc, + 0, + [200.0, 700.0, 300.0, 715.0], + &links::LinkAction::Uri("https://example.com".into()), + &links::LinkStyle { highlight: links::Highlight::Inset, visible: true, ..Default::default() }, + ) + .expect("links"); + add_annotation( + &mut doc, + &ann(0, Shape::Line { from: [10.0, 200.0], to: [80.0, 240.0], start: LineEnding::RClosedArrow, end: LineEnding::Slash }, "l"), + &meta("e2"), + ) + .expect("adds line"); + + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + // The page holds the note, its pop-up, then the link and the line. + assert_eq!(name_of(&reopened, &annot_at(&reopened, 0, 0, path), b"Name").as_deref(), Some("NewParagraph"), "{path:?}"); + assert_eq!(name_of(&reopened, &annot_at(&reopened, 0, 2, path), b"H").as_deref(), Some("P"), "{path:?}: Inset highlight is /H /P (§12.5.3)"); + assert_eq!( + name_array(&reopened, &annot_at(&reopened, 0, 3, path), b"LE").as_deref(), + Some(&["RClosedArrow".to_string(), "Slash".to_string()][..]), + "{path:?}: both line endings" + ); + assert_eq!(props(&reopened, 0, 3).and_then(|p| p.endings), Some(vec![LineEnding::RClosedArrow, LineEnding::Slash]), "{path:?}"); + if !matches!(path, Save::FullStreams) { + assert!(bytes::has_name(&file, "NewParagraph"), "{path:?}"); + assert!(bytes::has_name(&file, "RClosedArrow") && bytes::has_name(&file, "Slash"), "{path:?}"); + } + } +} + +/// Which subtypes count as a comment is a reading rule, and it must not shift when the file is +/// rewritten: pop-ups and links stay out of `summaries`, everything else stays in. +#[test] +fn comment_and_non_comment_subtypes_stay_separated_after_saving() { + let mut doc = blank(1); + add_annotation( + &mut doc, + &ann(0, Shape::TextMarkup { kind: Markup::StrikeOut, quads: vec![[10.0, 700.0, 90.0, 700.0, 10.0, 686.0, 90.0, 686.0]] }, "strike"), + &meta("c1"), + ) + .expect("adds"); + add_annotation(&mut doc, &ann(0, Shape::Note { at: [10.0, 600.0], icon: NoteIcon::Comment }, "note"), &meta("c2")).expect("adds"); + links::add(&mut doc, 0, [10.0, 500.0, 90.0, 520.0], &links::LinkAction::Uri("https://example.com".into()), &links::LinkStyle::default()) + .expect("adds link"); + for path in ALL_SAVES { + let (_, reopened) = save_and_reopen(&doc, path); + assert_eq!(kinds(&reopened, 0), vec!["StrikeOut", "Text", "Popup", "Link"], "{path:?}"); + let mut listed: Vec = summaries(&reopened).iter().map(|s| s.subtype.clone()).collect(); + listed.sort(); + assert_eq!(listed, vec!["StrikeOut".to_string(), "Text".to_string()], "{path:?}: pop-ups and links are not comments"); + } +} + +/// A full save with object streams and one without must describe the same annotations: same +/// count, same subtypes, same rectangles. That makes the two writer paths interchangeable for +/// annotation data, which is what "the object graph is the model" promises. +#[test] +fn a_full_rewrite_into_object_streams_describes_the_same_comments_as_a_plain_table() { + let mut doc = blank(2); + add_annotation(&mut doc, &ann(0, Shape::Note { at: [10.0, 700.0], icon: NoteIcon::Paragraph }, "both paths"), &meta("cmp1")).expect("adds"); + add_annotation(&mut doc, &ann(0, Shape::Rectangle { rect: [10.0, 20.0, 90.0, 60.0] }, "box"), &meta("cmp2")).expect("adds"); + add_annotation( + &mut doc, + &ann(1, Shape::TextMarkup { kind: Markup::Underline, quads: vec![[50.0, 600.0, 150.0, 600.0, 50.0, 586.0, 150.0, 586.0]] }, "u"), + &meta("cmp3"), + ) + .expect("adds"); + + let (_, plain) = save_and_reopen(&doc, Save::FullTable); + let (_, packed) = save_and_reopen(&doc, Save::FullStreams); + let shape_of = |d: &Document| -> Vec<(usize, Vec, Vec<[f64; 4]>)> { + (0..page_object_numbers(d).len()) + .map(|p| { + let e = annot_entries(d, p); + ( + e.len(), + kinds(d, p), + e.iter() + .filter_map(|x| dict_of(d, x)) + .filter_map(|x| nums(d, &x, b"Rect")) + .filter_map(|v| <[f64; 4]>::try_from(v).ok()) + .collect(), + ) + }) + .filter(|t: &(usize, Vec, Vec<[f64; 4]>)| t.0 > 0) + .collect() + }; + assert_eq!(shape_of(&plain), shape_of(&packed), "the two full-save paths must agree"); + assert_eq!(shape_of(&plain).len(), 2, "and both must find the two pages that have comments"); + assert_eq!(summaries(&plain).len(), summaries(&packed).len()); + + // The plain-table output is bigger here: object streams compress, which is the point of them. + let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false }; + let packed_bytes = pdfcraft_cos::write_full(&doc, &opts).expect("writes"); + assert!( + packed_bytes.len() < pdfcraft_cos::write_full(&doc, &SaveOptions { object_streams: false, ..opts }).expect("writes").len(), + "the packed file should be smaller" + ); +} + +// ── measured clamps, pinned so a change is visible (§12.5.3 border width) ────────────────── + +/// Negative border width — CURRENT behaviour, measured on this branch, not an endorsement. +/// +/// `add_annotation` screens width for NON-FINITENESS only. The guard at +/// `crates/annot/src/create.rs:416` reads +/// `!finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite()`: the +/// `abs() < 1e7` cap belongs to `finite()` (`create.rs:17-19`) and is applied to `color` alone, so width +/// carries no magnitude limit at all. Measured on this branch: `width = 1e9` and `width = 1e299` +/// are both ACCEPTED and written to `/BS /W` verbatim (a 10-digit number, then a 300-digit one), +/// while `color = [1e9, 0, 0]` is refused with `Invalid("invalid style")`. +/// So `width = -4.0` is ACCEPTED too; the value reaching `/BS /W` comes from `style.width.max(0.0)` +/// (`create.rs:216`) and the `/Rect` growth from `style.width.max(0.0) / 2.0` (`create.rs:47`). The file then holds +/// `0`, and neither document's repair log records it. (`finite()` magnitude-screens `color`; +/// `opacity` and `width` get finiteness checks only, and the interior `fill` is not screened by it.) +/// +/// The edit path behaves identically for width: `set_style` applies the same kind of screen +/// (`modify.rs:513`) and `width = Some(-2.5)` is accepted, storing `0`. There is therefore NO +/// create-vs-edit asymmetry for negative widths — unlike a huge or non-finite fill colour, which +/// creation never screens (`create.rs:416` magnitude-screens `color`, finiteness-checks `opacity` and +/// `width`, and takes no look at `fill`, which is merely clamped component-wise by `rgb()` at +/// `create.rs:13-15`) while the edit path refuses the same +/// value explicitly near `modify.rs:626`. Flagged for maintainers rather than asserted as +/// correct: a refusal, or at minimum a repair-log entry naming the substitution, would be the +/// stricter design. If either clamp changes or goes away, this test fails on purpose so that +/// decision is made in the open. +#[test] +fn negative_border_width_is_accepted_and_stored_as_zero() { + for (label, width) in [("minus-four", -4.0f64), ("minus-half", -0.5)] { + let mut doc = blank(1); + add_annotation(&mut doc, &styled(0, Shape::Oval { rect: [5.0, 5.0, 65.0, 35.0] }, "w", [1.0, 0.0, 0.0], 1.0, width, None), &meta("neg")) + .unwrap_or_else(|e| panic!("{label}: negative width {width} should be accepted today, got {e:?}")); + for path in ALL_SAVES { + let (file, reopened) = save_and_reopen(&doc, path); + let d = annot_at(&reopened, 0, 0, path); + let w_stored = d.get(b"BS").map(|o| reopened.resolve(o)).and_then(|o| o.as_dict().cloned()).and_then(|bs| num(&reopened, &bs, b"W")); + assert_eq!(w_stored, Some(0.0), "{label}: {path:?} stores the clamped zero, not {width}"); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.width), Some(0.0), "{label}: {path:?} reports the clamped zero"); + assert!(!file.windows(4).any(|x| x == b"-4.0" || x == b"-0.5"), "{label}: {path:?} must not write the negative literal it was given"); + assert!(doc.repair_log().is_empty() && reopened.repair_log().is_empty(), "{label}: {path:?} records nothing about the substitution"); + } + } + + let mut doc = blank(1); + add_annotation(&mut doc, &styled(0, Shape::Oval { rect: [5.0, 5.0, 65.0, 35.0] }, "w", [1.0, 0.0, 0.0], 1.0, 2.0, None), &meta("neg2")) + .expect("adds"); + set_style(&mut doc, 0, 0, StyleChange::new(None, None, Some(-2.5), None), &meta("neg2")) + .expect("the edit path screens non-finite and magnitude, not sign"); + let (file, reopened) = save_and_reopen(&doc, Save::FullTable); + assert_eq!(props(&reopened, 0, 0).and_then(|p| p.width), Some(0.0), "an edited negative width is stored as zero too"); + assert!(!file.windows(4).any(|x| x == b"-2.5"), "the negative literal never reaches the file"); + assert!(doc.repair_log().is_empty() && reopened.repair_log().is_empty(), "silently, with nothing recorded"); +} + +/// The `/Rect` half of the same guard (`create.rs:62-82` and `:47`). Measured on this branch: `Rectangle` and +/// `Oval` store the given `/Rect` verbatim, so they cannot detect this guard at all — a first +/// version of this test compared rectangles and survived the mutation, which is exactly how an +/// empty test looks green. `Shape::Line` IS padded by it (`create.rs:87`, `pad = half + arrow`), so the +/// comparison is made there: with `-9pt` and `0pt` borders a line's `/Rect` must grow identically, +/// because `max(0.0)` collapses both before the padding is applied. +#[test] +fn a_negative_and_a_zero_border_pad_a_line_identically() { + let line = |w: f64| { + let mut doc = blank(1); + add_annotation( + &mut doc, + &styled( + 0, + Shape::Line { from: [20.0, 700.0], to: [120.0, 740.0], start: LineEnding::None, end: LineEnding::None }, + "l", + [0.0, 0.0, 0.0], + 1.0, + w, + None, + ), + &meta("ln"), + ) + .expect("adds a line"); + save_and_reopen(&doc, Save::FullTable).0 + }; + let minus = line(-9.0); + let zero = line(0.0); + let rect_minus = bytes::numbers_of(&minus, "Rect"); + let rect_zero = bytes::numbers_of(&zero, "Rect"); + assert!(!rect_minus.is_empty(), "the -9pt file must contain a /Rect array of numbers"); + assert!(!rect_zero.is_empty(), "the 0pt file must contain a /Rect array of numbers"); + assert_eq!(rect_minus, rect_zero, "-9pt and 0pt borders must pad a line's /Rect identically — max(0.0) at create.rs:47 is what guarantees it"); + // `/BS /W` is a SCALAR real, never an array, so `numbers_of` (which only accepts `[...]`) + // compared two empty lists here and passed whatever the file contained. `scalars_of` is the + // right helper, and both sides are guarded non-empty so this can never go green on missing data. + let w_minus = bytes::scalars_of(&minus, "W"); + let w_zero = bytes::scalars_of(&zero, "W"); + assert!(!w_minus.is_empty() && !w_zero.is_empty(), "both files must actually write a /BS /W, got {w_minus:?} vs {w_zero:?}"); + assert_eq!(w_minus, w_zero, "and both store the same /BS /W"); + assert_eq!(w_minus.as_slice(), &[0.0], "the clamp at create.rs:47 stores a negative border width as 0"); +} diff --git a/crates/annot/tests/support/bytes.rs b/crates/annot/tests/support/bytes.rs new file mode 100644 index 0000000000..b06f92f6da --- /dev/null +++ b/crates/annot/tests/support/bytes.rs @@ -0,0 +1,336 @@ +//! Shared helpers compile into every integration-test binary of this crate, and not every +//! binary uses every one of them; `dead_code` would then fail `clippy -D warnings` for reasons +//! that have nothing to do with the test being written. +#![allow(dead_code)] + +//! A deliberately strict reader over the *bytes* a save produced, independent of `pdfcraft-cos`. +//! +//! Reopening saved bytes with `Document::open` and comparing dictionaries proves that our writer +//! and our reader agree. It does not prove what is actually *in the file*: a lenient parser can +//! forgive output that another implementation refuses (an exponent in what should be a fixed +//! decimal number, an unterminated string, a key written twice). These helpers look at the bytes +//! themselves and reject anything outside the narrow grammar ISO 32000-2 §7.3 allows for the +//! object types annotations use, so an assertion here is a claim about the file rather than about +//! a round trip through our own pair of implementations. +//! +//! Scope: dictionary keys whose values are number arrays (`/Rect`, `/QuadPoints`, `/L`, +//! `/Vertices`, `/CL`, `/RD`), number arrays of arrays (`/InkList`), text strings (`/Contents`, +//! `/T`, `/NM`, `/M`) and names (`/Subtype`). That covers the entries these tests care about; it +//! is not a general PDF parser and does not try to be. + +/// Every value token written for `/key` in the raw bytes, in file order. +/// +/// A name-keyed dictionary entry is `/key` preceded and followed by delimiters, so searching for +/// `Rect` does not match inside `/MyRectangle`. The returned spans include the enclosing brackets +/// or string delimiters, which the decoders below strip. +pub fn value_tokens(bytes: &[u8], key: &[u8]) -> Vec> { + let mut out = Vec::new(); + let mut i = 0; + while i + key.len() + 1 < bytes.len() { + if bytes[i] != b'/' || &bytes[i + 1..i + 1 + key.len()] != key { + i += 1; + continue; + } + let after = i + 1 + key.len(); + // The key must end here: a longer name is a different key. + if after < bytes.len() && is_name_byte(bytes[after]) { + i += 1; + continue; + } + let Some((end, token)) = capture(bytes, after) else { + i += 1; + continue; + }; + // A `/Key /Other` hit is ambiguous: it may be a key whose value is a name, or the *name* + // that is some earlier key's value (`/S /URI`). Re-scan from the next byte so a later real + // occurrence of `/Key` is still found; an array, string or number value is unambiguous. + let name_valued = token.starts_with(b"/"); + out.push(token); + i = if name_valued { i + 1 } else { end }; + } + out +} + +fn is_name_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'#' | b'%') +} + +/// Capture the object that starts at `at`, with bracket/paren balance respected. A literal +/// string's brackets do not count; an array containing a string does nest. +fn capture(bytes: &[u8], mut at: usize) -> Option<(usize, Vec)> { + while bytes.get(at).is_some_and(|b| b.is_ascii_whitespace()) { + at += 1; + } + let first = *bytes.get(at)?; + match first { + b'[' => balanced(bytes, at, b'[', b']'), + b'(' => literal_string(bytes, at), + b'<' if bytes.get(at + 1) == Some(&b'<') => balanced(bytes, at, b'<', b'>'), + // A hex string: `<...>`, closed by the first `>` that is not part of a `>>`. + b'<' => { + let close = bytes.get(at + 1..)?.iter().position(|&b| b == b'>')?; + Some((at + close + 2, bytes[at..at + close + 2].to_vec())) + } + b'/' => { + let mut j = at + 1; + while bytes.get(j).is_some_and(|b| !is_delimiter(*b)) { + j += 1; + } + Some((j, bytes[at..j].to_vec())) + } + _ => { + let mut j = at; + while bytes.get(j).is_some_and(|b| !is_delimiter(*b)) { + j += 1; + } + Some((j, bytes[at..j].to_vec())) + } + } +} + +fn is_delimiter(b: u8) -> bool { + b.is_ascii_whitespace() || matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +/// `open` at `at`, closed by the matching `close`, skipping over literal strings so that a +/// delimiter inside `(…)` does not end the span. +fn balanced(bytes: &[u8], at: usize, open: u8, close: u8) -> Option<(usize, Vec)> { + let mut depth = 0usize; + let mut i = at; + while i < bytes.len() { + match bytes[i] { + b'(' => { + let (end, _) = literal_string(bytes, i)?; + i = end; + continue; + } + b if b == open => depth += 1, + b if b == close => { + depth -= 1; + if depth == 0 { + return Some((i + 1, bytes[at..=i].to_vec())); + } + } + _ => {} + } + i += 1; + } + None +} + +fn literal_string(bytes: &[u8], at: usize) -> Option<(usize, Vec)> { + let mut i = at + 1; + while i < bytes.len() { + match bytes[i] { + b'\\' => i += 2, + b')' => return Some((i + 1, bytes[at..=i].to_vec())), + _ => i += 1, + } + } + None +} + +/// The numbers of an array token, written in fixed decimal notation (§7.3.3: no exponent form). +/// `None` when the token is not an array, holds a non-number, or uses `e`. +pub fn numbers(token: &[u8]) -> Option> { + let inner = token.strip_prefix(b"[")?.strip_suffix(b"]")?.to_vec(); + let mut out = Vec::new(); + for word in split_words(&inner) { + if word.first() == Some(&b'[') { + // A nested array (`/InkList`): its numbers count as this one's, flattened. + out.extend(numbers(&word)?); + } else { + out.push(fixed_decimal(&word)?); + } + } + Some(out) +} + +/// A single number written for `/key` (`/CA`, `/F`, a stream's `/Length`), strictly decimal. +pub fn scalars_of(bytes: &[u8], key: &str) -> Vec { + value_tokens(bytes, key.as_bytes()).iter().filter_map(|t| fixed_decimal(t)).collect() +} + +/// All numbers of an ARRAY token written for `/key`, with the strict fixed-decimal rule. +/// +/// ONLY valid for keys whose value is an array (`/Rect`, `/QuadPoints`, `/L`, `/IC`, +/// `/PCPictureSize`). For a SCALAR key (`/W`, `/CA`, `/F`) every token fails `numbers` and the +/// result is an empty vector — so comparing two such calls against each other is vacuous: it +/// passes whether or not the file holds anything. Use [`scalars_of`] for scalars, and always +/// assert non-emptiness when a value is expected. A scalar misuse was found and fixed in +/// `round_trip.rs` (a `/BS /W` comparison that silently compared `[] == []`). +pub fn numbers_of(bytes: &[u8], key: &str) -> Vec> { + value_tokens(bytes, key.as_bytes()).iter().filter_map(|t| numbers(t)).collect() +} + +/// A number written as `[+-]?digits[.]?` or `[+-]?digits[.]digits`, with no exponent and no +/// stray characters. `str::parse::` alone would accept `1e7`, which PDF does not use. +fn fixed_decimal(word: &[u8]) -> Option { + if word.is_empty() || word.iter().any(|b| *b == b'e' || *b == b'E') { + return None; + } + let body = match word[0] { + b'+' | b'-' => &word[1..], + _ => word, + }; + if body.is_empty() { + return None; + } + let mut digits = 0; + let mut dots = 0; + for &b in body { + match b { + b'0'..=b'9' => digits += 1, + b'.' => dots += 1, + _ => return None, + } + } + if digits == 0 || dots > 1 { + return None; + } + std::str::from_utf8(word).ok()?.parse::().ok() +} + +/// The decoded bytes of a string token (literal with escapes, or hex), `None` if malformed. +pub fn raw_string(token: &[u8]) -> Option> { + match (token.first(), token.last()) { + (Some(b'('), Some(b')')) => { + let mut out = Vec::new(); + let body = &token[1..token.len() - 1]; + let mut i = 0; + while i < body.len() { + if body[i] != b'\\' { + out.push(body[i]); + i += 1; + continue; + } + let e = *body.get(i + 1)?; + match e { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'b' => out.push(0x08), + b'f' => out.push(0x0C), + b'(' | b')' | b'\\' => out.push(e), + b'0'..=b'7' => { + let mut v = 0u32; + let mut j = i + 1; + let mut n = 0; + while j < body.len() && n < 3 && (b'0'..=b'7').contains(&body[j]) { + v = v * 8 + u32::from(body[j] - b'0'); + j += 1; + n += 1; + } + out.push(u8::try_from(v).ok()?); + i = j; + continue; + } + b'\n' => {} + _ => return None, + } + i += 2; + } + Some(out) + } + (Some(b'<'), Some(b'>')) => { + let hex: Vec = token[1..token.len() - 1].iter().copied().filter(|b| !b.is_ascii_whitespace()).collect(); + if !hex.len().is_multiple_of(2) { + return None; + } + let mut out = Vec::with_capacity(hex.len() / 2); + for pair in hex.as_chunks::<2>().0 { + let s = std::str::from_utf8(pair).ok()?; + out.push(u8::from_str_radix(s, 16).ok()?); + } + Some(out) + } + _ => None, + } +} + +/// Text as the file holds it: UTF-16BE behind a BOM, PDF 2.0's UTF-8 BOM, or PDFDocEncoding — +/// approximated by Latin-1 above 0x7F. The two differ only at a handful of bytes between 0x18 +/// and 0x9F, none of which these tests assert on; ASCII and the UTF-16 cases are exact. +pub fn text_of_raw(bytes: &[u8]) -> String { + match bytes { + [0xFE, 0xFF, rest @ ..] => String::from_utf16_lossy(&rest.as_chunks::<2>().0.iter().map(|p| u16::from_be_bytes(*p)).collect::>()), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + b => b.iter().map(|&c| char::from(c)).collect(), + } +} + +/// Every text value written for `/key`, decoded from the bytes. +pub fn texts_of(bytes: &[u8], key: &str) -> Vec { + value_tokens(bytes, key.as_bytes()).iter().filter_map(|t| raw_string(t)).map(|b| text_of_raw(&b)).collect() +} + +/// A name token's bytes (`/Foo` with `#hh` escapes decoded), or the bare name of a token. +pub fn name_of_token(token: &[u8]) -> Option> { + if *token.first()? != b'/' { + return None; + } + let body = &token[1..]; + let mut out = Vec::new(); + let mut i = 0; + while i < body.len() { + if body[i] == b'#' { + let s = std::str::from_utf8(body.get(i + 1..i + 3)?).ok()?; + out.push(u8::from_str_radix(s, 16).ok()?); + i += 3; + } else { + out.push(body[i]); + i += 1; + } + } + Some(out) +} + +/// Every name written for `/key`. +pub fn names_of(bytes: &[u8], key: &str) -> Vec { + value_tokens(bytes, key.as_bytes()).iter().filter_map(|t| name_of_token(t)).map(|n| String::from_utf8_lossy(&n).into_owned()).collect() +} + +/// Whether the file holds the name `/name` as its own token, so searching `Rect` cannot match +/// inside `/Rectangle`. It does not know about string objects, so a name-looking sequence inside +/// literal text would also match: use it only for names distinctive enough to be unambiguous. +pub fn has_name(bytes: &[u8], name: &str) -> bool { + let n = name.as_bytes(); + if n.is_empty() { + return false; + } + let mut i = 0; + while i + n.len() < bytes.len() { + if bytes[i] == b'/' && &bytes[i + 1..i + 1 + n.len()] == n { + let after = i + 1 + n.len(); + if after >= bytes.len() || !is_name_byte(bytes[after]) { + return true; + } + } + i += 1; + } + false +} + +/// Tokens split on whitespace, with `[` … `]` groups kept whole. +fn split_words(bytes: &[u8]) -> Vec> { + let mut out = Vec::new(); + let mut i = 0; + while i < bytes.len() { + if bytes[i].is_ascii_whitespace() { + i += 1; + continue; + } + if bytes[i] == b'[' { + let (end, tok) = balanced(bytes, i, b'[', b']').expect("an opened array closes in a token we captured"); + out.push(tok); + i = end; + continue; + } + let start = i; + while bytes.get(i).is_some_and(|b| !b.is_ascii_whitespace() && *b != b'[') { + i += 1; + } + out.push(bytes[start..i].to_vec()); + } + out +} diff --git a/crates/annot/tests/support/fixture.rs b/crates/annot/tests/support/fixture.rs new file mode 100644 index 0000000000..69567b34e9 --- /dev/null +++ b/crates/annot/tests/support/fixture.rs @@ -0,0 +1,207 @@ +//! Shared helpers compile into every integration-test binary of this crate, and not every +//! binary uses every one of them; `dead_code` would then fail `clippy -D warnings` for reasons +//! that have nothing to do with the test being written. +#![allow(dead_code)] + +//! Hand-written PDF skeletons and the save/reopen helpers these tests share. +//! +//! The shape follows `crates/annot/src/tests.rs::fixture`: build the bytes of a small +//! cross-referenced PDF by hand, open it with `pdfcraft_cos::Document::open`, and let +//! `pdfcraft-annot` add comments through its public API. Doing it this way (rather than +//! constructing a `Document` in memory) matters for these tests: the file has a real +//! cross-reference chain, so `write_incremental` takes its genuine incremental path instead of +//! silently falling back to a full rewrite. +//! +//! Every save here goes through one of three writer paths, and the tests replay their assertions +//! over all three: +//! +//! * `Save::Incremental` — the original bytes plus an appended revision and `/Prev`; +//! * `Save::FullTable` — a full rewrite with a classic cross-reference table; +//! * `Save::FullStreams` — a full rewrite that packs objects into compressed object streams and +//! renumbers everything from 1. +//! +//! The third path is the interesting one for annotation *identity*: object numbers change, so a +//! `/P`, `/Popup` or `/IRT` that survives it has really been re-pointed, not copied. + +use std::sync::Arc; + +use pdfcraft_cos::{Dict, Document, Object, SaveOptions, write_full, write_incremental}; + +/// Which writer path a round trip should take. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Save { + Incremental, + FullTable, + FullStreams, +} + +/// Every path, in the order tests report them. +pub const ALL_SAVES: [Save; 3] = [Save::Incremental, Save::FullTable, Save::FullStreams]; + +/// The paths whose output holds plain (uncompressed) objects, so raw-byte assertions can look at +/// them. Object streams are Flate-compressed by `write_full`, so their bytes need decoding +/// first; those cases are checked through the reopened document instead. +pub const UNCOMPRESSED_SAVES: [Save; 2] = [Save::Incremental, Save::FullTable]; + +/// Objects written as indirect objects plus a classic cross-reference table and trailer. The +/// catalog is object 1, so `objs` starts with it. +pub fn pdf(objs: &[&[u8]]) -> Vec { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::with_capacity(objs.len()); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +/// A document of `pages` blank pages (612×792, no `/Annots` anywhere). +pub fn blank(pages: usize) -> Document { + let mut kids = String::new(); + for i in 0..pages { + kids.push_str(&format!("{} 0 R ", 3 + i)); + } + let mut objs: Vec> = + vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), format!("<>").into_bytes()]; + for _ in 0..pages { + objs.push(b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec()); + } + open(&pdf_refs(&objs)) +} + +/// Like [`blank`], but page `page` starts with an indirect (and initially empty) `/Annots` +/// array, so writes to it go through `set_annots`' shared-array branch. +pub fn blank_with_indirect_annots(pages: usize, page: usize) -> Document { + let mut objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + format!("<< /Type /Pages /Kids [{}] /Count {pages} >>", (0..pages).map(|i| format!("{} 0 R", 3 + i)).collect::>().join(" ")) + .into_bytes(), + ]; + for i in 0..pages { + objs.push(if i == page { + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots {} 0 R >>", 3 + pages).into_bytes() + } else { + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec() + }); + } + objs.push(b"[]".to_vec()); + open(&pdf_refs(&objs)) +} + +/// [`pdf`] over already-owned object bodies. +fn pdf_refs(objs: &[Vec]) -> Vec { + let borrowed: Vec<&[u8]> = objs.iter().map(Vec::as_slice).collect(); + pdf(&borrowed) +} + +fn open(bytes: &[u8]) -> Document { + Document::open(Arc::new(bytes.to_vec())).expect("the skeleton parses") +} + +/// Save one document, then reopen the bytes with our reader. A second, independent parser must +/// accept the same bytes first — that is what makes "it reloads" mean more than "our own writer +/// and reader agree with each other". +pub fn save_and_reopen(doc: &Document, path: Save) -> (Vec, Document) { + let bytes = save(doc, path); + hayro_syntax::Pdf::new(bytes.clone()).unwrap_or_else(|e| panic!("{path:?} output rejected by hayro-syntax: {e:?}")); + (bytes.clone(), Document::open(Arc::new(bytes)).unwrap_or_else(|e| panic!("{path:?} output rejected by our reader: {e:?}"))) +} + +/// Save with the path's options. `/Info /ModDate` is left unset so a full save adds nothing that +/// would make byte comparisons depend on the clock. +pub fn save(doc: &Document, path: Save) -> Vec { + let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: path == Save::FullStreams, drop_unlinked: false }; + match path { + Save::Incremental => write_incremental(doc, &opts), + Save::FullTable | Save::FullStreams => write_full(doc, &opts), + } + .expect("saves") +} + +/// The leaf pages, in `/Kids` order. Local so these tests do not depend on `annot::page_refs` +/// about a page tree they are only incidentally exercising. +pub fn page_object_numbers(doc: &Document) -> Vec { + let root = doc.root().expect("a catalog"); + let pages = doc.get(root).as_dict().and_then(|d| d.reference(b"Pages")).expect("/Pages"); + let mut out = Vec::new(); + let mut seen = std::collections::HashSet::new(); + collect_pages(doc, pages, &mut seen, &mut out); + out +} + +fn collect_pages(doc: &Document, node: pdfcraft_cos::ObjRef, seen: &mut std::collections::HashSet, out: &mut Vec) { + // `seen` bounds the walk, so a cyclic page tree visits each node once and cannot recurse forever. + if !seen.insert(node) || seen.len() > 10_000 { + return; + } + let obj = doc.get(node); + let Some(d) = obj.as_dict() else { return }; + if d.name(b"Type") == Some(b"Page") { + out.push(node.num); + return; + } + let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) else { return }; + for k in kids { + // The array element itself is the reference; resolving it would give the page dictionary. + if let Object::Ref(r) = k { + collect_pages(doc, r, seen, out); + } + } +} + +/// The raw entries of page `page`'s `/Annots`, in array order (references or inline dictionaries). +pub fn annot_entries(doc: &Document, page: usize) -> Vec { + let num = *page_object_numbers(doc).get(page).expect("the page exists"); + let d = doc.get(pdfcraft_cos::ObjRef::new(num, 0)); + let Some(a) = d.as_dict().and_then(|d| d.get(b"Annots").map(|a| doc.resolve(a))) else { return Vec::new() }; + a.as_array().cloned().unwrap_or_default() +} + +/// The dictionary an `/Annots` entry names (a stream's dictionary counts as one). +pub fn dict_of(doc: &Document, entry: &Object) -> Option { + doc.resolve(entry).as_dict().cloned() +} + +/// A dictionary's number array with every element resolved, as PDF numbers. An entry that is not +/// a number (a name, a string, a dictionary) yields `None` here rather than 0.0, so tests can +/// tell "absent or wrong type" apart from "present and zero". +pub fn nums(doc: &Document, d: &Dict, key: &[u8]) -> Option> { + let a = doc.resolve(d.get(key)?).as_array()?.clone(); + a.iter().map(|x| doc.resolve(x).as_f64()).collect() +} + +/// A single number entry (`/CA`, `/BS /W`), resolving an indirect value. +pub fn num(doc: &Document, d: &Dict, key: &[u8]) -> Option { + doc.resolve(d.get(key)?).as_f64() +} + +/// A dictionary's text entry, decoded with our reader (`None` when absent or not a string). +pub fn str_of(doc: &Document, d: &Dict, key: &[u8]) -> Option { + doc.resolve(d.get(key)?).as_string().map(|s| s.to_text()) +} + +/// A dictionary's name entry as a `&str` where it is ASCII, for readable assertion messages. +pub fn name_of(doc: &Document, d: &Dict, key: &[u8]) -> Option { + let o = doc.resolve(d.get(key)?); + Some(String::from_utf8_lossy(o.as_name()?).into_owned()) +} + +/// Annotation flag bit masks, ISO 32000-2 §12.5.3 Table 165 (the spec numbers bits from 1). +/// `pdfcraft-annot` keeps these private, so they are restated here from the standard: this is +/// deliberately *not* read back from the crate, otherwise a wrong bit would be tested against +/// itself. +pub const FLAG_INVALID: i64 = 1 << 0; // bit 1 +pub const FLAG_HIDDEN: i64 = 1 << 1; // bit 2 +pub const FLAG_PRINT: i64 = 1 << 2; // bit 3 +pub const FLAG_NO_ZOOM: i64 = 1 << 3; // bit 4 +pub const FLAG_NO_ROTATE: i64 = 1 << 4; // bit 5 +pub const FLAG_NO_VIEW: i64 = 1 << 5; // bit 6 +pub const FLAG_READONLY: i64 = 1 << 7; // bit 8 (`/ReadOnly`, PdfCraft's Locked) From cc0edc29d1bc36a50916e239fac67f4cfba37fef Mon Sep 17 00:00:00 2001 From: Perchenko Anton <101743951+PerchAnton@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:30:26 +0200 Subject: [PATCH 12/27] fix(edit): preserve source fonts in mixed-script paragraphs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Follow-up after #6806 The main mixed-script font change landed in #6806. This PR covers the remaining case where the source font lacks only a variation selector (U+FE00–U+FE0F). A visible letter now selects the fallback face. The regression compares implicit and explicit fallback in two source fonts, including character spacing, alignment, and save/reopen. Verified locally on macOS arm64 with the CI-pinned craft-fonts input: `cargo test --locked -p pdfcraft-edit` and `cargo test --locked -p pdfcraft-automation --test it mixed_script` passed, as did formatting, scoped Clippy, the layer and asset checks, and the UI WebAssembly build. **Latest compatibility update (2026-10-27):** [d10080eb](https://github.com/PerchAnton/pdfcraft/commit/d10080eb060d112d75bbcfd0a74e4e0bab38af61) includes main `1dd2737b` through a normal merge. Source/fallback helpers follow the extracted text modules. The original per-rewrite advance cache, source spaces and batched missing-glyph fallback are preserved. The cache regressions were run with the pinned optional OFL font input. Local macOS arm64 / Rust 1.99.1: focused regression tests, formatting, scoped all-target Clippy with `-D warnings`, layering and scoped WebAssembly checks pass. Assets and parity checks also pass. Hosted CI is tracked separately on this head. Temporary build outputs and fixtures are cleaned after validation. **Latest integration checks (2026-10-25):** head `54423364bba795cff0b56e7c8f168f355062e3bb` includes main `418ac6a2af49b7ac2fed44ca2cae8d5d1d2cec0d` through a normal merge. On macOS arm64 with Rust 1.99.1, 980 scoped tests pass (0 failed, 5 ignored). Formatting, scoped all-target Clippy with `-D warnings`, layers, assets, parity, and the scoped wasm check pass. Test executables and fixtures were removed after each target. Full-workspace and other-platform checks belong to CI on this head. Six permitted OFL craft-fonts faces at release pin `3d9ab3a1` were SHA-256 verified for the font-dependent regressions. ## What this changes Fixes #2750. Adding `шалом` to an upright, single-style Helvetica paragraph used to redraw the Latin text in the fallback face. Keep source fonts now preserves characters with actual source glyphs and batches only missing glyphs in Type 3 fallback fonts. Unencodable boundary spaces remain real, extractable fallback glyphs; source spaces with glyphs keep their face. Original font dictionaries stay intact. Mixed-run classification and width measurement share a per-character cache within one paragraph rewrite. It stores both source advances and missing-glyph results for that rewrite's metrics, size and character spacing. Wrapping, alignment, justification and underline measurements reuse these widths; the normalized `Tw = 0` state, scaling and summation order stay consistent with drawing. The cache never survives into another rewrite. ## How you verified it **Current integration verification (2026-10-19):** main `43550c44` is included through a normal merge, preserving published history. Current head [5ea12797](https://github.com/PerchAnton/pdfcraft/commit/5ea127978fce56e64b93e70e7172cda5a193c41c). Both roadmaps retain every current-main record and estimate, with only this PR's own status, progress and single milestone-row additions. Automatically merged hunks in the touched modules were reviewed. **732 scoped tests passed, 0 failed, 4 ignored** (edit, engine and automation). Formatting, strict scoped all-target Clippy, scoped WebAssembly and layers/assets/parity pass; whitespace and both roadmap MD028 scans pass. Checks ran on macOS with Rust 1.95, the existing low-disk profile, two Cargo jobs, locked offline dependencies and command timeouts. Optional fonts use the verified release pin `3d9ab3a1`; no new assets or persistent build settings. These are the checks of the refreshed branch. Broader/native UI observations below are historical; full-workspace and other operating-system checks belong to current-head hosted CI and are tracked separately. The deterministic work-budget regression was actually RED before caching: 32 source-character measurements for eight distinct characters. It now passes eight cases across two fonts, short/repeated drafts, narrow/maximum-width frames, justification and underlines. A separate saved-document test checks cache isolation across fonts, sizes, spacing and scale against the saved font metrics, wrapped baselines and underline endpoints. Existing extraction, font preservation, fallback batching and refusal regressions pass. ### Reproducible performance probe `cargo test -p pdfcraft-edit --lib mixed_script_paragraph_rewrite_timing_probe --profile low-disk --locked --offline -j 2 -- --ignored --nocapture` macOS arm64, Rust 1.95.0, the same existing optimized development profile and release-pinned craft-fonts `3d9ab3a132ed0eff457e424226a435a901da30d3`. Medians of three full `rewrite_block` calls, excluding fixture open, Cargo and extraction. Input repeats `The quick brown fox шалом ` with centre alignment, underline, `Tc = 1.25` and `Tz = 80`. | UTF-8 bytes | Frame width (pt) | Before (ms) | Cached (ms) | Speedup | |---|---|---|---|---| | 992 | 480 | 3.845 | 0.730 | 5.27x | | 15872 | 480 | 26.913 | 5.333 | 5.05x | | 63488 | 480 | 103.914 | 19.830 | 5.24x | | 15872 | 14400 | 418.305 | 28.449 | 14.7x | Baseline production code is head `7de05471`. These are synthetic measurements, not release-build or 4 MB draft results. Normal tests enforce a deterministic measurement budget rather than a wall-clock threshold. Greedy wrapping still scans candidates, and final run encoding remains necessary. ## Never-crash, provenance and security - [x] No new production panic paths, input-derived slicing or unsafe code. UTF-8 encoding uses a fixed four-byte buffer; cache keys are distinct input characters. - [x] Contributor-original synthetic fixtures only; no Adobe assets, font binaries or copied copyleft implementation. - [x] Existing atomic refusal, root confinement and opt-in MCP/control behaviour are retained; no new network or permission surface. ## Parity and reach Existing `text_edit`, `text_edit_layout`, CLI and MCP reach this path. Both roadmaps retain one product note with unchanged estimates; text-editing parity remains partial. ## Anything a reviewer should look at first This applies to upright single-style paragraphs in Keep source fonts mode. Explicit family/weight changes and turned/RTL/visual-order text retain their selection paths. The separate styled-path one-font-per-character issue (#2592), wider glyph coverage (#2593), unused-resource cleanup (#2487) and a different wrapping algorithm remain outside this PR. --- crates/edit/src/tests.rs | 27 +++++++++++++++++++++++++++ crates/edit/src/text/fallback.rs | 1 + crates/edit/src/text/rewrite.rs | 9 ++++++++- parity/acrobat-features.toml | 4 ++-- 4 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 974f298fb2..dd6ba09c11 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -12669,6 +12669,33 @@ fn q_inside_a_text_object_restores_the_text_matrices() { } } +/// A supported letter plus selectors must not become an empty fallback request. The implicit +/// fallback and the explicitly chosen family agree on layout, including character spacing, +/// for selectors in the supported U+FE00..U+FE0F range. +#[test] +fn variation_source_letters_and_selectors_survive_paragraph_save() { + for font in ["F1", "F2"] { + for replacement in ["a\u{FE0F}", "ab\u{FE00}", "a\u{FE0F}b\u{FE00}"] { + let mut doc = text_page(&format!("BT /{font} 12 Tf 72 700 Td (ab) Tj ET")); + let fonts = page_fonts(&doc, &pdfcraft_model::pages(&doc)[0]); + let original_font = doc.resolve(fonts.get(font.as_bytes()).unwrap()).as_dict().unwrap().clone(); + let mut explicit = doc.clone(); + let style = text::BlockStyle { width: Some(100.0), align: Some(added::Align::Center), char_spacing: Some(2.0), ..Default::default() }; + text::rewrite_block(&mut doc, 0, 0, Some(replacement), &style).unwrap(); + let explicit_style = text::BlockStyle { family: Some((added::Family::Helvetica, false, false)), ..style }; + text::rewrite_block(&mut explicit, 0, 0, Some(replacement), &explicit_style).unwrap(); + let doc = reopen(&doc); + let lines = text::text_lines(&doc, 0).unwrap(); + let expected = text::text_lines(&reopen(&explicit), 0).unwrap(); + assert_eq!(lines.len(), 1, "{font}: {replacement:?}"); + assert_eq!(lines[0].text, replacement, "{font}"); + assert!(close(lines[0].rect, expected[0].rect), "{font}: {:?} != {:?}", lines[0].rect, expected[0].rect); + let fonts = page_fonts(&doc, &pdfcraft_model::pages(&doc)[0]); + assert_eq!(doc.resolve(fonts.get(font.as_bytes()).unwrap()).as_dict(), Some(&original_font), "the source font is unchanged"); + } + } +} + #[test] fn variation_public_line_and_block_edits_preserve_selectors_after_reopen() { let replacement = "1\u{FE0F}"; diff --git a/crates/edit/src/text/fallback.rs b/crates/edit/src/text/fallback.rs index 1a3d918102..41ca730595 100644 --- a/crates/edit/src/text/fallback.rs +++ b/crates/edit/src/text/fallback.rs @@ -741,6 +741,7 @@ thread_local! { } #[cfg(test)] +/// Returns the number of source-character measurements on this thread and resets the counter. pub(crate) fn take_source_character_measurements() -> usize { SOURCE_CHARACTER_MEASUREMENTS.with(|count| count.replace(0)) } diff --git a/crates/edit/src/text/rewrite.rs b/crates/edit/src/text/rewrite.rs index baea82d429..b9c7f21c8a 100644 --- a/crates/edit/src/text/rewrite.rs +++ b/crates/edit/src/text/rewrite.rs @@ -531,6 +531,7 @@ struct Advance<'a> { } impl Advance<'_> { + /// Measures the advance in user space, combining source and fallback glyph widths for mixed runs. fn of(&self, s: &str) -> f64 { // A variation selector draws nothing and adds no spacing: it takes no room. let extra = s.chars().filter(|ch| !is_variation_selector(*ch)).count() as f64 * self.char_spacing; @@ -871,6 +872,7 @@ impl LineWriter<'_> { Ok((dx, dx + w, cursor.y - self.size * 0.12)) } + /// Emits text-showing operators for each source or fallback run and tracks the selected font across pieces. fn show_piece(&self, piece: &str, line: &str, tw: f64, cursor: &mut LineCursor, ops: &mut Vec) -> Result<(), EditError> { let n = pdfcraft_content::num; for (source, run) in source_fallback_runs(piece, self.partial_chars) { @@ -1109,7 +1111,7 @@ pub(crate) fn rewrite_block_from( // Preserve every drawable source glyph; cache missing-glyph lookups as well. let visual_indic = source.metrics.as_ref().is_some_and(|m| m.visual_order) || first.visual_order; let hebrew = flat.chars().any(crate::bidi::is_hebrew); - let source_advances: HashMap> = source + let mut source_advances: HashMap> = source .metrics .as_ref() .filter(|_| !reuse && upright && !hebrew && !visual_indic && style.family.is_none() && style.bold.is_none() && needs_type3(&flat)) @@ -1121,6 +1123,11 @@ pub(crate) fn rewrite_block_from( advances }) .unwrap_or_default(); + // A fallback face needs a visible glyph. If only selectors are missing, use the whole + // paragraph as before; clear the advances too so measuring and drawing use the same font. + if !source_advances.is_empty() && flat.chars().filter(|ch| source_advances.get(ch).copied().flatten().is_none()).all(is_variation_selector) { + source_advances.clear(); + } let source_chars: HashSet = source_advances.iter().filter_map(|(&ch, width)| width.map(|_| ch)).collect(); let partial_reuse = !source_chars.is_empty(); // The chosen style also determines the real Japanese fallback outlines and advances. diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 2eadbefd62..0063367715 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -1907,8 +1907,8 @@ milestone = "M7" status = "partial" commands = ["edit.edit_text"] tools = ["text_prepare", "text_lines", "text_paragraphs", "text_edit", "text_edit_layout", "text_font_files", "text_font_import", "text_fonts"] -evidence = ["crates/edit/src/tests.rs::editing_legacy_thai_keeps_the_embedded_face_weight_size_spacing_and_paint_after_reopen", "crates/edit/src/tests.rs::editing_legacy_thai_shapes_a_run_across_subsets_of_the_same_face", "crates/edit/src/tests.rs::grouped_text_nested_past_the_level_limit_is_reported", "crates/edit/src/tests.rs::grouped_image_artwork_is_not_prepared", "crates/edit/src/tests.rs::grouped_text_in_an_rgb_group_needs_a_page_that_blends_in_rgb", "crates/fonts/src/pdf/thai.rs::recovered_thai_map_checks_every_kept_glyph_against_the_font_program", "crates/automation/tests/it/automation.rs::text_prepare_refuses_pages_without_grouped_text", "crates/fonts/src/pdf/tests.rs::composite_subset_without_cmap_uses_pdf_glyph_ids_in_editor_and_shaper_without_replacing_the_program", "crates/automation/tests/it/automation.rs::grouped_existing_thai_body_edits_saves_reopens_and_undo_restores_original_glyphs", "crates/edit/src/tests.rs::grouped_text_preparation_keeps_unsafe_compositing_paths_and_malformed_forms_intact", "crates/automation/tests/it/automation.rs::explicit_bundled_thai_font_choice_layout_edit_undo_and_reopen", "crates/edit/src/tests.rs::existing_thai_subset_uses_shaped_matching_face_without_embedding_variable_font", "crates/edit/src/tests.rs::paragraphs_are_found_and_rewrapped", "crates/edit/src/tests.rs::text_lines_are_found_and_replaced_in_place", "crates/ui-egui/tests/it/editing.rs::editing_existing_text_in_place", "crates/automation/tests/it/automation.rs::editing_existing_text_through_tools", "crates/edit/src/tests.rs::a_line_whose_operator_starts_the_next_stream_can_be_edited", "crates/automation/tests/it/automation.rs::a_line_split_across_content_streams_is_listed_and_edited", "crates/ui-egui/tests/it/editing.rs::selected_text_formatting_keeps_the_rest_of_the_paragraph_and_reopens", "crates/edit/src/tests.rs::marked_paragraph_boundaries_and_cross_stream_transforms_survive_rewrite", "crates/automation/tests/it/automation.rs::explicit_font_and_disjoint_ranges_save_reopen_through_tools", "crates/edit/src/tests.rs::disjoint_style_ranges_preserve_unselected_runs_and_validate_utf8_atomically", "crates/engine/tests/it/document_fonts.rs::opentype_cff_document_font_preserves_program_codes_and_rendering_after_reopen", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::mixed_styles_and_matrix_sizes_form_visual_regions_without_merging_columns", "crates/edit/src/tests.rs::rich_region_edits_preserve_styles_positions_and_delete_all_runs_after_reopen", "crates/ui-egui/tests/it/editing.rs::one_editor_contains_mixed_styles_and_visual_rows", "crates/ui-egui/tests/it/editing.rs::inline_editor_preserves_source_font_and_previews_live_bounds", "crates/fonts/src/pdf/tests.rs::mac_subset_cmap_uses_pdf_unicode_without_changing_source_program", "crates/automation/tests/it/automation.rs::mixed_visual_region_edit_preview_save_reopen_and_undo_through_tools", "crates/ui-egui/tests/it/ui.rs::the_edit_tab_turns_on_edit_text_and_images", "crates/ui-egui/tests/it/editing.rs::the_caret_on_a_small_row_is_as_tall_as_that_row", "crates/edit/src/tests.rs::uzbek_and_kazakh_cyrillic_use_the_bundled_latin_face", "crates/automation/tests/it/automation.rs::editing_uzbek_and_kazakh_cyrillic_through_tools", "crates/edit/src/tests.rs::styled_paragraph_batches_cyrillic_without_changing_source_fonts", "crates/edit/src/tests.rs::styled_paragraph_over_240_fallback_glyphs_splits_and_refuses_atomically", "crates/edit/src/tests.rs::styled_fallback_batches_keep_face_choices_and_range_styles", "crates/edit/src/tests.rs::styled_fallback_shards_keep_text_advances_and_alignment", "crates/edit/src/tests.rs::styled_fallback_budget_is_enforced_before_objects_are_written", "crates/edit/src/tests.rs::styled_fallback_same_base_font_and_character_keep_both_weights", "crates/automation/tests/it/automation.rs::styled_cyrillic_fallback_is_batched_through_tools_and_reopen", "crates/ui-egui/tests/it/editing.rs::escape_in_an_open_paragraph_selects_its_box_for_delete", "crates/edit/src/tests.rs::ungrouping_form_artwork_makes_its_text_editable", "crates/automation/tests/it/automation.rs::ungrouping_a_table_drawn_in_a_form_makes_its_text_editable", "crates/ui-egui/tests/it/editing.rs::ungroup_in_the_artwork_menu_makes_a_forms_text_editable", "crates/edit/src/tests.rs::ungroup_carries_the_placement_into_the_patterns_it_selects", "crates/automation/tests/it/automation.rs::ungrouping_keeps_patterns_where_the_forms_placement_put_them", "crates/edit/src/tests.rs::ungroup_refuses_a_form_with_its_own_default_colour_space", "crates/edit/src/tests.rs::ungroup_renames_the_name_operand_the_renderer_reads", "crates/ui-egui/tests/it/editing.rs::one_click_on_grouped_text_opens_it_for_editing", "crates/edit/src/tests.rs::grouped_text_at_says_which_artwork_preparation_would_open", "crates/edit/src/tests.rs::legacy_thai_map_repair_needs_no_grouped_text", "crates/edit/src/tests.rs::ungroup_refuses_a_form_drawn_inside_text_or_a_path", "crates/edit/src/tests.rs::ungroup_reads_what_a_group_draws_within_one_allowance", "crates/edit/src/tests.rs::unicode_row_breaks_break_the_row_instead_of_needing_a_glyph", "crates/ui-egui/tests/it/ui.rs::edit_a_pdf_from_all_tools_turns_on_editing", "crates/ui-egui/tests/it/editing.rs::another_tool_from_edit_a_pdf_applies_the_open_paragraph", "crates/edit/src/tests.rs::mixed_script_subset_spaces_remain_extractable_after_saving", "crates/edit/src/tests.rs::mixed_script_paragraph_keeps_the_source_font_without_an_explicit_line_break", "crates/edit/src/tests.rs::mixed_script_runs_use_source_and_fallback_advances_for_alignment", "crates/edit/src/tests.rs::mixed_script_paragraph_batches_only_missing_glyphs_and_refuses_atomically", "crates/automation/tests/it/automation.rs::mixed_script_paragraph_keeps_source_fonts_through_tools_and_reopen", "crates/edit/src/tests.rs::variation_public_selector_does_not_shift_centered_text_with_character_spacing", "crates/edit/src/tests.rs::mixed_source_subset_without_space_keeps_fallback_runs_after_reopen", "crates/edit/src/tests.rs::only_the_words_a_subset_cannot_show_are_substituted"] -notes = "Upright single-style Keep source fonts edits without a line break preserve encodable source runs and batch only missing glyphs in Type 3 fallbacks (#2750); wrapping/alignment use both faces and keep source resources. Unencodable spaces at source/fallback boundaries are extractable glyphs, not numeric-only positioning; encodable spaces stay in the source face. In Edit text, one click on text in a supported grouped Form prepares its page (one undoable step) and opens the paragraph clicked, so its existing source glyphs are edited directly; nothing is prepared while pages are only shown, a drag still moves the selected group, and a click on grouped artwork that preparation wouldn't open (a logo, a refused group) selects it as before. text_prepare does the same headlessly, with the same code as Ungroup. Unsafe groups remain intact and are reported by text_prepare and in the repair log when the page is prepared, as is text grouped more than eight levels deep; image-only forms are left grouped. Narrow legacy THSarabunPSK character-map recovery, checked glyph by glyph against the subset's own advances, is recorded, also for text that was never grouped (text_prepare). Legacy Thai source editing reuses original font programs, positional glyphs and same-face subsets (a Thai run split across subsets is shaped cluster by cluster; what no subset can show in its codes is shaped whole by a complete program of the face, such as one from Load font), preserving Regular/Bold, point size, spacing and paint. A different Thai family requires explicit selection; the Noto replacement is Regular only; mixed contextual style runs remain limited. The Edit tab turns Edit text & images on at once, as in Acrobat, and so does All tools ▸ Edit a PDF (also from Home, the command palette and the control channel); leaving the tab, or Edit a PDF for another tool from All tools, puts the tool down and applies an edit in progress; Esc in an open paragraph leaves its text and selects its box, so Delete removes it (the unapplied draft is discarded); click a paragraph box and retype it in place (font reused or Helvetica substituted, colour and spacing kept, rewrapped; replacing one line keeps the source font for every word it can show and sets only the other words in Helvetica (#2378)); a page's /Contents pieces are parsed joined, so a line whose operands and operator sit in different pieces is listed and edited (lines and paragraphs still don't join across pieces; Edit image still parses each piece alone); drag a box to move it or its right-edge handle to rewrap it (edit.text-move-resize); per-character formatting changes are next Since #1116: mixed-style visual regions retain source rows, subset encodings, colour and baseline anchors in one textless-background editor. Explicit paragraph/heading scopes constrain grouping; compatible graphics planes permit cross-stream regions. Full matching document fonts complete absent subset glyphs; installed/file selection, TrueType/OpenType-CFF embedding and disjoint UTF-8 range styles have save/reopen coverage. Single-face OpenType shaping/bidi retains logical text through ToUnicode/ActualText. Replacement text the paragraph's font can't show takes the craft-fonts Japanese faces when they draw all of it (Uzbek қ, Kazakh ә are in none of them), else the bundled Inter face, so those letters write in every build (#2593). Legacy non-SFNT preview, mixed-font/style contextual runs, full structure-tree preservation and author intent in untagged PDFs remain limited; Styled-path outline fallback batches by actual face with 240 glyphs per font and preserves source styles; adjacent equal-font/style characters form runs. At most 15360 distinct fallback glyphs per styled paragraph; missing glyphs are refused before fallback objects are written. The Unicode row breaks (U+2028, U+2029, U+0085, vertical tab, form feed and the information separators) break the row instead of being looked up as glyphs (#6272). Glyph coverage, mixed contextual shaping and stale-font cleanup are unchanged; the single-style source/fallback path above is handled separately; see docs/editing-existing-text.md. Text drawn inside a Form XObject (HTML-to-PDF output, stamped or imposed pages) is grouped artwork until Ungroup (artwork right-click menu; image_edit action ungroup) draws that placement in place with its resources merged; knockout groups and transparency groups that blend inside, are drawn translucent or blend in a colour space other than the page's are refused, as are forms with resources of their own whose /DefaultGray, /DefaultRGB or /DefaultCMYK differs from the page's, either side lacking it included (ISO 32000-2 §8.6.5.6), and forms drawn inside a text object or an unfinished path, each resource name is read from the operand the renderer uses (a surplus operand before it is ignored; an operator whose operands can't be read is refused), and a pattern the form fills with is drawn from a copy whose /Matrix carries the placement (ISO 32000-2 §8.7.2), so ungrouping never changes the pixels." +evidence = ["crates/edit/src/tests.rs::editing_legacy_thai_keeps_the_embedded_face_weight_size_spacing_and_paint_after_reopen", "crates/edit/src/tests.rs::editing_legacy_thai_shapes_a_run_across_subsets_of_the_same_face", "crates/edit/src/tests.rs::grouped_text_nested_past_the_level_limit_is_reported", "crates/edit/src/tests.rs::grouped_image_artwork_is_not_prepared", "crates/edit/src/tests.rs::grouped_text_in_an_rgb_group_needs_a_page_that_blends_in_rgb", "crates/fonts/src/pdf/thai.rs::recovered_thai_map_checks_every_kept_glyph_against_the_font_program", "crates/automation/tests/it/automation.rs::text_prepare_refuses_pages_without_grouped_text", "crates/fonts/src/pdf/tests.rs::composite_subset_without_cmap_uses_pdf_glyph_ids_in_editor_and_shaper_without_replacing_the_program", "crates/automation/tests/it/automation.rs::grouped_existing_thai_body_edits_saves_reopens_and_undo_restores_original_glyphs", "crates/edit/src/tests.rs::grouped_text_preparation_keeps_unsafe_compositing_paths_and_malformed_forms_intact", "crates/automation/tests/it/automation.rs::explicit_bundled_thai_font_choice_layout_edit_undo_and_reopen", "crates/edit/src/tests.rs::existing_thai_subset_uses_shaped_matching_face_without_embedding_variable_font", "crates/edit/src/tests.rs::paragraphs_are_found_and_rewrapped", "crates/edit/src/tests.rs::text_lines_are_found_and_replaced_in_place", "crates/ui-egui/tests/it/editing.rs::editing_existing_text_in_place", "crates/automation/tests/it/automation.rs::editing_existing_text_through_tools", "crates/edit/src/tests.rs::a_line_whose_operator_starts_the_next_stream_can_be_edited", "crates/automation/tests/it/automation.rs::a_line_split_across_content_streams_is_listed_and_edited", "crates/ui-egui/tests/it/editing.rs::selected_text_formatting_keeps_the_rest_of_the_paragraph_and_reopens", "crates/edit/src/tests.rs::marked_paragraph_boundaries_and_cross_stream_transforms_survive_rewrite", "crates/automation/tests/it/automation.rs::explicit_font_and_disjoint_ranges_save_reopen_through_tools", "crates/edit/src/tests.rs::disjoint_style_ranges_preserve_unselected_runs_and_validate_utf8_atomically", "crates/engine/tests/it/document_fonts.rs::opentype_cff_document_font_preserves_program_codes_and_rendering_after_reopen", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::mixed_styles_and_matrix_sizes_form_visual_regions_without_merging_columns", "crates/edit/src/tests.rs::rich_region_edits_preserve_styles_positions_and_delete_all_runs_after_reopen", "crates/ui-egui/tests/it/editing.rs::one_editor_contains_mixed_styles_and_visual_rows", "crates/ui-egui/tests/it/editing.rs::inline_editor_preserves_source_font_and_previews_live_bounds", "crates/fonts/src/pdf/tests.rs::mac_subset_cmap_uses_pdf_unicode_without_changing_source_program", "crates/automation/tests/it/automation.rs::mixed_visual_region_edit_preview_save_reopen_and_undo_through_tools", "crates/ui-egui/tests/it/ui.rs::the_edit_tab_turns_on_edit_text_and_images", "crates/ui-egui/tests/it/editing.rs::the_caret_on_a_small_row_is_as_tall_as_that_row", "crates/edit/src/tests.rs::uzbek_and_kazakh_cyrillic_use_the_bundled_latin_face", "crates/automation/tests/it/automation.rs::editing_uzbek_and_kazakh_cyrillic_through_tools", "crates/edit/src/tests.rs::styled_paragraph_batches_cyrillic_without_changing_source_fonts", "crates/edit/src/tests.rs::styled_paragraph_over_240_fallback_glyphs_splits_and_refuses_atomically", "crates/edit/src/tests.rs::styled_fallback_batches_keep_face_choices_and_range_styles", "crates/edit/src/tests.rs::styled_fallback_shards_keep_text_advances_and_alignment", "crates/edit/src/tests.rs::styled_fallback_budget_is_enforced_before_objects_are_written", "crates/edit/src/tests.rs::styled_fallback_same_base_font_and_character_keep_both_weights", "crates/automation/tests/it/automation.rs::styled_cyrillic_fallback_is_batched_through_tools_and_reopen", "crates/ui-egui/tests/it/editing.rs::escape_in_an_open_paragraph_selects_its_box_for_delete", "crates/edit/src/tests.rs::ungrouping_form_artwork_makes_its_text_editable", "crates/automation/tests/it/automation.rs::ungrouping_a_table_drawn_in_a_form_makes_its_text_editable", "crates/ui-egui/tests/it/editing.rs::ungroup_in_the_artwork_menu_makes_a_forms_text_editable", "crates/edit/src/tests.rs::ungroup_carries_the_placement_into_the_patterns_it_selects", "crates/automation/tests/it/automation.rs::ungrouping_keeps_patterns_where_the_forms_placement_put_them", "crates/edit/src/tests.rs::ungroup_refuses_a_form_with_its_own_default_colour_space", "crates/edit/src/tests.rs::ungroup_renames_the_name_operand_the_renderer_reads", "crates/ui-egui/tests/it/editing.rs::one_click_on_grouped_text_opens_it_for_editing", "crates/edit/src/tests.rs::grouped_text_at_says_which_artwork_preparation_would_open", "crates/edit/src/tests.rs::legacy_thai_map_repair_needs_no_grouped_text", "crates/edit/src/tests.rs::ungroup_refuses_a_form_drawn_inside_text_or_a_path", "crates/edit/src/tests.rs::ungroup_reads_what_a_group_draws_within_one_allowance", "crates/edit/src/tests.rs::unicode_row_breaks_break_the_row_instead_of_needing_a_glyph", "crates/ui-egui/tests/it/ui.rs::edit_a_pdf_from_all_tools_turns_on_editing", "crates/ui-egui/tests/it/editing.rs::another_tool_from_edit_a_pdf_applies_the_open_paragraph", "crates/edit/src/tests.rs::mixed_script_subset_spaces_remain_extractable_after_saving", "crates/edit/src/tests.rs::mixed_script_paragraph_keeps_the_source_font_without_an_explicit_line_break", "crates/edit/src/tests.rs::mixed_script_runs_use_source_and_fallback_advances_for_alignment", "crates/edit/src/tests.rs::mixed_script_paragraph_batches_only_missing_glyphs_and_refuses_atomically", "crates/automation/tests/it/automation.rs::mixed_script_paragraph_keeps_source_fonts_through_tools_and_reopen", "crates/edit/src/tests.rs::variation_public_selector_does_not_shift_centered_text_with_character_spacing", "crates/edit/src/tests.rs::mixed_source_subset_without_space_keeps_fallback_runs_after_reopen", "crates/edit/src/tests.rs::only_the_words_a_subset_cannot_show_are_substituted", "crates/edit/src/tests.rs::variation_source_letters_and_selectors_survive_paragraph_save"] +notes = "Upright single-style Keep source fonts edits without a line break preserve encodable source runs and batch only missing glyphs in Type 3 fallbacks (#2750); wrapping/alignment use both faces and keep source resources. Unencodable spaces at source/fallback boundaries are extractable glyphs, not numeric-only positioning; encodable spaces stay in the source face. When only variation selectors are missing, the whole paragraph uses the fallback so a visible letter can select its face. In Edit text, one click on text in a supported grouped Form prepares its page (one undoable step) and opens the paragraph clicked, so its existing source glyphs are edited directly; nothing is prepared while pages are only shown, a drag still moves the selected group, and a click on grouped artwork that preparation wouldn't open (a logo, a refused group) selects it as before. text_prepare does the same headlessly, with the same code as Ungroup. Unsafe groups remain intact and are reported by text_prepare and in the repair log when the page is prepared, as is text grouped more than eight levels deep; image-only forms are left grouped. Narrow legacy THSarabunPSK character-map recovery, checked glyph by glyph against the subset's own advances, is recorded, also for text that was never grouped (text_prepare). Legacy Thai source editing reuses original font programs, positional glyphs and same-face subsets (a Thai run split across subsets is shaped cluster by cluster; what no subset can show in its codes is shaped whole by a complete program of the face, such as one from Load font), preserving Regular/Bold, point size, spacing and paint. A different Thai family requires explicit selection; the Noto replacement is Regular only; mixed contextual style runs remain limited. The Edit tab turns Edit text & images on at once, as in Acrobat, and so does All tools ▸ Edit a PDF (also from Home, the command palette and the control channel); leaving the tab, or Edit a PDF for another tool from All tools, puts the tool down and applies an edit in progress; Esc in an open paragraph leaves its text and selects its box, so Delete removes it (the unapplied draft is discarded); click a paragraph box and retype it in place (font reused or Helvetica substituted, colour and spacing kept, rewrapped; replacing one line keeps the source font for every word it can show and sets only the other words in Helvetica (#2378)); a page's /Contents pieces are parsed joined, so a line whose operands and operator sit in different pieces is listed and edited (lines and paragraphs still don't join across pieces; Edit image still parses each piece alone); drag a box to move it or its right-edge handle to rewrap it (edit.text-move-resize); per-character formatting changes are next Since #1116: mixed-style visual regions retain source rows, subset encodings, colour and baseline anchors in one textless-background editor. Explicit paragraph/heading scopes constrain grouping; compatible graphics planes permit cross-stream regions. Full matching document fonts complete absent subset glyphs; installed/file selection, TrueType/OpenType-CFF embedding and disjoint UTF-8 range styles have save/reopen coverage. Single-face OpenType shaping/bidi retains logical text through ToUnicode/ActualText. Replacement text the paragraph's font can't show takes the craft-fonts Japanese faces when they draw all of it (Uzbek қ, Kazakh ә are in none of them), else the bundled Inter face, so those letters write in every build (#2593). Legacy non-SFNT preview, mixed-font/style contextual runs, full structure-tree preservation and author intent in untagged PDFs remain limited; Styled-path outline fallback batches by actual face with 240 glyphs per font and preserves source styles; adjacent equal-font/style characters form runs. At most 15360 distinct fallback glyphs per styled paragraph; missing glyphs are refused before fallback objects are written. The Unicode row breaks (U+2028, U+2029, U+0085, vertical tab, form feed and the information separators) break the row instead of being looked up as glyphs (#6272). Glyph coverage, mixed contextual shaping and stale-font cleanup are unchanged; the single-style source/fallback path above is handled separately; see docs/editing-existing-text.md. Text drawn inside a Form XObject (HTML-to-PDF output, stamped or imposed pages) is grouped artwork until Ungroup (artwork right-click menu; image_edit action ungroup) draws that placement in place with its resources merged; knockout groups and transparency groups that blend inside, are drawn translucent or blend in a colour space other than the page's are refused, as are forms with resources of their own whose /DefaultGray, /DefaultRGB or /DefaultCMYK differs from the page's, either side lacking it included (ISO 32000-2 §8.6.5.6), and forms drawn inside a text object or an unfinished path, each resource name is read from the operand the renderer uses (a surplus operand before it is ignored; an operator whose operands can't be read is refused), and a pattern the form fills with is drawn from a copy whose /Matrix carries the placement (ISO 32000-2 §8.7.2), so ungrouping never changes the pixels." [[feature]] id = "edit.text-reflow" From 0c39992c99f76e68e5d0cef4093f134e8e5b7791 Mon Sep 17 00:00:00 2001 From: Perchenko Anton <101743951+PerchAnton@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:31:06 +0200 Subject: [PATCH 13/27] Print: make a long printer list easier to browse and search (#4399) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Update on 2026-11-03 (`db57e7de`).** Merged main `ecdd1e65` and preserved both sets of parity evidence. The picker now uses the public `ComboBox::show_ui` response to track the open menu and clear its search when it closes. All 30 print UI tests passed locally on macOS arm64, including the three printer-picker regressions. Formatting and `cargo xtask parity` passed. [CI](https://github.com/storytold/pdfcraft/actions/runs/41673448570) and [SonarCloud](https://github.com/storytold/pdfcraft/actions/runs/41673448592) track this commit. ## What this changes Fixes #4399. The printer picker opens a wider, taller menu with a name filter. Long device names wrap, while Search and Save as PDF stay visible as the device list scrolls. Search ignores case, trims surrounding spaces and keeps the current destination until a row is chosen. Reopening clears the filter and brings the selected device into view. The large-fleet test now checks that the selected row is between Search and Save as PDF after reopening, without manually scrolling at that point. This catches a broken automatic reveal instead of hiding it with a test-side scroll. ## How you verified it - At `d14aed41`, the [hosted gate](https://github.com/storytold/pdfcraft/actions/runs/40305529036/job/121513571419) passes: 5,194 tests, 21 skipped. All three `printer_picker` tests explicitly pass, including the new reopening visibility assertion. Formatting, strict Clippy, layers, assets, parity and wasm checks pass in that gate. - CodeRabbit's refreshed documentation check passes at 100%; both remaining test helpers are documented. - The three original UI regressions failed against the original production module. They cover a 120-device fleet, Unicode/case matching, selection, reopening, no matches, long names and a 1024×768 window. A separate earlier before/after check caught an initially clipped Save as PDF row by physically clicking it. - Earlier macOS validation inspected headless captures and exercised the real Print dialog through its control channel. Those are earlier-run results, not a new native macOS run on this head. - The current local Windows Cargo 1.95 run cannot resolve the pinned craft-menu manifest and does not reach the UI tests. Runtime validation of this latest test update is the hosted gate above; no local test pass is claimed. ## Safety, provenance and reach - [x] No new panicking shortcuts, unsafe code or input-derived indexing. - [x] No new assets, fonts or dependencies. - [x] Existing printer discovery, properties and print submission paths are used. - [x] Automation remains available through `printers`, `printer_options` and `doc_print`; UI controls remain opt-in. - [x] Printer-selection parity evidence and M10 progress notes are updated. ## Limits of verification Physical printing was not tested. Keyboard injection into the earlier background native macOS window did not enter text; filter typing and selection were verified through egui_kittest. AI assistance: implementation, tests and validation used Codex. --- ROADMAP.md | 1 + crates/ui-egui/src/workflows/print_ui/body.rs | 112 +++++++++++++---- crates/ui-egui/tests/it/print.rs | 118 ++++++++++++++++++ docs/roadmap.md | 3 +- parity/acrobat-features.toml | 4 +- 5 files changed, 209 insertions(+), 29 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 56bbcd4c74..adb9fcbe10 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -353,6 +353,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-26 (M3, view.text-select):** Text selection runs across pages: dragging onto another page (also a quick flick off the page, and the edge and wheel scrolling of #721/#1670) or ⇧-clicking there selects the rest of the first page, the pages between and the last page up to the pointer. Copy has each page's part on a line of its own, reading pages not yet read off the UI thread; highlight, underline, strikethrough and Redact put one mark on each page in one undo step (a tool that finishes first marks once the pages are read; Redact refuses a selection over a page whose text could not be read); Add comment and Replace text stay one-page. A drag from one page's text that is already over the next when it starts no longer begins a Redact or area-highlight box there. Estimates unchanged. - **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged. - **2026-10-25 (M7, #2750):** Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. Estimates unchanged. +- **2026-10-25 (M10, #4399):** The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. Estimates unchanged. - **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes. - **2026-10-25 (M10):** Vector printing keeps field and comment artwork whose rectangle coordinates are indirect, requiring exactly four finite resolved values. - **2026-10-26 (M10):** Vector printing follows up to 64 indirect references for annotation rectangles, coordinates and appearance-state names, rejecting cycles and longer chains without changing source objects. diff --git a/crates/ui-egui/src/workflows/print_ui/body.rs b/crates/ui-egui/src/workflows/print_ui/body.rs index d9a0f7280f..da4fa0ebc7 100644 --- a/crates/ui-egui/src/workflows/print_ui/body.rs +++ b/crates/ui-egui/src/workflows/print_ui/body.rs @@ -103,6 +103,91 @@ fn combo(ui: &mut egui::Ui, id: &str, name: &str, value: &m .accessible_name(name); } +/// A wide, searchable fleet list; filtering never changes the selected destination. +fn printer_picker(ui: &mut egui::Ui, d: &mut PrintDraft) -> egui::Response { + let filter_id = ui.make_persistent_id("printer-filter"); + // Keep the search only while the combo box renders its popup contents. + let previous_filter = ui.data(|data| data.get_temp::(filter_id)); + let opening = previous_filter.is_none(); + let mut filter = previous_filter.unwrap_or_default(); + let shown = match d.printer.as_deref() { + Some(p) => printer_label(p), + None if still_looking(d) => tl!("Looking for printers…").to_string(), + None => tl!("Save as PDF").to_string(), + }; + let screen = ui.ctx().content_rect(); + let width = 430.0_f32.min((screen.width() - 32.0).max(0.0)); + let height = 420.0_f32.min(screen.height() * 0.6); + let response = craft_ui::ComboBox::from_id_salt("printer") + .selected_text(&shown) + .width(260.0) + .truncate() + .height(height) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show_ui(ui, |ui| { + ui.set_width(width); + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); + let search_label = ui.label(tl!("Search printers")); + let search = ui.add(widgets::line(&mut filter).desired_width(f32::INFINITY).char_limit(256)).labelled_by(search_label.id); + if opening { + search.request_focus(); + } + let query = pdfcraft_render::text::fold_case(filter.trim()); + if d.printers_loading { + ui.add_enabled(false, egui::Label::new(tl!("Looking for printers…"))); + } + // Keep the search and Save as PDF visible while the devices scroll. + // The popup's actual clip can be shorter than the requested height. + let footer_height = ui.spacing().interact_size.y + 4.0 * ui.spacing().item_spacing.y; + let list_height = (ui.clip_rect().bottom() - ui.cursor().top() - footer_height).clamp(0.0, height); + let mut list = egui::ScrollArea::vertical().id_salt("printer-results").max_height(list_height); + if search.changed() { + list = list.vertical_scroll_offset(0.0); + } + list.show(ui, |ui| { + let mut matched = false; + for p in &d.printers { + let name = printer_label(&p.name); + if !query.is_empty() && !pdfcraft_render::text::fold_case(&name).contains(&query) { + continue; + } + matched = true; + let label = if p.default && p.name != crate::web_print::BROWSER_PRINTER { + crate::i18n::fmt(tl!("{name} (default)"), &[("name", &name)]) + } else { + name + }; + let selected = d.printer.as_deref() == Some(p.name.as_str()); + let choice = ui.selectable_value(&mut d.printer, Some(p.name.clone()), label); + if opening && selected { + choice.scroll_to_me(Some(egui::Align::Center)); + } + if choice.clicked() { + d.printer_picked = true; + ui.close(); + } + } + if !matched && !query.is_empty() && !d.printers_loading { + ui.label(tl!("No printers match.")); + } + }); + ui.separator(); + // An explicit choice also protects PDF from a late default-printer refresh. + if ui.selectable_value(&mut d.printer, None, tl!("Save as PDF")).clicked() { + d.printer_picked = true; + ui.close(); + } + }); + ui.data_mut(|data| { + if response.inner.is_some() { + data.insert_temp(filter_id, filter); + } else { + data.remove::(filter_id); + } + }); + response.response.on_hover_text(shown) +} + /// Draw the dialog. `thumb` gives a page's thumbnail texture when there is one. Returns /// (print, cancel). pub(crate) fn body( @@ -146,32 +231,7 @@ pub(crate) fn body( // The browser's print dialog sets copies, two-sided printing and colour itself. let browser = d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER); ui.horizontal(|ui| { - let shown = match d.printer.as_deref() { - Some(p) => printer_label(p), - None if still_looking(d) => tl!("Looking for printers…").to_string(), - None => tl!("Save as PDF").to_string(), - }; - craft_ui::ComboBox::from_id_salt("printer").selected_text(shown).width(260.0).show_ui(ui, |ui| { - if d.printers_loading { - ui.add_enabled(false, egui::Label::new(tl!("Looking for printers…"))); - } - for p in &d.printers { - let name = printer_label(&p.name); - let label = if p.default && p.name != crate::web_print::BROWSER_PRINTER { - crate::i18n::fmt(tl!("{name} (default)"), &[("name", &name)]) - } else { - name - }; - ui.selectable_value(&mut d.printer, Some(p.name.clone()), label); - } - // Chosen even when it was already the selection, so the list arriving - // later doesn't replace it with the default printer. - if ui.selectable_value(&mut d.printer, None, tl!("Save as PDF")).clicked() { - d.printer_picked = true; - } - }) - .response - .labelled_by(printer_caption.id); + printer_picker(ui, d).labelled_by(printer_caption.id); let tip = if spool::HAS_PRINTER_PREFERENCES { tl!("Opens the printer driver's preferences. They are saved for every print from this computer; the copies, two-sided, grayscale and paper chosen here still apply.") } else { diff --git a/crates/ui-egui/tests/it/print.rs b/crates/ui-egui/tests/it/print.rs index cf382e095b..7a1470c1fa 100644 --- a/crates/ui-egui/tests/it/print.rs +++ b/crates/ui-egui/tests/it/print.rs @@ -5,10 +5,12 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use pdfcraft_ui_egui::{Dialog, PdfCraftApp}; +/// Open a bundled synthetic form with the default print settings. fn harness() -> Harness<'static, PdfCraftApp> { harness_with_settings(None) } +/// Restore optional settings before opening the form and settling the shell frames. fn harness_with_settings(settings: Option) -> Harness<'static, PdfCraftApp> { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { let mut app = PdfCraftApp::new(); @@ -23,6 +25,122 @@ fn harness_with_settings(settings: Option) -> Harness<'static, PdfCraftA h } +/// A large synthetic fleet, independent of the host's installed printers. +fn harness_with_printers() -> (Harness<'static, PdfCraftApp>, String) { + use pdfcraft_engine::print::spool::Printer; + let mut h = harness(); + let last = "München Satellite 119 - Engineering floor 4 (network queue) - colour duplex device, Building North".to_string(); + let mut printers: Vec<_> = (0..119) + .map(|i| Printer { + name: format!("Office {i:03} - Engineering floor 4 (network queue)"), + description: String::new(), + default: i == 0, + two_sided: None, + }) + .collect(); + printers.push(Printer { name: last.clone(), description: String::new(), default: false, two_sided: None }); + h.state_mut().printer_source = Some(std::sync::Arc::new(move || printers.clone())); + assert!(h.state_mut().execute("print.dialog")); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while h.state().print_draft.printers_loading && std::time::Instant::now() < deadline { + h.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!h.state().print_draft.printers_loading); + h.run_steps(3); + (h, last) +} + +/// Searching folds names without selecting a device, and reopening restores the fleet. +#[test] +fn printer_picker_filters_a_large_fleet_without_changing_the_selection() { + let (mut h, last) = harness_with_printers(); + let initial = h.state().print_draft.printer.clone(); + h.get_by_value(initial.as_deref().unwrap()).click(); + h.run_steps(3); + let search = h.get_by_role_and_label(Role::TextInput, "Search printers"); + assert!(search.rect().width() > 350.0, "room for long device names"); + search.type_text(" MÜNCHEN satellite "); + h.run_steps(3); + assert_eq!(h.state().print_draft.printer, initial, "typing is not a printer choice"); + assert!(!h.state().print_draft.printer_picked); + assert!(h.query_by_label("Office 001 - Engineering floor 4 (network queue)").is_none()); + h.get_by_label(&last).click(); + h.run_steps(3); + assert_eq!(h.state().print_draft.printer.as_deref(), Some(last.as_str())); + assert!(h.state().print_draft.printer_picked); + assert!(h.query_by_role_and_label(Role::TextInput, "Search printers").is_none(), "choosing closes the popup"); + + // A fresh opening shows the whole fleet again, including a choice outside the old filter. + h.get_by_value(&last).click(); + h.run_steps(3); + h.get_by_label("Office 001 - Engineering floor 4 (network queue)").scroll_to_me(); + h.run_steps(4); + h.get_by_label("Office 001 - Engineering floor 4 (network queue)").click(); + h.run_steps(2); + assert_eq!(h.state().print_draft.printer.as_deref(), Some("Office 001 - Engineering floor 4 (network queue)")); +} + +/// PDF remains an explicit destination even when no physical device matches the search. +#[test] +fn printer_picker_keeps_save_as_pdf_available_when_the_filter_matches_nothing() { + let (mut h, _) = harness_with_printers(); + let initial = h.state().print_draft.printer.clone(); + h.get_by_value(initial.as_deref().unwrap()).click(); + h.run_steps(3); + // Clicking in the filter must not close the popup, unlike choosing a device. + h.get_by_role_and_label(Role::TextInput, "Search printers").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Search printers").type_text("no-such-printer"); + h.run_steps(3); + h.get_by_label("No printers match."); + assert_eq!(h.state().print_draft.printer, initial); + h.get_by_label("Save as PDF").click(); + h.run_steps(3); + assert_eq!(h.state().print_draft.printer, None); + assert!(h.state().print_draft.printer_picked); + assert!(h.query_by_role_and_label(Role::TextInput, "Search printers").is_none()); + assert_eq!(h.state().dialog, Some(Dialog::Print), "selecting PDF must not submit the job"); +} + +/// Scrolling and wrapped names must leave the pinned footer physically clickable. +#[test] +fn printer_picker_scrolls_long_names_without_losing_the_search_or_pdf_choice() { + let (mut h, last) = harness_with_printers(); + let size = egui::vec2(1024.0, 768.0); + h.set_size(size); + h.run_steps(4); + let initial = h.state().print_draft.printer.clone(); + h.get_by_value(initial.as_deref().unwrap()).click(); + h.run_steps(3); + let search = h.get_by_role_and_label(Role::TextInput, "Search printers").rect(); + let pdf = h.get_by_label("Save as PDF").rect(); + assert!(pdf.top() - search.bottom() > 200.0, "show more than a few device rows"); + h.get_by_label(&last).scroll_to_me(); + h.run_steps(5); + let row = h.get_by_label(&last).rect(); + assert!(row.left() >= 0.0 && row.right() <= size.x, "long names wrap within the viewport: {row:?}"); + let search = h.get_by_role_and_label(Role::TextInput, "Search printers").rect(); + let pdf = h.get_by_label("Save as PDF").rect(); + assert!(search.top() >= 0.0 && pdf.bottom() <= size.y, "search and PDF stay on screen"); + h.get_by_label(&last).click(); + h.run_steps(3); + assert_eq!(h.state().print_draft.printer.as_deref(), Some(last.as_str())); + h.get_by_value(&last).click(); + h.run_steps(3); + // Reopening must scroll to the selection itself; manual scrolling would mask a regression. + let search = h.get_by_role_and_label(Role::TextInput, "Search printers").rect(); + let row = h.get_by_label(&last).rect(); + let pdf = h.get_by_label("Save as PDF").rect(); + assert!( + row.top() >= search.bottom() && row.bottom() <= pdf.top(), + "the selected printer is visible on reopening: {row:?}, search {search:?}, PDF {pdf:?}" + ); + h.get_by_label("Save as PDF").click(); + h.run_steps(3); + assert_eq!(h.state().print_draft.printer, None, "the PDF row must be clickable with the full fleet shown"); +} + /// The page-range field is labelled by the Pages radio button rather than floating unnamed. #[test] fn the_page_range_field_is_named_for_screen_readers() { diff --git a/docs/roadmap.md b/docs/roadmap.md index 1ff189e481..fd12d39615 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -291,7 +291,7 @@ total matches the parity estimate. | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | | M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.
Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Image redaction removes alternate images and unsupported masks only on affected images. Changed marked-content spans lose replacement descriptions; untouched spans keep theirs. Hidden-text cleanup retires unused named descriptions across inherited/shared page and form resources (64 focused tests and scoped Rust 1.96 Clippy/wasm checks pass; publication CI pending). Retained text/image-bearing or unreadable tiling-pattern cells now make Apply refuse atomically after a bounded check of rewritten resources; fully removed cells still apply, and cross-page retention is checked. The redaction audit counts a filled cover that hides half of any one word of a long line (#2662), applied or not. Phone-pattern redaction also matches labelled Italian geographic numbers with `+39` and a slash after the area code (#3205 follow-up); unlabelled international slash numbers remain unsupported. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding | | M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.
Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork, placed in the widget's bottom-right corner as it lies on the page, at a quarter of its shorter side and 48 screen points at most, so they annotate the artwork from a corner instead of covering the middle of it and turn with the page and the view (a field falling under 32 screen points, as a page does when zoomed out to fit, keeps its outline), snapshot tabs that reuse instead of multiplying, named-layer signature appearances redrawn for their real state (#79; display, the CLI's render, exports and printing, never saves; captions in the interface language, Chinese in English; the badge stays). Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 | -| M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: Windows Printer default sends native two-sided bindings only when automatic duplex support is confirmed, preserving manual driver defaults (#5130/#5772); physical output remains unqualified. DocumentDuplex-only bindings use the supported scope through craft-print 9fe50c94. create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).
Done since: Word, Excel, PowerPoint, OpenDocument and RTF files open from File ▸ Open as new PDFs through an installed LibreOffice (`create.from-office` partial); embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Model staging fetches SHA-256-verified ONNX detection/recognition files after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, then complete legacy RTEN pairs, without mixing formats or changing directory precedence. Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Web OCR downloads its models on first use and reads in Web Workers with SIMD (`ocr.ocr-web`, shipped). Missing: OCR languages beyond Latin, web OCR near native speed, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. Done since: Enhance scanned file cleans scanned pages in place (background removal, edge shadow removal, despeckle; the OCR text layer and comments stay; #4119 partial). | +| M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: Windows Printer default sends native two-sided bindings only when automatic duplex support is confirmed, preserving manual driver defaults (#5130/#5772); physical output remains unqualified. DocumentDuplex-only bindings use the supported scope through craft-print 9fe50c94. create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).
Done since: Word, Excel, PowerPoint, OpenDocument and RTF files open from File ▸ Open as new PDFs through an installed LibreOffice (`create.from-office` partial); embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Model staging fetches SHA-256-verified ONNX detection/recognition files after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, then complete legacy RTEN pairs, without mixing formats or changing directory precedence. Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Web OCR downloads its models on first use and reads in Web Workers with SIMD (`ocr.ocr-web`, shipped). Missing: OCR languages beyond Latin, web OCR near native speed, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. Done since: Enhance scanned file cleans scanned pages in place (background removal, edge shadow removal, despeckle; the OCR text layer and comments stay; #4119 partial). Candidate #4399: The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. | | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178); black-and-white images stored losslessly as CCITT Group 4 when smaller, averaged down to 300 ppi above 450 (halftones aside), Group 3 stored again as Group 4, and black-and-white RGB and indexed images that use only palette entries 0 and 1 packed to one bit. Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | | M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.
Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Image redaction removes alternate images and unsupported masks only on affected images. Changed marked-content spans lose replacement descriptions; untouched spans keep theirs. Hidden-text cleanup retires unused named descriptions across inherited/shared page and form resources (64 focused tests and scoped Rust 1.96 Clippy/wasm checks pass; publication CI pending). The redaction audit counts a filled cover that hides half of any one word of a long line (#2662), applied or not. Phone-pattern redaction also matches labelled Italian geographic numbers with `+39` and a slash after the area code (#3205 follow-up); unlabelled international slash numbers remain unsupported. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding | | M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.
Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 | @@ -406,6 +406,7 @@ Estimates unchanged. | 2026-10-29 | minor | M2: non-interpolated images drawn below their resolution are area-averaged to whole device pixels instead of nearest-neighbour (scanned text kept one sample in N per axis); page-scan-size images are smoothed when enlarged. Estimates unchanged. | | 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. | | 2026-10-25 | minor | M4, #4594 review: function documentation, stale-notice translation scanning and explicit dependency-policy/shared-release prerequisites; draft behavior and estimates unchanged. | +| 2026-10-25 | minor | M10, #4399: The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. Estimates unchanged. | | 2026-10-20 | minor | M9 #79 review, M2, M8: /ActualText that marks no glyph extracts where it paints, as far as it is visible; redaction strips /ActualText around paint it clips; named-layer recognition needs the layer form to draw n1 and n3. Estimates unchanged. | | 2026-10-25 | minor | M10: vector printing resolves annotation rectangle coordinates; synthetic regression evidence, estimates unchanged. | | 2026-10-26 | minor | M10: annotation rectangles, coordinates and appearance-state names follow up to 64 indirect references with cycle detection; standalone-object save/reopen and malformed-chain regressions, estimates unchanged. | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0063367715..ff1f354df7 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -8215,8 +8215,8 @@ milestone = "M10" status = "shipped" commands = ["print.dialog"] tools = ["printers", "printer_options", "doc_print"] -evidence = ["crates/print/src/tests.rs::spooler_arguments_and_printer_list", "crates/print/src/tests.rs::a_job_names_its_title_and_owner_to_the_spooler", "crates/print/src/tests.rs::a_job_keeps_the_title_and_owner_it_already_sets", "crates/print/src/tests.rs::a_submitted_job_reaches_lp_named", "crates/print/src/tests.rs::driverless_printers_join_the_list_without_a_queue", "crates/print/src/tests.rs::windows_printers_carry_one_default_and_keep_their_names", "crates/print/src/tests.rs::printer_options_come_from_the_ppd", "crates/print/src/tests.rs::printer_option_defaults_and_job_arguments", "crates/ui-egui/tests/it/print.rs::print_dialog_shows_the_printer_driver_options", "crates/ui-egui/tests/it/print.rs::printers_listed_in_the_background_preselect_the_default_unless_one_was_picked", "crates/ui-egui/src/workflows/web_print.rs::resolution_falls_with_the_sheet_count_and_long_jobs_are_refused", "crates/ui-egui/src/workflows/web_print.rs::large_sheets_are_drawn_within_the_pixel_cap_and_bad_sizes_are_refused", "crates/ui-egui/src/workflows/web_print.rs::a_sink_error_or_a_page_that_isnt_there_stops_the_job", "crates/print/src/tests.rs::a_command_that_never_answers_is_stopped_at_the_deadline", "crates/ui-egui/tests/it/print.rs::printer_options_are_read_off_the_gui_thread_and_a_dead_read_offers_nothing", "crates/optimize/tests/tiles.rs::a_grid_of_tiles_keeps_its_rows_and_columns_in_place", "crates/engine/src/spooler.rs::a_large_image_goes_to_the_spooler_as_tiles"] -notes = "CUPS queues via lpstat -p -d and driverless destinations without a queue via lpstat -e; on Windows shared craft-print lists the queues (EnumPrinters), the default (GetDefaultPrinter) and each driver's two-sided support in this process, and draws jobs as vectors with Windows.Data.Pdf into the XPS print API with a driver-validated PrintTicket (exact paper, orientation, no scaling; portrait and landscape sheets in one job via /Rotate; an image of more than 2²² pixels as tiles under that size, which Windows.Data.Pdf would draw from a shrunk copy, #5131), starting no PowerShell, so printing works under App Control script enforcement (#1107); the printer list and submission run on workers; Save as PDF on every platform. Properties…: on CUPS the driver's own PPD job options (tray, paper type, finishing …, not installable options or what the dialog sets) for this job, sent as lp -o; on Windows the driver's Printing Preferences window (printui), saved as that printer's per-user defaults rather than per job. On the web: \"Browser's print dialog\" (the default there) reaches the system's printers through the browser; PdfCraft draws the sheets itself (300 dpi up to 100 sheets, 200 up to 300, 150 up to 1,000; at most 64 megapixels a sheet and 1 GiB a job) and prints them from a hidden iframe, one per printed page, a landscape sheet among portrait ones turned onto the paper; copies, two-sided and colour are chosen in the browser's dialog; a browser that refuses to print gets the print-ready PDF as a download. Checked in headless Chromium, not yet in Firefox or Safari; pictures, not vectors; sheets of another paper size print at their own size only where the browser honours named @page sizes (Chromium doesn't). Properties… on CUPS reads the driver options off the GUI thread and gives lpoptions ten seconds before the PPD defaults stand (#1818); on macOS lp jobs also carry the job name and owner (com.apple.print.JobInfo.PMJobName and PMJobOwner) that the system print dialog sends and some vendors' filters need (#5743). Not yet checked on a physical Kyocera printer. The copy sent to the Windows spooler renames every embedded TrueType/OpenType program (name table, /BaseFont, /FontName), because Windows drew a subset's renumbered glyphs with the installed font of the same name and printed shifted letters (#3132); not yet checked on a physical Windows printer." +evidence = ["crates/print/src/tests.rs::spooler_arguments_and_printer_list", "crates/print/src/tests.rs::a_job_names_its_title_and_owner_to_the_spooler", "crates/print/src/tests.rs::a_job_keeps_the_title_and_owner_it_already_sets", "crates/print/src/tests.rs::a_submitted_job_reaches_lp_named", "crates/print/src/tests.rs::driverless_printers_join_the_list_without_a_queue", "crates/print/src/tests.rs::windows_printers_carry_one_default_and_keep_their_names", "crates/print/src/tests.rs::printer_options_come_from_the_ppd", "crates/print/src/tests.rs::printer_option_defaults_and_job_arguments", "crates/ui-egui/tests/it/print.rs::print_dialog_shows_the_printer_driver_options", "crates/ui-egui/tests/it/print.rs::printers_listed_in_the_background_preselect_the_default_unless_one_was_picked", "crates/ui-egui/src/workflows/web_print.rs::resolution_falls_with_the_sheet_count_and_long_jobs_are_refused", "crates/ui-egui/src/workflows/web_print.rs::large_sheets_are_drawn_within_the_pixel_cap_and_bad_sizes_are_refused", "crates/ui-egui/src/workflows/web_print.rs::a_sink_error_or_a_page_that_isnt_there_stops_the_job", "crates/print/src/tests.rs::a_command_that_never_answers_is_stopped_at_the_deadline", "crates/ui-egui/tests/it/print.rs::printer_options_are_read_off_the_gui_thread_and_a_dead_read_offers_nothing", "crates/optimize/tests/tiles.rs::a_grid_of_tiles_keeps_its_rows_and_columns_in_place", "crates/engine/src/spooler.rs::a_large_image_goes_to_the_spooler_as_tiles", "crates/ui-egui/tests/it/print.rs::printer_picker_filters_a_large_fleet_without_changing_the_selection", "crates/ui-egui/tests/it/print.rs::printer_picker_keeps_save_as_pdf_available_when_the_filter_matches_nothing", "crates/ui-egui/tests/it/print.rs::printer_picker_scrolls_long_names_without_losing_the_search_or_pdf_choice"] +notes = "The printer menu is wider and taller, filters names without regard to case, and wraps long names; search and Save as PDF remain visible while devices scroll (#4399). Filtering does not choose a destination and clears when the menu reopens. CUPS queues via lpstat -p -d and driverless destinations without a queue via lpstat -e; on Windows shared craft-print lists the queues (EnumPrinters), the default (GetDefaultPrinter) and each driver's two-sided support in this process, and draws jobs as vectors with Windows.Data.Pdf into the XPS print API with a driver-validated PrintTicket (exact paper, orientation, no scaling; portrait and landscape sheets in one job via /Rotate; an image of more than 2²² pixels as tiles under that size, which Windows.Data.Pdf would draw from a shrunk copy, #5131), starting no PowerShell, so printing works under App Control script enforcement (#1107); the printer list and submission run on workers; Save as PDF on every platform. Properties…: on CUPS the driver's own PPD job options (tray, paper type, finishing …, not installable options or what the dialog sets) for this job, sent as lp -o; on Windows the driver's Printing Preferences window (printui), saved as that printer's per-user defaults rather than per job. On the web: \"Browser's print dialog\" (the default there) reaches the system's printers through the browser; PdfCraft draws the sheets itself (300 dpi up to 100 sheets, 200 up to 300, 150 up to 1,000; at most 64 megapixels a sheet and 1 GiB a job) and prints them from a hidden iframe, one per printed page, a landscape sheet among portrait ones turned onto the paper; copies, two-sided and colour are chosen in the browser's dialog; a browser that refuses to print gets the print-ready PDF as a download. Checked in headless Chromium, not yet in Firefox or Safari; pictures, not vectors; sheets of another paper size print at their own size only where the browser honours named @page sizes (Chromium doesn't). Properties… on CUPS reads the driver options off the GUI thread and gives lpoptions ten seconds before the PPD defaults stand (#1818); on macOS lp jobs also carry the job name and owner (com.apple.print.JobInfo.PMJobName and PMJobOwner) that the system print dialog sends and some vendors' filters need (#5743). Not yet checked on a physical Kyocera printer. The copy sent to the Windows spooler renames every embedded TrueType/OpenType program (name table, /BaseFont, /FontName), because Windows drew a subset's renumbered glyphs with the installed font of the same name and printed shifted letters (#3132); not yet checked on a physical Windows printer." [[feature]] id = "print.copies-collate" From f435c182d2d60f27b13de8827c78218306222281 Mon Sep 17 00:00:00 2001 From: manurosado <11878842+manurosado@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:31:43 -0500 Subject: [PATCH 14/27] fix(xfa): render lines without width as vertical and without height as horizontal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this changes XFA templates often draw a vertical divider as a `` with `h` but no `w`, and a horizontal one with `w` but no `h`, while still declaring `slope="/"`. A width-less draw was measured as wide as its row and every line was drawn corner to corner along its slope, so these dividers came out as diagonals running across the form to the page edge. DAF Form 988 shows it on all 3 pages: its 66 vertical separators are all width-less lines. - `layout/measure.rs`: a line draw without a width is as wide as its stroke (clamped to 0.1 to 20pt, as it is drawn) plus its margin, capped at the available width, so a separator sits at its own x. - `layout/draw.rs`: a line without a width is vertical and one without a height is horizontal, whatever its slope says. A line whose box is no wider or no taller than twice its drawn stroke runs along the box's longer side, so a zero-height line is horizontal. Only a box with room for its stroke both ways follows `slope`. - `tests.rs`: `xfa_line_without_width_is_vertical_and_without_height_is_horizontal` covers six shapes: no width, no height, 1pt high, 1pt wide, a 48x72pt box with a 25pt stroke (drawn 20pt, so it still follows its slope) and 2pt by 0pt. It also pins the width-less line's x. ## How you verified it - `cargo test -p pdfcraft-xfa`: 314 passed. The new test fails with either half of the fix reverted. - `cargo test -p pdfcraft-engine xfa`: 86 passed. - `cargo fmt --all -- --check` and `cargo clippy -p pdfcraft-xfa --all-targets -- -D warnings`: clean. - DAF Form 988 laid out with `render_into`: 66 diagonal lines on `main`, none with this change (66 vertical, 68 horizontal). - [x] `cargo fmt --check` - [x] clippy with `-D warnings` on the crates I changed - [x] tests pass on the crates I changed - [ ] `cargo xtask layers` and `cargo xtask assets` (if you touched crate boundaries or any asset) ## Never-crash - [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests, unless it is provably infallible with a comment saying why - [x] No indexing or slicing with input-derived positions (`get`, and strings only at char boundaries); checked or saturating arithmetic; allocations sized by input are capped; recursion is bounded - [x] No `unsafe` - [x] Any crash this fixes has a small synthetic regression test ## Provenance - [x] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated - [x] No font files committed here (they live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts)) - [x] No GPL/AGPL code copied in — MuPDF, Ghostscript, Poppler, veraPDF and DSS may only be run as external oracle processes - [x] Behaviour comes from the specification or black-box observation, **not** from reading another implementation's source - [x] Every new asset has an `ATTRIBUTION.toml` entry and `cargo xtask assets` passes ## Security - [x] `--root` confinement still holds on every path, including ones reached by nested tool dispatch - [x] MCP and the UI control channel stay opt-in, loopback-only and token-authenticated - [x] No new outbound network access (that decision is the owner's) ## Parity and reach - [ ] `parity/acrobat-features.toml` updated in this PR, with `notes` saying what is *still* missing — `shipped` means "exists and tested", not "as good as Acrobat" - [ ] Reachable headlessly through an `automation` tool where that applies (`AGENTS.md` §3), so agents can drive it and not just the UI - [x] Docs updated if this changes a documented behaviour (`docs/`, crate README) ## Anything a reviewer should look at first The thin-box rule in `draw_draw`: it compares the box with twice the drawn (clamped) stroke and picks the longer side, so hairline borders never come out diagonal and a degenerate box never yields a zero-length segment. --- crates/xfa/src/layout/draw.rs | 17 +++++++++++-- crates/xfa/src/layout/measure.rs | 5 +++- crates/xfa/src/tests.rs | 41 ++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 3 deletions(-) diff --git a/crates/xfa/src/layout/draw.rs b/crates/xfa/src/layout/draw.rs index 6007005a3d..0000bf20dc 100644 --- a/crates/xfa/src/layout/draw.rs +++ b/crates/xfa/src/layout/draw.rs @@ -354,12 +354,25 @@ impl Layouter<'_> { if !edge.visible() { return Ok(()); } - let (from, to) = if *slope_up { + // A line without a width is vertical and one without a height is horizontal, + // whatever its slope says; one too narrow or too flat for its stroke runs along its + // box's longer side (a zero-height line is horizontal). + let width = edge.thickness.clamp(0.1, 20.0); + let thin = inner.w <= width * 2.0 || inner.h <= width * 2.0; + let vertical = d.common.w.is_none() || (d.common.h.is_some() && thin && inner.h > inner.w); + let horizontal = !vertical && (d.common.h.is_none() || thin); + let (from, to) = if vertical { + let x = inner.x + inner.w / 2.0; + ((x, inner.y), (x, inner.bottom())) + } else if horizontal { + let y = inner.y + inner.h / 2.0; + ((inner.x, y), (inner.right(), y)) + } else if *slope_up { ((inner.x, inner.bottom()), (inner.right(), inner.y)) } else { ((inner.x, inner.y), (inner.right(), inner.bottom())) }; - self.push(Item::Line { from, to, width: edge.thickness.clamp(0.1, 20.0), color: edge.color.0, dashed: edge.stroke == Stroke::Dashed }) + self.push(Item::Line { from, to, width, color: edge.color.0, dashed: edge.stroke == Stroke::Dashed }) } Value::Rectangle(b) => self.draw_border(b, inner), Value::Empty => Ok(()), diff --git a/crates/xfa/src/layout/measure.rs b/crates/xfa/src/layout/measure.rs index e8175553be..40c90f0197 100644 --- a/crates/xfa/src/layout/measure.rs +++ b/crates/xfa/src/layout/measure.rs @@ -70,7 +70,10 @@ impl Layouter<'_> { let inner = (avail_w - c.margin.horizontal()).max(1.0); (self.content_width(node, inner, ctx, depth) + c.margin.horizontal()).min(avail_w) } - Node::Draw(d) => self.natural_width(&d.value, &ctx.font, &ctx.para).map_or(avail_w, |t| (t + c.margin.horizontal()).min(avail_w)), + Node::Draw(d) => match &d.value { + Value::Line { edge, .. } => (edge.thickness.clamp(0.1, 20.0) + c.margin.horizontal()).min(avail_w), + _ => self.natural_width(&d.value, &ctx.font, &ctx.para).map_or(avail_w, |t| (t + c.margin.horizontal()).min(avail_w)), + }, Node::Field(f) if f.ui == Ui::Button => f .caption .as_ref() diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index c1abcce190..5eb4e00e48 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -8006,3 +8006,44 @@ two" assert_eq!(tree, before, "{structured}"); } } + +/// A line draw without a width is vertical; one without a height is horizontal, +/// even when the template declares a default slope="/". +#[test] +fn xfa_line_without_width_is_vertical_and_without_height_is_horizontal() { + let items = positioned( + r#" + + + + + + + "#, + ); + let lines: Vec<&Item> = items.iter().filter(|i| matches!(i, Item::Line { .. })).collect(); + assert_eq!(lines.len(), 6); + let is_vertical = |item: &Item| match item { + Item::Line { from, to, .. } => (from.0 - to.0).abs() < 1e-3, + _ => false, + }; + let is_horizontal = |item: &Item| match item { + Item::Line { from, to, .. } => (from.1 - to.1).abs() < 1e-3, + _ => false, + }; + assert!(is_vertical(lines[0]), "vert without width should be strictly vertical: {:?}", lines[0]); + // It is as wide as its stroke, so it sits at its own x (1in into a box at the content + // area's 0.5in), not in the middle of the row. + assert!(matches!(lines[0], Item::Line { from, .. } if (from.0 - (108.0 + 0.5)).abs() < 1e-3), "vert sits at its x: {:?}", lines[0]); + assert!(is_horizontal(lines[1]), "horiz without height should be strictly horizontal: {:?}", lines[1]); + assert!(is_horizontal(lines[2]), "a line 1pt high should be horizontal: {:?}", lines[2]); + assert!(is_vertical(lines[3]), "a line 1pt wide should be vertical: {:?}", lines[3]); + // A 25pt stroke is drawn 20pt wide, so a 48pt by 72pt box still follows its slope. + assert!(!is_vertical(lines[4]) && !is_horizontal(lines[4]), "a line wider than twice its drawn stroke follows its slope: {:?}", lines[4]); + // A 2pt by 0pt line is a 2pt horizontal stroke, not a zero-length vertical one. + assert!( + matches!(lines[5], Item::Line { from, to, .. } if (from.1 - to.1).abs() < 1e-3 && (to.0 - from.0).abs() > 1.9), + "a zero-height line is horizontal: {:?}", + lines[5] + ); +} From 5aae9dbae25e1e68731e42acfe08e2bd4f5b42a3 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:32:21 +0100 Subject: [PATCH 15/27] Keep the part of an email address before an apostrophe when redacting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this changes Email redaction no longer drops the part of an address before an apostrophe. The email scanner's `local` closure in `crates/redact/src/patterns.rs` did not accept an apostrophe in the local part. It treated `'` as a boundary and started the match after it, so for `o'brien@example.com` only `brien@example.com` matched. Search and Redact share that span, so the leading `o'` stayed visible. The local part may now contain an apostrophe, but a match cannot start on one. `o'brien@example.com` and `'john'@example.com` are now matched as `o'brien@example.com` and `john'@example.com`. A quote around an address (`'john@example.com'`) stays outside the match. No linked issue. Found while testing `crates/redact/src/patterns.rs:216` (email, `local` closure). ## How you verified it - [ ] `cargo fmt --check` - [ ] clippy with `-D warnings` on the crates I changed - [x] tests pass on the crates I changed - [ ] `cargo xtask layers` and `cargo xtask assets` (if you touched crate boundaries or any asset) - Regression test `patterns::tests::email_local_part_may_contain_an_apostrophe` covers all three cases. It fails on `main` without the fix and passes with it (`cargo test -p pdfcraft-redact email_local_part_may_contain_an_apostrophe`). - `cargo xtask ci` passes. ## Never-crash - [ ] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests, unless it is provably infallible with a comment saying why - [ ] No indexing or slicing with input-derived positions (`get`, and strings only at char boundaries); checked or saturating arithmetic; allocations sized by input are capped; recursion is bounded - [ ] No `unsafe` - [ ] Any crash this fixes has a small synthetic regression test ## Provenance - [ ] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated - [ ] No font files committed here (they live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts)) - [ ] No GPL/AGPL code copied in (MuPDF, Ghostscript, Poppler, veraPDF and DSS may only be run as external oracle processes) - [ ] Behaviour comes from the specification or black-box observation, not from reading another implementation's source - [ ] Every new asset has an `ATTRIBUTION.toml` entry and `cargo xtask assets` passes ## Security - [ ] `--root` confinement still holds on every path, including ones reached by nested tool dispatch - [ ] MCP and the UI control channel stay opt-in, loopback-only and token-authenticated - [ ] No new outbound network access ## Parity and reach - [ ] `parity/acrobat-features.toml` updated in this PR, with `notes` saying what is still missing - [ ] Reachable headlessly through an `automation` tool where that applies, so agents can drive it and not just the UI - [ ] Docs updated if this changes a documented behaviour (`docs/`, crate README) ## Anything a reviewer should look at first - A quote right before the local part, as in `'john'@example.com`, stays outside the match, so that leading quote stays visible after Redact. Matching it would also pick up the quote around quoted addresses. This is a deliberate restraint. - The domain scan and the other patterns are unchanged. 🤖 Generated with AI by [ApolloOffice](https://github.com/Silvertree2010/ApolloOffice), see the Co-Authored-By trailers for the models --- crates/redact/src/patterns.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/redact/src/patterns.rs b/crates/redact/src/patterns.rs index 9662602671..643f0c4c58 100644 --- a/crates/redact/src/patterns.rs +++ b/crates/redact/src/patterns.rs @@ -219,11 +219,15 @@ fn email(s: &[char], i: usize) -> Option { let local = |c: &char| address_char(*c) || "._%+-".contains(*c); // A match starts at the first character of a run of local characters, which may be // punctuation ("_admin@host.com"), but the run needs a letter or digit. - if !local(&s[i]) || i.checked_sub(1).and_then(|p| s.get(p)).is_some_and(local) { + // An apostrophe ("o'brien@example.com") belongs to the local part but never starts it, so a + // quote around an address ("'john@example.com'") stays outside the match. + let inner = |c: &char| local(c) || *c == '\''; + let before = |n: usize| i.checked_sub(n).and_then(|p| s.get(p)); + if !local(&s[i]) || before(1).is_some_and(local) || (before(1) == Some(&'\'') && before(2).is_some_and(inner)) { return None; } let mut j = i; - while j < s.len() && local(&s[j]) { + while j < s.len() && inner(&s[j]) { j += 1; } if s.get(j) != Some(&'@') || !s[i..j].iter().any(|c| address_char(*c)) { @@ -627,6 +631,14 @@ mod tests { find(p, &c).into_iter().map(|r| c[r].iter().collect()).collect() } + #[test] + fn email_local_part_may_contain_an_apostrophe() { + assert_eq!(found(Pattern::Email, "Mail o'brien@example.com today"), ["o'brien@example.com"]); + assert_eq!(found(Pattern::Email, "Mail 'john@example.com' today"), ["john@example.com"]); + // Only the leading quote stays outside; the whole local part is matched. + assert_eq!(found(Pattern::Email, "Mail 'john'@example.com today"), ["john'@example.com"]); + } + #[test] fn phone_numbers() { assert_eq!( From 55983f1f929992af710be23670e90b9eafdb03e5 Mon Sep 17 00:00:00 2001 From: Livio Oswald <125505497+Lcoding15@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:32:59 +0100 Subject: [PATCH 16/27] M12: forms show and add pages from page templates (#1429) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this changes Part of #1429. The form in that report keeps pages it shows on demand as **page templates**: the name dictionary's `/Templates` tree names pages kept out of the page tree, and `/Pages` names visible ones (ISO 32000-2 §7.7.4). Until now their fields were listed as unplaced, and the form's JavaScript could not reach them, so buttons that add a page or show a section did nothing. - **organize**: `templates`, `spawn_template` and `set_template_hidden`. - A spawned page is a copy of the template page. - With renaming, its fields become fields of their own under `P.