From d292b85d5f62d2597bfa5c9ce1d474c8f8dfe7a8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 31 Oct 2026 13:32:19 +0100 Subject: [PATCH 01/21] M3: reveal recent files from the Home context menu (#5452) Co-Authored-By: Codex --- ROADMAP.md | 3 +++ contributors/people.toml | 3 +++ crates/ui-egui/src/home.rs | 14 ++++++++++ crates/ui-egui/src/menus/tab_context.rs | 14 +++++++--- crates/ui-egui/tests/it/ui.rs | 35 +++++++++++++++++++++++++ docs/roadmap.md | 5 +++- parity/acrobat-features.toml | 4 +-- 7 files changed, 71 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 56f6237e8d..96c1f0e1a5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,6 @@ # PdfCraft roadmap +> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** minor (M3, #5452: native Recent rows gain Reveal in Finder / File Explorer; estimates unchanged) > **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: GBK rasters compared with explicit Unicode and independently selected installed faces; wrong-glyph and wrong-family negative controls fail; estimates unchanged) > **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: integrate main fa5f9f8c; retain CJK viewer and upstream raster regressions, restore explicit display_config imports; estimates unchanged) > **Last reviewed:** 2026-10-28 · **Last updated:** 2026-10-28 · **Change:** patch (M2, PR #4172: integrate main 5af10276; retain both roadmap histories and viewer-only CJK font policy; estimates unchanged) @@ -213,6 +214,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md ## Progress log +- **2026-10-31 (M3, #5452):** Native Home Recent rows offer Reveal in Finder / File Explorer from their context menu. They reuse the tab action’s platform dispatch and missing-file notification without opening the PDF or changing Recent. Browser behavior and milestone estimates unchanged. + - **2026-10-31 (M2, PR #4172 review):** Added same-machine pixel oracles for GBK Song, Hei, Kai and FangSong, including all four subset-prefixed Founder aliases. Reference PDFs use explicit Unicode mappings and independently selected installed faces; font data and rasters remain in memory. All eight cases ran; wrong-glyph and wrong-family production mutations each failed the new assertion and were restored. Validation: 422 renderer unit tests, renderer all-target Clippy with -D warnings, formatting, layers/assets/parity and renderer WASM checks passed; existing optional-patch/WASM warnings and parity notes remain. Estimates unchanged. - **2026-10-31 (M2, PR #4172):** Integrated main fa5f9f8c, retaining both roadmap histories and raster regression groups. Restored display_config and thumbnail_config imports after the upstream explicit-import migration. Validation: 422 renderer unit tests, engine/UI all-target checks, scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Existing optional-patch/WASM warnings and parity notes remain; no full engine/UI runtime test rerun. Display-only font policy and estimates unchanged. diff --git a/contributors/people.toml b/contributors/people.toml index a5a47f5c52..7ad98e88db 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -180,3 +180,6 @@ sync_github_name = true [people.dylanmtaylor] sync_github_name = true + +[people.vangel76] +sync_github_name = true diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index 390b059228..39b43226cb 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -156,9 +156,19 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { } let mut open = None; let mut remove = None; + #[cfg(not(target_arch = "wasm32"))] + let mut reveal = None; for r in &app.recent { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), Sense::click()); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &r.name)); + #[cfg(not(target_arch = "wasm32"))] + resp.context_menu(|ui| { + let label = if cfg!(target_os = "macos") { tl!("Reveal in Finder") } else { tl!("Reveal in File Explorer") }; + if ui.button(label).clicked() { + reveal = Some(r.path.clone()); + ui.close(); + } + }); let press = theme::Press::track(ui, &resp); // The row, not its response: the pointer stays "in" the row over its remove button. let hovered = ui.rect_contains_pointer(rect); @@ -209,6 +219,10 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { if let Some(p) = open { app.open_recent(&p); } + #[cfg(not(target_arch = "wasm32"))] + if let Some(p) = reveal { + app.reveal_path(std::path::Path::new(&p)); + } if let Some(p) = remove { app.recent.retain(|r| r.path != p); } diff --git a/crates/ui-egui/src/menus/tab_context.rs b/crates/ui-egui/src/menus/tab_context.rs index 9590969baf..6f8298d7b6 100644 --- a/crates/ui-egui/src/menus/tab_context.rs +++ b/crates/ui-egui/src/menus/tab_context.rs @@ -8,6 +8,14 @@ pub(crate) enum Action { } impl crate::PdfCraftApp { + /// Reveal a local file without opening it or changing document/Recent state. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn reveal_path(&mut self, path: &std::path::Path) { + if let Err(e) = reveal(path) { + self.notify_error(e); + } + } + pub(crate) fn tab_action(&mut self, action: Action) { match action { Action::Close(id) => { @@ -35,10 +43,8 @@ impl crate::PdfCraftApp { } Action::Reveal(id) => { #[cfg(not(target_arch = "wasm32"))] - if let Some(path) = self.session.get(id).and_then(|d| d.path.clone()) - && let Err(e) = reveal(std::path::Path::new(&path)) - { - self.notify_error(e); + if let Some(path) = self.session.get(id).and_then(|d| d.path.clone()) { + self.reveal_path(std::path::Path::new(&path)); } #[cfg(target_arch = "wasm32")] let _ = id; diff --git a/crates/ui-egui/tests/it/ui.rs b/crates/ui-egui/tests/it/ui.rs index 69be82e7a7..62677c4459 100644 --- a/crates/ui-egui/tests/it/ui.rs +++ b/crates/ui-egui/tests/it/ui.rs @@ -1865,3 +1865,38 @@ fn full_screen_neither_is_remembered_nor_hides_the_last_view() { view.leave_presentation(); assert_eq!((view.fit, view.zoom, view.layout, view.continuous), (Fit::None, 0.5, PageLayout::TwoUp, false), "the remembered view"); } + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn home_recent_context_menu_reveals_the_target_without_opening_or_removing_it() { + let missing = std::env::temp_dir().join(format!("pdfcraft-recent-missing-{}", std::process::id())).join("jährlicher report.pdf"); + assert!(!missing.exists()); + let expected = missing.to_string_lossy().into_owned(); + let target = expected.clone(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1600.0)).build_eframe(move |_| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + for (name, path) in [("first.pdf", ".".to_owned()), ("target.pdf", target)] { + app.recent.push(pdfcraft_ui_egui::RecentFile { name: name.into(), path, pages: 1, size: 0 }); + } + app + }); + h.run_steps(4); + let label = if cfg!(target_os = "macos") { "Reveal in Finder" } else { "Reveal in File Explorer" }; + h.get_by_label("target.pdf").click_secondary(); + h.run_steps(3); + assert!(!h.get_by_label(label).accesskit_node().is_disabled()); + assert!(h.state().views.is_empty(), "right-click must not open the PDF"); + assert_eq!(h.state().recent.len(), 2); + h.get_by_label(label).click(); + h.run_steps(3); + assert!(h.query_by_label(label).is_none(), "choosing the action closes its menu"); + assert!(h.state().views.is_empty(), "reveal must not open the PDF"); + assert_eq!(h.state().active, None); + assert_eq!(h.state().recent.len(), 2, "reveal must not remove missing recent files"); + assert_eq!(h.state().recent[1].path, expected); + assert!( + h.state().toast.as_ref().is_some_and(|(text, _)| text.contains("The file no longer exists")), + "the selected path is checked and the existing reveal error is shown" + ); +} diff --git a/docs/roadmap.md b/docs/roadmap.md index 0f1fb6f4d5..f04798249c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,5 +1,6 @@ # PdfCraft roadmap: milestones and what's next +> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** minor (M3, #5452: native Recent rows gain Reveal in Finder / File Explorer; estimates unchanged) > **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: GBK rasters compared with explicit Unicode and independently selected installed faces; wrong-glyph and wrong-family negative controls fail; estimates unchanged) > **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: integrate main fa5f9f8c; retain CJK viewer and upstream raster regressions, restore explicit display_config imports; estimates unchanged) > **Last reviewed:** 2026-10-28 · **Last updated:** 2026-10-28 · **Change:** patch (M2, PR #4172: integrate main 5af10276; retain both roadmap histories and viewer-only CJK font policy; estimates unchanged) @@ -194,7 +195,7 @@ total matches the parity estimate. | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. Forms without Resources use page Properties for ActualText and layer visibility; own dictionaries stop fallback. Oversized missing inline-image samples, including header and terminator overhead, no longer pin the content window (#3107 / PR #3438); normal large streamed images retain deterministic sample boundaries. Radial luminosity fades have synthetic coverage for the existing #2132 mask guard, including per-pixel references, antialiased clips, previews, scales and tiles; no additional production fix was needed. Dotted TOC leaders no longer inflate letter tracking or hide word spaces (#3086); phrase search and selection are covered. Short tracked ellipses retain their gap samples and remain searchable. Missing spacing glyphs in non-embedded Japanese CID substitutes render blank without changing PDF advances or Unicode (#3601). The desktop viewer can use installed CJK fonts, including Windows GBK Song/Hei/Kai/FangSong and subset-prefixed Founder names; Combine thumbnails and accessibility figure previews use the same display-only fallback, without changing export or print font policy (#234, continuation of #1567, review #4172). Print previews exclude installed faces and isolate their font cache; GBK regressions cover view/print switching for inline and pooled whole-page/tile rendering. Installed-font helpers and their regression contracts have function documentation. GBK regression rasters match explicit-Unicode references with independently selected installed faces; wrong-glyph and wrong-family negative controls fail. Integration with main fa5f9f8c retains viewer fallback across the split engine session modules, renderer tests and Combine thumbnail workers. | | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. The renderer keeps its one-point crop-size floor in physical points after UserUnit scaling, with regression coverage for crop origins, rotations and f32 reciprocal rounding. Existing unit policy and nearly-zero fallback are retained. | | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings | -| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. | +| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Native Recent rows also offer Reveal in Finder / File Explorer (#5452). | | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. Wrapped revision buttons stay above Binding in Document Properties (#2739); a synthetic UI test checks layout and saved revision content. | | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Later native-open replies stay queued while a modal or picker owns the foreground; regressions cover recipient ownership, completion/cancellation and one-shot wakes. | | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. #1980: exact quit modifiers preserve Ctrl+Alt+Q email input; Ctrl+Q/Cmd+Q asks before discarding unsaved documents. | @@ -274,6 +275,8 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st ## Revision history +**2026-10-31 · minor:** M3/#5452: native Home Recent context menus reuse tab reveal, retaining missing-file errors and leaving documents and history unchanged. Estimates unchanged. + **2026-10-26 · patch:** M2/PR #4172: reconcile current main and preserve upstream Japanese serif/weight selection alongside the installed CJK viewer and preview fallback. Estimates unchanged. **2026-10-25 · minor:** M14 localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Estimates unchanged. diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0b6f658dd6..5e34c20a3d 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -682,8 +682,8 @@ milestone = "M3" status = "shipped" commands = ["file.open_recent", "file.clear_recent"] tools = [] -evidence = ["crates/ui-egui/tests/it/ui.rs::persistence_round_trips_and_tolerates_garbage", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_lists_files_and_opens_one", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_is_disabled_while_the_list_is_empty", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_at_the_foot_of_open_recent_empties_the_list", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_runs_from_the_palette_and_is_saved", "crates/ui-egui/tests/it/ui.rs::home_removes_one_recent_file_or_clears_them_all"] -notes = "never reads other apps' lists; File ▸ Open Recent lists them (#290), an already-open file focuses its tab instead of reopening it, from any open path (#1620); Clear Recent Files at the foot of Open Recent, on Home and in the palette, and a remove button on each Home row (#430); missing: the row's remove button shows on pointer hover only (keyboard users clear the whole list)" +evidence = ["crates/ui-egui/tests/it/ui.rs::persistence_round_trips_and_tolerates_garbage", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_lists_files_and_opens_one", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_is_disabled_while_the_list_is_empty", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_at_the_foot_of_open_recent_empties_the_list", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_runs_from_the_palette_and_is_saved", "crates/ui-egui/tests/it/ui.rs::home_removes_one_recent_file_or_clears_them_all", "crates/ui-egui/tests/it/ui.rs::home_recent_context_menu_reveals_the_target_without_opening_or_removing_it"] +notes = "never reads other apps' lists; File ▸ Open Recent lists them (#290), an already-open file focuses its tab instead of reopening it, from any open path (#1620); Clear Recent Files at the foot of Open Recent, on Home and in the palette, and a remove button on each Home row (#430); native Home rows offer Reveal in Finder / File Explorer through their context menu (#5452), reusing tab reveal without opening or removing the file (browser has no local file manager); missing: the row's remove button shows on pointer hover only (keyboard users clear the whole list)" [[feature]] id = "core.reopen-last-session" From 0ac9f72d95ca4ec9a21bd6b91bb83171d87814b2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:53:18 +0100 Subject: [PATCH 02/21] home: reveal from the keyboard, and run Reveal off the UI thread The Menu key or Shift+F10 on a focused Recent row opens the Reveal menu. The existence check and file-manager call now run on a worker on every platform; a failure comes back to the UI thread and is shown as a notification. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/app.rs | 3 ++ crates/ui-egui/src/home.rs | 39 ++++++++++++++++--- crates/ui-egui/src/lib.rs | 3 ++ crates/ui-egui/src/menus/tab_context.rs | 50 +++++++++++++++++++------ 4 files changed, 77 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 04dbd19447..7962321060 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -152,6 +152,8 @@ impl PdfCraftApp { open_prepare_gate: None, pinned: Default::default(), recent_check: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + reveal_errors: Default::default(), pinned_tools: Vec::new(), pin_tool_search: String::new(), toast: None, @@ -468,6 +470,7 @@ impl eframe::App for PdfCraftApp { worker.set_context(ctx); } self.poll_pending_opens(); + self.show_reveal_errors(); } self.check_restored_recent(); // Chinese wants its own faces before the Japanese ones (one baseline per line). diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index d229402a16..817655b3ca 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -213,13 +213,23 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), Sense::click()); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &r.name)); #[cfg(not(target_arch = "wasm32"))] - resp.context_menu(|ui| { - let label = if cfg!(target_os = "macos") { tl!("Reveal in Finder") } else { tl!("Reveal in File Explorer") }; - if ui.button(label).clicked() { - reveal = Some(r.path.clone()); - ui.close(); + { + // The Menu key or Shift+F10 on the focused row opens the same menu a secondary + // click does, under the row, so Reveal works from the keyboard. + let by_key = + resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Menu) || (i.modifiers.shift && i.key_pressed(egui::Key::F10))); + let mut popup = egui::Popup::context_menu(&resp); + if by_key { + popup = popup.open_memory(egui::SetOpenCommand::Bool(true)).anchor(rect).align(egui::RectAlign::BOTTOM_START); } - }); + popup.show(|ui| { + let label = if cfg!(target_os = "macos") { tl!("Reveal in Finder") } else { tl!("Reveal in File Explorer") }; + if ui.button(label).clicked() { + reveal = Some(r.path.clone()); + ui.close(); + } + }); + } let press = theme::Press::track(ui, &resp); // The row, not its response: the pointer stays "in" the row over its remove button. let hovered = ui.rect_contains_pointer(rect); @@ -329,6 +339,23 @@ mod tests { assert!(h.state().pinned_tools.is_empty()); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_focused_recent_row_opens_its_reveal_menu_from_the_keyboard() { + use egui_kittest::kittest::Queryable; + for chord in [(egui::Modifiers::NONE, egui::Key::Menu), (egui::Modifiers::SHIFT, egui::Key::F10)] { + let mut h = review_home_harness(); + h.state_mut().recent = vec![crate::RecentFile { name: "notes.pdf".into(), path: "/nowhere/notes.pdf".into(), pages: 2, size: 2048 }]; + h.run_steps(3); + assert!(!egui::Popup::is_any_open(&h.ctx)); + h.get_by_label("notes.pdf").focus(); + h.run_steps(2); + h.key_press_modifiers(chord.0, chord.1); + h.run_steps(3); + assert!(egui::Popup::is_any_open(&h.ctx), "{chord:?} did not open the Reveal menu"); + } + } + #[test] fn translated_card_description_leaves_room_for_the_action() { if !crate::i18n::needs_catalogs() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 380f84a644..ac3bc98704 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -416,6 +416,9 @@ pub struct PdfCraftApp { pub pinned: folders_ui::PinnedFolders, /// The recent files restored from settings, checked off the UI thread (#5682). recent_check: persist::recent_check::RecentCheck, + /// Failures of the Reveal worker, taken each frame and shown as a notification. + #[cfg(not(target_arch = "wasm32"))] + reveal_errors: std::sync::Arc>>, /// Tools pinned to Home, in user-defined order. pub pinned_tools: Vec, /// Search query for the Pin a tool selection dialog. diff --git a/crates/ui-egui/src/menus/tab_context.rs b/crates/ui-egui/src/menus/tab_context.rs index 6f8298d7b6..b1db76a4e4 100644 --- a/crates/ui-egui/src/menus/tab_context.rs +++ b/crates/ui-egui/src/menus/tab_context.rs @@ -8,10 +8,35 @@ pub(crate) enum Action { } impl crate::PdfCraftApp { - /// Reveal a local file without opening it or changing document/Recent state. + /// Reveal a local file without opening it or changing document/Recent state. The existence + /// check and the file manager call can block (a disconnected network mount, a slow `dbus-send` + /// or `explorer.exe`), so they run on a worker; a failure is shown by + /// [`Self::show_reveal_errors`]. Tests run it inline ([`PdfCraftApp::run_inline`]). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn reveal_path(&mut self, path: &std::path::Path) { - if let Err(e) = reveal(path) { + let path = path.to_path_buf(); + let errors = self.reveal_errors.clone(); + let ctx = self.ctx.clone(); + let work = move || { + if let Err(e) = reveal(&path) { + errors.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(e); + if let Some(ctx) = &ctx { + ctx.request_repaint(); + } + } + }; + if self.run_inline { + work(); + } else if let Err(e) = std::thread::Builder::new().name("pdfcraft-reveal".into()).spawn(work) { + self.notify_error(e); + } + } + + /// Show the failures the reveal worker has reported (called each frame). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn show_reveal_errors(&mut self) { + let errors = std::mem::take(&mut *self.reveal_errors.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + for e in errors { self.notify_error(e); } } @@ -54,6 +79,7 @@ impl crate::PdfCraftApp { } #[cfg(not(target_arch = "wasm32"))] +/// Blocking: call it from a worker thread ([`crate::PdfCraftApp::reveal_path`]). fn reveal(path: &std::path::Path) -> Result<(), String> { // Absolute paths also prevent a filename starting with '-' becoming an option. let path = std::path::absolute(path).map_err(|e| e.to_string())?; @@ -63,16 +89,6 @@ fn reveal(path: &std::path::Path) -> Result<(), String> { let platform = std::env::consts::OS; let run = |program: &str, args: &[std::ffi::OsString]| reveal_process(program, args).output().map(|o| o.status.success()).map_err(|e| e.to_string()); - if matches!(platform, "linux" | "freebsd") { - // `dbus-send --print-reply` waits up to 2 s for the file manager (then xdg-open may run), - // so it runs off the UI thread; a failure there is only logged. - let spawned = std::thread::Builder::new().name("pdfcraft-reveal".into()).spawn(move || { - if let Err(e) = reveal_via(platform, &path, run) { - log::warn!("reveal {}: {e}", path.display()); - } - }); - return spawned.map(|_| ()).map_err(|e| e.to_string()); - } reveal_via(platform, &path, run) } @@ -236,6 +252,16 @@ mod tests { std::fs::remove_file(path).unwrap(); } + #[test] + fn a_failed_reveal_is_reported_back_to_the_ui_thread() { + let mut app = crate::PdfCraftApp::new(); + app.run_inline = true; + app.reveal_path(std::path::Path::new("/pdfcraft-no-such-dir/missing.pdf")); + assert!(app.toast.is_none(), "nothing is shown until the UI thread takes the report"); + app.show_reveal_errors(); + assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("The file no longer exists")); + } + #[test] fn unavailable_file_manager_falls_back_safely_and_reports_failure() { let path = std::path::Path::new("/tmp/年度 & reports/file.pdf"); From 795bc1144b422ff21c2d1c4146970779327fea16 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:04:56 +0800 Subject: [PATCH 03/21] fix(js): each unit-test thread counts its own document script workers Parallel unit tests in one process shared the process-wide count of live document script workers, so unrelated tests together reached the 16-worker cap and failed at random with "document script worker limit reached". Under cfg(test) each test thread now has its own count against the same cap; a permit releases the count it was taken from. The production cap and its process-wide count are unchanged. --- crates/js/src/session.rs | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/js/src/session.rs b/crates/js/src/session.rs index 1e01674df1..691f3ea7af 100644 --- a/crates/js/src/session.rs +++ b/crates/js/src/session.rs @@ -258,25 +258,43 @@ impl Realm { } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), not(test)))] static LIVE_WORKERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); #[cfg(not(target_arch = "wasm32"))] const MAX_DOCUMENT_WORKERS: usize = if usize::BITS == 32 { 4 } else { 16 }; +/// The count of live document workers that the cap applies to: one per process. +#[cfg(all(not(target_arch = "wasm32"), not(test)))] +fn live_workers() -> &'static std::sync::atomic::AtomicUsize { + &LIVE_WORKERS +} +/// Unit tests run in parallel threads of one process, so one process-wide count lets +/// unrelated tests exhaust the cap together. Each test thread counts its own workers +/// instead, against the same cap; the leak is one counter per test thread. +#[cfg(all(not(target_arch = "wasm32"), test))] +fn live_workers() -> &'static std::sync::atomic::AtomicUsize { + thread_local! { + static LIVE_WORKERS: &'static std::sync::atomic::AtomicUsize = + Box::leak(Box::new(std::sync::atomic::AtomicUsize::new(0))); + } + LIVE_WORKERS.with(|count| *count) +} /// A reservation is released only when its worker exits, including detached timed-out workers. +/// It releases the count it was taken from, whichever thread drops it. #[cfg(not(target_arch = "wasm32"))] -struct WorkerPermit; +struct WorkerPermit(&'static std::sync::atomic::AtomicUsize); #[cfg(not(target_arch = "wasm32"))] impl WorkerPermit { /// Reserve bounded address space without evicting another document's retained state. fn acquire() -> Result { use std::sync::atomic::Ordering::SeqCst; - let mut live = LIVE_WORKERS.load(SeqCst); + let count = live_workers(); + let mut live = count.load(SeqCst); loop { if live >= MAX_DOCUMENT_WORKERS { return Err("document script worker limit reached; close a scripted document and retry".into()); } - match LIVE_WORKERS.compare_exchange(live, live.saturating_add(1), SeqCst, SeqCst) { - Ok(_) => return Ok(Self), + match count.compare_exchange(live, live.saturating_add(1), SeqCst, SeqCst) { + Ok(_) => return Ok(Self(count)), Err(current) => live = current, } } @@ -285,7 +303,7 @@ impl WorkerPermit { #[cfg(not(target_arch = "wasm32"))] impl Drop for WorkerPermit { fn drop(&mut self) { - LIVE_WORKERS.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); } } @@ -915,7 +933,7 @@ mod tests { assert_eq!(session.run(capture, &[]).result.as_deref(), Some("retained")); } - /// Exercise the actual process-wide cap in isolation, then recover a slot without resetting other documents. + /// Exercise the cap in isolation, then recover a slot without resetting other documents. #[cfg(not(target_arch = "wasm32"))] #[test] fn document_worker_capacity_is_bounded_and_reusable() { @@ -939,7 +957,7 @@ mod tests { assert!(extra.start(job("1")).unwrap_err().contains("worker limit")); drop(workers.pop()); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - while LIVE_WORKERS.load(std::sync::atomic::Ordering::SeqCst) == MAX_DOCUMENT_WORKERS { + while live_workers().load(std::sync::atomic::Ordering::SeqCst) == MAX_DOCUMENT_WORKERS { assert!(std::time::Instant::now() < deadline); std::thread::sleep(std::time::Duration::from_millis(5)); } From b06bedefa691d4f1a931ed3e915413c9d2ec24b1 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:14:32 +0800 Subject: [PATCH 04/21] fix(hayro-syntax): a lone sign in a dictionary or array is unreadable, not a panic A lone + or ++ passes the first pass, which skips it as a number, but no number is read from it (ISO 32000-2 7.3.3). Dict::entries and Dict's Debug unwrapped the failed read and panicked, Array::raw_iter did too, and Array::iter stopped there and dropped the items after it. Vendor patch (46): a dictionary leaves such an entry out, as Dict::get already did (7.3.7), and an array reads it as null in its slot (7.3.9). A typed read still ends at it, as at any value of another type. --- crates/content/tests/hayro_sign_tokens.rs | 129 ++++++++++++++++++++++ vendor/README.md | 2 +- vendor/hayro-syntax/src/object/array.rs | 50 +++++++-- vendor/hayro-syntax/src/object/dict.rs | 21 ++-- 4 files changed, 185 insertions(+), 17 deletions(-) create mode 100644 crates/content/tests/hayro_sign_tokens.rs diff --git a/crates/content/tests/hayro_sign_tokens.rs b/crates/content/tests/hayro_sign_tokens.rs new file mode 100644 index 0000000000..f5fc9b67a7 --- /dev/null +++ b/crates/content/tests/hayro_sign_tokens.rs @@ -0,0 +1,129 @@ +//! A lone `+` or `++` is accepted by `hayro-syntax`'s first pass over a dictionary or array, +//! which skips it as a number, but no number is read from it. Such an entry is unreadable, like +//! any other malformed value: a dictionary leaves it out and keeps its other entries, and an +//! array reads it as null in its slot (vendor patch (46)). Before, `Dict::entries` and +//! `Array::raw_iter` (and `Dict`'s `Debug`) unwrapped the failed read and panicked, and `Array::iter` ended at the +//! token, dropping the items after it. Sign runs a number is read from (`-` reads as 0) keep +//! reading as before. + +use hayro_syntax::object::{Array, Dict, FromBytes, Number, Object}; + +/// Sign-only tokens, and two of them in a row. +const SIGN_TOKENS: [&str; 8] = ["+", "++", "-", "--", "+-", "-+", "+ -", "+ +"]; + +/// Whether no number is read from this sign run, so it is the unreadable kind. +fn unreadable(sign: &str) -> bool { + Number::from_bytes(sign.as_bytes()).is_none() +} + +#[test] +fn a_dictionary_leaves_out_an_entry_made_only_of_signs() { + for tok in SIGN_TOKENS { + let src = format!("<< /A {tok} /B 7 >>"); + let Some(dict) = Dict::from_bytes(src.as_bytes()) else { + // Refused as a whole, as other unreadable dictionaries are: nothing to iterate. + continue; + }; + let entries: Vec<_> = dict.entries().map(|(k, _)| k.as_str().to_owned()).collect(); + let a = dict.get::>("A"); + if unreadable(tok) { + assert_eq!(entries, ["B"], "{src}"); + assert!(a.is_none(), "{src}"); + } else { + assert_eq!(entries, ["A", "B"], "{src}"); + assert!(matches!(a, Some(Object::Number(_))), "{src}: {a:?}"); + } + assert_eq!(dict.get::("B"), Some(7), "{src}"); + } +} + +#[test] +fn an_array_reads_a_token_made_only_of_signs_as_null_in_its_slot() { + for tok in SIGN_TOKENS { + let src = format!("[0 {tok} 7]"); + let Some(array) = Array::from_bytes(src.as_bytes()) else { + continue; + }; + let signs = tok.split_whitespace().count(); + let raw: Vec<_> = array.raw_iter().collect(); + let items: Vec<_> = array.iter::>().collect(); + assert_eq!(raw.len(), signs + 2, "{src}"); + assert_eq!(items.len(), signs + 2, "{src}"); + assert_eq!(items.first().and_then(|o| o.clone().into_i32()), Some(0), "{src}"); + assert_eq!(items.last().and_then(|o| o.clone().into_i32()), Some(7), "{src}"); + for (item, sign) in items.iter().skip(1).zip(tok.split_whitespace()) { + if unreadable(sign) { + assert!(matches!(item, Object::Null(_)), "{src}: {item:?}"); + } else { + assert!(matches!(item, Object::Number(_)), "{src}: {item:?}"); + } + } + // A typed read still stops at a slot that is not a number, as at any other value. + let numbers_before = 1 + tok.split_whitespace().take_while(|sign| !unreadable(sign)).count(); + let expected = if numbers_before == signs + 1 { signs + 2 } else { numbers_before }; + assert_eq!(array.iter::().count(), expected, "{src}"); + } +} + +/// Every token of up to five characters over signs, digits, `.` and `e` that starts with a +/// sign, in each position a value can take, iterates without panicking, and an array never +/// loses the item after it. +#[test] +fn short_sign_led_tokens_never_panic_in_a_dictionary_or_array() { + const ALPHABET: &[u8] = b"+-1.e "; + let mut checked = 0usize; + let mut tok = Vec::new(); + for len in 1..=5u32 { + let total = ALPHABET.len().pow(len); + for code in 0..total { + tok.clear(); + let mut k = code; + for _ in 0..len { + tok.push(ALPHABET.get(k % ALPHABET.len()).copied().unwrap_or(b' ')); + k /= ALPHABET.len(); + } + if !matches!(tok.first(), Some(b'+' | b'-')) || tok.last() == Some(&b' ') { + continue; + } + let tok = std::str::from_utf8(&tok).unwrap_or_default().to_owned(); + checked += 1; + for src in [format!("[{tok}]"), format!("[0 {tok} 7]"), format!("<< /A {tok} /B 7 >>")] { + let outcome = std::panic::catch_unwind(|| { + if src.starts_with('[') { + Array::from_bytes(src.as_bytes()).map(|a| { + let _ = format!("{a:?}"); + let raw = a.raw_iter().count(); + let items: Vec<_> = a.iter::>().collect(); + (raw, items.len(), items.last().and_then(|o| o.clone().into_i32())) + }) + } else { + Dict::from_bytes(src.as_bytes()).map(|d| { + let _ = format!("{d:?}"); + let entries = d.entries().count(); + let _ = d.get::>("A"); + (entries, entries, d.get::("B")) + }) + } + }); + let Ok(result) = outcome else { + panic!("{src:?} panicked"); + }; + let Some((raw, items, last)) = result else { + continue; + }; + if src.starts_with('[') { + assert_eq!(raw, items, "{src:?}: raw_iter and iter disagree"); + if src.starts_with("[0 ") { + assert_eq!(last, Some(7), "{src:?}: the item after the token was lost"); + } + } else { + assert_eq!(last, Some(7), "{src:?}: /B was lost"); + } + } + } + } + // Two leading signs, then 6^(len-2) middles and 5 last characters (no trailing space). + assert_eq!(checked, 2 + 2 * 5 + 2 * 6 * 5 + 2 * 36 * 5 + 2 * 216 * 5); + // A sign-led number still reads as one. + assert_eq!(Number::from_bytes(b"+1").map(|n| n.as_f64()), Some(1.0)); +} diff --git a/vendor/README.md b/vendor/README.md index 558dbbbc12..d6871aa1a1 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -59,7 +59,7 @@ Other resource categories retain their existing parent-chain lookup. | hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour (since (21), only inside Type 3 glyphs), planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (21) an image that does not request interpolation and is drawn below its resolution, outside a Type 3 glyph, is shrunk by area averaging (`area_shrink`: each device pixel the coverage-weighted mean of the samples it covers, in 16.16 fixed point whose weights sum to exactly one, premultiplied when the image has a mask; a soft mask no larger than the image is first sampled onto the image's grid by `mask_on_image_grid` (nearest-neighbour, or bilinearly when the mask asks for `/Interpolate`, so its edge stays as smooth as an enlarged mask's), so its colour and mask are averaged together instead of the averaged colour of transparent samples showing under a mask layer at the mask's edges) to its snapped device rectangle, instead of nearest-neighbour: `/Interpolate` asks for smoothing only when an image is enlarged (ISO 32000-2 §8.9.5.3), and nearest-neighbour kept one sample in N per axis, so the text of a 300 dpi scan at 100% lost most of its strokes (sampling them again at a fractional offset dropped more). PicScale's `Box` and `Area` filters were not used: shrinking, both average a window four target pixels wide. On a 13-page 300 dpi scan every rendered sample at 96, 120 and 192 dpi is within 1 of the exact area average (it was up to 255 off, 17-23% of samples by more than 1). A snapped image whose shrink failed keeps the full transform, so it is not drawn at its source size. The shrink never enlarges: a side drawn at or above its resolution (an image shrunk across and stretched down, as a 204 × 98 dpi fax is) keeps its samples for the sampler. Each target row averages the whole source rows it covers (contiguous, cheap) and is then shrunk across with taps worked out once per image, which made the shrink about three times faster (a 300 dpi page at 96 dpi: 25 ms, nearest-neighbour 11 ms); working a row at a time (`area_shrink_rows`) keeps its work memory to a few rows. An image with a soft mask, a stencil's ink included, is premultiplied a source row at a time as it is averaged (`area_shrink_premultiplied`), never as a full-resolution RGBA copy: a 10718 × 13701 stencil shown at page size peaked at 1.16 GB with that copy and peaks at 1.03 GB without it, as with nearest-neighbour. A source with a side over `MAX_RESAMPLING_SOURCE_SIDE` (2^20) keeps (10)'s nearest-neighbour shrink, and `area_shrink` refuses it, so its accumulator row and tap table stay a few times one source row (a 2^27 × 2 image of zeros is a tiny file); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971); (23) backport of hayro 0.8: shadings that `as_svg_gradient` can represent are painted as a `vello_cpu` linear or two-point radial gradient instead of a texture sampled pixel by pixel through the shading function (InDesign fades are luminosity soft masks of one full-page axial `sh`: 40 on a report page took 15 s at 144 dpi, now under 1 s); without upstream's half-pixel shift, which suits vello_cpu 0.3 but moves 0.0.8's gradients off pixel centres; (25) a tiling cell is drawn at the scale that makes one `/XStep` (`/YStep`) exactly the cell pixmap's whole number of pixels (`tiling_cell_pixels`, at least 1 and at most the cap), so the repeated pixmap puts cells at whole multiples of the step at any device scale; drawing at the unrounded scale repeated the cell up to half a pixel off at every step, and the error grew with distance from the pattern's origin (ISO 32000-2 8.7.3.1); (28) an image of page-scan size (`SMOOTHED_IMAGE_SIDE`: 512 samples or more on its shorter side) that does not request interpolation is drawn with `ImageQuality::Medium` (bilinear, as interpolated images are) when enlarged by more than 1% on either side (`SMOOTHED_IMAGE_SCALE`: a scan drawn at its resolution can come out a few ulps above 1, and blurred by half a pixel at a half-pixel offset), also when the other side is shrunk (the area shrink leaves that side at 1:1), outside a Type 3 glyph: scans rarely set `/Interpolate`, and drawn nearest-neighbour every sample of a zoomed scan became a block, so its text had staircase edges; icons, QR codes and pixel art keep their hard pixels. Bicubic (`High`) looked the same on a zoomed 300 dpi scan and drew four 1024 px tiles at 400% in 267 ms against 50 ms; (30) a stencil mask painted with a pattern is drawn under a clip of its device rectangle, padded by two pixels: the pattern in an isolated layer, cut to the stencil by a layer holding it composited with `Compose::DestIn` (drawn without a Type 3 glyph's image rules, as the sub-render it replaces was), instead of through a canvas-sized luminance mask rendered for every draw; and a coloured tiling pattern's cell pixmap, repeated or shown once under patch (20), is drawn once per setting of the pattern and cell scale (`Renderer::tiling_cell`, `TilingCells`, eight entries per renderer, keyed by hayro-interpret patch (78)'s `TilingPattern::instance`) instead of once per fill, where every cell was kept until the page was composited. pdf.js issue 8078 paints 73,047 16 × 16 stencils with one pattern whose cell is 3.5 MB at 36 dpi: it ran out of memory after 5 minutes and now renders in about 5 s. For its tests, `offscreen_draws` counts on each thread the tiling cells drawn and the pixels of every pixmap drawn offscreen (all made by `offscreen_pixmap`), so a page's cost is checked by count, not by time; (31) `RenderSettings::max_coverage` keeps the rasterizer to that many coverage values for the page (vello_cpu patch 1), and a page whose paths it left out says so with `InterpreterWarning::ContentTruncated` | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_averages_the_columns_each_pixel_covers`, `raster::tests::non_integer_minification_averages_colour_and_mask_together`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::minified_image_edges_snap_to_whole_pixels`, `raster::tests::a_tile_snaps_half_pixel_image_edges_as_the_whole_page_does` (`cargo test -p hayro`), `raster::tests::a_turned_or_mirrored_minified_image_snaps_to_whole_pixels`, `rotated_image_snap::a_shrunk_image_on_a_turned_page_is_the_upright_render_turned` (`cargo test -p pdfcraft-render --test it`), `renderer::snap_tests::a_skew_that_moves_a_far_edge_is_not_snapped` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path`; (21) `raster::tests::non_interpolated_minification_keeps_thin_strokes`, `raster::tests::non_integer_minification_averages_the_columns_each_pixel_covers`, `raster::tests::non_integer_minification_averages_colour_and_mask_together`, `raster::tests::non_interpolated_minification_does_not_bleed_transparent_colour`, `raster::tests::a_smaller_soft_mask_does_not_bleed_transparent_colour_when_minified`, `raster::tests::an_interpolated_smaller_soft_mask_stays_smooth_when_its_image_is_minified`, `raster::tests::a_shrunk_stencil_mask_keeps_thin_strokes`, `raster::tests::minified_image_edges_snap_to_whole_pixels`, `raster::tests::an_image_shrunk_one_way_and_stretched_the_other_is_still_averaged`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`, `renderer::area_shrink_tests` (`cargo test -p hayro`); (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (25) `tiling_cell_placement::{far_cells_of_a_fill_sit_at_whole_steps, far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix, far_cells_of_a_stroke_sit_at_whole_steps, a_cell_pixmap_spans_exactly_one_step}` (`cargo test -p pdfcraft-render --test it`); (28) `raster::tests::large_non_interpolated_images_are_smoothed_when_enlarged`, `raster::tests::small_non_interpolated_images_keep_hard_pixels_when_enlarged`, `raster::tests::a_scan_shrunk_one_way_is_smoothed_the_way_it_is_stretched`, `raster::tests::a_scan_drawn_a_rounding_error_above_its_resolution_stays_sharp`; (30) `raster::tests::{a_patterned_stencil_mask_paints_only_where_it_inks, a_patterned_stencil_mask_under_a_soft_mask_is_masked_once, a_patterned_stencil_mask_in_a_type3_glyph_keeps_thin_strokes, many_patterned_stencil_masks_draw_no_page_sized_masks, fills_of_one_pattern_setting_share_its_cell, fills_of_interleaved_pattern_settings_each_show_their_own_cell, an_uncoloured_pattern_shows_each_settings_colour}`; (31) `raster::tests::coverage_budget::a_page_past_its_coverage_leaves_the_rest_out_and_says_so` | | hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most as many symbol pixels per symbol dictionary as the largest page bitmap holds, 2^28 (a fuzzed dictionary decoded for minutes; each symbol now pays for its pixels out of the stream's decoding work and is held in the retained bitmaps, and at the earlier 2^26 the soft mask of a scanned drawing, one dictionary of 7,559 symbols, was refused: #6722), and a refusal by one of the decoder's limits is told apart from damaged data (`DecodeError::is_limit`, `OverflowError::BitmapLimit`); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and the page with it. `Bitmap::combine_region` keeps such a location past the page. A refinement of another region refines it where it is, as Table 35 has it (GRREFERENCEDX and GRREFERENCEDY 0), whatever the two locations say; a refinement of the page, see (16); (15) a refinement whose reference is offset right of it (GRREFERENCEDX above 0, which a refined text instance has from a wider bitmap, Table 12, and a refined symbol from an RDX above 0, Table 18) read the reference's first 32 columns as 0: `RefinementContextGatherer::maybe_reload_buffers` emptied its buffers left of the reference and didn't load them again at its first column. Such a refinement decoded to other pixels than were coded, or failed and lost the page. Left of the reference the buffers now keep the words of its first column each row starts with; with an offset of 0 or less nothing changes; (16) a refinement of the page refines "the current contents of the page buffer, restricted to the area of the page buffer specified by this segment's region segment information field" (7.4.7.4), at an offset of 0 (Table 35): `Bitmap::area` copies that area a word at a time, 0 off the page and past its width whatever the padding of its rows holds, and every refinement region reads its reference at offset 0. The page around the area was read too, so a refinement of the page decoded to other pixels than were coded, and one wider or taller than the page was refused. And `RefinementContextGatherer::start_row` loads the reference's words a column left of where a row starts in it, as the reload would, not from column 0: with the reference offset 32 or more left of the refinement (GRREFERENCEDX below −31, as a refined text instance has from a narrower bitmap or an RDX below −31, and a refined symbol from such an RDX), each row's first context read 0 for the reference column it starts at, and from 33 left for the one before it too, and the refinement decoded to other pixels or failed; (17) `Image::new_embedded` reads data that starts with a JBIG2 file header (the ID string `0x97 4A 42 32 0D 0A 1A 0A`, flags and an optional page count, D.4) past it, in the organization the header declares (sequential or random access), its segments counted together with the globals' as (8) has them: ISO 32000-1 7.4.7 has `JBIG2Decode` data in the embedded organization (D.3), but some producers write the file header too, and Acrobat and PDFBox draw such streams. The header's ID string was read as a segment header and the image failed (`unknown or reserved segment type`), so the page drew white | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`, `raster::tests::jbig2_halftone_grids_past_their_bound_are_refused`; (2) the nightly `cargo xtask fuzz` finding (about a second at the earlier 2^26 bound; not run at 2^28), `raster::tests::a_symbol_dictionary_holds_as_many_pixels_as_a_page`, and for `is_limit` and `BitmapLimit` `error::pdfcraft_limit_tests`, `bitmap::pdfcraft_limit_tests` and `gray_scale::pdfcraft_limit_tests` (hayro-jbig2); (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`); (5) `raster::tests::jbig2_regions_held_past_a_pages_bound_are_refused`, `jbig2_symbols_without_pixels_count_towards_a_pages_bound`, `jbig2_retained_contexts_count_towards_a_pages_bound`, `jbig2_huffman_tables_count_towards_a_pages_bound`, `jbig2_new_symbols_count_towards_a_pages_bound`, `jbig2_new_symbols_are_held_to_what_a_page_has_left`, `jbig2_pattern_dictionaries_count_towards_a_pages_bound`, and in the crate (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) `decode::symbol::tests::exported_symbols_are_counted_before_they_are_copied`, `tests::the_room_left_shrinks_as_segments_are_stored`; (6) `raster::tests::jbig2_segments_referring_to_too_many_symbols_are_refused`; (7) `raster::tests::jbig2_pattern_dictionaries_too_large_to_shift_still_draw`, `jbig2_shifted_patterns_never_refuse_an_image`; (8) `raster::tests::jbig2_huffman_tables_of_too_many_lines_are_refused`, `jbig2_streams_of_too_many_segments_are_refused`, `jbig2_streams_of_too_many_references_are_refused`, and in the crate `tests::the_segments_of_a_stream_and_its_globals_count_together`; (9) `raster::tests::jbig2_pages_past_the_bounds_are_refused_before_anything_is_sized_from_them`, `tests::a_page_past_the_bounds_is_refused_when_opened`; (10) `raster::tests::jbig2_decoding_work_is_counted_item_by_item`; (11) `jbig2::decode::tests::a_run_of_images_spends_its_allowance_down_to_the_step` (pdfcraft-filters); (12) `raster::tests::jbig2_placements_at_the_end_of_an_i32_draw_nothing`; (13) `jbig2::decode::tests::a_refinement_reads_nothing_past_its_references_width` (pdfcraft-filters), and in the crate `tests::a_bitmap_of_1s_has_nothing_past_its_width`; (14) `jbig2::decode::tests::a_region_located_past_i32_max_is_off_the_page` (pdfcraft-filters), and in the crate `tests::a_region_located_past_i32_max_is_off_the_page` and `tests::a_refinement_of_a_region_decodes_the_same_wherever_they_are`; (15) `jbig2::decode::tests::a_refinement_reads_a_reference_right_of_it_from_its_first_column` (pdfcraft-filters), and in the crate `tests::a_refinement_reads_a_reference_right_of_it_from_its_first_column`; (16) `jbig2::decode::tests::a_refinement_refines_the_page_in_its_area_and_any_reference_where_it_is` (pdfcraft-filters), and in the crate `tests::a_refinement_refines_the_page_in_its_area_and_any_reference_where_it_is` and `tests::a_page_area_is_the_page_inside_it_and_0_outside` ; (17) `jbig2::decode::tests::a_stream_with_a_jbig2_file_header_decodes_past_it`, `jbig2::decode::tests::a_truncated_jbig2_file_header_is_an_error`, `jbig2::decode::tests::segments_after_a_jbig2_file_header_count_with_the_globals` (pdfcraft-filters), `raster::tests::a_jbig2_image_with_a_file_header_draws` (pdfcraft-render) | | lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365); (7) object parsing builds at most 4,194,304 objects (every array element and dictionary value at any depth, `parser::MAX_OBJECT_NODES`, the same cap as `pdfcraft_cos`) per top-level object, an object stream reads at most 1,000,000 index entries (cos's `/N` clamp), and one load builds at most 8,388,608 objects from all of its object streams together, shared across rayon workers (a decoded stream of `0 0 0 ...` inside the 256 MiB decompression limit built ~120M objects, 10+ GB, and aborted). A lookup parses only the member it wants, so it isn't skipped behind a large member, and a load parses only the members it would add: none its cross-reference table places in another stream (stale copies) and none already loaded as an ordinary object or from an earlier stream. Members the table doesn't list at all are still parsed (a rebuilt table lists no compressed objects) and share the budget, so they can spend it before listed members of the same stream; a load expands its object streams one at a time in object-number order, a stream's members in parallel only when the budget holds all of them and otherwise in index order, so a spent budget skips the same members on every load (#5083) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog`; (7) `inspect::tests::{object_stream_members_over_the_node_cap_are_skipped, object_stream_index_entries_past_the_clamp_are_ignored, object_streams_of_one_load_share_their_node_budget, object_streams_loaded_in_parallel_share_their_node_budget, a_malformed_object_stream_member_refunds_its_reservation, a_tight_budget_builds_object_stream_members_in_index_order, a_lookup_in_an_object_stream_parses_only_the_member_it_wants}` (pdfcraft-render; `NodeBudget` and `ObjectStream::new_within` are public so these can use a small budget) | -| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260); (29) a `/JBIG2Globals` stream that is itself JBIG2 isn't decoded: globals are raw segments, and a chain of 16,000 such streams overflowed the stack, which aborts the process; (30) a stream's own crypt filter: `/Crypt` in its chain read as the filter it names, `/Identity` without one, instead of the document's filter and then a filter that can't be decoded, which left such a stream unreadable in any spelling (ISO 32000-2 §7.4.10); (31) `set_page_jbig2_work`: the JBIG2 images decoded on a thread spend one allowance, set per page, 2^30 steps (`MAX_PAGE_JBIG2_WORK`), so a page of many images made to reach their own limit stops at one, and what they cost to read counts, whether they decode or not, and `jbig2_limited` says whether the image decoded last on the thread was refused by one of the decoder's limits rather than its data, and `jbig2_limited_by_stream` whether that limit is one the stream reaches by itself rather than its decoding work, which may be the page's; `clear_jbig2_limited` and each new page forget it; unbounded until a page sets it; (32) a group of array items read together (a tuple: an image's `/Decode`, `/W`, `/W2`, and a function's `/Domain`, `/Range`, `/Encode` and `/Decode`) can start with a reference: it was taken for the whole group and lost, which ended the array, so an image with `/Decode [7 0 R 0]` didn't draw and CID widths fell back to `/DW`; (33) an object that holds only a reference stands for what that names, stored on its own or in an object stream, up to 32 references: read as a number it was the reference's own object number, so a `/Decode` or `/W` entry naming such an object took a wrong value, and as anything else it was lost. Past 32, as any cycle goes, it reads as a missing object. An object stream isn't reached that way, as its checks are of the object named; reading its index counts against the 64 nested loads and reads its dictionary alone, as a chain of them, each with a member of the next for its `/N`, `/First` or `/Length`, ran out of stack; and a comment inside a reference counts as white space; (34) a table rebuilt by scanning the file (`fallback_xref_map`) finds an object by its number when its header names another generation, including one no generation may be (`3 18446744073709551616 obj` in `poppler-85140-0.pdf`, #5580): the header is read leniently only in that scan (`read_object_header`), the object is also filed under generation 0 unless a real `N 0 obj` holds that key (a later header for the number moves the stand-in), `XRef::get_with` matches by object number only in a repaired table, and `XRef::objects` yields each location once; (35) PNG predictors (`lzw_flate::unfilter_png`) are undone a byte row at a time on slices, as the PNG filters are defined, instead of through the bit-level readers TIFF predictors need: a 993 × 936 RGB image took about 63 ms to unfilter whatever its row filters, and now takes about 3 ms (Up) to 16 ms (Paeth) in a release build (#5430); a row ending part-way through a pixel (three 4-bit samples, an odd width) keeps its last byte, where the bit-level readers dropped it and each later row started a byte early, shearing the picture; (36) a stream with no `endstream` left after it is the bytes its `/Length` gives, "how many bytes of the PDF file are used for the stream's data" (ISO 32000-2 7.3.8.2), when the file holds that many (`parse_declared`: first, before the search for `endstream`, when the `/Length` ends before a whole `endstream` token, or a whole `endstrea` or `endobj` token after which the object ends too (the end of the data, another object's `N G obj` header, `xref`, `trailer` or `startxref`: not payload such as `endobject` or `endobj more`, ISO 32000-2 7.2.3), or at the end of the data, so the search can't run on into a later object's stream; then after the search finds none; `parse_proper` and the search for `endstream` take only a whole token, not `endstreamer`): a producer that writes `endstrea` after every stream lost every font and page content, and its pages drew blank while other readers draw them; (37) a document that encrypts only its embedded files, authorised when one is opened (`/AuthEvent /EFOpen`, ISO 32000-2 §7.6.6, Table 25: every encrypting crypt filter is EFOpen, `/EFF` names one, `/StmF` and `/StrF` don't), opens without a password with the pass-through decryptor: its strings and streams are in the clear and nothing drawn reads an embedded file; (38) a page box that encloses no area is read as a missing one: a `/MediaBox` without area (`[0 0 0 0]`) as missing (an inherited one with area, else the default page, US Letter since patch 44), and a `/CropBox` without area, or with none in common with the media box, as missing (an inherited one, else the media box; ISO 32000-2 §14.11.2, Table 33); kept, the visible region had no area, so nothing was drawn and no text extracted (pdf.js `boundingBox_invalid`); (40) the last Flate filter of an image whose PNG predictor (`/Predictor` 10–15) its writer declared but never applied gives the image's samples as they are: when the inflated data is exactly `/Height` rows of the predictor's row length with no filter-type byte before each (where predicted rows would need one more byte each, ISO 32000-2 §7.4.4.4), `untagged_png_rows` takes it for unpredicted samples and reports it (`warn!`), as PDFium, MuPDF and Poppler read it; read with the predictor, each row's first sample was taken for a filter type and the image came out a row short and shifted, drawn in fragments (PDFBOX-3932). `Filter::apply` is given the image's rows for its last filter only; any other length is predicted as before; (41) CCITT `/Rows` above the image's `/Height` decodes to the height too, so the decoder is never asked for more rows than the image has (ISO 32000-2 Table 87): a scan with `/Rows 1084975104` on 2,592 columns had the size check refuse every page, and all 17 drew blank (PDFBOX-771); `/Rows` still counts for a stream decoded without an image's height; (42) TIFF predictor 2 on 8- and 16-bit samples (`lzw_flate::undo_tiff_bytes`) is undone a byte row at a time on slices, each sample added to the same component of the pixel to its left, wrapping at the sample's width (16-bit samples big-endian), instead of through the bit-level readers 1-, 2- and 4-bit samples still need; the bytes are those the bit-level path wrote, and a partial last row is still dropped. A page of 45 full-page 2445 × 4724 8-bit grey images so predicted (PDFBOX-1350) took about 23 s to render at 96 dpi and now takes about 4 s, with the same pixels; (43) a last update cut off before its trailer (the last `startxref` more than 4 KiB from the end of the file, as `pdfcraft-cos` judges the footer, with `N G obj` headers after it: `cut_off_update_follows`) is read by rebuilding the table from object headers (`Pdf::new_with_password` calls `fallback` first, after the table the last `startxref` names has refused a wrong password, and takes the rebuilt table only when it is encrypted exactly when that one is), the latest definition of each object winning, as `pdfcraft-cos` reads such a file; the older table the last `startxref` names is read only when the rebuilt table has no page (a file cut short inside the update, whose new page tree names pages that are not there). The renderer had shown the older revision while the document model read the newer one (PDFBOX-3934: 12 pages against 13; ISO 32000-2 §7.5.6). A `startxref` near the end, or one followed only by data that holds no object header, is read as before; (44) a page with no `/MediaBox`, its own or inherited, or one without area (`[0 0 0 0]`, which now counts as missing, so the page is placed and clipped by the region it is sized by and its content shows), is US Letter (`LETTER`, 612 × 792 pt), not A4, and so is the `base_dimensions` fallback for a visible region without area: ISO 32000-2 Table 31 requires the box and gives no default, other readers use Letter, and PdfCraft's page model and inspector already did (PDFBOX-4001); (45) `root_xref`: when the newest cross-reference section names no earlier one (no `/Prev`, ISO 32000-2 §7.5.6, §7.5.8.2; a hybrid section's `/XRefStm` stream belongs to the same update and doesn't count, §7.5.8.4), the file holds another `startxref`, and the catalog's `/Pages` can't be read, the table is rebuilt by scanning the file (`XRef::repair`) before the page tree is read, so the cut-off page tree is found instead of the page dictionaries `Pages::new_brute_force` turns up (the signed files of PDFBOX-2720 and PDFBOX-2942 showed 2 blank pages for 1, 10, 13 and 1754); `Pdf::rebuilt_unlinked_update` says so, and `pdfcraft-cos` rebuilds under the same conditions | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content`; (29) `raster::tests::jbig2_globals_that_are_jbig2_themselves_are_not_decoded`, `raster::tests::jbig2_globals_are_read`, `raster::tests::the_jbig2_images_of_a_page_share_one_allowance`, `raster::tests::an_image_that_fails_spends_the_pages_allowance_too`; (31) `jbig2_limited`: `raster::tests::a_picture_whose_jbig2_mask_a_decoder_limit_refuses_is_not_drawn`, `raster::tests::a_limit_refusal_says_nothing_of_the_next_image`, `raster::tests::failed_image_decodes::a_picture_whose_jbig2_mask_is_refused_for_its_work_is_decoded_at_every_draw`; (30) `raster::tests::a_stream_with_a_crypt_filter_of_its_own_is_drawn`; (32) `raster::tests::a_decode_array_with_references_in_it_is_read`, `raster::tests::a_functions_arrays_can_start_with_a_reference` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret); (33) `raster::tests::a_reference_to_a_reference_is_what_it_names`, `raster::tests::a_decode_array_with_references_in_it_is_read` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret), `xref::tests::an_object_stream_isnt_reached_through_a_reference`, `xref::tests::a_chain_of_object_streams_ends_at_the_limit_of_nested_loads`, `xref::tests::a_chain_of_object_streams_takes_no_more_work_for_two_ways_on`, `xref::tests::a_reference_held_in_either_storage_is_followed`, `xref::tests::a_page_a_reference_is_held_to_is_found_once` (hayro-syntax); (34) `raster::tests::a_rebuilt_table_finds_an_object_whose_header_names_another_generation`, `raster::tests::a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object` (pdfcraft-render), `xref::tests::an_object_stream_and_its_first_member_are_both_enumerated` (hayro-syntax); (35) `filter::lzw_flate::pdfcraft_png_predictor_tests` (hayro-syntax: every filter type at 1–16 bits and 1–4 colours against the PNG specification's byte-by-byte definition, a row ending part-way through a pixel, Average and Paeth over 6-byte pixels), `raster::tests::png_predicted_images::a_four_bit_rgb_image_of_odd_width_with_up_predicted_rows_is_not_sheared`; (36) `raster::tests::a_content_stream_without_endstream_is_drawn_to_its_length`, `raster::tests::a_content_stream_without_endstream_is_not_read_into_a_later_stream`, `raster::tests::hayro_reads_a_stream_without_endstream_to_its_length_before_a_later_one`, `raster::tests::hayro_does_not_end_a_stream_inside_a_longer_word` (pdfcraft-render); (37) `inspect::tests::a_document_encrypting_only_its_embedded_files_opens_without_a_password`; (38) `text::tests::text_on_a_page_whose_box_has_no_area_is_extracted` (pdfcraft-render); (40) `filter::lzw_flate::pdfcraft_png_predictor_tests::an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples`, `an_image_whose_rows_carry_png_tags_still_has_its_predictor_undone`, `data_of_neither_length_decodes_as_it_did`, `rows_of_no_bytes_or_of_more_than_memory_holds_do_not_panic` (hayro-syntax), `raster::tests::png_predicted_images::an_image_and_soft_mask_whose_rows_carry_no_png_tags_draw_their_samples`, `an_image_one_byte_short_of_untagged_rows_still_goes_through_the_predictor`; (41) `raster::tests::group4_fax_with_rows_past_its_height_decodes_to_the_image_height`; (42) `filter::lzw_flate::pdfcraft_tiff_predictor_tests` (hayro-syntax: random 8- and 16-bit rows at 1–7 colours and 1–50 columns against the bit-level path, partial and empty rows, and a row counter showing whole-byte samples skip the bit-level path), `raster::tests::tiff_predicted_images`; (43) `raster::tests::an_update_cut_off_before_its_trailer_shows_its_pages_as_the_model_reads_them`, `raster::tests::a_complete_update_reads_as_before`, `raster::tests::trailing_data_without_objects_reads_as_before`, `raster::tests::a_short_cut_off_update_reads_as_before`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_delimiter_is_rebuilt`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_comment_is_rebuilt`, `raster::tests::trailing_data_with_an_object_header_reads_as_the_model_reads_it`, `raster::tests::an_update_cut_off_before_its_new_pages_keeps_the_older_table`, `raster::tests::an_encrypted_file_with_a_cut_off_update_still_needs_its_password`, `raster::tests::a_rebuild_whose_trailer_lacks_the_encryption_dictionary_is_not_taken` (pdfcraft-render); (44) `raster::tests::a_page_without_a_media_box_is_letter`, `raster::tests::raw_crop_unit_floor_preserves_nearly_zero_fallback` (pdfcraft-render), `pdfcraft-model::tests::{a_page_without_a_media_box_is_letter, a_page_whose_media_box_has_no_area_is_letter}`; (45) `inspect::core::unlinked_update_tests::an_update_without_prev_shows_the_page_tree_and_says_it_was_rebuilt`, `inspect::core::unlinked_update_tests::a_hybrid_update_without_prev_is_rebuilt_as_the_document_model_rebuilds_it` (pdfcraft-render) | +| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260); (29) a `/JBIG2Globals` stream that is itself JBIG2 isn't decoded: globals are raw segments, and a chain of 16,000 such streams overflowed the stack, which aborts the process; (30) a stream's own crypt filter: `/Crypt` in its chain read as the filter it names, `/Identity` without one, instead of the document's filter and then a filter that can't be decoded, which left such a stream unreadable in any spelling (ISO 32000-2 §7.4.10); (31) `set_page_jbig2_work`: the JBIG2 images decoded on a thread spend one allowance, set per page, 2^30 steps (`MAX_PAGE_JBIG2_WORK`), so a page of many images made to reach their own limit stops at one, and what they cost to read counts, whether they decode or not, and `jbig2_limited` says whether the image decoded last on the thread was refused by one of the decoder's limits rather than its data, and `jbig2_limited_by_stream` whether that limit is one the stream reaches by itself rather than its decoding work, which may be the page's; `clear_jbig2_limited` and each new page forget it; unbounded until a page sets it; (32) a group of array items read together (a tuple: an image's `/Decode`, `/W`, `/W2`, and a function's `/Domain`, `/Range`, `/Encode` and `/Decode`) can start with a reference: it was taken for the whole group and lost, which ended the array, so an image with `/Decode [7 0 R 0]` didn't draw and CID widths fell back to `/DW`; (33) an object that holds only a reference stands for what that names, stored on its own or in an object stream, up to 32 references: read as a number it was the reference's own object number, so a `/Decode` or `/W` entry naming such an object took a wrong value, and as anything else it was lost. Past 32, as any cycle goes, it reads as a missing object. An object stream isn't reached that way, as its checks are of the object named; reading its index counts against the 64 nested loads and reads its dictionary alone, as a chain of them, each with a member of the next for its `/N`, `/First` or `/Length`, ran out of stack; and a comment inside a reference counts as white space; (34) a table rebuilt by scanning the file (`fallback_xref_map`) finds an object by its number when its header names another generation, including one no generation may be (`3 18446744073709551616 obj` in `poppler-85140-0.pdf`, #5580): the header is read leniently only in that scan (`read_object_header`), the object is also filed under generation 0 unless a real `N 0 obj` holds that key (a later header for the number moves the stand-in), `XRef::get_with` matches by object number only in a repaired table, and `XRef::objects` yields each location once; (35) PNG predictors (`lzw_flate::unfilter_png`) are undone a byte row at a time on slices, as the PNG filters are defined, instead of through the bit-level readers TIFF predictors need: a 993 × 936 RGB image took about 63 ms to unfilter whatever its row filters, and now takes about 3 ms (Up) to 16 ms (Paeth) in a release build (#5430); a row ending part-way through a pixel (three 4-bit samples, an odd width) keeps its last byte, where the bit-level readers dropped it and each later row started a byte early, shearing the picture; (36) a stream with no `endstream` left after it is the bytes its `/Length` gives, "how many bytes of the PDF file are used for the stream's data" (ISO 32000-2 7.3.8.2), when the file holds that many (`parse_declared`: first, before the search for `endstream`, when the `/Length` ends before a whole `endstream` token, or a whole `endstrea` or `endobj` token after which the object ends too (the end of the data, another object's `N G obj` header, `xref`, `trailer` or `startxref`: not payload such as `endobject` or `endobj more`, ISO 32000-2 7.2.3), or at the end of the data, so the search can't run on into a later object's stream; then after the search finds none; `parse_proper` and the search for `endstream` take only a whole token, not `endstreamer`): a producer that writes `endstrea` after every stream lost every font and page content, and its pages drew blank while other readers draw them; (37) a document that encrypts only its embedded files, authorised when one is opened (`/AuthEvent /EFOpen`, ISO 32000-2 §7.6.6, Table 25: every encrypting crypt filter is EFOpen, `/EFF` names one, `/StmF` and `/StrF` don't), opens without a password with the pass-through decryptor: its strings and streams are in the clear and nothing drawn reads an embedded file; (38) a page box that encloses no area is read as a missing one: a `/MediaBox` without area (`[0 0 0 0]`) as missing (an inherited one with area, else the default page, US Letter since patch 44), and a `/CropBox` without area, or with none in common with the media box, as missing (an inherited one, else the media box; ISO 32000-2 §14.11.2, Table 33); kept, the visible region had no area, so nothing was drawn and no text extracted (pdf.js `boundingBox_invalid`); (40) the last Flate filter of an image whose PNG predictor (`/Predictor` 10–15) its writer declared but never applied gives the image's samples as they are: when the inflated data is exactly `/Height` rows of the predictor's row length with no filter-type byte before each (where predicted rows would need one more byte each, ISO 32000-2 §7.4.4.4), `untagged_png_rows` takes it for unpredicted samples and reports it (`warn!`), as PDFium, MuPDF and Poppler read it; read with the predictor, each row's first sample was taken for a filter type and the image came out a row short and shifted, drawn in fragments (PDFBOX-3932). `Filter::apply` is given the image's rows for its last filter only; any other length is predicted as before; (41) CCITT `/Rows` above the image's `/Height` decodes to the height too, so the decoder is never asked for more rows than the image has (ISO 32000-2 Table 87): a scan with `/Rows 1084975104` on 2,592 columns had the size check refuse every page, and all 17 drew blank (PDFBOX-771); `/Rows` still counts for a stream decoded without an image's height; (42) TIFF predictor 2 on 8- and 16-bit samples (`lzw_flate::undo_tiff_bytes`) is undone a byte row at a time on slices, each sample added to the same component of the pixel to its left, wrapping at the sample's width (16-bit samples big-endian), instead of through the bit-level readers 1-, 2- and 4-bit samples still need; the bytes are those the bit-level path wrote, and a partial last row is still dropped. A page of 45 full-page 2445 × 4724 8-bit grey images so predicted (PDFBOX-1350) took about 23 s to render at 96 dpi and now takes about 4 s, with the same pixels; (43) a last update cut off before its trailer (the last `startxref` more than 4 KiB from the end of the file, as `pdfcraft-cos` judges the footer, with `N G obj` headers after it: `cut_off_update_follows`) is read by rebuilding the table from object headers (`Pdf::new_with_password` calls `fallback` first, after the table the last `startxref` names has refused a wrong password, and takes the rebuilt table only when it is encrypted exactly when that one is), the latest definition of each object winning, as `pdfcraft-cos` reads such a file; the older table the last `startxref` names is read only when the rebuilt table has no page (a file cut short inside the update, whose new page tree names pages that are not there). The renderer had shown the older revision while the document model read the newer one (PDFBOX-3934: 12 pages against 13; ISO 32000-2 §7.5.6). A `startxref` near the end, or one followed only by data that holds no object header, is read as before; (44) a page with no `/MediaBox`, its own or inherited, or one without area (`[0 0 0 0]`, which now counts as missing, so the page is placed and clipped by the region it is sized by and its content shows), is US Letter (`LETTER`, 612 × 792 pt), not A4, and so is the `base_dimensions` fallback for a visible region without area: ISO 32000-2 Table 31 requires the box and gives no default, other readers use Letter, and PdfCraft's page model and inspector already did (PDFBOX-4001); (45) `root_xref`: when the newest cross-reference section names no earlier one (no `/Prev`, ISO 32000-2 §7.5.6, §7.5.8.2; a hybrid section's `/XRefStm` stream belongs to the same update and doesn't count, §7.5.8.4), the file holds another `startxref`, and the catalog's `/Pages` can't be read, the table is rebuilt by scanning the file (`XRef::repair`) before the page tree is read, so the cut-off page tree is found instead of the page dictionaries `Pages::new_brute_force` turns up (the signed files of PDFBOX-2720 and PDFBOX-2942 showed 2 blank pages for 1, 10, 13 and 1754); `Pdf::rebuilt_unlinked_update` says so, and `pdfcraft-cos` rebuilds under the same conditions; (46) a dictionary or array item that the first pass skips as a number but no number is read from (a lone `+` or `++`, ISO 32000-2 §7.3.3) is unreadable like any other malformed value: `Dict::entries` and `Dict`'s `Debug` leave the entry out, as `Dict::get` already did, and `Array::raw_iter` and `Array::iter` read it as null in its slot (§7.3.9), where `entries`, `Debug` and `raw_iter` unwrapped the failed read and panicked and `iter` ended there and dropped the items after it; a typed read (`iter::`) still ends at it | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content`; (29) `raster::tests::jbig2_globals_that_are_jbig2_themselves_are_not_decoded`, `raster::tests::jbig2_globals_are_read`, `raster::tests::the_jbig2_images_of_a_page_share_one_allowance`, `raster::tests::an_image_that_fails_spends_the_pages_allowance_too`; (31) `jbig2_limited`: `raster::tests::a_picture_whose_jbig2_mask_a_decoder_limit_refuses_is_not_drawn`, `raster::tests::a_limit_refusal_says_nothing_of_the_next_image`, `raster::tests::failed_image_decodes::a_picture_whose_jbig2_mask_is_refused_for_its_work_is_decoded_at_every_draw`; (30) `raster::tests::a_stream_with_a_crypt_filter_of_its_own_is_drawn`; (32) `raster::tests::a_decode_array_with_references_in_it_is_read`, `raster::tests::a_functions_arrays_can_start_with_a_reference` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret); (33) `raster::tests::a_reference_to_a_reference_is_what_it_names`, `raster::tests::a_decode_array_with_references_in_it_is_read` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret), `xref::tests::an_object_stream_isnt_reached_through_a_reference`, `xref::tests::a_chain_of_object_streams_ends_at_the_limit_of_nested_loads`, `xref::tests::a_chain_of_object_streams_takes_no_more_work_for_two_ways_on`, `xref::tests::a_reference_held_in_either_storage_is_followed`, `xref::tests::a_page_a_reference_is_held_to_is_found_once` (hayro-syntax); (34) `raster::tests::a_rebuilt_table_finds_an_object_whose_header_names_another_generation`, `raster::tests::a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object` (pdfcraft-render), `xref::tests::an_object_stream_and_its_first_member_are_both_enumerated` (hayro-syntax); (35) `filter::lzw_flate::pdfcraft_png_predictor_tests` (hayro-syntax: every filter type at 1–16 bits and 1–4 colours against the PNG specification's byte-by-byte definition, a row ending part-way through a pixel, Average and Paeth over 6-byte pixels), `raster::tests::png_predicted_images::a_four_bit_rgb_image_of_odd_width_with_up_predicted_rows_is_not_sheared`; (36) `raster::tests::a_content_stream_without_endstream_is_drawn_to_its_length`, `raster::tests::a_content_stream_without_endstream_is_not_read_into_a_later_stream`, `raster::tests::hayro_reads_a_stream_without_endstream_to_its_length_before_a_later_one`, `raster::tests::hayro_does_not_end_a_stream_inside_a_longer_word` (pdfcraft-render); (37) `inspect::tests::a_document_encrypting_only_its_embedded_files_opens_without_a_password`; (38) `text::tests::text_on_a_page_whose_box_has_no_area_is_extracted` (pdfcraft-render); (40) `filter::lzw_flate::pdfcraft_png_predictor_tests::an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples`, `an_image_whose_rows_carry_png_tags_still_has_its_predictor_undone`, `data_of_neither_length_decodes_as_it_did`, `rows_of_no_bytes_or_of_more_than_memory_holds_do_not_panic` (hayro-syntax), `raster::tests::png_predicted_images::an_image_and_soft_mask_whose_rows_carry_no_png_tags_draw_their_samples`, `an_image_one_byte_short_of_untagged_rows_still_goes_through_the_predictor`; (41) `raster::tests::group4_fax_with_rows_past_its_height_decodes_to_the_image_height`; (42) `filter::lzw_flate::pdfcraft_tiff_predictor_tests` (hayro-syntax: random 8- and 16-bit rows at 1–7 colours and 1–50 columns against the bit-level path, partial and empty rows, and a row counter showing whole-byte samples skip the bit-level path), `raster::tests::tiff_predicted_images`; (43) `raster::tests::an_update_cut_off_before_its_trailer_shows_its_pages_as_the_model_reads_them`, `raster::tests::a_complete_update_reads_as_before`, `raster::tests::trailing_data_without_objects_reads_as_before`, `raster::tests::a_short_cut_off_update_reads_as_before`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_delimiter_is_rebuilt`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_comment_is_rebuilt`, `raster::tests::trailing_data_with_an_object_header_reads_as_the_model_reads_it`, `raster::tests::an_update_cut_off_before_its_new_pages_keeps_the_older_table`, `raster::tests::an_encrypted_file_with_a_cut_off_update_still_needs_its_password`, `raster::tests::a_rebuild_whose_trailer_lacks_the_encryption_dictionary_is_not_taken` (pdfcraft-render); (44) `raster::tests::a_page_without_a_media_box_is_letter`, `raster::tests::raw_crop_unit_floor_preserves_nearly_zero_fallback` (pdfcraft-render), `pdfcraft-model::tests::{a_page_without_a_media_box_is_letter, a_page_whose_media_box_has_no_area_is_letter}`; (45) `inspect::core::unlinked_update_tests::an_update_without_prev_shows_the_page_tree_and_says_it_was_rebuilt`, `inspect::core::unlinked_update_tests::a_hybrid_update_without_prev_is_rebuilt_as_the_document_model_rebuilds_it` (pdfcraft-render); (46) `hayro_sign_tokens` (pdfcraft-content: dictionary and array cases, and every sign-led token of up to five characters in each position) | | winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, non-repeated first key whose one callback inserts that same jamo, with IME enabled and nothing composed, focus and input source unchanged, is retried (`ime_startup.rs`). Port of [winit#4744](https://github.com/rust-windowing/winit/pull/4744), with its policy tests.; (11) on X11 without `Xft.dpi`, the scale factor comes from the X screen's configured DPI (its size in pixels and millimetres) before the output's physical density from RandR: Xorg can deliberately run a dense panel at 96 DPI, and only winit applications then looked zoomed; `Xft.dpi` still wins, `WINIT_X11_SCALE_FACTOR` still overrides, and a screen reporting no size keeps the RandR fallback. PdfCraft patch (#1150, replacing the launcher pin proposed in #908). (12) on macOS, `WinitView` answers `mouseDownCanMoveWindow` with the window's `movable_by_window_background` attribute (NO unless asked): NSView answers YES for a view that isn't opaque, so with the transparent title bar and full-size content view PdfCraft uses, AppKit moved the window for any drag that began in the 28 pt title-bar band before the app saw it, and document tabs (which live in that band) could not be dragged to reorder them. The empty strip still moves the window through `ViewportCommand::StartDrag`. PdfCraft patch. The published crate's asset files (`docs/res/*.svg`, `examples/data/*.png`) are left out, so its `window` example doesn't build; (13) on Wayland, pixel-only wheel, wheel-tilt and continuous-source scroll events report `Moved` rather than starting an unterminated finger gesture, so egui follows modifier release instead of keeping Ctrl zoom latched (#991). Finger gestures and unknown sources retain their existing phase policy | (1) `pdfcraft` `tests::winit_carries_the_windows_11_monitor_scale_fix` keeps the patch in the build; the drag itself needs two monitors with different scale factors on Windows 11; (2) `pdfcraft` `tests/winit_wayland_text_input.rs`; the capability change itself needs a Wayland session and an input method; (3) `pdfcraft` `tests/winit_windows_ime_cursor.rs`; composing itself needs the Microsoft Korean IME; (4) `pdfcraft` `tests/winit_windows_hidden_maximized.rs`; the start-up itself needs Windows and a window that was closed maximized; (5) `pdfcraft` `tests/winit_x11_ime_focus.rs`; switching fields itself needs an X11 session and an input method (IBus, fcitx5); (6) `pdfcraft` `tests/winit_macos_ime_commit.rs`; composing itself needs macOS and an input method; (7) `pdfcraft` `tests/winit_macos_ime_discard.rs`; composing itself needs macOS and an input method; (8) `pdfcraft` `tests/winit_macos_emoji_picker.rs`; the picker itself needs macOS; (9) `pdfcraft` `tests/winit_macos_korean_space.rs`; composing itself needs macOS and Apple Korean; (10) `pdfcraft` `tests/winit_macos_korean_first_key.rs` and `ime_startup.rs`'s own tests (run them with `rustc --test`); typing itself needs macOS and Apple Korean; (11) `pdfcraft` `tests/winit_x11_dpi.rs` keeps the patch in the build, and `util::randr` tests the policy (run them in the vendored crate); the scale itself needs an X11 session; (12) `pdfcraft` `tests/winit_macos_title_bar_drag.rs` keeps the patch in the build; the drag itself needs macOS and a pointer; (13) `pdfcraft` `tests/winit_wayland_scroll.rs` compiles the production phase policy and exercises modifier release through egui; live COSMIC confirmation remains open | | egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure | | vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical; (2) `StripStorage::room_for_path{,_within}`: whether one more path's coverage (at most the whole surface, counted twice) still fits below 2^31 values, the most a strip's packed alpha index reaches (`Strip::new` asserts it), or below a smaller limit; (4) `flatten::stroke`: when kurbo 0.13.1's stroker returns an outline containing NaN, which `fill` would drop whole, the path is stroked again from a copy (`robust_for_stroking`, one element out per element in) in which each curve whose control points lie within the stroke tolerance of its chord is a line (the #4907 fix, a nearly straight cubic given a NaN join, kurbo issues #617 and #519; its row here was lost in a merge and is restored with this entry) and each cubic whose second control point is its end point, as `y` builds (ISO 32000-2 §8.5.2.1 Table 58), has that control point moved the tolerance towards its first (`open_zero_end_handle`; the curve moves by at most 4/9 of the tolerance): kurbo's cusp search on such a curve's offset can stop on the end point, where the derivative is zero, and normalising it gives NaN, so at 16, 32 and 63 pt a two-curve `y` path drew nothing and a file in the PDFBox tracker lost its 32 pt "XX" outline. Only an exact zero triggers it (none of 192,000 random strokes with a handle 1e-9 long, nor of 256,000 `v` strokes, came back with NaN; 1,073 of 192,000 random `y`/`v` strokes at 1–64 pt did before and none after). A finite outline takes the old path unchanged | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate; (2) `strip_generator::pdfcraft_tests::strips_have_room_until_a_surface_short_of_the_limit`; (4) `flatten::tests::a_tiny_degenerate_cubic_does_not_drop_the_stroke` and the render crate's `stroke_degenerate_cubic` fail without the near-line replacement, `flatten::tests::a_wide_stroke_of_a_curve_with_a_zero_end_tangent_is_drawn` (widths 1–64, every join and cap, `y` and the mirrored `v`) and the render crate's `stroke_zero_end_tangent` fail without the moved control point; `a_finite_outline_is_stroked_as_before` and `a_path_with_nan_is_still_dropped` pass either way | diff --git a/vendor/hayro-syntax/src/object/array.rs b/vendor/hayro-syntax/src/object/array.rs index fb136e867a..6bb9876e67 100644 --- a/vendor/hayro-syntax/src/object/array.rs +++ b/vendor/hayro-syntax/src/object/array.rs @@ -2,7 +2,7 @@ use crate::object::macros::object; use crate::object::r#ref::MaybeRef; -use crate::object::{FromBytes, Object, ObjectLike}; +use crate::object::{FromBytes, Null, Object, ObjectLike}; use crate::reader::Reader; use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable}; use alloc::vec::Vec; @@ -129,18 +129,37 @@ impl<'a> Iterator for ArrayIter<'a> { self.reader.skip_white_spaces_and_comments(); if !self.reader.at_end() { - // Objects are already guaranteed to be valid. - let item = self + // PdfCraft patch (46): the first pass validated each item by skipping it, but a lone + // sign (`+`, `++`) is skipped as a number and no number is read from it. Such an item + // reads as null in its slot instead of unwrapping the failed read. + let start = self.reader.clone(); + if let Some(item) = self .reader .read_with_context::>>(&self.ctx) - .unwrap(); - return Some(item); + { + return Some(item); + } + self.reader = skip_unreadable_item(start, &self.ctx)?; + return Some(MaybeRef::NotRef(Object::Null(Null))); } None } } +/// PdfCraft patch (46): step over an array item at `start` that the first pass skipped but no +/// object is read from. `None` (end the iteration) if it can't be skipped or the skip makes no +/// progress, so a caller never loops. +fn skip_unreadable_item<'a>(mut start: Reader<'a>, ctx: &ReaderContext<'a>) -> Option> { + let from = start.offset(); + if ctx.in_content_stream() { + start.skip::>(true)?; + } else { + start.skip::>>(false)?; + } + (start.offset() > from).then_some(start) +} + /// An iterator over the array that resolves objects of a specific type. pub struct ResolvedArrayIter<'a, T> { flex_iter: FlexArrayIter<'a>, @@ -197,9 +216,24 @@ impl<'a> FlexArrayIter<'a> { return self.reader.read_with_context::(&self.ctx); } - return match self.reader.read_with_context::>(&self.ctx)? { - MaybeRef::Ref(r) => self.ctx.xref().get_with::(r.into(), &self.ctx), - MaybeRef::NotRef(i) => Some(i), + let start = self.reader.clone(); + return match self.reader.read_with_context::>(&self.ctx) { + Some(MaybeRef::Ref(r)) => self.ctx.xref().get_with::(r.into(), &self.ctx), + Some(MaybeRef::NotRef(i)) => Some(i), + // PdfCraft patch (46): an item no object is read from (a lone sign such as `+`) + // reads as null in its slot, as in `raw_iter`, instead of ending the iteration + // and losing the items after it. An object of another type still ends it. + None => { + let mut probe = start.clone(); + if probe + .read_with_context::>>(&self.ctx) + .is_some() + { + return None; + } + self.reader = skip_unreadable_item(start, &self.ctx)?; + Object::Null(Null).cast::() + } }; } diff --git a/vendor/hayro-syntax/src/object/dict.rs b/vendor/hayro-syntax/src/object/dict.rs index 1e016b567e..8578fd2579 100644 --- a/vendor/hayro-syntax/src/object/dict.rs +++ b/vendor/hayro-syntax/src/object/dict.rs @@ -100,9 +100,12 @@ impl<'a> Dict<'a> { pub fn entries(&self) -> impl Iterator, MaybeRef>)> + '_ { let mut sorted_keys = self.keys().collect::>(); sorted_keys.sort_by(|n1, n2| n1.as_ref().cmp(n2.as_ref())); - sorted_keys.into_iter().map(|k| { - let obj = self.get_raw(k.deref()).unwrap(); - (k, obj) + // PdfCraft patch (46): an entry whose value the first pass skipped but no object is read + // from (a lone sign such as `+` or `++`) is left out, as `get` leaves it unread, rather + // than unwrapping the failed read. + sorted_keys.into_iter().filter_map(|k| { + let obj = self.get_raw(k.deref())?; + Some((k, obj)) }) } @@ -163,11 +166,13 @@ impl Debug for Dict<'_> { for (key, val) in offsets { r.jump(*val); - debug_struct.field( - &format!("{:?}", key.as_str()), - &r.read_with_context::>>(&ReaderContext::dummy()) - .unwrap(), - ); + // PdfCraft patch (46): an entry no object is read from is left out, as in + // `entries`, instead of unwrapping the failed read. + if let Some(value) = + r.read_with_context::>>(&ReaderContext::dummy()) + { + debug_struct.field(&format!("{:?}", key.as_str()), &value); + } } } Ok(()) From 503a19467f2cc760ec81a599845d377a641f0006 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:21:51 +0800 Subject: [PATCH 05/21] M7: a form edit reads the document's fields once (form.fill-text) The fields of a document are kept with the state they were read from (pdfcraft_cos::ReadState), and a document that still reads as that state gets a copy instead of a new walk. One value edit read them four times on an AcroForm (fill, recalculate, refresh, display) and seven on a laid-out XFA form (plus the data sync twice and the scripts), mostly with nothing changed in between; it now walks them once, and twice on an XFA form (once more after its data is written). --- crates/engine/tests/form_edit_reads.rs | 107 +++++++++++++++++++++++++ crates/forms/README.md | 6 ++ crates/forms/src/lib.rs | 4 +- crates/forms/src/read.rs | 45 ++++++++--- crates/forms/src/tests.rs | 42 +++++++++- parity/acrobat-features.toml | 2 +- 6 files changed, 193 insertions(+), 13 deletions(-) create mode 100644 crates/engine/tests/form_edit_reads.rs diff --git a/crates/engine/tests/form_edit_reads.rs b/crates/engine/tests/form_edit_reads.rs new file mode 100644 index 0000000000..a746fe887f --- /dev/null +++ b/crates/engine/tests/form_edit_reads.rs @@ -0,0 +1,107 @@ +//! A form edit reads the document's fields once, however many the form holds: filling, +//! recalculating, the XFA data and the view each read them, mostly with nothing changed since +//! the step before, and on a form with a thousand fields each reading takes tens of milliseconds. +//! Counted, not timed: `form_reads_on_this_thread` counts the whole-form walks this thread made. + +use std::sync::Arc; + +use pdfcraft_engine::{DocId, Edit, FieldValue, Session}; +use pdfcraft_forms::form_reads_on_this_thread as form_reads; + +/// An AcroForm of `n` text fields `f0`…, fifty to a page. +fn acroform(n: usize) -> Vec { + let pages = n.div_ceil(50).max(1); + let first_page = 5; + let first_field = first_page + pages; + let refs = |from: usize, count: usize| (from..from + count).map(|i| format!("{i} 0 R")).collect::>().join(" "); + let mut objs = vec![ + "<< /Type /Catalog /Pages 2 0 R /AcroForm 3 0 R >>".to_string(), + format!("<< /Type /Pages /Kids [{}] /Count {pages} /MediaBox [0 0 612 792] >>", refs(first_page, pages)), + format!("<< /Fields [{}] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 4 0 R >> >> >>", refs(first_field, n)), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(), + ]; + for p in 0..pages { + let count = 50.min(n - p * 50); + objs.push(format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", refs(first_field + p * 50, count))); + } + for i in 0..n { + let (page, row) = (i / 50, i % 50); + let y = 760 - 15 * row; + objs.push(format!( + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (f{i}) /TU (Field {i}) /Rect [40 {} 300 {y}] /P {} 0 R /F 4 >>", + y - 12, + first_page + page + )); + } + 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 +} + +/// Fill `name` with `value`, returning how many times the fields were read for it. +fn fill(s: &mut Session, id: DocId, name: &str, value: &str) -> usize { + let before = form_reads(); + s.apply(id, Edit::SetFieldValue { name: name.into(), value: FieldValue::Text(value.into()) }).unwrap(); + form_reads() - before +} + +fn value(s: &Session, id: DocId, name: &str) -> Vec { + s.get(id).unwrap().form.iter().find(|f| f.name == name).unwrap().value.clone() +} + +#[test] +fn a_form_edit_reads_the_fields_once_however_many_the_form_holds() { + for n in [20, 600] { + let mut s = Session::new(); + let id = s.open("form.pdf", None, Arc::new(acroform(n)), None).unwrap(); + for k in 0..3 { + let name = format!("f{k}"); + assert_eq!(fill(&mut s, id, &name, &format!("value {k}")), 1, "{n} fields, edit {k}"); + assert_eq!(value(&s, id, &name), [format!("value {k}")]); + } + let shown = |s: &Session| s.get(id).unwrap().info.fields.iter().find(|f| f.name == "f2").and_then(|f| f.value.clone()); + assert_eq!(shown(&s).as_deref(), Some("value 2")); + // Undo and redo read the restored state once each, and show it. + let before = form_reads(); + s.undo(id).unwrap(); + assert!(value(&s, id, "f2").is_empty()); + assert_eq!(shown(&s), None); + s.redo(id).unwrap(); + assert_eq!(value(&s, id, "f2"), ["value 2"]); + assert!(form_reads() - before <= 2, "{n} fields: undo and redo read {} times", form_reads() - before); + // The same value again changes nothing and still reads the form at most once. + assert!(fill(&mut s, id, "f2", "value 2") <= 1); + } +} + +/// A laid-out XFA form keeps its data in step with the fields as well: the edit reads them +/// once to fill and once after its data is written (its scripts read the fields), however many +/// fields the form holds. +#[test] +fn an_xfa_form_edit_reads_the_fields_a_fixed_number_of_times() { + let mut counts = Vec::new(); + for rows in [2, 60] { + let mut s = Session::new(); + let xdp = pdfcraft_xfa::fixtures::template(rows); + let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&xdp)), None).unwrap(); + let name = s.get(id).unwrap().form.iter().find(|f| f.name.contains("familyName")).unwrap().name.clone(); + let fields = s.get(id).unwrap().form.len(); + let reads: Vec = (0..3).map(|k| fill(&mut s, id, &name, &format!("Name {k}"))).collect(); + assert_eq!(value(&s, id, &name), ["Name 2"]); + counts.push((fields, reads)); + } + let [(small, a), (large, b)] = counts.as_slice() else { panic!("{counts:?}") }; + assert!(large > small, "{counts:?}"); + assert_eq!(a, b, "{counts:?}"); + assert!(a.iter().all(|&r| r <= 2), "{counts:?}"); +} diff --git a/crates/forms/README.md b/crates/forms/README.md index 67ca3b3bfb..73a25c503b 100644 --- a/crates/forms/README.md +++ b/crates/forms/README.md @@ -39,6 +39,12 @@ let cells: Vec = grid.cells_for(names)?; // "Table1_1", "Table ## Behaviour +- `fields` and `fields_with_adopted` keep their last reading on each thread with the state of the + document it read (`pdfcraft_cos::ReadState`, which any change to the document replaces), and + give a copy of it to a document that still reads as that state. A form edit reads the fields in + 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. - 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/lib.rs b/crates/forms/src/lib.rs index 414132b42b..c9b30c067e 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -43,9 +43,9 @@ mod values; pub use appearances::{FieldAppearanceCache, declares_pdfa, need_appearances, undrawn_fields, with_field_appearances, with_field_appearances_cached}; pub(crate) use read::page_refs; pub use read::selected_options; -pub use read::{Fields, acroform, adopted_page_fields, fields, fields_with_adopted}; +pub use read::{Fields, acroform, adopted_page_fields, fields, fields_with_adopted, form_reads_on_this_thread}; #[cfg(test)] -use read::{MAX_SCRIPT_BYTES, PageWalk, enumerate, form_reads}; +use read::{MAX_SCRIPT_BYTES, PageWalk, enumerate, form_reads_on_this_thread as form_reads}; use read::{first_by_export, script, script_budget}; pub use tab_order::{TabOrder, move_in_tab_order, set_tab_order, tab_orders}; #[cfg(test)] diff --git a/crates/forms/src/read.rs b/crates/forms/src/read.rs index 4a7904f620..f1025e5925 100644 --- a/crates/forms/src/read.rs +++ b/crates/forms/src/read.rs @@ -407,26 +407,53 @@ pub struct Fields { } /// Read all terminal fields and the page-only adoption count in one enumeration. +/// +/// The last reading on this thread is kept with the state of the document it read +/// ([`pdfcraft_cos::ReadState`], which every change to the document replaces), and a document +/// that still reads as that state gets a copy of it instead of a new walk. One form edit reads +/// the fields in several steps (filling, recalculating, the XFA data, the view), most of them +/// with nothing changed since the step before: on a form with a thousand fields each walk takes +/// tens of milliseconds. pub fn fields_with_adopted(doc: &Document) -> Fields { + let kept = LAST_READING + .try_with(|last| match last.try_borrow().as_deref() { + Ok(Some((state, fields))) if state.matches(doc) => Some(fields.clone()), + _ => None, + }) + .ok() + .flatten(); + if let Some(fields) = kept { + return fields; + } let (items, adopted_page_fields) = enumerate(doc); - Fields { items, adopted_page_fields } + let fields = Fields { items, adopted_page_fields }; + // Not kept (the thread is ending, or the slot is in use) costs only a later walk. + let _ = LAST_READING.try_with(|last| { + if let Ok(mut last) = last.try_borrow_mut() { + *last = Some((doc.read_state(), fields.clone())); + } + }); + fields } -#[cfg(test)] thread_local! { - /// Whole-form readings ([`enumerate`]) on this thread. + /// The last [`fields_with_adopted`] on this thread, with the state of the document it read. + /// One entry: one form's fields, and the objects that document had changed when it was read. + static LAST_READING: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Whole-form walks ([`enumerate`]) on this thread. static FORM_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// How many times this thread has read the whole form. -#[cfg(test)] -pub(crate) fn form_reads() -> usize { - FORM_READS.with(std::cell::Cell::get) +/// How many times this thread has walked a whole form: [`fields`] and the readings like it, but +/// not one answered from the last reading. Per thread, so tests running in parallel don't count +/// each other's; for tests that check how often an edit reads the form. +#[doc(hidden)] +pub fn form_reads_on_this_thread() -> usize { + FORM_READS.try_with(std::cell::Cell::get).unwrap_or(0) } pub(crate) fn enumerate(doc: &Document) -> (Vec, usize) { - #[cfg(test)] - FORM_READS.with(|n| n.set(n.get() + 1)); + let _ = FORM_READS.try_with(|n| n.set(n.get().saturating_add(1))); let af = acroform(doc); let mut page_of = std::collections::HashMap::new(); let mut annot_index = std::collections::HashMap::new(); diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index a2a87f3a73..f5b925816a 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -6029,7 +6029,8 @@ fn set_values_reads_the_form_once_not_per_value() { let before = form_reads(); assert!(set_values(&mut doc, &again).unwrap().iter().all(Result::is_ok)); let reads = form_reads() - before; - assert_eq!(reads, 3, "one to fill, one when f0 comes again, one to recalculate"); + // Filling starts from the reading the check above made, nothing having changed since. + assert_eq!(reads, 2, "one when f0 comes again, one to recalculate"); } /// Redrawing every field of a large form reads the form once, not once per field: a laid out XFA @@ -6060,6 +6061,45 @@ fn redraw_fields_reads_the_form_once_however_many_fields_it_holds() { } } +/// The fields of a document that has not changed since they were last read are not read again, +/// and any change, a clone's state or another document reads afresh: a form edit reads them in +/// several steps, most with nothing changed in between. +#[test] +fn fields_are_read_again_only_after_the_document_changes() { + let objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), + "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(), + "<< /Fields [5 0 R] /DA (/Helv 10 Tf 0 g) >>".into(), + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (old) /Rect [50 10 250 30] /P 3 0 R >>".into(), + ]; + let value = |doc: &Document| field(&fields(doc), "name").value.clone(); + let mut doc = document(&objs); + let before = form_reads(); + assert_eq!(value(&doc), ["old"]); + assert_eq!(value(&doc), ["old"]); + assert_eq!(fields_with_adopted(&doc).items, fields(&doc)); + assert_eq!(form_reads() - before, 1, "nothing changed: read once"); + let unchanged = doc.clone(); + doc.update_dict(ObjRef::new(5, 0), |d| d.set(b"V".to_vec(), Object::String(PdfString::text("new")))).unwrap(); + let before = form_reads(); + assert_eq!(value(&doc), ["new"], "an edit is read"); + assert_eq!(value(&unchanged), ["old"], "a copy kept from before it is read as it is"); + assert_eq!(value(&doc), ["new"]); + assert_eq!(form_reads() - before, 3); + // An object another field's value refers to counts as a change too. + let r = doc.add(Object::String(PdfString::text("indirect"))); + doc.update_dict(ObjRef::new(5, 0), |d| d.set(b"V".to_vec(), Object::Ref(r))).unwrap(); + assert_eq!(value(&doc), ["indirect"]); + doc.set(r, Object::String(PdfString::text("changed in place"))); + assert_eq!(value(&doc), ["changed in place"]); + // Another document with the same bytes is read, not given this one's fields. + let other = document(&objs); + let before = form_reads(); + assert_eq!(value(&other), ["old"]); + assert_eq!(form_reads() - before, 1); +} + /// A radio group `size` with the buttons Small (on), Medium and Large, a per-widget `/Opt`, and /// the group's buttons in the calculation order; and a text field `name` with two widgets. fn radio_group_form() -> Document { diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0cdbc3e856..000b4bdda0 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4638,7 +4638,7 @@ milestone = "M6" status = "shipped" commands = ["form.fields"] tools = ["form_fill", "form_fields"] -evidence = ["crates/ui-egui/tests/it/forms.rs::typing_into_a_text_field_and_tabbing_on", "crates/ui-egui/tests/it/forms.rs::auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box", "crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/engine/src/tests.rs::filling_a_form_shows_saves_and_undoes", "crates/automation/tests/it/automation.rs::orphan_form_fields_through_tools", "crates/forms/src/tests.rs::fields_sharing_a_name_take_the_same_value", "crates/ui-egui/tests/it/forms.rs::hovering_a_field_shows_its_tooltip", "crates/forms/src/tests.rs::zero_max_len_is_unlimited_and_overrides_inherited_limit", "crates/engine/src/tests.rs::password_field_values_are_kept_in_memory_but_written_to_no_file", "crates/forms/src/tests.rs::a_cleared_password_field_returns_to_its_default_value", "crates/forms/src/tests.rs::a_text_field_says_what_fits_it_as_its_appearance_draws_it", "crates/forms/src/tests.rs::an_edit_to_a_full_field_keeps_what_fits", "crates/ui-egui/tests/it/forms.rs::a_field_that_doesnt_scroll_stops_taking_text_when_full", "crates/ui-egui/tests/it/forms.rs::a_multi_line_auto_sized_field_that_doesnt_scroll_stops_when_full", "crates/engine/src/tests.rs::an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box", "crates/xfa/src/tests.rs::fields_that_dont_scroll_are_written_with_do_not_scroll", "crates/forms/src/tests.rs::comb_fields_show_their_cells", "crates/forms/src/tests.rs::thai_a_field_font_cannot_hold_is_drawn_from_the_thai_face", "crates/automation/tests/it/automation.rs::thai_in_fill_sign_text_comments_fields_and_page_marks_is_drawn_and_found"] +evidence = ["crates/ui-egui/tests/it/forms.rs::typing_into_a_text_field_and_tabbing_on", "crates/ui-egui/tests/it/forms.rs::auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box", "crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/engine/src/tests.rs::filling_a_form_shows_saves_and_undoes", "crates/automation/tests/it/automation.rs::orphan_form_fields_through_tools", "crates/forms/src/tests.rs::fields_sharing_a_name_take_the_same_value", "crates/ui-egui/tests/it/forms.rs::hovering_a_field_shows_its_tooltip", "crates/forms/src/tests.rs::zero_max_len_is_unlimited_and_overrides_inherited_limit", "crates/engine/src/tests.rs::password_field_values_are_kept_in_memory_but_written_to_no_file", "crates/forms/src/tests.rs::a_cleared_password_field_returns_to_its_default_value", "crates/forms/src/tests.rs::a_text_field_says_what_fits_it_as_its_appearance_draws_it", "crates/forms/src/tests.rs::an_edit_to_a_full_field_keeps_what_fits", "crates/ui-egui/tests/it/forms.rs::a_field_that_doesnt_scroll_stops_taking_text_when_full", "crates/ui-egui/tests/it/forms.rs::a_multi_line_auto_sized_field_that_doesnt_scroll_stops_when_full", "crates/engine/src/tests.rs::an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box", "crates/xfa/src/tests.rs::fields_that_dont_scroll_are_written_with_do_not_scroll", "crates/forms/src/tests.rs::comb_fields_show_their_cells", "crates/forms/src/tests.rs::thai_a_field_font_cannot_hold_is_drawn_from_the_thai_face", "crates/automation/tests/it/automation.rs::thai_in_fill_sign_text_comments_fields_and_page_marks_is_drawn_and_found", "crates/engine/tests/form_edit_reads.rs::a_form_edit_reads_the_fields_once_however_many_the_form_holds"] notes = "in-place editor; Thai the field's /DA font can't hold is drawn from the craft-fonts Thai face as Add text draws it (Type 3 glyphs with a ToUnicode map beside the field's font, /DA kept, no /NeedAppearances asked for; the ink of stacked marks and descenders kept inside the border, an automatic size shrinking for it), and refused, saying what to do, in a build without a Thai face (#2354); comb and list fields still draw Thai as `?`, marked; Enter or clicking away commits, Escape cancels; auto-size (0 Tf) fields shrink, and multiline ones wrap, the text being typed to fit the box, on screen as on the page (the screen measures in the interface font, so its size can be a little smaller than the page's Helvetica fit); fixed sizes are kept and clip, as in Acrobat; a field that doesn't scroll (DoNotScroll, ISO 32000-2 Table 228, and XFA's hScrollPolicy/vScrollPolicy=\"off\", written as it) takes no more text than its appearance shows, measured in the field's own font, padding and size (the smallest automatic size, 4 pt, for 0 Tf): typing into a full field adds nothing, and a paste or a replaced selection keeps what fits (form_fill isn't interactive and still takes any value); no format/keystroke JavaScript yet (M6.4); resting the pointer on any field shows its tooltip (/TU), as Acrobat does (#3854); imported MaxLen 0 permits text input and overrides inherited limits; positive limits remain enforced. A text field with the Password flag is saved as Acrobat saves it (#3926, black-box test): the typed value is written to no file (Save, Save As, Reduce File Size, recovery, Extract/Split/Combine, signing); the field gets back its default value (/DV) or is left empty, and its asterisks are redrawn from that value. /DV and the field's scripts stay. Known limits, which Acrobat shares: a script that copies the password into an ordinary field saves it there (Acrobat recalculates a Calculate copy on save, PdfCraft does not), and an incremental save leaves a password stored by an earlier revision in that revision. A comb field with a border colour shows its MaxLen cells as lines in that colour, in the appearances PdfCraft saves and in display-only ones (up to 500 cells)." [[feature]] From ae279a27f497700d2f6048a180f0bc2f5b4d9ca1 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:43:00 +0800 Subject: [PATCH 06/21] fix(tests): saves compared byte for byte don't fail when the clock crosses a second between them The three script-refusal tests built on reset_order_session save, run a refused edit or script, save again and compare the bytes. Each save stamps /ModDate from the system clock, so the comparison failed whenever the two saves fell in different seconds. The helper now pins the session clock with Session::with_clock, as session_with and the other byte-comparing tests do. --- crates/engine/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 91b00df4cc..0acf377f26 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -14188,7 +14188,8 @@ fn reset_order_session(reset: &str) -> (Session, DocId) { }) .unwrap(); let bytes = Arc::new(pdfcraft_cos::write_full(&cos, &Default::default()).unwrap()); - let mut s = Session::new(); + // Callers compare two saves byte for byte, and each save stamps `/ModDate`: pin the clock. + let mut s = Session::new().with_clock(|| 1_700_000_000); s.set_javascript(false); let id = s.open("reset-order.pdf", None, bytes, None).unwrap(); s.apply( From 50ed2e55da061411c656faa9be173828b13ec2f9 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:28:05 +0800 Subject: [PATCH 07/21] fix(hayro-syntax): a failed typed read leaves an unreadable array slot in place FlexArrayIter::next:: stepped over a lone-sign slot before finding that null is not a T, so a caller that then read the slot as another type got the item after it. The slot is now passed only when null is a T, as a value of another type is left in place. The sign-token tests also require the lone-sign fixtures to parse and check raw_iter's null slots directly. --- crates/content/tests/hayro_sign_tokens.rs | 33 +++++++++++++++++++++-- vendor/README.md | 2 +- vendor/hayro-syntax/src/object/array.rs | 10 ++++--- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/crates/content/tests/hayro_sign_tokens.rs b/crates/content/tests/hayro_sign_tokens.rs index f5fc9b67a7..a6ae471c82 100644 --- a/crates/content/tests/hayro_sign_tokens.rs +++ b/crates/content/tests/hayro_sign_tokens.rs @@ -6,11 +6,16 @@ //! token, dropping the items after it. Sign runs a number is read from (`-` reads as 0) keep //! reading as before. -use hayro_syntax::object::{Array, Dict, FromBytes, Number, Object}; +use hayro_syntax::object::{Array, Dict, FromBytes, MaybeRef, Number, Object}; /// Sign-only tokens, and two of them in a row. const SIGN_TOKENS: [&str; 8] = ["+", "++", "-", "--", "+-", "-+", "+ -", "+ +"]; +/// The lone signs the first pass accepts: a dictionary or array holding one must still parse. +fn must_parse(tok: &str) -> bool { + matches!(tok, "+" | "++") +} + /// Whether no number is read from this sign run, so it is the unreadable kind. fn unreadable(sign: &str) -> bool { Number::from_bytes(sign.as_bytes()).is_none() @@ -22,6 +27,7 @@ fn a_dictionary_leaves_out_an_entry_made_only_of_signs() { let src = format!("<< /A {tok} /B 7 >>"); let Some(dict) = Dict::from_bytes(src.as_bytes()) else { // Refused as a whole, as other unreadable dictionaries are: nothing to iterate. + assert!(!must_parse(tok), "{src} was refused"); continue; }; let entries: Vec<_> = dict.entries().map(|(k, _)| k.as_str().to_owned()).collect(); @@ -42,6 +48,7 @@ fn an_array_reads_a_token_made_only_of_signs_as_null_in_its_slot() { for tok in SIGN_TOKENS { let src = format!("[0 {tok} 7]"); let Some(array) = Array::from_bytes(src.as_bytes()) else { + assert!(!must_parse(tok), "{src} was refused"); continue; }; let signs = tok.split_whitespace().count(); @@ -51,11 +58,13 @@ fn an_array_reads_a_token_made_only_of_signs_as_null_in_its_slot() { assert_eq!(items.len(), signs + 2, "{src}"); assert_eq!(items.first().and_then(|o| o.clone().into_i32()), Some(0), "{src}"); assert_eq!(items.last().and_then(|o| o.clone().into_i32()), Some(7), "{src}"); - for (item, sign) in items.iter().skip(1).zip(tok.split_whitespace()) { + for ((item, raw), sign) in items.iter().zip(raw.iter()).skip(1).zip(tok.split_whitespace()) { if unreadable(sign) { assert!(matches!(item, Object::Null(_)), "{src}: {item:?}"); + assert!(matches!(raw, MaybeRef::NotRef(Object::Null(_))), "{src}: raw {raw:?}"); } else { assert!(matches!(item, Object::Number(_)), "{src}: {item:?}"); + assert!(matches!(raw, MaybeRef::NotRef(Object::Number(_))), "{src}: raw {raw:?}"); } } // A typed read still stops at a slot that is not a number, as at any other value. @@ -65,6 +74,26 @@ fn an_array_reads_a_token_made_only_of_signs_as_null_in_its_slot() { } } +/// A typed read that stops at an unreadable slot leaves the slot in place, as at a value of +/// another type, so the caller can read it as an object and go on to the items after it. +#[test] +fn a_failed_typed_read_leaves_the_unreadable_slot_in_place() { + for (src, stop) in [("[0 + 7]", "+"), ("[0 /N 7]", "/N")] { + let array = Array::from_bytes(src.as_bytes()).unwrap_or_else(|| panic!("{src} parses")); + let mut iter = array.flex_iter(); + assert_eq!(iter.next::(), Some(0.0), "{src}"); + assert_eq!(iter.next::(), None, "{src}: {stop} is not a number"); + let slot = iter.next::>(); + if stop == "+" { + assert!(matches!(slot, Some(Object::Null(_))), "{src}: {slot:?}"); + } else { + assert!(matches!(slot, Some(Object::Name(_))), "{src}: {slot:?}"); + } + assert_eq!(iter.next::(), Some(7.0), "{src}"); + assert_eq!(iter.next::(), None, "{src}"); + } +} + /// Every token of up to five characters over signs, digits, `.` and `e` that starts with a /// sign, in each position a value can take, iterates without panicking, and an array never /// loses the item after it. diff --git a/vendor/README.md b/vendor/README.md index d6871aa1a1..8fdc874a12 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -59,7 +59,7 @@ Other resource categories retain their existing parent-chain lookup. | hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour (since (21), only inside Type 3 glyphs), planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (21) an image that does not request interpolation and is drawn below its resolution, outside a Type 3 glyph, is shrunk by area averaging (`area_shrink`: each device pixel the coverage-weighted mean of the samples it covers, in 16.16 fixed point whose weights sum to exactly one, premultiplied when the image has a mask; a soft mask no larger than the image is first sampled onto the image's grid by `mask_on_image_grid` (nearest-neighbour, or bilinearly when the mask asks for `/Interpolate`, so its edge stays as smooth as an enlarged mask's), so its colour and mask are averaged together instead of the averaged colour of transparent samples showing under a mask layer at the mask's edges) to its snapped device rectangle, instead of nearest-neighbour: `/Interpolate` asks for smoothing only when an image is enlarged (ISO 32000-2 §8.9.5.3), and nearest-neighbour kept one sample in N per axis, so the text of a 300 dpi scan at 100% lost most of its strokes (sampling them again at a fractional offset dropped more). PicScale's `Box` and `Area` filters were not used: shrinking, both average a window four target pixels wide. On a 13-page 300 dpi scan every rendered sample at 96, 120 and 192 dpi is within 1 of the exact area average (it was up to 255 off, 17-23% of samples by more than 1). A snapped image whose shrink failed keeps the full transform, so it is not drawn at its source size. The shrink never enlarges: a side drawn at or above its resolution (an image shrunk across and stretched down, as a 204 × 98 dpi fax is) keeps its samples for the sampler. Each target row averages the whole source rows it covers (contiguous, cheap) and is then shrunk across with taps worked out once per image, which made the shrink about three times faster (a 300 dpi page at 96 dpi: 25 ms, nearest-neighbour 11 ms); working a row at a time (`area_shrink_rows`) keeps its work memory to a few rows. An image with a soft mask, a stencil's ink included, is premultiplied a source row at a time as it is averaged (`area_shrink_premultiplied`), never as a full-resolution RGBA copy: a 10718 × 13701 stencil shown at page size peaked at 1.16 GB with that copy and peaks at 1.03 GB without it, as with nearest-neighbour. A source with a side over `MAX_RESAMPLING_SOURCE_SIDE` (2^20) keeps (10)'s nearest-neighbour shrink, and `area_shrink` refuses it, so its accumulator row and tap table stay a few times one source row (a 2^27 × 2 image of zeros is a tiny file); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971); (23) backport of hayro 0.8: shadings that `as_svg_gradient` can represent are painted as a `vello_cpu` linear or two-point radial gradient instead of a texture sampled pixel by pixel through the shading function (InDesign fades are luminosity soft masks of one full-page axial `sh`: 40 on a report page took 15 s at 144 dpi, now under 1 s); without upstream's half-pixel shift, which suits vello_cpu 0.3 but moves 0.0.8's gradients off pixel centres; (25) a tiling cell is drawn at the scale that makes one `/XStep` (`/YStep`) exactly the cell pixmap's whole number of pixels (`tiling_cell_pixels`, at least 1 and at most the cap), so the repeated pixmap puts cells at whole multiples of the step at any device scale; drawing at the unrounded scale repeated the cell up to half a pixel off at every step, and the error grew with distance from the pattern's origin (ISO 32000-2 8.7.3.1); (28) an image of page-scan size (`SMOOTHED_IMAGE_SIDE`: 512 samples or more on its shorter side) that does not request interpolation is drawn with `ImageQuality::Medium` (bilinear, as interpolated images are) when enlarged by more than 1% on either side (`SMOOTHED_IMAGE_SCALE`: a scan drawn at its resolution can come out a few ulps above 1, and blurred by half a pixel at a half-pixel offset), also when the other side is shrunk (the area shrink leaves that side at 1:1), outside a Type 3 glyph: scans rarely set `/Interpolate`, and drawn nearest-neighbour every sample of a zoomed scan became a block, so its text had staircase edges; icons, QR codes and pixel art keep their hard pixels. Bicubic (`High`) looked the same on a zoomed 300 dpi scan and drew four 1024 px tiles at 400% in 267 ms against 50 ms; (30) a stencil mask painted with a pattern is drawn under a clip of its device rectangle, padded by two pixels: the pattern in an isolated layer, cut to the stencil by a layer holding it composited with `Compose::DestIn` (drawn without a Type 3 glyph's image rules, as the sub-render it replaces was), instead of through a canvas-sized luminance mask rendered for every draw; and a coloured tiling pattern's cell pixmap, repeated or shown once under patch (20), is drawn once per setting of the pattern and cell scale (`Renderer::tiling_cell`, `TilingCells`, eight entries per renderer, keyed by hayro-interpret patch (78)'s `TilingPattern::instance`) instead of once per fill, where every cell was kept until the page was composited. pdf.js issue 8078 paints 73,047 16 × 16 stencils with one pattern whose cell is 3.5 MB at 36 dpi: it ran out of memory after 5 minutes and now renders in about 5 s. For its tests, `offscreen_draws` counts on each thread the tiling cells drawn and the pixels of every pixmap drawn offscreen (all made by `offscreen_pixmap`), so a page's cost is checked by count, not by time; (31) `RenderSettings::max_coverage` keeps the rasterizer to that many coverage values for the page (vello_cpu patch 1), and a page whose paths it left out says so with `InterpreterWarning::ContentTruncated` | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_averages_the_columns_each_pixel_covers`, `raster::tests::non_integer_minification_averages_colour_and_mask_together`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::minified_image_edges_snap_to_whole_pixels`, `raster::tests::a_tile_snaps_half_pixel_image_edges_as_the_whole_page_does` (`cargo test -p hayro`), `raster::tests::a_turned_or_mirrored_minified_image_snaps_to_whole_pixels`, `rotated_image_snap::a_shrunk_image_on_a_turned_page_is_the_upright_render_turned` (`cargo test -p pdfcraft-render --test it`), `renderer::snap_tests::a_skew_that_moves_a_far_edge_is_not_snapped` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path`; (21) `raster::tests::non_interpolated_minification_keeps_thin_strokes`, `raster::tests::non_integer_minification_averages_the_columns_each_pixel_covers`, `raster::tests::non_integer_minification_averages_colour_and_mask_together`, `raster::tests::non_interpolated_minification_does_not_bleed_transparent_colour`, `raster::tests::a_smaller_soft_mask_does_not_bleed_transparent_colour_when_minified`, `raster::tests::an_interpolated_smaller_soft_mask_stays_smooth_when_its_image_is_minified`, `raster::tests::a_shrunk_stencil_mask_keeps_thin_strokes`, `raster::tests::minified_image_edges_snap_to_whole_pixels`, `raster::tests::an_image_shrunk_one_way_and_stretched_the_other_is_still_averaged`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`, `renderer::area_shrink_tests` (`cargo test -p hayro`); (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (25) `tiling_cell_placement::{far_cells_of_a_fill_sit_at_whole_steps, far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix, far_cells_of_a_stroke_sit_at_whole_steps, a_cell_pixmap_spans_exactly_one_step}` (`cargo test -p pdfcraft-render --test it`); (28) `raster::tests::large_non_interpolated_images_are_smoothed_when_enlarged`, `raster::tests::small_non_interpolated_images_keep_hard_pixels_when_enlarged`, `raster::tests::a_scan_shrunk_one_way_is_smoothed_the_way_it_is_stretched`, `raster::tests::a_scan_drawn_a_rounding_error_above_its_resolution_stays_sharp`; (30) `raster::tests::{a_patterned_stencil_mask_paints_only_where_it_inks, a_patterned_stencil_mask_under_a_soft_mask_is_masked_once, a_patterned_stencil_mask_in_a_type3_glyph_keeps_thin_strokes, many_patterned_stencil_masks_draw_no_page_sized_masks, fills_of_one_pattern_setting_share_its_cell, fills_of_interleaved_pattern_settings_each_show_their_own_cell, an_uncoloured_pattern_shows_each_settings_colour}`; (31) `raster::tests::coverage_budget::a_page_past_its_coverage_leaves_the_rest_out_and_says_so` | | hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most as many symbol pixels per symbol dictionary as the largest page bitmap holds, 2^28 (a fuzzed dictionary decoded for minutes; each symbol now pays for its pixels out of the stream's decoding work and is held in the retained bitmaps, and at the earlier 2^26 the soft mask of a scanned drawing, one dictionary of 7,559 symbols, was refused: #6722), and a refusal by one of the decoder's limits is told apart from damaged data (`DecodeError::is_limit`, `OverflowError::BitmapLimit`); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and the page with it. `Bitmap::combine_region` keeps such a location past the page. A refinement of another region refines it where it is, as Table 35 has it (GRREFERENCEDX and GRREFERENCEDY 0), whatever the two locations say; a refinement of the page, see (16); (15) a refinement whose reference is offset right of it (GRREFERENCEDX above 0, which a refined text instance has from a wider bitmap, Table 12, and a refined symbol from an RDX above 0, Table 18) read the reference's first 32 columns as 0: `RefinementContextGatherer::maybe_reload_buffers` emptied its buffers left of the reference and didn't load them again at its first column. Such a refinement decoded to other pixels than were coded, or failed and lost the page. Left of the reference the buffers now keep the words of its first column each row starts with; with an offset of 0 or less nothing changes; (16) a refinement of the page refines "the current contents of the page buffer, restricted to the area of the page buffer specified by this segment's region segment information field" (7.4.7.4), at an offset of 0 (Table 35): `Bitmap::area` copies that area a word at a time, 0 off the page and past its width whatever the padding of its rows holds, and every refinement region reads its reference at offset 0. The page around the area was read too, so a refinement of the page decoded to other pixels than were coded, and one wider or taller than the page was refused. And `RefinementContextGatherer::start_row` loads the reference's words a column left of where a row starts in it, as the reload would, not from column 0: with the reference offset 32 or more left of the refinement (GRREFERENCEDX below −31, as a refined text instance has from a narrower bitmap or an RDX below −31, and a refined symbol from such an RDX), each row's first context read 0 for the reference column it starts at, and from 33 left for the one before it too, and the refinement decoded to other pixels or failed; (17) `Image::new_embedded` reads data that starts with a JBIG2 file header (the ID string `0x97 4A 42 32 0D 0A 1A 0A`, flags and an optional page count, D.4) past it, in the organization the header declares (sequential or random access), its segments counted together with the globals' as (8) has them: ISO 32000-1 7.4.7 has `JBIG2Decode` data in the embedded organization (D.3), but some producers write the file header too, and Acrobat and PDFBox draw such streams. The header's ID string was read as a segment header and the image failed (`unknown or reserved segment type`), so the page drew white | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`, `raster::tests::jbig2_halftone_grids_past_their_bound_are_refused`; (2) the nightly `cargo xtask fuzz` finding (about a second at the earlier 2^26 bound; not run at 2^28), `raster::tests::a_symbol_dictionary_holds_as_many_pixels_as_a_page`, and for `is_limit` and `BitmapLimit` `error::pdfcraft_limit_tests`, `bitmap::pdfcraft_limit_tests` and `gray_scale::pdfcraft_limit_tests` (hayro-jbig2); (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`); (5) `raster::tests::jbig2_regions_held_past_a_pages_bound_are_refused`, `jbig2_symbols_without_pixels_count_towards_a_pages_bound`, `jbig2_retained_contexts_count_towards_a_pages_bound`, `jbig2_huffman_tables_count_towards_a_pages_bound`, `jbig2_new_symbols_count_towards_a_pages_bound`, `jbig2_new_symbols_are_held_to_what_a_page_has_left`, `jbig2_pattern_dictionaries_count_towards_a_pages_bound`, and in the crate (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) `decode::symbol::tests::exported_symbols_are_counted_before_they_are_copied`, `tests::the_room_left_shrinks_as_segments_are_stored`; (6) `raster::tests::jbig2_segments_referring_to_too_many_symbols_are_refused`; (7) `raster::tests::jbig2_pattern_dictionaries_too_large_to_shift_still_draw`, `jbig2_shifted_patterns_never_refuse_an_image`; (8) `raster::tests::jbig2_huffman_tables_of_too_many_lines_are_refused`, `jbig2_streams_of_too_many_segments_are_refused`, `jbig2_streams_of_too_many_references_are_refused`, and in the crate `tests::the_segments_of_a_stream_and_its_globals_count_together`; (9) `raster::tests::jbig2_pages_past_the_bounds_are_refused_before_anything_is_sized_from_them`, `tests::a_page_past_the_bounds_is_refused_when_opened`; (10) `raster::tests::jbig2_decoding_work_is_counted_item_by_item`; (11) `jbig2::decode::tests::a_run_of_images_spends_its_allowance_down_to_the_step` (pdfcraft-filters); (12) `raster::tests::jbig2_placements_at_the_end_of_an_i32_draw_nothing`; (13) `jbig2::decode::tests::a_refinement_reads_nothing_past_its_references_width` (pdfcraft-filters), and in the crate `tests::a_bitmap_of_1s_has_nothing_past_its_width`; (14) `jbig2::decode::tests::a_region_located_past_i32_max_is_off_the_page` (pdfcraft-filters), and in the crate `tests::a_region_located_past_i32_max_is_off_the_page` and `tests::a_refinement_of_a_region_decodes_the_same_wherever_they_are`; (15) `jbig2::decode::tests::a_refinement_reads_a_reference_right_of_it_from_its_first_column` (pdfcraft-filters), and in the crate `tests::a_refinement_reads_a_reference_right_of_it_from_its_first_column`; (16) `jbig2::decode::tests::a_refinement_refines_the_page_in_its_area_and_any_reference_where_it_is` (pdfcraft-filters), and in the crate `tests::a_refinement_refines_the_page_in_its_area_and_any_reference_where_it_is` and `tests::a_page_area_is_the_page_inside_it_and_0_outside` ; (17) `jbig2::decode::tests::a_stream_with_a_jbig2_file_header_decodes_past_it`, `jbig2::decode::tests::a_truncated_jbig2_file_header_is_an_error`, `jbig2::decode::tests::segments_after_a_jbig2_file_header_count_with_the_globals` (pdfcraft-filters), `raster::tests::a_jbig2_image_with_a_file_header_draws` (pdfcraft-render) | | lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365); (7) object parsing builds at most 4,194,304 objects (every array element and dictionary value at any depth, `parser::MAX_OBJECT_NODES`, the same cap as `pdfcraft_cos`) per top-level object, an object stream reads at most 1,000,000 index entries (cos's `/N` clamp), and one load builds at most 8,388,608 objects from all of its object streams together, shared across rayon workers (a decoded stream of `0 0 0 ...` inside the 256 MiB decompression limit built ~120M objects, 10+ GB, and aborted). A lookup parses only the member it wants, so it isn't skipped behind a large member, and a load parses only the members it would add: none its cross-reference table places in another stream (stale copies) and none already loaded as an ordinary object or from an earlier stream. Members the table doesn't list at all are still parsed (a rebuilt table lists no compressed objects) and share the budget, so they can spend it before listed members of the same stream; a load expands its object streams one at a time in object-number order, a stream's members in parallel only when the budget holds all of them and otherwise in index order, so a spent budget skips the same members on every load (#5083) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog`; (7) `inspect::tests::{object_stream_members_over_the_node_cap_are_skipped, object_stream_index_entries_past_the_clamp_are_ignored, object_streams_of_one_load_share_their_node_budget, object_streams_loaded_in_parallel_share_their_node_budget, a_malformed_object_stream_member_refunds_its_reservation, a_tight_budget_builds_object_stream_members_in_index_order, a_lookup_in_an_object_stream_parses_only_the_member_it_wants}` (pdfcraft-render; `NodeBudget` and `ObjectStream::new_within` are public so these can use a small budget) | -| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260); (29) a `/JBIG2Globals` stream that is itself JBIG2 isn't decoded: globals are raw segments, and a chain of 16,000 such streams overflowed the stack, which aborts the process; (30) a stream's own crypt filter: `/Crypt` in its chain read as the filter it names, `/Identity` without one, instead of the document's filter and then a filter that can't be decoded, which left such a stream unreadable in any spelling (ISO 32000-2 §7.4.10); (31) `set_page_jbig2_work`: the JBIG2 images decoded on a thread spend one allowance, set per page, 2^30 steps (`MAX_PAGE_JBIG2_WORK`), so a page of many images made to reach their own limit stops at one, and what they cost to read counts, whether they decode or not, and `jbig2_limited` says whether the image decoded last on the thread was refused by one of the decoder's limits rather than its data, and `jbig2_limited_by_stream` whether that limit is one the stream reaches by itself rather than its decoding work, which may be the page's; `clear_jbig2_limited` and each new page forget it; unbounded until a page sets it; (32) a group of array items read together (a tuple: an image's `/Decode`, `/W`, `/W2`, and a function's `/Domain`, `/Range`, `/Encode` and `/Decode`) can start with a reference: it was taken for the whole group and lost, which ended the array, so an image with `/Decode [7 0 R 0]` didn't draw and CID widths fell back to `/DW`; (33) an object that holds only a reference stands for what that names, stored on its own or in an object stream, up to 32 references: read as a number it was the reference's own object number, so a `/Decode` or `/W` entry naming such an object took a wrong value, and as anything else it was lost. Past 32, as any cycle goes, it reads as a missing object. An object stream isn't reached that way, as its checks are of the object named; reading its index counts against the 64 nested loads and reads its dictionary alone, as a chain of them, each with a member of the next for its `/N`, `/First` or `/Length`, ran out of stack; and a comment inside a reference counts as white space; (34) a table rebuilt by scanning the file (`fallback_xref_map`) finds an object by its number when its header names another generation, including one no generation may be (`3 18446744073709551616 obj` in `poppler-85140-0.pdf`, #5580): the header is read leniently only in that scan (`read_object_header`), the object is also filed under generation 0 unless a real `N 0 obj` holds that key (a later header for the number moves the stand-in), `XRef::get_with` matches by object number only in a repaired table, and `XRef::objects` yields each location once; (35) PNG predictors (`lzw_flate::unfilter_png`) are undone a byte row at a time on slices, as the PNG filters are defined, instead of through the bit-level readers TIFF predictors need: a 993 × 936 RGB image took about 63 ms to unfilter whatever its row filters, and now takes about 3 ms (Up) to 16 ms (Paeth) in a release build (#5430); a row ending part-way through a pixel (three 4-bit samples, an odd width) keeps its last byte, where the bit-level readers dropped it and each later row started a byte early, shearing the picture; (36) a stream with no `endstream` left after it is the bytes its `/Length` gives, "how many bytes of the PDF file are used for the stream's data" (ISO 32000-2 7.3.8.2), when the file holds that many (`parse_declared`: first, before the search for `endstream`, when the `/Length` ends before a whole `endstream` token, or a whole `endstrea` or `endobj` token after which the object ends too (the end of the data, another object's `N G obj` header, `xref`, `trailer` or `startxref`: not payload such as `endobject` or `endobj more`, ISO 32000-2 7.2.3), or at the end of the data, so the search can't run on into a later object's stream; then after the search finds none; `parse_proper` and the search for `endstream` take only a whole token, not `endstreamer`): a producer that writes `endstrea` after every stream lost every font and page content, and its pages drew blank while other readers draw them; (37) a document that encrypts only its embedded files, authorised when one is opened (`/AuthEvent /EFOpen`, ISO 32000-2 §7.6.6, Table 25: every encrypting crypt filter is EFOpen, `/EFF` names one, `/StmF` and `/StrF` don't), opens without a password with the pass-through decryptor: its strings and streams are in the clear and nothing drawn reads an embedded file; (38) a page box that encloses no area is read as a missing one: a `/MediaBox` without area (`[0 0 0 0]`) as missing (an inherited one with area, else the default page, US Letter since patch 44), and a `/CropBox` without area, or with none in common with the media box, as missing (an inherited one, else the media box; ISO 32000-2 §14.11.2, Table 33); kept, the visible region had no area, so nothing was drawn and no text extracted (pdf.js `boundingBox_invalid`); (40) the last Flate filter of an image whose PNG predictor (`/Predictor` 10–15) its writer declared but never applied gives the image's samples as they are: when the inflated data is exactly `/Height` rows of the predictor's row length with no filter-type byte before each (where predicted rows would need one more byte each, ISO 32000-2 §7.4.4.4), `untagged_png_rows` takes it for unpredicted samples and reports it (`warn!`), as PDFium, MuPDF and Poppler read it; read with the predictor, each row's first sample was taken for a filter type and the image came out a row short and shifted, drawn in fragments (PDFBOX-3932). `Filter::apply` is given the image's rows for its last filter only; any other length is predicted as before; (41) CCITT `/Rows` above the image's `/Height` decodes to the height too, so the decoder is never asked for more rows than the image has (ISO 32000-2 Table 87): a scan with `/Rows 1084975104` on 2,592 columns had the size check refuse every page, and all 17 drew blank (PDFBOX-771); `/Rows` still counts for a stream decoded without an image's height; (42) TIFF predictor 2 on 8- and 16-bit samples (`lzw_flate::undo_tiff_bytes`) is undone a byte row at a time on slices, each sample added to the same component of the pixel to its left, wrapping at the sample's width (16-bit samples big-endian), instead of through the bit-level readers 1-, 2- and 4-bit samples still need; the bytes are those the bit-level path wrote, and a partial last row is still dropped. A page of 45 full-page 2445 × 4724 8-bit grey images so predicted (PDFBOX-1350) took about 23 s to render at 96 dpi and now takes about 4 s, with the same pixels; (43) a last update cut off before its trailer (the last `startxref` more than 4 KiB from the end of the file, as `pdfcraft-cos` judges the footer, with `N G obj` headers after it: `cut_off_update_follows`) is read by rebuilding the table from object headers (`Pdf::new_with_password` calls `fallback` first, after the table the last `startxref` names has refused a wrong password, and takes the rebuilt table only when it is encrypted exactly when that one is), the latest definition of each object winning, as `pdfcraft-cos` reads such a file; the older table the last `startxref` names is read only when the rebuilt table has no page (a file cut short inside the update, whose new page tree names pages that are not there). The renderer had shown the older revision while the document model read the newer one (PDFBOX-3934: 12 pages against 13; ISO 32000-2 §7.5.6). A `startxref` near the end, or one followed only by data that holds no object header, is read as before; (44) a page with no `/MediaBox`, its own or inherited, or one without area (`[0 0 0 0]`, which now counts as missing, so the page is placed and clipped by the region it is sized by and its content shows), is US Letter (`LETTER`, 612 × 792 pt), not A4, and so is the `base_dimensions` fallback for a visible region without area: ISO 32000-2 Table 31 requires the box and gives no default, other readers use Letter, and PdfCraft's page model and inspector already did (PDFBOX-4001); (45) `root_xref`: when the newest cross-reference section names no earlier one (no `/Prev`, ISO 32000-2 §7.5.6, §7.5.8.2; a hybrid section's `/XRefStm` stream belongs to the same update and doesn't count, §7.5.8.4), the file holds another `startxref`, and the catalog's `/Pages` can't be read, the table is rebuilt by scanning the file (`XRef::repair`) before the page tree is read, so the cut-off page tree is found instead of the page dictionaries `Pages::new_brute_force` turns up (the signed files of PDFBOX-2720 and PDFBOX-2942 showed 2 blank pages for 1, 10, 13 and 1754); `Pdf::rebuilt_unlinked_update` says so, and `pdfcraft-cos` rebuilds under the same conditions; (46) a dictionary or array item that the first pass skips as a number but no number is read from (a lone `+` or `++`, ISO 32000-2 §7.3.3) is unreadable like any other malformed value: `Dict::entries` and `Dict`'s `Debug` leave the entry out, as `Dict::get` already did, and `Array::raw_iter` and `Array::iter` read it as null in its slot (§7.3.9), where `entries`, `Debug` and `raw_iter` unwrapped the failed read and panicked and `iter` ended there and dropped the items after it; a typed read (`iter::`) still ends at it | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content`; (29) `raster::tests::jbig2_globals_that_are_jbig2_themselves_are_not_decoded`, `raster::tests::jbig2_globals_are_read`, `raster::tests::the_jbig2_images_of_a_page_share_one_allowance`, `raster::tests::an_image_that_fails_spends_the_pages_allowance_too`; (31) `jbig2_limited`: `raster::tests::a_picture_whose_jbig2_mask_a_decoder_limit_refuses_is_not_drawn`, `raster::tests::a_limit_refusal_says_nothing_of_the_next_image`, `raster::tests::failed_image_decodes::a_picture_whose_jbig2_mask_is_refused_for_its_work_is_decoded_at_every_draw`; (30) `raster::tests::a_stream_with_a_crypt_filter_of_its_own_is_drawn`; (32) `raster::tests::a_decode_array_with_references_in_it_is_read`, `raster::tests::a_functions_arrays_can_start_with_a_reference` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret); (33) `raster::tests::a_reference_to_a_reference_is_what_it_names`, `raster::tests::a_decode_array_with_references_in_it_is_read` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret), `xref::tests::an_object_stream_isnt_reached_through_a_reference`, `xref::tests::a_chain_of_object_streams_ends_at_the_limit_of_nested_loads`, `xref::tests::a_chain_of_object_streams_takes_no_more_work_for_two_ways_on`, `xref::tests::a_reference_held_in_either_storage_is_followed`, `xref::tests::a_page_a_reference_is_held_to_is_found_once` (hayro-syntax); (34) `raster::tests::a_rebuilt_table_finds_an_object_whose_header_names_another_generation`, `raster::tests::a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object` (pdfcraft-render), `xref::tests::an_object_stream_and_its_first_member_are_both_enumerated` (hayro-syntax); (35) `filter::lzw_flate::pdfcraft_png_predictor_tests` (hayro-syntax: every filter type at 1–16 bits and 1–4 colours against the PNG specification's byte-by-byte definition, a row ending part-way through a pixel, Average and Paeth over 6-byte pixels), `raster::tests::png_predicted_images::a_four_bit_rgb_image_of_odd_width_with_up_predicted_rows_is_not_sheared`; (36) `raster::tests::a_content_stream_without_endstream_is_drawn_to_its_length`, `raster::tests::a_content_stream_without_endstream_is_not_read_into_a_later_stream`, `raster::tests::hayro_reads_a_stream_without_endstream_to_its_length_before_a_later_one`, `raster::tests::hayro_does_not_end_a_stream_inside_a_longer_word` (pdfcraft-render); (37) `inspect::tests::a_document_encrypting_only_its_embedded_files_opens_without_a_password`; (38) `text::tests::text_on_a_page_whose_box_has_no_area_is_extracted` (pdfcraft-render); (40) `filter::lzw_flate::pdfcraft_png_predictor_tests::an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples`, `an_image_whose_rows_carry_png_tags_still_has_its_predictor_undone`, `data_of_neither_length_decodes_as_it_did`, `rows_of_no_bytes_or_of_more_than_memory_holds_do_not_panic` (hayro-syntax), `raster::tests::png_predicted_images::an_image_and_soft_mask_whose_rows_carry_no_png_tags_draw_their_samples`, `an_image_one_byte_short_of_untagged_rows_still_goes_through_the_predictor`; (41) `raster::tests::group4_fax_with_rows_past_its_height_decodes_to_the_image_height`; (42) `filter::lzw_flate::pdfcraft_tiff_predictor_tests` (hayro-syntax: random 8- and 16-bit rows at 1–7 colours and 1–50 columns against the bit-level path, partial and empty rows, and a row counter showing whole-byte samples skip the bit-level path), `raster::tests::tiff_predicted_images`; (43) `raster::tests::an_update_cut_off_before_its_trailer_shows_its_pages_as_the_model_reads_them`, `raster::tests::a_complete_update_reads_as_before`, `raster::tests::trailing_data_without_objects_reads_as_before`, `raster::tests::a_short_cut_off_update_reads_as_before`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_delimiter_is_rebuilt`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_comment_is_rebuilt`, `raster::tests::trailing_data_with_an_object_header_reads_as_the_model_reads_it`, `raster::tests::an_update_cut_off_before_its_new_pages_keeps_the_older_table`, `raster::tests::an_encrypted_file_with_a_cut_off_update_still_needs_its_password`, `raster::tests::a_rebuild_whose_trailer_lacks_the_encryption_dictionary_is_not_taken` (pdfcraft-render); (44) `raster::tests::a_page_without_a_media_box_is_letter`, `raster::tests::raw_crop_unit_floor_preserves_nearly_zero_fallback` (pdfcraft-render), `pdfcraft-model::tests::{a_page_without_a_media_box_is_letter, a_page_whose_media_box_has_no_area_is_letter}`; (45) `inspect::core::unlinked_update_tests::an_update_without_prev_shows_the_page_tree_and_says_it_was_rebuilt`, `inspect::core::unlinked_update_tests::a_hybrid_update_without_prev_is_rebuilt_as_the_document_model_rebuilds_it` (pdfcraft-render); (46) `hayro_sign_tokens` (pdfcraft-content: dictionary and array cases, and every sign-led token of up to five characters in each position) | +| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260); (29) a `/JBIG2Globals` stream that is itself JBIG2 isn't decoded: globals are raw segments, and a chain of 16,000 such streams overflowed the stack, which aborts the process; (30) a stream's own crypt filter: `/Crypt` in its chain read as the filter it names, `/Identity` without one, instead of the document's filter and then a filter that can't be decoded, which left such a stream unreadable in any spelling (ISO 32000-2 §7.4.10); (31) `set_page_jbig2_work`: the JBIG2 images decoded on a thread spend one allowance, set per page, 2^30 steps (`MAX_PAGE_JBIG2_WORK`), so a page of many images made to reach their own limit stops at one, and what they cost to read counts, whether they decode or not, and `jbig2_limited` says whether the image decoded last on the thread was refused by one of the decoder's limits rather than its data, and `jbig2_limited_by_stream` whether that limit is one the stream reaches by itself rather than its decoding work, which may be the page's; `clear_jbig2_limited` and each new page forget it; unbounded until a page sets it; (32) a group of array items read together (a tuple: an image's `/Decode`, `/W`, `/W2`, and a function's `/Domain`, `/Range`, `/Encode` and `/Decode`) can start with a reference: it was taken for the whole group and lost, which ended the array, so an image with `/Decode [7 0 R 0]` didn't draw and CID widths fell back to `/DW`; (33) an object that holds only a reference stands for what that names, stored on its own or in an object stream, up to 32 references: read as a number it was the reference's own object number, so a `/Decode` or `/W` entry naming such an object took a wrong value, and as anything else it was lost. Past 32, as any cycle goes, it reads as a missing object. An object stream isn't reached that way, as its checks are of the object named; reading its index counts against the 64 nested loads and reads its dictionary alone, as a chain of them, each with a member of the next for its `/N`, `/First` or `/Length`, ran out of stack; and a comment inside a reference counts as white space; (34) a table rebuilt by scanning the file (`fallback_xref_map`) finds an object by its number when its header names another generation, including one no generation may be (`3 18446744073709551616 obj` in `poppler-85140-0.pdf`, #5580): the header is read leniently only in that scan (`read_object_header`), the object is also filed under generation 0 unless a real `N 0 obj` holds that key (a later header for the number moves the stand-in), `XRef::get_with` matches by object number only in a repaired table, and `XRef::objects` yields each location once; (35) PNG predictors (`lzw_flate::unfilter_png`) are undone a byte row at a time on slices, as the PNG filters are defined, instead of through the bit-level readers TIFF predictors need: a 993 × 936 RGB image took about 63 ms to unfilter whatever its row filters, and now takes about 3 ms (Up) to 16 ms (Paeth) in a release build (#5430); a row ending part-way through a pixel (three 4-bit samples, an odd width) keeps its last byte, where the bit-level readers dropped it and each later row started a byte early, shearing the picture; (36) a stream with no `endstream` left after it is the bytes its `/Length` gives, "how many bytes of the PDF file are used for the stream's data" (ISO 32000-2 7.3.8.2), when the file holds that many (`parse_declared`: first, before the search for `endstream`, when the `/Length` ends before a whole `endstream` token, or a whole `endstrea` or `endobj` token after which the object ends too (the end of the data, another object's `N G obj` header, `xref`, `trailer` or `startxref`: not payload such as `endobject` or `endobj more`, ISO 32000-2 7.2.3), or at the end of the data, so the search can't run on into a later object's stream; then after the search finds none; `parse_proper` and the search for `endstream` take only a whole token, not `endstreamer`): a producer that writes `endstrea` after every stream lost every font and page content, and its pages drew blank while other readers draw them; (37) a document that encrypts only its embedded files, authorised when one is opened (`/AuthEvent /EFOpen`, ISO 32000-2 §7.6.6, Table 25: every encrypting crypt filter is EFOpen, `/EFF` names one, `/StmF` and `/StrF` don't), opens without a password with the pass-through decryptor: its strings and streams are in the clear and nothing drawn reads an embedded file; (38) a page box that encloses no area is read as a missing one: a `/MediaBox` without area (`[0 0 0 0]`) as missing (an inherited one with area, else the default page, US Letter since patch 44), and a `/CropBox` without area, or with none in common with the media box, as missing (an inherited one, else the media box; ISO 32000-2 §14.11.2, Table 33); kept, the visible region had no area, so nothing was drawn and no text extracted (pdf.js `boundingBox_invalid`); (40) the last Flate filter of an image whose PNG predictor (`/Predictor` 10–15) its writer declared but never applied gives the image's samples as they are: when the inflated data is exactly `/Height` rows of the predictor's row length with no filter-type byte before each (where predicted rows would need one more byte each, ISO 32000-2 §7.4.4.4), `untagged_png_rows` takes it for unpredicted samples and reports it (`warn!`), as PDFium, MuPDF and Poppler read it; read with the predictor, each row's first sample was taken for a filter type and the image came out a row short and shifted, drawn in fragments (PDFBOX-3932). `Filter::apply` is given the image's rows for its last filter only; any other length is predicted as before; (41) CCITT `/Rows` above the image's `/Height` decodes to the height too, so the decoder is never asked for more rows than the image has (ISO 32000-2 Table 87): a scan with `/Rows 1084975104` on 2,592 columns had the size check refuse every page, and all 17 drew blank (PDFBOX-771); `/Rows` still counts for a stream decoded without an image's height; (42) TIFF predictor 2 on 8- and 16-bit samples (`lzw_flate::undo_tiff_bytes`) is undone a byte row at a time on slices, each sample added to the same component of the pixel to its left, wrapping at the sample's width (16-bit samples big-endian), instead of through the bit-level readers 1-, 2- and 4-bit samples still need; the bytes are those the bit-level path wrote, and a partial last row is still dropped. A page of 45 full-page 2445 × 4724 8-bit grey images so predicted (PDFBOX-1350) took about 23 s to render at 96 dpi and now takes about 4 s, with the same pixels; (43) a last update cut off before its trailer (the last `startxref` more than 4 KiB from the end of the file, as `pdfcraft-cos` judges the footer, with `N G obj` headers after it: `cut_off_update_follows`) is read by rebuilding the table from object headers (`Pdf::new_with_password` calls `fallback` first, after the table the last `startxref` names has refused a wrong password, and takes the rebuilt table only when it is encrypted exactly when that one is), the latest definition of each object winning, as `pdfcraft-cos` reads such a file; the older table the last `startxref` names is read only when the rebuilt table has no page (a file cut short inside the update, whose new page tree names pages that are not there). The renderer had shown the older revision while the document model read the newer one (PDFBOX-3934: 12 pages against 13; ISO 32000-2 §7.5.6). A `startxref` near the end, or one followed only by data that holds no object header, is read as before; (44) a page with no `/MediaBox`, its own or inherited, or one without area (`[0 0 0 0]`, which now counts as missing, so the page is placed and clipped by the region it is sized by and its content shows), is US Letter (`LETTER`, 612 × 792 pt), not A4, and so is the `base_dimensions` fallback for a visible region without area: ISO 32000-2 Table 31 requires the box and gives no default, other readers use Letter, and PdfCraft's page model and inspector already did (PDFBOX-4001); (45) `root_xref`: when the newest cross-reference section names no earlier one (no `/Prev`, ISO 32000-2 §7.5.6, §7.5.8.2; a hybrid section's `/XRefStm` stream belongs to the same update and doesn't count, §7.5.8.4), the file holds another `startxref`, and the catalog's `/Pages` can't be read, the table is rebuilt by scanning the file (`XRef::repair`) before the page tree is read, so the cut-off page tree is found instead of the page dictionaries `Pages::new_brute_force` turns up (the signed files of PDFBOX-2720 and PDFBOX-2942 showed 2 blank pages for 1, 10, 13 and 1754); `Pdf::rebuilt_unlinked_update` says so, and `pdfcraft-cos` rebuilds under the same conditions; (46) a dictionary or array item that the first pass skips as a number but no number is read from (a lone `+` or `++`, ISO 32000-2 §7.3.3) is unreadable like any other malformed value: `Dict::entries` and `Dict`'s `Debug` leave the entry out, as `Dict::get` already did, and `Array::raw_iter` and `Array::iter` read it as null in its slot (§7.3.9), where `entries`, `Debug` and `raw_iter` unwrapped the failed read and panicked and `iter` ended there and dropped the items after it; a typed read (`iter::`) still ends at it, and a failed typed read through `flex_iter` leaves the slot in place, as at a value of another type | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content`; (29) `raster::tests::jbig2_globals_that_are_jbig2_themselves_are_not_decoded`, `raster::tests::jbig2_globals_are_read`, `raster::tests::the_jbig2_images_of_a_page_share_one_allowance`, `raster::tests::an_image_that_fails_spends_the_pages_allowance_too`; (31) `jbig2_limited`: `raster::tests::a_picture_whose_jbig2_mask_a_decoder_limit_refuses_is_not_drawn`, `raster::tests::a_limit_refusal_says_nothing_of_the_next_image`, `raster::tests::failed_image_decodes::a_picture_whose_jbig2_mask_is_refused_for_its_work_is_decoded_at_every_draw`; (30) `raster::tests::a_stream_with_a_crypt_filter_of_its_own_is_drawn`; (32) `raster::tests::a_decode_array_with_references_in_it_is_read`, `raster::tests::a_functions_arrays_can_start_with_a_reference` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret); (33) `raster::tests::a_reference_to_a_reference_is_what_it_names`, `raster::tests::a_decode_array_with_references_in_it_is_read` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret), `xref::tests::an_object_stream_isnt_reached_through_a_reference`, `xref::tests::a_chain_of_object_streams_ends_at_the_limit_of_nested_loads`, `xref::tests::a_chain_of_object_streams_takes_no_more_work_for_two_ways_on`, `xref::tests::a_reference_held_in_either_storage_is_followed`, `xref::tests::a_page_a_reference_is_held_to_is_found_once` (hayro-syntax); (34) `raster::tests::a_rebuilt_table_finds_an_object_whose_header_names_another_generation`, `raster::tests::a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object` (pdfcraft-render), `xref::tests::an_object_stream_and_its_first_member_are_both_enumerated` (hayro-syntax); (35) `filter::lzw_flate::pdfcraft_png_predictor_tests` (hayro-syntax: every filter type at 1–16 bits and 1–4 colours against the PNG specification's byte-by-byte definition, a row ending part-way through a pixel, Average and Paeth over 6-byte pixels), `raster::tests::png_predicted_images::a_four_bit_rgb_image_of_odd_width_with_up_predicted_rows_is_not_sheared`; (36) `raster::tests::a_content_stream_without_endstream_is_drawn_to_its_length`, `raster::tests::a_content_stream_without_endstream_is_not_read_into_a_later_stream`, `raster::tests::hayro_reads_a_stream_without_endstream_to_its_length_before_a_later_one`, `raster::tests::hayro_does_not_end_a_stream_inside_a_longer_word` (pdfcraft-render); (37) `inspect::tests::a_document_encrypting_only_its_embedded_files_opens_without_a_password`; (38) `text::tests::text_on_a_page_whose_box_has_no_area_is_extracted` (pdfcraft-render); (40) `filter::lzw_flate::pdfcraft_png_predictor_tests::an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples`, `an_image_whose_rows_carry_png_tags_still_has_its_predictor_undone`, `data_of_neither_length_decodes_as_it_did`, `rows_of_no_bytes_or_of_more_than_memory_holds_do_not_panic` (hayro-syntax), `raster::tests::png_predicted_images::an_image_and_soft_mask_whose_rows_carry_no_png_tags_draw_their_samples`, `an_image_one_byte_short_of_untagged_rows_still_goes_through_the_predictor`; (41) `raster::tests::group4_fax_with_rows_past_its_height_decodes_to_the_image_height`; (42) `filter::lzw_flate::pdfcraft_tiff_predictor_tests` (hayro-syntax: random 8- and 16-bit rows at 1–7 colours and 1–50 columns against the bit-level path, partial and empty rows, and a row counter showing whole-byte samples skip the bit-level path), `raster::tests::tiff_predicted_images`; (43) `raster::tests::an_update_cut_off_before_its_trailer_shows_its_pages_as_the_model_reads_them`, `raster::tests::a_complete_update_reads_as_before`, `raster::tests::trailing_data_without_objects_reads_as_before`, `raster::tests::a_short_cut_off_update_reads_as_before`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_delimiter_is_rebuilt`, `raster::tests::a_cut_off_update_with_obj_followed_by_a_comment_is_rebuilt`, `raster::tests::trailing_data_with_an_object_header_reads_as_the_model_reads_it`, `raster::tests::an_update_cut_off_before_its_new_pages_keeps_the_older_table`, `raster::tests::an_encrypted_file_with_a_cut_off_update_still_needs_its_password`, `raster::tests::a_rebuild_whose_trailer_lacks_the_encryption_dictionary_is_not_taken` (pdfcraft-render); (44) `raster::tests::a_page_without_a_media_box_is_letter`, `raster::tests::raw_crop_unit_floor_preserves_nearly_zero_fallback` (pdfcraft-render), `pdfcraft-model::tests::{a_page_without_a_media_box_is_letter, a_page_whose_media_box_has_no_area_is_letter}`; (45) `inspect::core::unlinked_update_tests::an_update_without_prev_shows_the_page_tree_and_says_it_was_rebuilt`, `inspect::core::unlinked_update_tests::a_hybrid_update_without_prev_is_rebuilt_as_the_document_model_rebuilds_it` (pdfcraft-render); (46) `hayro_sign_tokens` (pdfcraft-content: dictionary and array cases, and every sign-led token of up to five characters in each position) | | winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, non-repeated first key whose one callback inserts that same jamo, with IME enabled and nothing composed, focus and input source unchanged, is retried (`ime_startup.rs`). Port of [winit#4744](https://github.com/rust-windowing/winit/pull/4744), with its policy tests.; (11) on X11 without `Xft.dpi`, the scale factor comes from the X screen's configured DPI (its size in pixels and millimetres) before the output's physical density from RandR: Xorg can deliberately run a dense panel at 96 DPI, and only winit applications then looked zoomed; `Xft.dpi` still wins, `WINIT_X11_SCALE_FACTOR` still overrides, and a screen reporting no size keeps the RandR fallback. PdfCraft patch (#1150, replacing the launcher pin proposed in #908). (12) on macOS, `WinitView` answers `mouseDownCanMoveWindow` with the window's `movable_by_window_background` attribute (NO unless asked): NSView answers YES for a view that isn't opaque, so with the transparent title bar and full-size content view PdfCraft uses, AppKit moved the window for any drag that began in the 28 pt title-bar band before the app saw it, and document tabs (which live in that band) could not be dragged to reorder them. The empty strip still moves the window through `ViewportCommand::StartDrag`. PdfCraft patch. The published crate's asset files (`docs/res/*.svg`, `examples/data/*.png`) are left out, so its `window` example doesn't build; (13) on Wayland, pixel-only wheel, wheel-tilt and continuous-source scroll events report `Moved` rather than starting an unterminated finger gesture, so egui follows modifier release instead of keeping Ctrl zoom latched (#991). Finger gestures and unknown sources retain their existing phase policy | (1) `pdfcraft` `tests::winit_carries_the_windows_11_monitor_scale_fix` keeps the patch in the build; the drag itself needs two monitors with different scale factors on Windows 11; (2) `pdfcraft` `tests/winit_wayland_text_input.rs`; the capability change itself needs a Wayland session and an input method; (3) `pdfcraft` `tests/winit_windows_ime_cursor.rs`; composing itself needs the Microsoft Korean IME; (4) `pdfcraft` `tests/winit_windows_hidden_maximized.rs`; the start-up itself needs Windows and a window that was closed maximized; (5) `pdfcraft` `tests/winit_x11_ime_focus.rs`; switching fields itself needs an X11 session and an input method (IBus, fcitx5); (6) `pdfcraft` `tests/winit_macos_ime_commit.rs`; composing itself needs macOS and an input method; (7) `pdfcraft` `tests/winit_macos_ime_discard.rs`; composing itself needs macOS and an input method; (8) `pdfcraft` `tests/winit_macos_emoji_picker.rs`; the picker itself needs macOS; (9) `pdfcraft` `tests/winit_macos_korean_space.rs`; composing itself needs macOS and Apple Korean; (10) `pdfcraft` `tests/winit_macos_korean_first_key.rs` and `ime_startup.rs`'s own tests (run them with `rustc --test`); typing itself needs macOS and Apple Korean; (11) `pdfcraft` `tests/winit_x11_dpi.rs` keeps the patch in the build, and `util::randr` tests the policy (run them in the vendored crate); the scale itself needs an X11 session; (12) `pdfcraft` `tests/winit_macos_title_bar_drag.rs` keeps the patch in the build; the drag itself needs macOS and a pointer; (13) `pdfcraft` `tests/winit_wayland_scroll.rs` compiles the production phase policy and exercises modifier release through egui; live COSMIC confirmation remains open | | egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure | | vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical; (2) `StripStorage::room_for_path{,_within}`: whether one more path's coverage (at most the whole surface, counted twice) still fits below 2^31 values, the most a strip's packed alpha index reaches (`Strip::new` asserts it), or below a smaller limit; (4) `flatten::stroke`: when kurbo 0.13.1's stroker returns an outline containing NaN, which `fill` would drop whole, the path is stroked again from a copy (`robust_for_stroking`, one element out per element in) in which each curve whose control points lie within the stroke tolerance of its chord is a line (the #4907 fix, a nearly straight cubic given a NaN join, kurbo issues #617 and #519; its row here was lost in a merge and is restored with this entry) and each cubic whose second control point is its end point, as `y` builds (ISO 32000-2 §8.5.2.1 Table 58), has that control point moved the tolerance towards its first (`open_zero_end_handle`; the curve moves by at most 4/9 of the tolerance): kurbo's cusp search on such a curve's offset can stop on the end point, where the derivative is zero, and normalising it gives NaN, so at 16, 32 and 63 pt a two-curve `y` path drew nothing and a file in the PDFBox tracker lost its 32 pt "XX" outline. Only an exact zero triggers it (none of 192,000 random strokes with a handle 1e-9 long, nor of 256,000 `v` strokes, came back with NaN; 1,073 of 192,000 random `y`/`v` strokes at 1–64 pt did before and none after). A finite outline takes the old path unchanged | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate; (2) `strip_generator::pdfcraft_tests::strips_have_room_until_a_surface_short_of_the_limit`; (4) `flatten::tests::a_tiny_degenerate_cubic_does_not_drop_the_stroke` and the render crate's `stroke_degenerate_cubic` fail without the near-line replacement, `flatten::tests::a_wide_stroke_of_a_curve_with_a_zero_end_tangent_is_drawn` (widths 1–64, every join and cap, `y` and the mirrored `v`) and the render crate's `stroke_zero_end_tangent` fail without the moved control point; `a_finite_outline_is_stroked_as_before` and `a_path_with_nan_is_still_dropped` pass either way | diff --git a/vendor/hayro-syntax/src/object/array.rs b/vendor/hayro-syntax/src/object/array.rs index 6bb9876e67..bbc81c72a7 100644 --- a/vendor/hayro-syntax/src/object/array.rs +++ b/vendor/hayro-syntax/src/object/array.rs @@ -222,7 +222,9 @@ impl<'a> FlexArrayIter<'a> { Some(MaybeRef::NotRef(i)) => Some(i), // PdfCraft patch (46): an item no object is read from (a lone sign such as `+`) // reads as null in its slot, as in `raw_iter`, instead of ending the iteration - // and losing the items after it. An object of another type still ends it. + // and losing the items after it. An object of another type still ends it. The + // slot is passed only when null is a `T`: a typed read that fails leaves it in + // place, as a value of another type is, so the caller can read it as another type. None => { let mut probe = start.clone(); if probe @@ -231,8 +233,10 @@ impl<'a> FlexArrayIter<'a> { { return None; } - self.reader = skip_unreadable_item(start, &self.ctx)?; - Object::Null(Null).cast::() + let after = skip_unreadable_item(start, &self.ctx)?; + let item = Object::Null(Null).cast::()?; + self.reader = after; + Some(item) } }; } From 87d8deaced5542bd29bbe3fb5077177ce11450f5 Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Thu, 12 Nov 2026 21:28:38 +0800 Subject: [PATCH 08/21] fix(measure): read compound and fractional number formats (ISO 32000-2 12.9.2) Scale::read refused number format arrays of more than one unit (feet and inches) and the /F, /T formats, so measuring inside an Acrobat-calibrated viewport failed and such saved measurements were listed as unsupported. Read them into Scale::formats, label readings with them (whole units, then the rest as decimals, a fraction, rounded or cut off; a last unit that rounds up carries) and write them back when a measurement is added with that scale. Single-unit decimal scales read and label exactly as before. --- crates/measure/README.md | 2 +- crates/measure/src/lib.rs | 103 ++++-- crates/measure/src/number_format.rs | 510 ++++++++++++++++++++++++++++ crates/measure/src/tests.rs | 51 ++- 4 files changed, 628 insertions(+), 38 deletions(-) create mode 100644 crates/measure/src/number_format.rs diff --git a/crates/measure/README.md b/crates/measure/README.md index 2e438d7a1e..292fcc4a3c 100644 --- a/crates/measure/README.md +++ b/crates/measure/README.md @@ -10,6 +10,6 @@ The desktop Measure objects panel exposes all three tools, live values and coord Snapping interprets painted paths and nested Form XObjects, including graphics-state transforms. Cubic paths are flattened to a maximum deviation of 0.2 user units. Raster edges, glyph outlines, clipping and optional-content visibility are not interpreted. Extraction stops at 8,000,000 segments, 24,000,000 endpoint and midpoint targets, 512 MiB of decoded content, 4,096 streams, 32 nested forms or 256 nested `q`; intersection searches use at most 256 nearby segments. Extraction is lenient: a content stream that can't be decoded is skipped and counted, and the rest of the page still snaps. The UI and automation report these limits. -Imported single-unit decimal rectilinear scales support differing X and Y conversion factors when CYX is present. Unit labels are text strings and may be non-ASCII ("m²"). Compound units (such as feet and inches), fraction formats and non-rectilinear scales are not supported: `list` reports such measurements, and ones with invalid geometry, under `unsupported` with a reason instead of failing, and leaves their PDF data untouched. A polygon whose last vertex repeats the first is treated as closed. Interoperability with Acrobat-authored measurements is untested. Geospatial and 3D measuring are outside this component. +Imported single-unit decimal rectilinear scales support differing X and Y conversion factors when CYX is present. Unit labels are text strings and may be non-ASCII ("m²"). Imported compound units (such as feet and inches, up to 8 units), fractions and values cut off to whole units (ISO 32000-2 §12.9.2 number format arrays) are read too: readings are labelled with them (`3 ft 6 1/2 in`, a last unit that rounds up carrying into the one before) and a measurement added with such a scale writes them back. Authoring them, differing coordinate and distance units, and non-rectilinear scales are not supported: `list` reports such measurements, and ones with invalid geometry, under `unsupported` with a reason instead of failing, and leaves their PDF data untouched. A polygon whose last vertex repeats the first is treated as closed. Interoperability with Acrobat-authored measurements is untested. Geospatial and 3D measuring are outside this component. Synthetic tests cover geometry, calibration, viewport precedence, coordinate transforms, saved annotations and captions, snapping targets, cyclic forms, malformed arguments, permissions, undo, save/reopen, rendering and spreadsheet-safe CSV. No sample PDF or font assets are added. diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index bd60a192c1..d8bfda587d 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -3,7 +3,9 @@ //! annotations use the measurement intents of line, polygon and polyline annotations (§12.5.6). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod number_format; pub mod snap; +use number_format::{Formats, NumberFormat}; use pdfcraft_annot::{Meta, NewAnnotation, Shape, Style}; use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString}; use serde::Serialize; @@ -69,6 +71,13 @@ pub struct Scale { pub area_unit: String, pub precision: u8, pub ratio: String, + /// The number format arrays of an imported scale whose units are compound (feet and inches) + /// or whose values show as fractions or cut off to whole units (ISO 32000-2 §12.9.2): + /// readings are labelled with them, and a measurement added with this scale writes them + /// back. `unit`, `area_unit` and the factors are their first units'. `None` for single-unit + /// decimal scales, which `unit`, `area_unit` and `precision` describe. + #[serde(skip_serializing_if = "Option::is_none")] + pub formats: Option, } impl Default for Scale { fn default() -> Self { @@ -81,6 +90,7 @@ impl Default for Scale { area_unit: "in^2".into(), precision: 2, ratio: "1 in = 1 in".into(), + formats: None, } } } @@ -95,6 +105,7 @@ impl Scale { area_unit: format!("{unit}^2"), precision, ratio: format!("1 pt = {units_per_user_unit} {unit}"), + formats: None, }; out.validate()?; Ok(out) @@ -142,6 +153,9 @@ impl Scale { if self.ratio.len() > 256 || self.ratio.chars().any(char::is_control) { return Err(invalid("invalid scale ratio")); } + if let Some(formats) = &self.formats { + formats.validate().map_err(invalid)?; + } Ok(()) } pub fn dictionary(&self) -> Result { @@ -159,10 +173,25 @@ impl Scale { d.set(b"SS".to_vec(), PdfString::text("")); Object::Array(vec![Object::Dict(d)]) }; + // An imported array is written as read, its first unit given this scale's label and factor. + let imported = |formats: &[NumberFormat], unit: &str, factor: f64| { + let first = formats.first().map(|f| NumberFormat { unit: unit.into(), factor, ..f.clone() }); + Object::Array(first.iter().chain(formats.iter().skip(1)).map(NumberFormat::dictionary).collect()) + }; let mut d = Dict::new(); d.set(b"Type".to_vec(), Object::name("Measure")); d.set(b"Subtype".to_vec(), Object::name("RL")); d.set(b"R".to_vec(), PdfString::text(&self.ratio)); + if let Some(f) = &self.formats { + d.set(b"X".to_vec(), imported(&f.x, &self.unit, self.x)); + if self.x != self.y { + d.set(b"Y".to_vec(), imported(f.y.as_deref().unwrap_or(&f.x), &self.unit, self.y)); + d.set(b"CYX".to_vec(), Object::Real(1.0)); + } + d.set(b"D".to_vec(), imported(&f.distance, &self.unit, self.distance_factor)); + d.set(b"A".to_vec(), imported(&f.area, &self.area_unit, self.area_factor)); + return Ok(d); + } d.set(b"X".to_vec(), format(&self.unit, self.x)); if self.x != self.y { d.set(b"Y".to_vec(), format(&self.unit, self.y)); @@ -172,50 +201,51 @@ impl Scale { d.set(b"A".to_vec(), format(&self.area_unit, self.area_factor)); Ok(d) } - /// Single-unit decimal scales are editable. Compound/fractional and non-rectilinear - /// imports are refused explicitly; their dictionaries and appearance remain untouched. + /// Single-unit decimal scales are editable. Compound units (feet and inches), fractions and + /// values cut off to whole units read too, keeping their number format arrays in + /// [`Scale::formats`] (ISO 32000-2 §12.9.2). Non-rectilinear scales and formats that can't be + /// shown are refused explicitly; their dictionaries and appearance remain untouched. pub fn read(doc: &Document, object: &Object) -> Result { let o = doc.resolve(object); let d = o.as_dict().ok_or_else(|| invalid("invalid measure dictionary"))?; if d.get(b"Subtype").map(|o| doc.resolve(o)).is_some_and(|o| !matches!(*o, Object::Null) && o.as_name() != Some(b"RL")) { return Err(invalid("only rectilinear measurement scales are supported")); } - let format = |key: &[u8]| -> Result<(String, f64, u8)> { - let a = doc.resolve(d.get(key).ok_or_else(|| invalid("measurement scale lacks a number format"))?); - let a = a.as_array().ok_or_else(|| invalid("invalid measurement number format"))?; - if a.len() != 1 { - return Err(invalid("compound measurement units are not supported yet")); + let format = |key: &[u8]| -> Result> { + let a = d.get(key).ok_or_else(|| invalid("measurement scale lacks a number format"))?; + number_format::read(doc, a).map_err(invalid) + }; + // The unit and factor a number format array converts to first. + let first = |a: &[NumberFormat]| a.first().map(|f| (f.unit.clone(), f.factor)).ok_or_else(|| invalid("empty number format")); + let xs = format(b"X")?; + let (unit, x) = first(&xs)?; + let ys = if d.contains(b"Y") { Some(format(b"Y")?) } else { None }; + let y = match &ys { + Some(ys) => { + first(ys)?.1 + * d.get(b"CYX").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("Y scale requires CYX for lengths and areas"))? } - let o = doc.resolve(a.first().ok_or_else(|| invalid("empty number format"))?); - let f = o.as_dict().ok_or_else(|| invalid("invalid number format dictionary"))?; - let fmt = f.get(b"F").map(|o| doc.resolve(o)); - let precision = match fmt.as_deref().and_then(Object::as_name) { - Some(b"R") => 0, - None | Some(b"D") => { - let denom = f.get(b"D").and_then(|o| doc.resolve(o).as_int()).unwrap_or(100); - (0..=6).find(|p| 10_i64.pow(*p) == denom).ok_or_else(|| invalid("unsupported measurement precision"))? - } - _ => return Err(invalid("fractional measurement formats are not supported yet")), - }; - Ok(( - text(doc, f, b"U"), - f.get(b"C").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("missing conversion factor"))?, - precision as u8, - )) + None => x, }; - let (unit, x, _) = format(b"X")?; - let y = if d.contains(b"Y") { - let (_, y, _) = format(b"Y")?; - y * d.get(b"CYX").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("Y scale requires CYX for lengths and areas"))? - } else { - x - }; - let (distance_unit, distance_factor, precision) = format(b"D")?; + let distances = format(b"D")?; + let (distance_unit, distance_factor) = first(&distances)?; if unit != distance_unit { return Err(invalid("different coordinate and distance units are not supported yet")); } - let (area_unit, area_factor, _) = format(b"A")?; - let out = Self { x, y, unit, distance_factor, area_factor, area_unit, precision, ratio: text(doc, d, b"R") }; + let areas = format(b"A")?; + let (area_unit, area_factor) = first(&areas)?; + let plain = [&xs, &distances, &areas].into_iter().chain(ys.as_ref()).all(|a| number_format::plain_precision(a).is_some()); + // The decimals a distance shows: of its only unit, or of its last one when compound. + let precision = number_format::plain_precision(&distances) + .or_else(|| { + distances + .last() + .filter(|f| f.remainder == number_format::Remainder::Decimal) + .and_then(|f| u8::try_from(f.denominator.max(1).ilog10()).ok()) + }) + .unwrap_or(0); + let formats = (!plain).then_some(Formats { x: xs, y: ys, distance: distances, area: areas }); + let out = Self { x, y, unit, distance_factor, area_factor, area_unit, precision, ratio: text(doc, d, b"R"), formats }; out.validate()?; Ok(out) } @@ -319,10 +349,13 @@ pub fn reading(kind: Kind, points: &[Point], scale: &Scale) -> Result { length *= scale.distance_factor; let value = if kind == Kind::Area { area } else { length }; let unit = if kind == Kind::Area { scale.area_unit.clone() } else { scale.unit.clone() }; - let label = format!("{value:.precision$} {unit}", precision = usize::from(scale.precision)); if !value.is_finite() { return Err(invalid("measurement overflows its scale")); } + let label = match &scale.formats { + Some(f) => number_format::format(value, if kind == Kind::Area { &f.area } else { &f.distance }), + None => format!("{value:.precision$} {unit}", precision = usize::from(scale.precision)), + }; Ok(Reading { kind, value, unit, label, delta_x: delta[0], delta_y: delta[1], angle: delta[1].atan2(delta[0]).to_degrees(), length, area }) } #[derive(Clone, Debug, PartialEq)] @@ -479,7 +512,7 @@ const MAX_LISTED_BYTES: usize = 32 << 20; /// The bytes a listed measurement keeps in points and text. fn retained(m: &Measurement) -> usize { let s = &m.scale; - [m.id.len(), m.author.len(), m.label.len(), s.unit.len(), s.area_unit.len(), s.ratio.len()] + [m.id.len(), m.author.len(), m.label.len(), s.unit.len(), s.area_unit.len(), s.ratio.len(), s.formats.as_ref().map_or(0, Formats::held_bytes)] .into_iter() .fold(m.points.len().saturating_mul(std::mem::size_of::()), usize::saturating_add) } diff --git a/crates/measure/src/number_format.rs b/crates/measure/src/number_format.rs new file mode 100644 index 0000000000..a4396a9717 --- /dev/null +++ b/crates/measure/src/number_format.rs @@ -0,0 +1,510 @@ +//! Number format arrays (ISO 32000-2 §12.9.2, number format dictionaries). +//! +//! A rectilinear measure dictionary's `X`, `Y`, `D` and `A` entries are arrays of number format +//! dictionaries. The first element's `C` converts to the largest unit; each later element's `C` +//! is how many of its (smaller) unit make one of the previous element's. A value shows as whole +//! units of every element but the last, then what is left in the last unit, shown as its `F` +//! says: decimals to `1/D` (`/D`), a fraction in `D`ths (`/F`), or whole units rounded (`/R`) or +//! cut off (`/T`). With miles, feet, and inches in eighths, 1.4505 mi shows as +//! "1 mi 2,378 ft 7 5/8 in". + +use pdfcraft_cos::{Dict, Document, Object, PdfString}; +use serde::Serialize; + +/// Most elements one number format array is read with (miles, yards, feet and inches are four). +pub const MAX_UNITS: usize = 8; +/// Longest unit label or separator, in characters, as for a scale's own unit labels. +const MAX_TEXT: usize = 24; +/// Largest denominator of a fraction (`F /F`). +const MAX_DENOMINATOR: i64 = 1 << 16; +/// A remainder this close below a whole step counts as the step: `3.5 ft` stored as +/// `3.4999999999 ft` still cuts to 6 in, not 5 in. +const NUDGE: f64 = 1e-6; + +/// How the part of the last unit below a whole one shows (`F`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Remainder { + /// `/D`: decimals, to `1 / denominator`. + Decimal, + /// `/F`: a fraction in `denominator`ths. + Fraction, + /// `/R`: rounded to whole units. + Round, + /// `/T`: cut off to whole units. + Truncate, +} + +/// One number format dictionary. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct NumberFormat { + /// `U`: the unit's label. + pub unit: String, + /// `C`: this unit in one of the previous element's unit (or, for the first element, in what + /// the measure dictionary's entry converts from). + pub factor: f64, + /// `F`. + pub remainder: Remainder, + /// `D`: the decimal precision (a power of ten) or the fraction's denominator; 1 for whole units. + pub denominator: i64, + /// `FD`: decimals keep their trailing zeros and fractions are not reduced. + pub exact: bool, + /// `RT`: between groups of thousands. + pub thousands: String, + /// `RD`: the decimal point. + pub decimal: String, + /// `PS`: before the label. + pub before: String, + /// `SS`: after the label. + pub after: String, + /// `O /P`: the label goes before the number instead of after it. + pub prefix: bool, +} + +impl NumberFormat { + /// Steps of this unit counted by its remainder: `1/denominator` for decimals and fractions. + fn steps(&self) -> f64 { + match self.remainder { + Remainder::Decimal | Remainder::Fraction => self.denominator.max(1) as f64, + Remainder::Round | Remainder::Truncate => 1.0, + } + } + + /// `count` steps of this unit (whole, finite and not negative) as text. + fn number(&self, count: f64) -> String { + let denominator = self.denominator.max(1); + match self.remainder { + Remainder::Round | Remainder::Truncate => grouped(&format!("{count:.0}"), &self.thousands), + Remainder::Decimal => { + let places = denominator.ilog10() as usize; + let text = format!("{:.places$}", count / denominator as f64); + let (whole, part) = text.split_once('.').unwrap_or((&text, "")); + let part = if self.exact { part } else { part.trim_end_matches('0') }; + let whole = grouped(whole, &self.thousands); + if part.is_empty() { whole } else { format!("{whole}{}{part}", self.decimal) } + } + Remainder::Fraction => { + // The numerator is below the denominator however large and inexact the count is. + let numerator = (count.rem_euclid(denominator as f64) as i64).clamp(0, denominator - 1); + let whole = ((count - numerator as f64) / denominator as f64).round().max(0.0); + let text = grouped(&format!("{whole:.0}"), &self.thousands); + if numerator == 0 { + return text; + } + let g = if self.exact { 1 } else { gcd(numerator, denominator) }; + let fraction = format!("{}/{}", numerator / g, denominator / g); + if whole == 0.0 { fraction } else { format!("{text} {fraction}") } + } + } + } + + /// This format as a number format dictionary, every entry written out. + pub(crate) fn dictionary(&self) -> Object { + let mut d = Dict::new(); + d.set(b"Type".to_vec(), Object::name("NumberFormat")); + d.set(b"U".to_vec(), PdfString::text(&self.unit)); + d.set(b"C".to_vec(), Object::Real(self.factor)); + let f = match self.remainder { + Remainder::Decimal => "D", + Remainder::Fraction => "F", + Remainder::Round => "R", + Remainder::Truncate => "T", + }; + d.set(b"F".to_vec(), Object::name(f)); + if matches!(self.remainder, Remainder::Decimal | Remainder::Fraction) { + d.set(b"D".to_vec(), Object::Int(self.denominator)); + } + d.set(b"FD".to_vec(), Object::Bool(self.exact)); + d.set(b"RT".to_vec(), PdfString::text(&self.thousands)); + d.set(b"RD".to_vec(), PdfString::text(&self.decimal)); + d.set(b"PS".to_vec(), PdfString::text(&self.before)); + d.set(b"SS".to_vec(), PdfString::text(&self.after)); + d.set(b"O".to_vec(), Object::name(if self.prefix { "P" } else { "S" })); + Object::Dict(d) + } +} + +/// The number format arrays of an imported scale that a single-unit decimal scale can't stand +/// for: compound units (feet and inches), fractions, or values cut off to whole units. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Formats { + pub x: Vec, + pub y: Option>, + pub distance: Vec, + pub area: Vec, +} + +impl Formats { + /// Every array, `y` after `x` when there is one. + fn arrays(&self) -> impl Iterator> { + [&self.x, &self.distance, &self.area].into_iter().chain(self.y.as_ref()) + } + + /// Checks every array as [`crate::Scale::validate`] checks a scale's own fields. + pub(crate) fn validate(&self) -> Result<(), &'static str> { + self.arrays().try_for_each(|a| validate(a)) + } + + /// Bytes held, elements and their text, for a listing's bound on what it keeps. + pub(crate) fn held_bytes(&self) -> usize { + self.arrays() + .flatten() + .flat_map(|f| [&f.unit, &f.thousands, &f.decimal, &f.before, &f.after]) + .fold(0usize, |n, s| n.saturating_add(s.len())) + .saturating_add(self.arrays().map(Vec::len).sum::().saturating_mul(std::mem::size_of::())) + } +} + +/// The decimal places of a single-element decimal (`/D`) or rounded (`/R`) array: what a +/// single-unit decimal scale's `precision` describes. `None` for anything else. +pub(crate) fn plain_precision(formats: &[NumberFormat]) -> Option { + match formats { + [f] if f.remainder == Remainder::Decimal => u8::try_from(f.denominator.max(1).ilog10()).ok(), + [f] if f.remainder == Remainder::Round => Some(0), + _ => None, + } +} + +/// Reads the number format array `object` (resolving references), refusing a structure it can't +/// read or a precision it can't show. Labels, separators and later units' factors are checked +/// only when they are shown ([`Formats::validate`]): a single-unit decimal array is read for its +/// unit, factor and precision alone, as it always was. +pub(crate) fn read(doc: &Document, object: &Object) -> Result, &'static str> { + let a = doc.resolve(object); + let a = a.as_array().ok_or("invalid measurement number format")?; + if a.is_empty() { + return Err("empty number format"); + } + if a.len() > MAX_UNITS { + return Err("number formats of more than 8 units are not supported"); + } + a.iter().map(|o| read_one(doc, &doc.resolve(o))).collect() +} + +fn read_one(doc: &Document, o: &Object) -> Result { + let f = o.as_dict().ok_or("invalid number format dictionary")?; + let get = |k: &[u8]| f.get(k).map(|v| doc.resolve(v)); + let text = |k: &[u8], default: &str| get(k).and_then(|v| v.as_string().map(PdfString::to_text)).unwrap_or_else(|| default.into()); + let remainder = match get(b"F").as_deref().and_then(Object::as_name) { + None | Some(b"D") => Remainder::Decimal, + Some(b"F") => Remainder::Fraction, + Some(b"R") => Remainder::Round, + Some(b"T") => Remainder::Truncate, + Some(_) => return Err("unknown measurement number format"), + }; + let denominator = match remainder { + Remainder::Decimal => get(b"D").and_then(|v| v.as_int()).unwrap_or(100), + Remainder::Fraction => get(b"D").and_then(|v| v.as_int()).unwrap_or(16), + Remainder::Round | Remainder::Truncate => 1, + }; + let denominator_ok = match remainder { + Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == denominator), + Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&denominator), + Remainder::Round | Remainder::Truncate => true, + }; + if !denominator_ok { + return Err("unsupported measurement precision"); + } + // An empty RD means the default decimal point. + let decimal = Some(text(b"RD", ".")).filter(|s| !s.is_empty()).unwrap_or_else(|| ".".into()); + Ok(NumberFormat { + unit: text(b"U", ""), + factor: get(b"C").and_then(|v| v.as_f64()).ok_or("missing conversion factor")?, + remainder, + denominator, + exact: matches!(get(b"FD").as_deref(), Some(Object::Bool(true))), + thousands: text(b"RT", ","), + decimal, + before: text(b"PS", " "), + after: text(b"SS", " "), + prefix: get(b"O").as_deref().and_then(Object::as_name) == Some(b"P".as_slice()), + }) +} + +/// Checks an array: 1 to [`MAX_UNITS`] elements, factors as a scale's, labels and separators of +/// at most 24 printable characters, a decimal precision of 0 to 6 places and a denominator of 1 +/// to 65,536. +fn validate(formats: &[NumberFormat]) -> Result<(), &'static str> { + if formats.is_empty() || formats.len() > MAX_UNITS { + return Err("number formats have 1 to 8 units"); + } + for f in formats { + if !f.factor.is_finite() || !(1e-12..=1e12).contains(&f.factor) { + return Err("scale factors must be finite and between 1e-12 and 1e12"); + } + if f.unit.trim().is_empty() || f.unit.chars().count() > MAX_TEXT || f.unit.chars().any(char::is_control) { + return Err("unit labels must be 1 to 24 printable characters"); + } + if [&f.thousands, &f.decimal, &f.before, &f.after].iter().any(|s| s.chars().count() > MAX_TEXT || s.chars().any(char::is_control)) { + return Err("number format separators must be at most 24 printable characters"); + } + let denominator_ok = match f.remainder { + Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == f.denominator), + Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&f.denominator), + Remainder::Round | Remainder::Truncate => f.denominator == 1, + }; + if !denominator_ok { + return Err("unsupported measurement precision"); + } + } + Ok(()) +} + +/// `value`, in the first element's unit, as `formats` show it (ISO 32000-2 §12.9.2): whole units +/// of every element but the last, then the rest in the last element's unit. A last unit that +/// rounds up to a whole one of the unit before carries into it ("1 ft 0 in", not "0 ft 12 in"). +/// Not-a-number and infinite values show as nothing. +pub(crate) fn format(value: f64, formats: &[NumberFormat]) -> String { + let Some(last) = formats.last() else { return String::new() }; + if !value.is_finite() { + return String::new(); + } + let mut wholes = Vec::with_capacity(formats.len()); + let mut rest = value.abs(); + for next in formats.iter().skip(1) { + let whole = (rest + NUDGE).floor(); + wholes.push(whole); + rest = ((rest - whole) * next.factor).max(0.0); + } + let steps = last.steps(); + let mut count = if last.remainder == Remainder::Truncate { (rest * steps + NUDGE).floor() } else { (rest * steps).round() }; + carry(&mut count, steps, &mut wholes, formats); + let mut out = String::new(); + if value < 0.0 && (count > 0.0 || wholes.iter().any(|w| *w > 0.0)) { + out.push('-'); + } + for (whole, f) in wholes.iter().zip(formats) { + push_segment(&mut out, &grouped(&format!("{whole:.0}"), &f.thousands), f); + } + push_segment(&mut out, &last.number(count), last); + out.trim().to_string() +} + +/// Carries a last unit's `count` of `steps` that reached a whole one of the unit before into +/// it, and then each whole count of a unit into the unit before that. Only whole conversion +/// factors carry: a unit that isn't a whole number of the next has no whole count to carry. +fn carry(count: &mut f64, steps: f64, wholes: &mut [f64], formats: &[NumberFormat]) { + let full = formats.last().map_or(0.0, |f| f.factor * steps); + let Some(previous) = wholes.last_mut() else { return }; + if !is_whole(full) || *count < full { + return; + } + *count -= full; + *previous += 1.0; + for i in (1..wholes.len()).rev() { + let per = formats.get(i).map_or(0.0, |f| f.factor); + let (Some(&w), true) = (wholes.get(i), is_whole(per)) else { continue }; + if w >= per + && let Some([before, here]) = wholes.get_mut(i - 1..=i) + { + *here -= per; + *before += 1.0; + } + } +} + +fn is_whole(v: f64) -> bool { + v.is_finite() && v >= 1.0 && v.fract() == 0.0 +} + +fn push_segment(out: &mut String, number: &str, f: &NumberFormat) { + let label = [f.before.as_str(), &f.unit, &f.after].concat(); + if f.prefix { + out.push_str(&label); + out.push_str(number); + } else { + out.push_str(number); + out.push_str(&label); + } +} + +/// The ASCII digits of a whole number with `separator` between groups of three, from the right. +fn grouped(digits: &str, separator: &str) -> String { + let n = digits.len(); + let mut out = String::with_capacity(n + n / 3 * separator.len()); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (n - i).is_multiple_of(3) { + out.push_str(separator); + } + out.push(c); + } + out +} + +fn gcd(mut a: i64, mut b: i64) -> i64 { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + fn unit(unit: &str, factor: f64, remainder: Remainder, denominator: i64) -> NumberFormat { + NumberFormat { + unit: unit.into(), + factor, + remainder, + denominator, + exact: false, + thousands: ",".into(), + decimal: ".".into(), + before: " ".into(), + after: " ".into(), + prefix: false, + } + } + + fn feet_inches(denominator: i64) -> Vec { + vec![unit("ft", 1.0 / 864.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Fraction, denominator)] + } + + /// A file of a catalog, an empty page tree and `objects`, numbered from 3. + fn doc_with(objects: &[&str]) -> Document { + let pdf = pdfcraft_testkit::Pdf::new().obj("<< /Type /Catalog /Pages 2 0 R >>").obj("<< /Type /Pages /Kids [] /Count 0 >>").objs(objects); + Document::open(Arc::new(pdf.build())).unwrap() + } + + /// Reads `array`, stored by reference as the object after `objects` (numbered from 3). + fn parsed(objects: &[&str], array: &str) -> Result, &'static str> { + let doc = doc_with(&[objects, &[array]].concat()); + let num = u32::try_from(objects.len() + 3).unwrap(); + read(&doc, &Object::Ref(pdfcraft_cos::ObjRef { num, generation: 0 })) + } + + /// The miles, feet and eighths of inches that show "1 mi 2,378 ft 7 5/8 in". + #[test] + fn compound_units_show_whole_units_then_the_rest() { + let formats = + vec![unit("mi", 1.0, Remainder::Decimal, 100), unit("ft", 5280.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Fraction, 8)]; + assert_eq!(format(1.4505, &formats), "1 mi 2,378 ft 7 5/8 in"); + // A remainder reduces (4/8 is 1/2) unless FD keeps its denominator. + assert_eq!(format(3.0 + 6.5 / 12.0, &feet_inches(8)), "3 ft 6 1/2 in"); + let mut exact = feet_inches(8); + exact[1].exact = true; + assert_eq!(format(3.0 + 6.5 / 12.0, &exact), "3 ft 6 4/8 in"); + // No fractional part: the whole number alone; under one unit: the fraction alone. + assert_eq!(format(2.5, &feet_inches(16)), "2 ft 6 in"); + assert_eq!(format(1.0 / 96.0, &feet_inches(16)), "0 ft 1/8 in"); + } + + /// A remainder that rounds up to a whole one of the unit before carries into it, through + /// every unit that becomes whole in turn. + #[test] + fn a_remainder_that_rounds_up_carries() { + assert_eq!(format(1.0 - 1e-4, &feet_inches(16)), "1 ft 0 in"); + let formats = vec![unit("yd", 1.0, Remainder::Decimal, 100), unit("ft", 3.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Round, 1)]; + assert_eq!(format(2.0 - 1e-4, &formats), "2 yd 0 ft 0 in"); + // A factor that isn't whole has no whole count to carry: the rounded rest stays. + let odd = vec![unit("a", 1.0, Remainder::Decimal, 100), unit("b", 2.5, Remainder::Round, 1)]; + assert_eq!(format(1.9, &odd), "1 a 2 b"); + // A whole unit stored a hair below itself is still whole, factor whole or not. + assert_eq!(format(2.0 - 1e-10, &odd), "2 a 0 b"); + // A value stored a hair below a whole step still cuts to it. + let cut = vec![unit("ft", 1.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Truncate, 1)]; + assert_eq!(format(3.4999999999, &cut), "3 ft 6 in"); + assert_eq!(format(3.49, &cut), "3 ft 5 in"); + } + + /// Single-unit decimals, rounding and cutting, with the spec's separators and label position. + #[test] + fn decimals_separators_and_label_position() { + let mut decimal = unit("m", 1.0, Remainder::Decimal, 1000); + assert_eq!(format(1234.5, std::slice::from_ref(&decimal)), "1,234.5 m"); + decimal.exact = true; + assert_eq!(format(1234.5, std::slice::from_ref(&decimal)), "1,234.500 m"); + let euro = NumberFormat { thousands: ".".into(), decimal: ",".into(), ..decimal.clone() }; + assert_eq!(format(1_234_567.25, std::slice::from_ref(&euro)), "1.234.567,250 m"); + assert_eq!(format(7.0, &[unit("m", 1.0, Remainder::Decimal, 100)]), "7 m"); + assert_eq!(format(7.6, &[unit("m", 1.0, Remainder::Round, 1)]), "8 m"); + assert_eq!(format(7.6, &[unit("m", 1.0, Remainder::Truncate, 1)]), "7 m"); + let prefixed = NumberFormat { prefix: true, before: String::new(), after: String::new(), ..unit("$", 1.0, Remainder::Decimal, 100) }; + assert_eq!(format(12.5, &[prefixed]), "$12.5"); + let tight = vec![ + NumberFormat { before: String::new(), after: String::new(), ..unit("'", 1.0, Remainder::Decimal, 100) }, + NumberFormat { before: String::new(), after: String::new(), ..unit("\"", 12.0, Remainder::Fraction, 4) }, + ]; + assert_eq!(format(12.0 + 3.25 / 12.0, &tight), "12'3 1/4\""); + // Negative values keep their sign; nothing shows for none and for non-finite values. + assert_eq!(format(-2.5, &feet_inches(16)), "-2 ft 6 in"); + assert_eq!(format(-0.0, &feet_inches(16)), "0 ft 0 in"); + assert_eq!(format(1.0, &[]), ""); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!(format(bad, &feet_inches(16)), ""); + } + // The largest values a scale allows show in full, without an exponent. + let huge = format(1e30, &feet_inches(16)); + assert!(huge.starts_with("1,000,000,000,000,000,019,884,624,838,656 ft"), "{huge}"); + // A fraction of a value too large to be exact still has a numerator below its denominator. + let fraction = format(1e30, &[unit("in", 1.0, Remainder::Fraction, 3)]); + let tokens: Vec<&str> = fraction.split_whitespace().collect(); + assert!(matches!(tokens.as_slice(), [_, "in"] | [_, "1/3" | "2/3", "in"]), "{fraction}"); + } + + /// Every entry is read with its default, references resolved, and written back as read. + #[test] + fn arrays_read_with_defaults_and_write_back() { + let source = "[<< /U (ft) /C 0.5 >> << /U 3 0 R /C 4 0 R /F 5 0 R /D 8 /FD true /RT (.) /RD () /PS () /SS (-) /O /P >>]"; + let read_back = parsed(&["(in)", "12", "/F"], source).unwrap(); + assert_eq!(read_back[0], unit("ft", 0.5, Remainder::Decimal, 100)); + let inches = &read_back[1]; + assert_eq!((inches.unit.as_str(), inches.factor, inches.remainder, inches.denominator), ("in", 12.0, Remainder::Fraction, 8)); + assert!(inches.exact && inches.prefix); + assert_eq!((inches.thousands.as_str(), inches.decimal.as_str(), inches.before.as_str(), inches.after.as_str()), (".", ".", "", "-")); + assert_eq!(parsed(&[], "[<< /U (in) /C 1 /F /F >>]").unwrap()[0].denominator, 16); + // Written out and read again, nothing changes. + let written = Object::Array(read_back.iter().map(NumberFormat::dictionary).collect()); + assert_eq!(read(&doc_with(&[]), &written).unwrap(), read_back); + assert_eq!(plain_precision(&read_back), None); + assert_eq!(plain_precision(&read_back[..1]), Some(2)); + assert_eq!(plain_precision(&[unit("m", 1.0, Remainder::Round, 1)]), Some(0)); + assert_eq!(plain_precision(&[unit("m", 1.0, Remainder::Fraction, 16)]), None); + assert_eq!(plain_precision(&[unit("m", 1.0, Remainder::Truncate, 1)]), None); + } + + /// What can't be shown faithfully is refused with a reason, before anything is formatted. + #[test] + fn unreadable_arrays_are_refused() { + let units = |n: usize| format!("[{}]", vec!["<< /U (u) /C 1 >>"; n].join(" ")); + let nine = units(9); + for (source, reason) in [ + ("[]", "empty number format"), + ("<< /U (ft) /C 1 >>", "invalid measurement number format"), + (nine.as_str(), "number formats of more than 8 units are not supported"), + ("[(ft)]", "invalid number format dictionary"), + ("[<< /U (ft) /C 1 /F /X >>]", "unknown measurement number format"), + ("[<< /U (ft) >>]", "missing conversion factor"), + ("[<< /U (ft) /C 0 >>]", "scale factors must be finite and between 1e-12 and 1e12"), + ("[<< /C 1 >>]", "unit labels must be 1 to 24 printable characters"), + ("[<< /U (ft) /C 1 /D 12 >>]", "unsupported measurement precision"), + ("[<< /U (ft) /C 1 /D 10000000 >>]", "unsupported measurement precision"), + ("[<< /U (ft) /C 1 /F /F /D 0 >>]", "unsupported measurement precision"), + ("[<< /U (ft) /C 1 /F /F /D 65537 >>]", "unsupported measurement precision"), + ("[<< /U (ft) /C 1 /SS (aaaaaaaaaaaaaaaaaaaaaaaaa) >>]", "number format separators must be at most 24 printable characters"), + ] { + assert_eq!(parsed(&[], source).and_then(|f| validate(&f).map(|()| f)), Err(reason), "{source}"); + } + assert_eq!(parsed(&[], "[<< /U (ft) /C 1 /F /F /D 65536 >>]").unwrap()[0].denominator, 65536); + assert_eq!(parsed(&[], &units(MAX_UNITS)).map(|f| f.len()), Ok(MAX_UNITS)); + } + + /// What formats hold is counted for the listing bound. + #[test] + fn formats_count_their_text() { + let f = Formats { + x: feet_inches(16), + y: Some(feet_inches(16)), + distance: feet_inches(16), + area: vec![unit("ft²", 1.0, Remainder::Decimal, 100)], + }; + // Each element holds its label and "," "." " " " " (4 bytes). + let elements = 3 * 2 + 1; + assert_eq!(f.held_bytes(), 3 * ((2 + 4) + (2 + 4)) + ("ft²".len() + 4) + elements * std::mem::size_of::()); + assert_eq!(f.validate(), Ok(())); + let bad = Formats { y: Some(Vec::new()), ..f }; + assert_eq!(bad.validate(), Err("number formats have 1 to 8 units")); + } +} diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 80d30fdefe..902ac34a4b 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -283,13 +283,14 @@ fn unsupported_measurements_are_reported_not_fatal() { let mut d = fixture("", "", &[]); add(&mut d, &new(Kind::Distance, vec![[0.0, 0.0], [3.0, 4.0]]), &Meta::default()).unwrap(); add(&mut d, &new(Kind::Distance, vec![[10.0, 0.0], [13.0, 4.0]]), &Meta::default()).unwrap(); - // An imported compound feet-and-inches format (two NumberFormat dictionaries). + // An imported format this crate can't show (an unknown /F). let (r, _) = annot(&d, 0, 1).unwrap(); let format = |unit: &str, c: f64| { let mut f = Dict::new(); f.set(b"Type".to_vec(), Object::name("NumberFormat")); f.set(b"U".to_vec(), PdfString::text(unit)); f.set(b"C".to_vec(), Object::Real(c)); + f.set(b"F".to_vec(), Object::name("X")); Object::Dict(f) }; d.update_dict(r, |a| { @@ -302,7 +303,7 @@ fn unsupported_measurements_are_reported_not_fatal() { assert_eq!(listing.measurements.len(), 1); assert_eq!(listing.unsupported.len(), 1); assert_eq!((listing.unsupported[0].page, listing.unsupported[0].index), (0, 1)); - assert!(listing.unsupported[0].reason.contains("compound"), "{}", listing.unsupported[0].reason); + assert_eq!(listing.unsupported[0].reason, "unknown measurement number format"); // Invalid geometry on an imported annotation is reported the same way. let (r, _) = annot(&d, 0, 0).unwrap(); d.update_dict(r, |a| a.set(b"L".to_vec(), nums([0.0, 0.0, f64::NAN, 1.0]))).unwrap(); @@ -632,3 +633,49 @@ fn indirect_scale_fields_and_closed_area_edges_are_handled() { assert_eq!(item.label, "Floor Plan"); assert_eq!(item.scale, Scale { y: 3.0, ..Scale::new(2.0, "m", 3).unwrap() }); } + +/// An Acrobat-style drawing scale of 1 in = 1 ft whose distances show in feet and sixteenths of +/// inches (ISO 32000-2 §12.9.2): a viewport and a saved measurement using it read, are labelled +/// in feet and inches, and a measurement added inside the viewport keeps the formats. +#[test] +fn compound_and_fractional_scales_read_label_and_carry_into_new_measurements() { + let feet_inches = "[<< /Type /NumberFormat /U (ft) /C 0.0138888888888889 /D 100 >> << /U (in) /C 12 /F /F /D 16 >>]"; + let measure = format!( + "<< /Type /Measure /Subtype /RL /R (1 in = 1 ft) /X {feet_inches} /D [<< /U (ft) /C 1 >> << /U (in) /C 12 /F /F /D 16 >>] /A [<< /U (sq ft) /C 1 /F /T >>] >>" + ); + let mut d = fixture("", &format!("/VP [<< /Type /Viewport /BBox [0 0 612 792] /Measure {measure} >>]"), &[]); + let scale = scale_at(&d, 0, [10.0, 10.0]).unwrap(); + assert_eq!((scale.unit.as_str(), scale.area_unit.as_str(), scale.precision), ("ft", "sq ft", 0)); + close(scale.x, 1.0 / 72.0); + let formats = scale.formats.as_ref().unwrap(); + assert_eq!(formats.distance.len(), 2); + // 3 ft 6 1/2 in at 1 in = 1 ft is 3 in and 6.5 / 12 in on the page: 216 + 39 points. + let distance = reading(Kind::Distance, &[[0.0, 0.0], [0.0, 255.0]], &scale).unwrap(); + close(distance.value, 255.0 / 72.0); + assert_eq!(distance.label, "3 ft 6 1/2 in"); + // Just short of 2 ft carries into the feet; an area of 2.9 sq ft is cut off to 2. + assert_eq!(reading(Kind::Distance, &[[0.0, 0.0], [143.99, 0.0]], &scale).unwrap().label, "2 ft 0 in"); + let side = (2.9f64).sqrt() * 72.0; + assert_eq!(reading(Kind::Area, &[[0.0, 0.0], [side, 0.0], [side, side], [0.0, side]], &scale).unwrap().label, "2 sq ft"); + + // Added inside the viewport, as the Measure tool and measure_distance do, the measurement + // keeps the compound formats and reads the same after a save. + let mut m = new(Kind::Distance, vec![[0.0, 0.0], [0.0, 255.0]]); + m.scale = scale.clone(); + add(&mut d, &m, &Meta { date: None, id: "plan".into() }).unwrap(); + let (_, dict) = annot(&d, 0, 0).unwrap(); + assert_eq!(text(&d, &dict, b"Contents"), "3 ft 6 1/2 in"); + let saved = d.resolve(dict.get(b"Measure").unwrap()); + let saved_d = d.resolve(saved.as_dict().unwrap().get(b"D").unwrap()); + let inches = saved_d.as_array().unwrap()[1].as_dict().unwrap().clone(); + assert_eq!(inches.get(b"F").and_then(Object::as_name), Some(b"F".as_slice())); + assert_eq!(inches.get(b"D").and_then(Object::as_int), Some(16)); + let reopened = Document::open(Arc::new(write_full(&d, &SaveOptions::default()).unwrap())).unwrap(); + let listing = list(&reopened); + assert!(listing.unsupported.is_empty(), "{:?}", listing.unsupported); + assert_eq!(listing.measurements[0].reading.label, "3 ft 6 1/2 in"); + close(listing.measurements[0].scale.x, scale.x); + assert_eq!(listing.measurements[0].scale.formats.as_ref().map(|f| (f.x.len(), f.distance.len(), f.area.len())), Some((2, 2, 1))); + // A plain decimal scale keeps no formats and labels as before. + assert_eq!(Scale::read(&d, &Object::Dict(Scale::new(2.0, "m", 3).unwrap().dictionary().unwrap())).unwrap().formats, None); +} From bbdc4f96deb0c9576e901215bb8db0f60a9d1bb6 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:35:27 +0800 Subject: [PATCH 09/21] Rerun CI: the gate failed on an automation batch test flake this PR doesn't touch From c2355b0b0eeafd3db920674eb6b70739f9db50d9 Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Thu, 12 Nov 2026 21:36:03 +0800 Subject: [PATCH 10/21] fix(measure): nudge whole units by a step of the last unit; keep Y's own units and CYX A whole-unit nudge measured in the larger unit could exceed a step of the last unit (1 km - 0.9 mm showed as 1 km 0 m). A compound Y in units other than X's was relabelled with X's unit and lost its CYX when written back. --- crates/measure/src/lib.rs | 27 +++++++++++++++++-------- crates/measure/src/number_format.rs | 31 ++++++++++++++++++++++++----- crates/measure/src/tests.rs | 23 +++++++++++++++++++++ 3 files changed, 68 insertions(+), 13 deletions(-) diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index d8bfda587d..111594a84a 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -69,6 +69,8 @@ pub struct Scale { pub distance_factor: f64, pub area_factor: f64, pub area_unit: String, + /// Decimal places of a distance. With [`Scale::formats`], those of the last distance unit + /// when it shows decimals (0 otherwise); the formats, not this, label the readings. pub precision: u8, pub ratio: String, /// The number format arrays of an imported scale whose units are compound (feet and inches) @@ -184,9 +186,18 @@ impl Scale { d.set(b"R".to_vec(), PdfString::text(&self.ratio)); if let Some(f) = &self.formats { d.set(b"X".to_vec(), imported(&f.x, &self.unit, self.x)); - if self.x != self.y { - d.set(b"Y".to_vec(), imported(f.y.as_deref().unwrap_or(&f.x), &self.unit, self.y)); - d.set(b"CYX".to_vec(), Object::Real(1.0)); + match &f.y { + // Y keeps its own units, and the CYX that converts them to X's. + Some(ys) => { + let unit = ys.first().map_or(self.unit.as_str(), |f| f.unit.as_str()); + d.set(b"Y".to_vec(), imported(ys, unit, self.y / f.cyx)); + d.set(b"CYX".to_vec(), Object::Real(f.cyx)); + } + None if self.x != self.y => { + d.set(b"Y".to_vec(), imported(&f.x, &self.unit, self.y)); + d.set(b"CYX".to_vec(), Object::Real(1.0)); + } + None => {} } d.set(b"D".to_vec(), imported(&f.distance, &self.unit, self.distance_factor)); d.set(b"A".to_vec(), imported(&f.area, &self.area_unit, self.area_factor)); @@ -220,12 +231,12 @@ impl Scale { let xs = format(b"X")?; let (unit, x) = first(&xs)?; let ys = if d.contains(b"Y") { Some(format(b"Y")?) } else { None }; - let y = match &ys { + let (y, cyx) = match &ys { Some(ys) => { - first(ys)?.1 - * d.get(b"CYX").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("Y scale requires CYX for lengths and areas"))? + let cyx = d.get(b"CYX").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("Y scale requires CYX for lengths and areas"))?; + (first(ys)?.1 * cyx, cyx) } - None => x, + None => (x, 1.0), }; let distances = format(b"D")?; let (distance_unit, distance_factor) = first(&distances)?; @@ -244,7 +255,7 @@ impl Scale { .and_then(|f| u8::try_from(f.denominator.max(1).ilog10()).ok()) }) .unwrap_or(0); - let formats = (!plain).then_some(Formats { x: xs, y: ys, distance: distances, area: areas }); + let formats = (!plain).then_some(Formats { x: xs, y: ys, cyx, distance: distances, area: areas }); let out = Self { x, y, unit, distance_factor, area_factor, area_unit, precision, ratio: text(doc, d, b"R"), formats }; out.validate()?; Ok(out) diff --git a/crates/measure/src/number_format.rs b/crates/measure/src/number_format.rs index a4396a9717..daafc80b9f 100644 --- a/crates/measure/src/number_format.rs +++ b/crates/measure/src/number_format.rs @@ -17,8 +17,8 @@ pub const MAX_UNITS: usize = 8; const MAX_TEXT: usize = 24; /// Largest denominator of a fraction (`F /F`). const MAX_DENOMINATOR: i64 = 1 << 16; -/// A remainder this close below a whole step counts as the step: `3.5 ft` stored as -/// `3.4999999999 ft` still cuts to 6 in, not 5 in. +/// A remainder this close below a whole step of the last unit, in steps, counts as the step: +/// `3.5 ft` stored as `3.4999999999 ft` still cuts to 6 in, not 5 in. const NUDGE: f64 = 1e-6; /// How the part of the last unit below a whole one shows (`F`). @@ -128,9 +128,15 @@ impl NumberFormat { /// for: compound units (feet and inches), fractions, or values cut off to whole units. #[derive(Clone, Debug, PartialEq, Serialize)] pub struct Formats { + /// `X`: changes along the x axis (and the y axis when there is no `Y`). pub x: Vec, + /// `Y`: changes along the y axis, in its own units, as read. pub y: Option>, + /// `CYX`: y-axis units in one x-axis unit, as read with `y` (1 without it). + pub cyx: f64, + /// `D`: distances. pub distance: Vec, + /// `A`: areas. pub area: Vec, } @@ -142,6 +148,9 @@ impl Formats { /// Checks every array as [`crate::Scale::validate`] checks a scale's own fields. pub(crate) fn validate(&self) -> Result<(), &'static str> { + if !self.cyx.is_finite() || !(1e-12..=1e12).contains(&self.cyx) { + return Err("scale factors must be finite and between 1e-12 and 1e12"); + } self.arrays().try_for_each(|a| validate(a)) } @@ -259,14 +268,17 @@ pub(crate) fn format(value: f64, formats: &[NumberFormat]) -> String { if !value.is_finite() { return String::new(); } + let steps = last.steps(); let mut wholes = Vec::with_capacity(formats.len()); let mut rest = value.abs(); - for next in formats.iter().skip(1) { - let whole = (rest + NUDGE).floor(); + for (i, next) in formats.iter().enumerate().skip(1) { + // The nudge is a fraction of a step of the last unit, however many units lie between. + let per_step = formats.iter().skip(i).fold(steps, |p, f| p * f.factor); + let nudge = if per_step.is_finite() && per_step > 1.0 { NUDGE / per_step } else { NUDGE }; + let whole = (rest + nudge).floor(); wholes.push(whole); rest = ((rest - whole) * next.factor).max(0.0); } - let steps = last.steps(); let mut count = if last.remainder == Remainder::Truncate { (rest * steps + NUDGE).floor() } else { (rest * steps).round() }; carry(&mut count, steps, &mut wholes, formats); let mut out = String::new(); @@ -403,6 +415,12 @@ mod tests { assert_eq!(format(1.9, &odd), "1 a 2 b"); // A whole unit stored a hair below itself is still whole, factor whole or not. assert_eq!(format(2.0 - 1e-10, &odd), "2 a 0 b"); + // ... but a value a step of the last unit short of it is not, however small the step. + let metres = vec![unit("km", 1.0, Remainder::Decimal, 100), unit("m", 1000.0, Remainder::Decimal, 1000)]; + assert_eq!(format(1.0 - 9e-7, &metres), "0 km 999.999 m"); + let miles = + vec![unit("mi", 1.0, Remainder::Decimal, 100), unit("ft", 5280.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Fraction, 64)]; + assert_eq!(format(1.0 - 9e-7, &miles), "0 mi 5,279 ft 11 15/16 in"); // A value stored a hair below a whole step still cuts to it. let cut = vec![unit("ft", 1.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Truncate, 1)]; assert_eq!(format(3.4999999999, &cut), "3 ft 6 in"); @@ -497,6 +515,7 @@ mod tests { let f = Formats { x: feet_inches(16), y: Some(feet_inches(16)), + cyx: 1.0, distance: feet_inches(16), area: vec![unit("ft²", 1.0, Remainder::Decimal, 100)], }; @@ -504,6 +523,8 @@ mod tests { let elements = 3 * 2 + 1; assert_eq!(f.held_bytes(), 3 * ((2 + 4) + (2 + 4)) + ("ft²".len() + 4) + elements * std::mem::size_of::()); assert_eq!(f.validate(), Ok(())); + let bad = Formats { cyx: 0.0, ..f.clone() }; + assert_eq!(bad.validate(), Err("scale factors must be finite and between 1e-12 and 1e12")); let bad = Formats { y: Some(Vec::new()), ..f }; assert_eq!(bad.validate(), Err("number formats have 1 to 8 units")); } diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 902ac34a4b..8d75d4ddf2 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -679,3 +679,26 @@ fn compound_and_fractional_scales_read_label_and_carry_into_new_measurements() { // A plain decimal scale keeps no formats and labels as before. assert_eq!(Scale::read(&d, &Object::Dict(Scale::new(2.0, "m", 3).unwrap().dictionary().unwrap())).unwrap().formats, None); } + +/// A compound Y in units of its own (metres and centimetres against feet and inches) is written +/// back as read, with its CYX, so a viewer showing y coordinates reads the same units. +#[test] +fn a_compound_y_keeps_its_units_and_cyx() { + let x = "[<< /U (ft) /C 0.0138888888888889 >> << /U (in) /C 12 /F /F /D 16 >>]"; + let y = "[<< /U (m) /C 0.000352778 >> << /U (cm) /C 100 /D 10 >>]"; + let measure = format!("<< /Type /Measure /Subtype /RL /X {x} /Y {y} /CYX 3.28084 /D {x} /A [<< /U (sq ft) /C 1 >>] >>"); + let d = fixture("", &format!("/VP [<< /Type /Viewport /BBox [0 0 612 792] /Measure {measure} >>]"), &[]); + let scale = scale_at(&d, 0, [10.0, 10.0]).unwrap(); + close(scale.y, 0.000352778 * 3.28084); + let written = scale.dictionary().unwrap(); + close(written.get(b"CYX").and_then(Object::as_f64).unwrap(), 3.28084); + let ys = written.get(b"Y").and_then(Object::as_array).unwrap(); + let first = ys[0].as_dict().unwrap(); + assert_eq!(text(&d, first, b"U"), "m"); + close(first.get(b"C").and_then(Object::as_f64).unwrap(), 0.000352778); + assert_eq!(text(&d, ys[1].as_dict().unwrap(), b"U"), "cm"); + let again = Scale::read(&d, &Object::Dict(written)).unwrap(); + close(again.y, scale.y); + let formats = again.formats.unwrap(); + assert_eq!((formats.y.unwrap()[1].factor, formats.cyx), (100.0, 3.28084)); +} From 4439794769106561e1a293dc1b18c50aedaada08 Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Thu, 12 Nov 2026 22:05:28 +0800 Subject: [PATCH 11/21] fix(measure): validate written Y factor and check /F and /D on last format only --- crates/measure/src/lib.rs | 6 +++ crates/measure/src/number_format.rs | 75 +++++++++++++++++------------ crates/measure/src/tests.rs | 7 +++ 3 files changed, 56 insertions(+), 32 deletions(-) diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index 111594a84a..67efab1a9a 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -157,6 +157,12 @@ impl Scale { } if let Some(formats) = &self.formats { formats.validate().map_err(invalid)?; + if formats.y.is_some() { + let yf = self.y / formats.cyx; + if !yf.is_finite() || !(1e-12..=1e12).contains(&yf) { + return Err(invalid("scale factors must be finite and between 1e-12 and 1e12")); + } + } } Ok(()) } diff --git a/crates/measure/src/number_format.rs b/crates/measure/src/number_format.rs index daafc80b9f..d844d789eb 100644 --- a/crates/measure/src/number_format.rs +++ b/crates/measure/src/number_format.rs @@ -187,33 +187,40 @@ pub(crate) fn read(doc: &Document, object: &Object) -> Result, if a.len() > MAX_UNITS { return Err("number formats of more than 8 units are not supported"); } - a.iter().map(|o| read_one(doc, &doc.resolve(o))).collect() + a.iter().enumerate().map(|(i, o)| read_one(doc, &doc.resolve(o), i + 1 == a.len())).collect() } -fn read_one(doc: &Document, o: &Object) -> Result { +fn read_one(doc: &Document, o: &Object, is_last: bool) -> Result { let f = o.as_dict().ok_or("invalid number format dictionary")?; let get = |k: &[u8]| f.get(k).map(|v| doc.resolve(v)); let text = |k: &[u8], default: &str| get(k).and_then(|v| v.as_string().map(PdfString::to_text)).unwrap_or_else(|| default.into()); - let remainder = match get(b"F").as_deref().and_then(Object::as_name) { - None | Some(b"D") => Remainder::Decimal, - Some(b"F") => Remainder::Fraction, - Some(b"R") => Remainder::Round, - Some(b"T") => Remainder::Truncate, - Some(_) => return Err("unknown measurement number format"), + // ISO 32000-2 §12.9.2: only the last element formats a remainder (`/F`, `/D`, `/FD`); + // earlier elements always format whole units. + let (remainder, denominator, exact) = if is_last { + let remainder = match get(b"F").as_deref().and_then(Object::as_name) { + None | Some(b"D") => Remainder::Decimal, + Some(b"F") => Remainder::Fraction, + Some(b"R") => Remainder::Round, + Some(b"T") => Remainder::Truncate, + Some(_) => return Err("unknown measurement number format"), + }; + let denominator = match remainder { + Remainder::Decimal => get(b"D").and_then(|v| v.as_int()).unwrap_or(100), + Remainder::Fraction => get(b"D").and_then(|v| v.as_int()).unwrap_or(16), + Remainder::Round | Remainder::Truncate => 1, + }; + let denominator_ok = match remainder { + Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == denominator), + Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&denominator), + Remainder::Round | Remainder::Truncate => true, + }; + if !denominator_ok { + return Err("unsupported measurement precision"); + } + (remainder, denominator, matches!(get(b"FD").as_deref(), Some(Object::Bool(true)))) + } else { + (Remainder::Decimal, 100, false) }; - let denominator = match remainder { - Remainder::Decimal => get(b"D").and_then(|v| v.as_int()).unwrap_or(100), - Remainder::Fraction => get(b"D").and_then(|v| v.as_int()).unwrap_or(16), - Remainder::Round | Remainder::Truncate => 1, - }; - let denominator_ok = match remainder { - Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == denominator), - Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&denominator), - Remainder::Round | Remainder::Truncate => true, - }; - if !denominator_ok { - return Err("unsupported measurement precision"); - } // An empty RD means the default decimal point. let decimal = Some(text(b"RD", ".")).filter(|s| !s.is_empty()).unwrap_or_else(|| ".".into()); Ok(NumberFormat { @@ -221,7 +228,7 @@ fn read_one(doc: &Document, o: &Object) -> Result { factor: get(b"C").and_then(|v| v.as_f64()).ok_or("missing conversion factor")?, remainder, denominator, - exact: matches!(get(b"FD").as_deref(), Some(Object::Bool(true))), + exact, thousands: text(b"RT", ","), decimal, before: text(b"PS", " "), @@ -231,13 +238,13 @@ fn read_one(doc: &Document, o: &Object) -> Result { } /// Checks an array: 1 to [`MAX_UNITS`] elements, factors as a scale's, labels and separators of -/// at most 24 printable characters, a decimal precision of 0 to 6 places and a denominator of 1 -/// to 65,536. +/// at most 24 printable characters, and on the last element a decimal precision of 0 to 6 places +/// or a fraction denominator of 1 to 65,536. fn validate(formats: &[NumberFormat]) -> Result<(), &'static str> { if formats.is_empty() || formats.len() > MAX_UNITS { return Err("number formats have 1 to 8 units"); } - for f in formats { + for (i, f) in formats.iter().enumerate() { if !f.factor.is_finite() || !(1e-12..=1e12).contains(&f.factor) { return Err("scale factors must be finite and between 1e-12 and 1e12"); } @@ -247,13 +254,15 @@ fn validate(formats: &[NumberFormat]) -> Result<(), &'static str> { if [&f.thousands, &f.decimal, &f.before, &f.after].iter().any(|s| s.chars().count() > MAX_TEXT || s.chars().any(char::is_control)) { return Err("number format separators must be at most 24 printable characters"); } - let denominator_ok = match f.remainder { - Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == f.denominator), - Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&f.denominator), - Remainder::Round | Remainder::Truncate => f.denominator == 1, - }; - if !denominator_ok { - return Err("unsupported measurement precision"); + if i + 1 == formats.len() { + let denominator_ok = match f.remainder { + Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == f.denominator), + Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&f.denominator), + Remainder::Round | Remainder::Truncate => f.denominator == 1, + }; + if !denominator_ok { + return Err("unsupported measurement precision"); + } } } Ok(()) @@ -506,6 +515,8 @@ mod tests { assert_eq!(parsed(&[], source).and_then(|f| validate(&f).map(|()| f)), Err(reason), "{source}"); } assert_eq!(parsed(&[], "[<< /U (ft) /C 1 /F /F /D 65536 >>]").unwrap()[0].denominator, 65536); + // Only the last element's `/F` and `/D` format a remainder; earlier elements' `/F` and `/D` are ignored. + assert_eq!(parsed(&[], "[<< /U (ft) /C 1 /F /X /D 12 >> << /U (in) /C 12 /F /F /D 16 >>]").map(|f| f.len()), Ok(2)); assert_eq!(parsed(&[], &units(MAX_UNITS)).map(|f| f.len()), Ok(MAX_UNITS)); } diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 8d75d4ddf2..80c09d039f 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -701,4 +701,11 @@ fn a_compound_y_keeps_its_units_and_cyx() { close(again.y, scale.y); let formats = again.formats.unwrap(); assert_eq!((formats.y.unwrap()[1].factor, formats.cyx), (100.0, 3.28084)); + // If `Scale.y` is mutated so `self.y / cyx` exceeds the factor bound, `dictionary()` refuses it. + let mut overflow_y = scale; + if let Some(f) = &mut overflow_y.formats { + f.cyx = 1e-12; + } + overflow_y.y = 2.0; + assert!(overflow_y.dictionary().is_err()); } From f52c6d8555ee4e3c5b80f64c1d0947263a68f6e9 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 12 Nov 2026 18:53:52 +0100 Subject: [PATCH 12/21] fix(startup): an OPENSSL_ia32cap naming a missing CPU feature no longer stops PdfCraft (#2916) --- .cargo/config.toml | 7 +++ apps/pdfcraft-cli/src/main.rs | 5 ++ apps/pdfcraft-cli/tests/it/cpu_override.rs | 30 ++++++++++ apps/pdfcraft-cli/tests/it/main.rs | 1 + apps/pdfcraft/src/main.rs | 8 +++ apps/pdfcraft/tests/help.rs | 17 +++++- crates/platform/src/crypto_env.rs | 66 ++++++++++++++++++++++ crates/platform/src/lib.rs | 4 +- 8 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 apps/pdfcraft-cli/tests/it/cpu_override.rs create mode 100644 crates/platform/src/crypto_env.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index a1caaeaa38..623a308be7 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -5,3 +5,10 @@ xtask = "run -p xtask --" # engine's kernels (rten-simd) and other vectorised code only use it when compiled in. [target.wasm32-unknown-unknown] rustflags = ["-C", "target-feature=+simd128"] + +# aws-lc (digital signatures and TLS, through aws-lc-rs) detects the CPU on first use, not in a +# static initializer before `main`. On x86 it reads `OPENSSL_ia32cap` then, and aborts when that +# asks for a feature the processor lacks; each executable first runs itself again without the +# variable (#2916, `pdfcraft_platform::crypto_env`), which it can only do once `main` runs. +[env] +AWS_LC_SYS_CFLAGS = "-DBORINGSSL_NO_STATIC_INITIALIZER" diff --git a/apps/pdfcraft-cli/src/main.rs b/apps/pdfcraft-cli/src/main.rs index 0c7fa9ba22..ab905c2846 100644 --- a/apps/pdfcraft-cli/src/main.rs +++ b/apps/pdfcraft-cli/src/main.rs @@ -98,6 +98,11 @@ help and feedback: https://discord.gg/artcraft" ); fn main() -> ExitCode { + // Before anything uses aws-lc: an `OPENSSL_ia32cap` naming a CPU feature this processor lacks + // would stop it, so the CLI runs again without it (#2916, `pdfcraft_platform::crypto_env`). + if let Some(code) = pdfcraft_platform::crypto_env::run_without_cpu_override() { + std::process::exit(code); + } // `std::env::args` panics on an argument that is not UTF-8 ("called `Result::unwrap()` on an // `Err` value"), which a Latin-1 file name is, and it panics while collecting them: even // `--help` ended that way. Such a name cannot be passed on either, since the paths here are diff --git a/apps/pdfcraft-cli/tests/it/cpu_override.rs b/apps/pdfcraft-cli/tests/it/cpu_override.rs new file mode 100644 index 0000000000..d5dc87c790 --- /dev/null +++ b/apps/pdfcraft-cli/tests/it/cpu_override.rs @@ -0,0 +1,30 @@ +//! An `OPENSSL_ia32cap` that asks for a CPU feature the processor lacks stops neither the CLI nor +//! its signing (#2916). aws-lc printed "Fatal Error: HW capability found: …" and aborted before +//! `main`. Built to detect the CPU on first use, it would abort at the first signature instead. + +use std::process::{Command, Output}; + +/// CPUID leaf 1, EDX bit 10: reserved, so no x86 processor reports it. +const MISSING_FEATURE: &str = "0x400"; + +fn run(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_pdfcraft-cli")).args(args).env("OPENSSL_ia32cap", MISSING_FEATURE).output().unwrap() +} + +#[test] +fn a_cpu_override_naming_a_missing_feature_stops_neither_the_cli_nor_signing() { + let out = run(&["--help"]); + assert!(out.status.success(), "--help: {:?} {}", out.status, String::from_utf8_lossy(&out.stderr)); + assert!(String::from_utf8_lossy(&out.stdout).contains("pdfcraft-cli render")); + + let dir = std::env::temp_dir().join(format!("pdfcraft-cli-cpu-override-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + // A new RSA key: the CLI's first use of aws-lc. + let id = dir.join("id.p12"); + let path = format!("path={}", id.display()); + let out = run(&["run", "sign_id_create", "name=Test", "password=correct horse", &path, "--root", dir.to_str().unwrap()]); + assert!(out.status.success(), "sign_id_create: {:?} {}", out.status, String::from_utf8_lossy(&out.stderr)); + assert!(std::fs::metadata(&id).is_ok_and(|m| m.len() > 0), "no digital ID at {}", id.display()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/pdfcraft-cli/tests/it/main.rs b/apps/pdfcraft-cli/tests/it/main.rs index 7b7292fe45..3fa64da799 100644 --- a/apps/pdfcraft-cli/tests/it/main.rs +++ b/apps/pdfcraft-cli/tests/it/main.rs @@ -5,6 +5,7 @@ mod automation_roots; mod batch; mod batch_exit; mod check; +mod cpu_override; mod edit; mod extract; mod help; diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 797e14e52f..eae60cc41f 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -201,6 +201,11 @@ fn rejoin_split_paths(args: Vec, exists: impl Fn(&str) -> bool) -> Vec eframe::Result { + // Before anything uses aws-lc: an `OPENSSL_ia32cap` naming a CPU feature this processor lacks + // would stop it, so PdfCraft runs again without it (#2916, `crypto_env`). + if let Some(code) = pdfcraft_platform::crypto_env::run_without_cpu_override() { + std::process::exit(code); + } // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] if let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { @@ -208,6 +213,9 @@ fn main() -> eframe::Result { } // First, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); + if let Some(value) = pdfcraft_platform::crypto_env::dropped() { + log::warn!("{} was set to {value}; PdfCraft started again without it (aws-lc stops on a CPU feature the processor lacks)", pdfcraft_platform::crypto_env::IA32CAP); + } // Last-resort guard (AGENTS.md §4): commands, edits, opens and saves catch panics and report // them; this hook logs every panic, caught or not, with a backtrace when RUST_BACKTRACE is set. std::panic::set_hook(Box::new(|info| { diff --git a/apps/pdfcraft/tests/help.rs b/apps/pdfcraft/tests/help.rs index fce9a8dd39..5c7782e0d8 100644 --- a/apps/pdfcraft/tests/help.rs +++ b/apps/pdfcraft/tests/help.rs @@ -8,7 +8,12 @@ const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft"); /// Run the app with `args`, failing if it is still running after 60 s (it opened its window). fn run(args: &[&str], stdout: Stdio) -> Output { - let mut child = Command::new(BIN).args(args).stdin(Stdio::null()).stdout(stdout).stderr(Stdio::piped()).spawn().unwrap(); + run_with(Command::new(BIN).args(args), stdout) +} + +fn run_with(command: &mut Command, stdout: Stdio) -> Output { + let args: Vec<_> = command.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let mut child = command.stdin(Stdio::null()).stdout(stdout).stderr(Stdio::piped()).spawn().unwrap(); let deadline = Instant::now() + Duration::from_secs(60); while child.try_wait().unwrap().is_none() { if Instant::now() > deadline { @@ -42,6 +47,16 @@ fn version_prints_the_version_and_exits() { assert!(String::from_utf8_lossy(&out.stdout).starts_with("pdfcraft "), "{}", String::from_utf8_lossy(&out.stdout)); } +/// An `OPENSSL_ia32cap` that asks for a CPU feature the processor lacks (CPUID leaf 1, EDX bit +/// 10, reserved on every x86) doesn't stop the app (#2916): aws-lc aborted before `main`, with no +/// window and nothing in the log. +#[test] +fn a_cpu_override_naming_a_missing_feature_does_not_stop_the_app() { + let out = run_with(Command::new(BIN).arg("--version").env("OPENSSL_ia32cap", "0x400"), Stdio::piped()); + assert!(out.status.success(), "{:?} {}", out.status, String::from_utf8_lossy(&out.stderr)); + assert!(String::from_utf8_lossy(&out.stdout).starts_with("pdfcraft "), "{}", String::from_utf8_lossy(&out.stdout)); +} + /// A standard output that can't be written (here a full device) ends the run normally: `println!` /// would panic and exit 101. #[cfg(target_os = "linux")] diff --git a/crates/platform/src/crypto_env.rs b/crates/platform/src/crypto_env.rs new file mode 100644 index 0000000000..ce5e75de6e --- /dev/null +++ b/crates/platform/src/crypto_env.rs @@ -0,0 +1,66 @@ +//! An `OPENSSL_ia32cap` left in the environment must not stop PdfCraft (#2916). +//! +//! aws-lc, the cryptography library behind digital signatures (through `aws-lc-rs`) and TLS, +//! reads `OPENSSL_ia32cap` when it detects the CPU's features on x86 and x86-64. A value that +//! asks for a feature the processor doesn't have makes it print "Fatal Error: HW capability +//! found: …, but HW capability requested: …" and call `abort()`. On Windows that is exit code +//! 0xC0000409 with no window, no message and nothing in the log. Tuning guides and other +//! programs leave the variable set for every program, so PdfCraft never started on those PCs +//! while other apps did. +//! +//! Two parts keep PdfCraft running: +//! - `.cargo/config.toml` builds aws-lc with `BORINGSSL_NO_STATIC_INITIALIZER`, so it detects +//! the CPU on first use (`CRYPTO_library_init`, which aws-lc-rs calls) instead of in a static +//! initializer before `main`. +//! - [`run_without_cpu_override`], the first thing each executable's `main` does, runs the +//! program again without the variable, before anything uses aws-lc. +//! +//! Removing the variable from this process instead wouldn't work: aws-lc reads it through the C +//! runtime's `getenv`, whose copy of the environment `std::env::remove_var` doesn't change on +//! Windows, and the workspace has no `unsafe` to call the C runtime with. + +use std::ffi::OsString; +use std::io::Write as _; + +/// The variable aws-lc reads on x86 and x86-64. +pub const IA32CAP: &str = "OPENSSL_ia32cap"; + +/// Set in the program started again to the value it was started without, for its log. +pub const DROPPED: &str = "PDFCRAFT_DROPPED_OPENSSL_IA32CAP"; + +/// When `OPENSSL_ia32cap` is set: run this executable again, with the same arguments and +/// standard streams but without the variable, and return its exit code once it ends. +/// +/// `None` when the variable isn't set, on processors aws-lc doesn't read it for (not x86), on +/// macOS (Finder hands files to the process it started, through Apple events, so a second one +/// would never get them), or when the program can't be started again. Then the caller carries +/// on: a value that asks for a missing CPU feature still stops it, at its first use of aws-lc. +pub fn run_without_cpu_override() -> Option { + if !cfg!(any(target_arch = "x86", target_arch = "x86_64")) || cfg!(target_os = "macos") { + return None; + } + let value = std::env::var_os(IA32CAP)?; + let run = || { + let exe = std::env::current_exe()?; + std::process::Command::new(exe).args(std::env::args_os().skip(1)).env_remove(IA32CAP).env(DROPPED, &value).status() + }; + match run() { + // A process ended by a signal (Unix) has no code: report a failure. + Ok(status) => Some(status.code().unwrap_or(1)), + Err(e) => { + // No logger yet; unlike `eprintln!`, this never panics on a closed standard error. + let _ = writeln!(std::io::stderr(), "{IA32CAP} is set to {}, and starting again without it failed: {e}", shown(&value)); + None + } + } +} + +/// The value this program was started without, when [`run_without_cpu_override`] started it. +pub fn dropped() -> Option { + std::env::var_os(DROPPED).map(|v| shown(&v)) +} + +/// A value for a message: lossy where it isn't Unicode, and short. +fn shown(value: &OsString) -> String { + value.to_string_lossy().chars().take(64).collect() +} diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs index 7763cb8102..27b8e25bfe 100644 --- a/crates/platform/src/lib.rs +++ b/crates/platform/src/lib.rs @@ -1,9 +1,11 @@ //! pdfcraft-platform — L7 operating-system services shared by the desktop app (`ui-egui`) and the //! automation tools (`automation`), which sit on the same layer and can't depend on each other, -//! and by the two executables (`owner_only`, for the `--control` file). +//! and by the two executables (`owner_only`, for the `--control` file; `crypto_env`, before +//! anything uses aws-lc). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod crypto_env; pub mod desktop_theme; pub mod owner_only; pub mod staging; From d0ab739f30fca2fa0e0b5647a1642d7f64a2c3d4 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 12 Nov 2026 19:35:17 +0100 Subject: [PATCH 13/21] style: wrap the dropped-OPENSSL_ia32cap log line for rustfmt --- apps/pdfcraft/src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index eae60cc41f..032b8d3fbf 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -214,7 +214,8 @@ fn main() -> eframe::Result { // First, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); if let Some(value) = pdfcraft_platform::crypto_env::dropped() { - log::warn!("{} was set to {value}; PdfCraft started again without it (aws-lc stops on a CPU feature the processor lacks)", pdfcraft_platform::crypto_env::IA32CAP); + let name = pdfcraft_platform::crypto_env::IA32CAP; + log::warn!("{name} was set to {value}; PdfCraft started again without it (aws-lc stops on a CPU feature the processor lacks)"); } // Last-resort guard (AGENTS.md §4): commands, edits, opens and saves catch panics and report // them; this hook logs every panic, caught or not, with a backtrace when RUST_BACKTRACE is set. From 5a53828c70634daac2c20e578b1b358d18cf2079 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 12 Nov 2026 19:39:12 +0100 Subject: [PATCH 14/21] fix(startup): detect aws-lc's CPU features at start, as before --- .cargo/config.toml | 9 +++++---- apps/pdfcraft-cli/src/main.rs | 2 ++ apps/pdfcraft/src/main.rs | 2 ++ crates/platform/src/crypto_env.rs | 7 ++++--- crates/sign/src/lib.rs | 10 ++++++++++ 5 files changed, 23 insertions(+), 7 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 623a308be7..2ccbcc61a3 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -6,9 +6,10 @@ xtask = "run -p xtask --" [target.wasm32-unknown-unknown] rustflags = ["-C", "target-feature=+simd128"] -# aws-lc (digital signatures and TLS, through aws-lc-rs) detects the CPU on first use, not in a -# static initializer before `main`. On x86 it reads `OPENSSL_ia32cap` then, and aborts when that -# asks for a feature the processor lacks; each executable first runs itself again without the -# variable (#2916, `pdfcraft_platform::crypto_env`), which it can only do once `main` runs. +# aws-lc (digital signatures and TLS, through aws-lc-rs) detects the CPU when `main` asks it to +# (`pdfcraft_sign::init_crypto`), not in a static initializer before `main`. On x86 it reads +# `OPENSSL_ia32cap` then, and aborts when that asks for a feature the processor lacks; each +# executable first runs itself again without the variable (#2916, `pdfcraft_platform::crypto_env`), +# which it can only do once `main` runs. [env] AWS_LC_SYS_CFLAGS = "-DBORINGSSL_NO_STATIC_INITIALIZER" diff --git a/apps/pdfcraft-cli/src/main.rs b/apps/pdfcraft-cli/src/main.rs index ab905c2846..9158d5e6f2 100644 --- a/apps/pdfcraft-cli/src/main.rs +++ b/apps/pdfcraft-cli/src/main.rs @@ -103,6 +103,8 @@ fn main() -> ExitCode { if let Some(code) = pdfcraft_platform::crypto_env::run_without_cpu_override() { std::process::exit(code); } + // aws-lc detects the CPU's features here, where it used to before `main` (`init_crypto`). + pdfcraft_engine::sign::init_crypto(); // `std::env::args` panics on an argument that is not UTF-8 ("called `Result::unwrap()` on an // `Err` value"), which a Latin-1 file name is, and it panics while collecting them: even // `--help` ended that way. Such a name cannot be passed on either, since the paths here are diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 032b8d3fbf..a2a4e4410a 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -206,6 +206,8 @@ fn main() -> eframe::Result { if let Some(code) = pdfcraft_platform::crypto_env::run_without_cpu_override() { std::process::exit(code); } + // aws-lc detects the CPU's features here, where it used to before `main` (`init_crypto`). + pdfcraft_engine::sign::init_crypto(); // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] if let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { diff --git a/crates/platform/src/crypto_env.rs b/crates/platform/src/crypto_env.rs index ce5e75de6e..52a39929d7 100644 --- a/crates/platform/src/crypto_env.rs +++ b/crates/platform/src/crypto_env.rs @@ -10,10 +10,11 @@ //! //! Two parts keep PdfCraft running: //! - `.cargo/config.toml` builds aws-lc with `BORINGSSL_NO_STATIC_INITIALIZER`, so it detects -//! the CPU on first use (`CRYPTO_library_init`, which aws-lc-rs calls) instead of in a static -//! initializer before `main`. +//! the CPU when `CRYPTO_library_init` is called instead of in a static initializer before +//! `main`. //! - [`run_without_cpu_override`], the first thing each executable's `main` does, runs the -//! program again without the variable, before anything uses aws-lc. +//! program again without the variable. Then `main` calls `pdfcraft_sign::init_crypto`, so the +//! CPU is detected at start as before, and every operation gets its fast code. //! //! Removing the variable from this process instead wouldn't work: aws-lc reads it through the C //! runtime's `getenv`, whose copy of the environment `std::env::remove_var` doesn't change on diff --git a/crates/sign/src/lib.rs b/crates/sign/src/lib.rs index 14363728a6..bfea4aecfa 100644 --- a/crates/sign/src/lib.rs +++ b/crates/sign/src/lib.rs @@ -37,6 +37,16 @@ pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, s pub use timestamp::{TimestampAuthority, TimestampQuery, TimestampToken}; pub use x509::{Certificate, Name}; +/// Detect the CPU's features for aws-lc now. This build has it do so on first use rather than in +/// a static initializer before `main` (`.cargo/config.toml`, `pdfcraft_platform::crypto_env`), and +/// aws-lc-rs asks for it before most operations but not all: an RSA key generation went without, +/// and ran on aws-lc's portable code. So each executable calls this once at start, after +/// `crypto_env` has run it again without an `OPENSSL_ia32cap` that would stop it here. +#[cfg(not(target_arch = "wasm32"))] +pub fn init_crypto() { + aws_lc_rs::init(); +} + #[derive(Debug, thiserror::Error)] pub enum SignError { #[error("malformed data: {0}")] From 175992b5a2045d00cdf8a20f812ea4aac522b099 Mon Sep 17 00:00:00 2001 From: asadosteaksnl Date: Fri, 13 Nov 2026 02:42:37 +0100 Subject: [PATCH 15/21] fix(ui): Recognize Text's settings scroll in a short window, its buttons stay in reach (#6599) (#6760) * fix(ui): Recognize Text's settings scroll in a short window, its buttons stay in reach (#6599) On a small screen or at a large display scale the dialog was taller than the window: it was centred with its title and its Cancel / Recognize text row off the screen, and nothing scrolled. The four settings groups (Pages, Settings, Skip, Output folder) now sit in a vertical scroll area capped to the window's height, as Preferences does (#3557). The title, the engine notice and the button row stay outside it, so they are always on screen; when the settings fit, nothing changes. The test opens the dialog in 400 to 700 pt windows and checks the title and both buttons are on screen, and that the last group scrolls in between the title and the buttons while they stay put. Without the fix it fails at 400 pt with the title at y = -267. * contributors: credit asadosteaksnl as Kas * fix(ui): Recognize Text's settings scroll in as little as 40 pt, so its buttons fit the smallest window (#6599) A 120 pt floor still pushed the dialog off a window shorter than about 340 pt: at 173 pt (the smallest window, 520 pt, at the largest interface size, 300%) the title sat at y = -32. The test now checks 173, 208 and 260 pt windows too, as the Preferences layout test does. * test(ui): the short-window Recognize Text test clicks Cancel and checks a 640 pt wide window (#6599) Cancel being on screen isn't proof it can be clicked: the test now clicks it at every height and checks the dialog closes. The window is 640 pt across, a 1280-pixel screen at 200%, and every control is checked to fit across as well as down. * test(ui): the Recognize Text title stays put while the settings scroll (#6599) * Revert "contributors: credit asadosteaksnl as Kas" This reverts commit 52470f66a75f6d90c44da4f7f33d496b7cdd7828. * docs(ui): document the Recognize Text dialog's body (#6599) * test(ui): the Recognize Text test also covers tall windows where nothing scrolls (#6599) The dialog is about 935 pt tall, so it scrolls up to a 900 pt window; at 1100 pt everything fits. Both now run, so the test also pins the case where the settings fit and the layout is unchanged. --------- Co-authored-by: asadosteaksnl <353856209+asadosteaksnl@users.noreply.github.com> --- crates/ui-egui/src/workflows/ocr_ui.rs | 238 ++++++++++++++----------- crates/ui-egui/tests/it/ocr.rs | 41 +++++ 2 files changed, 171 insertions(+), 108 deletions(-) diff --git a/crates/ui-egui/src/workflows/ocr_ui.rs b/crates/ui-egui/src/workflows/ocr_ui.rs index 91378d9172..799da09d7d 100644 --- a/crates/ui-egui/src/workflows/ocr_ui.rs +++ b/crates/ui-egui/src/workflows/ocr_ui.rs @@ -233,6 +233,16 @@ pub(crate) fn keep_asking_while_probing(ctx: &egui::Context) { } } +/// The dialog's height outside its scrolling settings: the title, a notice of up to two lines, +/// the Cancel / Recognize text row and the modal's own margins. +const OCR_DIALOG_RESERVE: f32 = 220.0; +/// The least the settings scroll in, however short the window: small enough that the title and the +/// buttons still fit the smallest window at the largest interface size (173 pt), as Preferences. +const OCR_MIN_SCROLL: f32 = 40.0; + +/// The Recognize Text dialog: the title, the settings groups (scrolling when the window is too +/// short for them), any engine notice, and the Cancel / Recognize text row. Returns +/// `(recognize, cancel)`, which of those buttons was clicked this frame. pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (bool, bool) { let pages = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len().max(1)); let d = &mut app.ocr_draft; @@ -248,115 +258,127 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo }); ui.add_space(8.0); }; - group(ui, "Pages", &mut |ui| { - widgets::radio_value(ui, &mut d.pages, OcrPages::All, tl!("All pages")); - widgets::radio_value(ui, &mut d.pages, OcrPages::Current, tl!("Current page")); - ui.horizontal(|ui| { - widgets::radio_value(ui, &mut d.pages, OcrPages::Range, tl!("From")); - let on = d.pages == OcrPages::Range; - ui.add_enabled(on, egui::DragValue::new(&mut d.from).range(1..=pages)); - ui.label(tl!("to")); - ui.add_enabled(on, egui::DragValue::new(&mut d.to).range(1..=pages)); + // The settings outgrow a short window or a large display scale (#6599): they scroll, and + // the notices and the Cancel / Recognize text row stay below the scroll, always in reach. + let max = (ui.ctx().content_rect().height() - OCR_DIALOG_RESERVE).max(OCR_MIN_SCROLL); + egui::ScrollArea::vertical() + .id_salt("ocr-dialog-scroll") + .max_height(max) + // Only applies when the settings overflow: the dialog then opens at its full height + // instead of growing frame by frame, as Preferences does. + .min_scrolled_height(max) + .auto_shrink([false, true]) + .show(ui, |ui| { + group(ui, "Pages", &mut |ui| { + widgets::radio_value(ui, &mut d.pages, OcrPages::All, tl!("All pages")); + widgets::radio_value(ui, &mut d.pages, OcrPages::Current, tl!("Current page")); + ui.horizontal(|ui| { + widgets::radio_value(ui, &mut d.pages, OcrPages::Range, tl!("From")); + let on = d.pages == OcrPages::Range; + ui.add_enabled(on, egui::DragValue::new(&mut d.from).range(1..=pages)); + ui.label(tl!("to")); + ui.add_enabled(on, egui::DragValue::new(&mut d.to).range(1..=pages)); + }); + }); + group(ui, "Settings", &mut |ui| { + egui::Grid::new("ocr-settings").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { + ui.label(tl!("Document language")); + let name = LANGUAGES.iter().find(|l| l.0 == d.language).map_or("English", |l| l.1); + craft_ui::ComboBox::from_id_salt("ocr-language").selected_text(tl!(name)).width(220.0).show_ui(ui, |ui| { + for (code, name) in LANGUAGES { + ui.selectable_value(&mut d.language, (*code).to_string(), tl!(*name)); + } + }); + ui.end_row(); + ui.label(tl!("Engine")); + let engine_name = match d.engine { + EngineChoice::Auto => tl!("Automatic"), + EngineChoice::Ocrs => tl!("Built-in"), + EngineChoice::Tesseract => tl!("Tesseract"), + }; + craft_ui::ComboBox::from_id_salt("ocr-engine").selected_text(engine_name).width(220.0).show_ui(ui, |ui| { + let choices: [(EngineChoice, &str); 3] = + [(EngineChoice::Auto, "Automatic"), (EngineChoice::Ocrs, "Built-in"), (EngineChoice::Tesseract, "Tesseract")]; + for (choice, name) in choices { + ui.selectable_value(&mut d.engine, choice, tl!(name)); + } + }); + ui.end_row(); + ui.label(tl!("Combine engines")); + let strategy_name = match d.strategy { + MergeStrategy::PrimaryOnly => tl!("Primary only"), + MergeStrategy::ConfidenceWeighted => tl!("Confidence weighted"), + MergeStrategy::RoverVote => tl!("ROVER vote"), + }; + craft_ui::ComboBox::from_id_salt("ocr-strategy").selected_text(strategy_name).width(220.0).show_ui(ui, |ui| { + let choices: [(MergeStrategy, &str); 3] = [ + (MergeStrategy::PrimaryOnly, "Primary only"), + (MergeStrategy::ConfidenceWeighted, "Confidence weighted"), + (MergeStrategy::RoverVote, "ROVER vote"), + ]; + for (choice, name) in choices { + ui.selectable_value(&mut d.strategy, choice, tl!(name)); + } + }); + ui.end_row(); + ui.label(tl!("Output")); + let mode_name = match d.output_mode { + OutputMode::Searchable => tl!("Searchable Image (Exact)"), + OutputMode::EditableText => tl!("Editable text"), + }; + craft_ui::ComboBox::from_id_salt("ocr-output").selected_text(mode_name).width(220.0).show_ui(ui, |ui| { + let s = ui + .selectable_label(d.output_mode == OutputMode::Searchable, tl!("Searchable Image (Exact)")) + .on_hover_text(tl!("Adds invisible text over each word; the page image is not changed")); + if s.clicked() { + d.output_mode = OutputMode::Searchable; + } + let e = ui + .selectable_label(d.output_mode == OutputMode::EditableText, tl!("Editable text")) + .on_hover_text(tl!("Writes a new document of visible text; the scan is not changed")); + if e.clicked() { + d.output_mode = OutputMode::EditableText; + } + }); + ui.end_row(); + ui.label(tl!("Downsample to")); + craft_ui::ComboBox::from_id_salt("ocr-dpi").selected_text(format!("{} dpi", d.dpi)).width(220.0).show_ui(ui, |ui| { + for v in [600, 300, 150, 72] { + ui.selectable_value(&mut d.dpi, v, format!("{v} dpi")); + } + }); + ui.end_row(); + }); + ui.add_space(4.0); + ui.add(crate::widgets::checkbox(&mut d.text_pages, tl!("Also recognize pages that already have text"))) + .on_hover_text(tl!("Pictures on those pages are recognized too; words already in the page's text are not added again")); + ui.add(crate::widgets::checkbox(&mut d.auto_rotate, tl!("Straighten pages scanned sideways or upside down"))); + ui.add(crate::widgets::checkbox(&mut d.deskew, tl!("Straighten skewed text lines"))); + ui.add(crate::widgets::checkbox(&mut d.denoise, tl!("Remove scan speckle"))); + ui.add(crate::widgets::checkbox(&mut d.binarize, tl!("Black and white (binarize)"))); + }); + group(ui, "Skip", &mut |ui| { + ui.add(crate::widgets::checkbox(&mut d.skip_text_pages, tl!("Skip pages that already have text"))) + .on_hover_text(tl!("Pages with renderable text are left alone and reported as skipped")); + ui.add(crate::widgets::checkbox(&mut d.skip_text_files, tl!("Skip files that already have text"))) + .on_hover_text(tl!("In multiple files: a file with any text is its own skipped bucket, and nothing is written for it")); + ui.add(crate::widgets::checkbox(&mut d.force_ocr, tl!("Force OCR (override skip options)"))) + .on_hover_text(tl!("Reads pages and files even where the skip options would leave them alone")); + }); + group(ui, "Output folder", &mut |ui| { + ui.horizontal(|ui| match &d.output_folder { + Some(f) => { + ui.monospace(f).on_hover_text(tl!("The searchable copies are written here under the source names")); + if ui.small_button(tl!("Clear")).clicked() { + d.output_folder = None; + } + } + None => { + ui.label(tl!("Automatic")).on_hover_text(tl!("A folder is asked for when a multiple-file run starts")); + } + }); + }); }); - }); - group(ui, "Settings", &mut |ui| { - egui::Grid::new("ocr-settings").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - ui.label(tl!("Document language")); - let name = LANGUAGES.iter().find(|l| l.0 == d.language).map_or("English", |l| l.1); - craft_ui::ComboBox::from_id_salt("ocr-language").selected_text(tl!(name)).width(220.0).show_ui(ui, |ui| { - for (code, name) in LANGUAGES { - ui.selectable_value(&mut d.language, (*code).to_string(), tl!(*name)); - } - }); - ui.end_row(); - ui.label(tl!("Engine")); - let engine_name = match d.engine { - EngineChoice::Auto => tl!("Automatic"), - EngineChoice::Ocrs => tl!("Built-in"), - EngineChoice::Tesseract => tl!("Tesseract"), - }; - craft_ui::ComboBox::from_id_salt("ocr-engine").selected_text(engine_name).width(220.0).show_ui(ui, |ui| { - let choices: [(EngineChoice, &str); 3] = - [(EngineChoice::Auto, "Automatic"), (EngineChoice::Ocrs, "Built-in"), (EngineChoice::Tesseract, "Tesseract")]; - for (choice, name) in choices { - ui.selectable_value(&mut d.engine, choice, tl!(name)); - } - }); - ui.end_row(); - ui.label(tl!("Combine engines")); - let strategy_name = match d.strategy { - MergeStrategy::PrimaryOnly => tl!("Primary only"), - MergeStrategy::ConfidenceWeighted => tl!("Confidence weighted"), - MergeStrategy::RoverVote => tl!("ROVER vote"), - }; - craft_ui::ComboBox::from_id_salt("ocr-strategy").selected_text(strategy_name).width(220.0).show_ui(ui, |ui| { - let choices: [(MergeStrategy, &str); 3] = [ - (MergeStrategy::PrimaryOnly, "Primary only"), - (MergeStrategy::ConfidenceWeighted, "Confidence weighted"), - (MergeStrategy::RoverVote, "ROVER vote"), - ]; - for (choice, name) in choices { - ui.selectable_value(&mut d.strategy, choice, tl!(name)); - } - }); - ui.end_row(); - ui.label(tl!("Output")); - let mode_name = match d.output_mode { - OutputMode::Searchable => tl!("Searchable Image (Exact)"), - OutputMode::EditableText => tl!("Editable text"), - }; - craft_ui::ComboBox::from_id_salt("ocr-output").selected_text(mode_name).width(220.0).show_ui(ui, |ui| { - let s = ui - .selectable_label(d.output_mode == OutputMode::Searchable, tl!("Searchable Image (Exact)")) - .on_hover_text(tl!("Adds invisible text over each word; the page image is not changed")); - if s.clicked() { - d.output_mode = OutputMode::Searchable; - } - let e = ui - .selectable_label(d.output_mode == OutputMode::EditableText, tl!("Editable text")) - .on_hover_text(tl!("Writes a new document of visible text; the scan is not changed")); - if e.clicked() { - d.output_mode = OutputMode::EditableText; - } - }); - ui.end_row(); - ui.label(tl!("Downsample to")); - craft_ui::ComboBox::from_id_salt("ocr-dpi").selected_text(format!("{} dpi", d.dpi)).width(220.0).show_ui(ui, |ui| { - for v in [600, 300, 150, 72] { - ui.selectable_value(&mut d.dpi, v, format!("{v} dpi")); - } - }); - ui.end_row(); - }); - ui.add_space(4.0); - ui.add(crate::widgets::checkbox(&mut d.text_pages, tl!("Also recognize pages that already have text"))) - .on_hover_text(tl!("Pictures on those pages are recognized too; words already in the page's text are not added again")); - ui.add(crate::widgets::checkbox(&mut d.auto_rotate, tl!("Straighten pages scanned sideways or upside down"))); - ui.add(crate::widgets::checkbox(&mut d.deskew, tl!("Straighten skewed text lines"))); - ui.add(crate::widgets::checkbox(&mut d.denoise, tl!("Remove scan speckle"))); - ui.add(crate::widgets::checkbox(&mut d.binarize, tl!("Black and white (binarize)"))); - }); - group(ui, "Skip", &mut |ui| { - ui.add(crate::widgets::checkbox(&mut d.skip_text_pages, tl!("Skip pages that already have text"))) - .on_hover_text(tl!("Pages with renderable text are left alone and reported as skipped")); - ui.add(crate::widgets::checkbox(&mut d.skip_text_files, tl!("Skip files that already have text"))) - .on_hover_text(tl!("In multiple files: a file with any text is its own skipped bucket, and nothing is written for it")); - ui.add(crate::widgets::checkbox(&mut d.force_ocr, tl!("Force OCR (override skip options)"))) - .on_hover_text(tl!("Reads pages and files even where the skip options would leave them alone")); - }); - group(ui, "Output folder", &mut |ui| { - ui.horizontal(|ui| match &d.output_folder { - Some(f) => { - ui.monospace(f).on_hover_text(tl!("The searchable copies are written here under the source names")); - if ui.small_button(tl!("Clear")).clicked() { - d.output_folder = None; - } - } - None => { - ui.label(tl!("Automatic")).on_hover_text(tl!("A folder is asked for when a multiple-file run starts")); - } - }); - }); keep_asking_while_probing(ui.ctx()); // The web build has no model files: it downloads the models the first time they're needed. #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/tests/it/ocr.rs b/crates/ui-egui/tests/it/ocr.rs index ec6af6d7de..483b1719cf 100644 --- a/crates/ui-egui/tests/it/ocr.rs +++ b/crates/ui-egui/tests/it/ocr.rs @@ -465,3 +465,44 @@ fn ocr_verify_screen_focus_ring_and_empty_walk() { assert!(moved, "Ctrl+Tab moves the focus"); assert_eq!(h.state().ocr_verify.focus, start, "the ring returns after the four panes"); } + +/// #6599: in a short window (a small screen, or a large display scale) the dialog's settings +/// scroll, and Cancel and Recognize text stay on screen below them instead of running off it. +#[test] +fn recognize_text_keeps_its_buttons_in_a_short_window() { + use egui::accesskit::Role; + // 173 is the smallest window (520 pt) at the largest interface size (300%), 208 is 250%. + // 640 pt across is a 1280-pixel-wide screen at 200%. At 1100 pt everything fits (the dialog + // is about 935 pt tall) and nothing scrolls. + let width = 640.0; + for height in [173.0, 208.0, 260.0, 400.0, 480.0, 560.0, 700.0, 900.0, 1100.0] { + let mut h = Harness::builder().with_size(egui::vec2(width, height)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("scan.pdf", None, scan()).unwrap(); + app + }); + h.run_steps(4); + assert!(h.state_mut().execute("ocr.recognize")); + h.run_steps(6); + let on_screen = |r: egui::Rect| r.min.x >= 0.0 && r.max.x <= width && r.min.y >= 0.0 && r.max.y <= height; + let title = h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Recognize Text")).rect(); + let run = h.get_by_role_and_label(Role::Button, "Recognize text").rect(); + let cancel = h.get_by_role_and_label(Role::Button, "Cancel").rect(); + assert!(on_screen(title), "{height}: the title at {title:?} is off the window"); + assert!(on_screen(run), "{height}: Recognize text at {run:?} is off the window"); + assert!(on_screen(cancel), "{height}: Cancel at {cancel:?} is off the window"); + // The last group scrolls in between the title and the buttons, which do not move. + h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Output folder")).scroll_to_me(); + h.run_steps(4); + let last = h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Output folder")).rect(); + assert!(last.min.y >= title.max.y && last.max.y <= run.min.y, "{height}: Output folder {last:?} between {title:?} and {run:?}"); + assert_eq!(h.get_by_role_and_label(Role::Button, "Recognize text").rect(), run, "{height}: the buttons stay put"); + let title_after = h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Recognize Text")).rect(); + assert_eq!(title_after, title, "{height}: the title stays put"); + // On screen is not enough: a click reaches Cancel and closes the dialog. + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(3); + assert!(h.state().dialog.is_none(), "{height}: Cancel closes the dialog"); + } +} From b0607f5cd38bede27c95c740b4654af06d3a7500 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 06:21:26 -0500 Subject: [PATCH 16/21] fix(optimize): a destination name given by reference is copied once however many dictionaries name it (#7035) * fix(optimize): a destination name given by reference is copied once however many dictionaries name it * fix(optimize): aliases of one destination-name object are copied once --- crates/optimize/src/links.rs | 22 ++++++++++++++++++++-- crates/optimize/tests/optimize.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/optimize/src/links.rs b/crates/optimize/src/links.rs index bef69c43b7..485e7912f0 100644 --- a/crates/optimize/src/links.rs +++ b/crates/optimize/src/links.rs @@ -2,6 +2,7 @@ //! refers to. use std::collections::{HashSet, VecDeque}; +use std::sync::Arc; use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString}; @@ -164,6 +165,8 @@ pub(crate) fn remove_invalid(doc: &mut Document, pages: &[ObjRef]) -> Result<(us fn referenced_names(doc: &Document) -> HashSet> { let mut out = HashSet::new(); let mut seen = HashSet::new(); + let mut named_refs = HashSet::new(); + let mut named_held: std::collections::HashMap<*const Object, Arc> = std::collections::HashMap::new(); let mut stack = vec![Object::Dict(doc.trailer().clone())]; if let Some(r) = doc.root() { stack.push(Object::Ref(r)); @@ -180,11 +183,26 @@ fn referenced_names(doc: &Document) -> HashSet> { // string, and an unresolved ref has no name, so the destination it uses would // look unreferenced and be removed. A GoToR or GoToE /D names a destination in // another document, so it does not count as a use of this one's. - if let Some(n) = d.get(b"Dest").and_then(|x| dest_name(doc.resolve(x).as_ref())) { + // A name given by reference is copied once, however many dictionaries (or aliases + // of the object) name it. The objects are kept so an address is never reused. + let mut named = |x: Option<&Object>| { + let x = x?; + if let Object::Ref(r) = x + && !named_refs.insert(*r) + { + return None; + } + let held = doc.resolve(x); + if matches!(x, Object::Ref(_)) && named_held.insert(Arc::as_ptr(&held), held.clone()).is_some() { + return None; + } + dest_name(held.as_ref()) + }; + if let Some(n) = named(d.get(b"Dest")) { out.insert(n); } if d.name(b"S") == Some(b"GoTo") - && let Some(n) = d.get(b"D").and_then(|x| dest_name(doc.resolve(x).as_ref())) + && let Some(n) = named(d.get(b"D")) { out.insert(n); } diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs index eee2e9570c..5bb20e8159 100644 --- a/crates/optimize/tests/optimize.rs +++ b/crates/optimize/tests/optimize.rs @@ -4439,6 +4439,36 @@ fn indirectly_referenced_destination_is_kept() { assert!(!left.contains(&b"unused".to_vec())); } +#[test] +fn many_links_naming_one_destination_string_by_reference_keep_it() { + // The name string is copied once however many links name it by reference; it is still a use. + let mut doc = Document::new_empty(); + let p = page(&mut doc, &[], "BT ET"); + let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t.as_bytes().to_vec())); + let name_ref = Object::Ref(doc.add(s("target"))); + let links: Vec = (0..50) + .map(|_| { + let mut link = Dict::new(); + link.set(b"Subtype".to_vec(), Object::name("Link")); + link.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()])); + link.set(b"Dest".to_vec(), name_ref.clone()); + Object::Ref(doc.add(Object::Dict(link))) + }) + .collect(); + doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(links))).unwrap(); + let fit = Object::Array(vec![Object::Ref(p), Object::name("Fit")]); + let mut tree = Dict::new(); + tree.set(b"Names".to_vec(), Object::Array(vec![s("target"), fit.clone(), s("unused"), fit])); + let tree = doc.add(Object::Dict(tree)); + let mut names = Dict::new(); + names.set(b"Dests".to_vec(), Object::Ref(tree)); + let root = doc.root().unwrap(); + doc.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names))).unwrap(); + let report = optimize(&mut doc, &Settings::default()).unwrap(); + assert_eq!(report.unreferenced_dests, 1); + assert_eq!(named_dest_keys(&doc), vec![b"target".to_vec()]); +} + #[test] fn a_destination_named_only_by_a_remote_or_embedded_go_to_is_removed() { // The /D of a GoToR or GoToE action names a destination in another document. A local From b167422b2e3429c32d0a2e5ff5f2660bce517f1e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 06:22:54 -0500 Subject: [PATCH 17/21] fix(sign): every signature's VRI entry shares the store's evidence arrays instead of copying them (#7038) --- crates/sign/src/dss.rs | 25 +++++++++++++++---------- crates/sign/tests/it/pdf.rs | 7 +++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/crates/sign/src/dss.rs b/crates/sign/src/dss.rs index 0c76ca1967..7e5fe5f7ad 100644 --- a/crates/sign/src/dss.rs +++ b/crates/sign/src/dss.rs @@ -69,12 +69,17 @@ pub fn embed(doc: &Document, evidence: &Evidence) -> Result, SignError> let mut dss = Dict::new(); dss.set(b"Type".to_vec(), Object::name("DSS")); dss.set(b"Filter".to_vec(), Object::name("Adobe.PPKLite")); - dss.set(b"Certs".to_vec(), Object::Ref(doc.add(Object::Array(cert_refs.clone())))); - if !ocsp_refs.is_empty() { - dss.set(b"OCSPs".to_vec(), Object::Ref(doc.add(Object::Array(ocsp_refs.clone())))); + // Each list is one indirect array the store and every signature's VRI entry point to, so the + // output does not grow with signatures times evidence. + let cert_list = Object::Ref(doc.add(Object::Array(cert_refs))); + let ocsp_list = (!ocsp_refs.is_empty()).then(|| Object::Ref(doc.add(Object::Array(ocsp_refs)))); + let crl_list = (!crl_refs.is_empty()).then(|| Object::Ref(doc.add(Object::Array(crl_refs)))); + dss.set(b"Certs".to_vec(), cert_list.clone()); + if let Some(l) = &ocsp_list { + dss.set(b"OCSPs".to_vec(), l.clone()); } - if !crl_refs.is_empty() { - dss.set(b"CRLs".to_vec(), Object::Ref(doc.add(Object::Array(crl_refs.clone())))); + if let Some(l) = &crl_list { + dss.set(b"CRLs".to_vec(), l.clone()); } // Keep any existing /VRI entries, then cover every signature in the file. let mut vri = @@ -82,12 +87,12 @@ pub fn embed(doc: &Document, evidence: &Evidence) -> Result, SignError> for contents in crate::pdf::signature_contents(&doc) { let mut e = Dict::new(); e.set(b"Type".to_vec(), Object::name("VRI")); - e.set(b"Cert".to_vec(), Object::Array(cert_refs.clone())); - if !ocsp_refs.is_empty() { - e.set(b"OCSP".to_vec(), Object::Array(ocsp_refs.clone())); + e.set(b"Cert".to_vec(), cert_list.clone()); + if let Some(l) = &ocsp_list { + e.set(b"OCSP".to_vec(), l.clone()); } - if !crl_refs.is_empty() { - e.set(b"CRL".to_vec(), Object::Array(crl_refs.clone())); + if let Some(l) = &crl_list { + e.set(b"CRL".to_vec(), l.clone()); } vri.set(vri_key(&contents).into_bytes(), Object::Dict(e)); } diff --git a/crates/sign/tests/it/pdf.rs b/crates/sign/tests/it/pdf.rs index 5d24d05dce..6e88830a7a 100644 --- a/crates/sign/tests/it/pdf.rs +++ b/crates/sign/tests/it/pdf.rs @@ -1050,6 +1050,13 @@ fn embedding_ltv_evidence_adds_a_dss_and_keeps_signatures_valid() { doc.get(root).as_dict().unwrap().get(b"DSS").map(|d| doc.resolve(d)).and_then(|d| d.as_dict().cloned()).unwrap(); assert_eq!(dss_dict.name(b"Type"), Some(b"DSS".as_slice())); assert!(dss_dict.contains(b"Certs") && dss_dict.contains(b"OCSPs") && dss_dict.contains(b"CRLs") && dss_dict.contains(b"VRI")); + // A signature's /VRI entry points at the store's arrays instead of holding its own copy of each. + let vri = dss_dict.get(b"VRI").map(|v| doc.resolve(v)).and_then(|v| v.as_dict().cloned()).unwrap(); + let entry = vri.iter().next().and_then(|(_, e)| e.as_dict().cloned()).unwrap(); + for (vri_key, dss_key) in [(&b"Cert"[..], &b"Certs"[..]), (b"OCSP", b"OCSPs"), (b"CRL", b"CRLs")] { + assert!(matches!(entry.get(vri_key), Some(pdfcraft_cos::Object::Ref(_)))); + assert_eq!(entry.get(vri_key), dss_dict.get(dss_key)); + } // The earlier signature still validates; the DSS counts as a permitted change. let s = signatures(&doc, <v, &TrustStore::default()).into_iter().find(|s| s.signed && !s.doc_timestamp).unwrap(); assert_eq!(s.status, Status::Unknown); From 785e7e510ce19e736961feb4c552076feecd4519 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 06:23:58 -0500 Subject: [PATCH 18/21] fix(forms): finding the first character a simple font cannot hold encodes the whole string once, then each distinct character once (#7047) --- crates/forms/src/appearance.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rs index ddbbe26590..91792a59c3 100644 --- a/crates/forms/src/appearance.rs +++ b/crates/forms/src/appearance.rs @@ -326,7 +326,15 @@ impl FontText { match self { Self::WinAnsi => pdfcraft_fonts::first_undrawable(s), Self::Simple(metrics) => { - s.chars().map(|c| if c == '\t' { ' ' } else { c }).find(|c| metrics.encode(c.encode_utf8(&mut [0; 4])).is_none()) + // A whole string that encodes has no such character, in one pass over the font's + // ranges. Otherwise each distinct character is asked once (a call scans every range). + if metrics.encode(&s.replace('\t', " ")).is_some() { + return None; + } + let mut held = std::collections::HashSet::new(); + s.chars() + .map(|c| if c == '\t' { ' ' } else { c }) + .find(|c| !held.contains(c) && !(metrics.encode(c.encode_utf8(&mut [0; 4])).is_some() && held.insert(*c))) } Self::Unicode(cmap) => cmap.first_unencodable(s), } @@ -1244,4 +1252,19 @@ mod tests { // When empty selection: assert_eq!(ListRows::top_showing(0, &[], 3, 5), 0); } + + #[test] + fn first_unencodable_finds_the_first_character_the_simple_font_cannot_hold() { + let doc = Document::new_empty(); + let mut f = Dict::new(); + f.set(b"Type".to_vec(), Object::name("Font")); + f.set(b"Subtype".to_vec(), Object::name("Type1")); + f.set(b"BaseFont".to_vec(), Object::name("Helvetica")); + f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding")); + let font = FontText::Simple(Box::new(Metrics::from_dict(&doc, &f))); + assert_eq!(font.first_unencodable("h\u{e9}llo\tw\u{e9}rld"), None); + assert_eq!(font.first_unencodable(&"a\u{e9}".repeat(1000)), None); + assert_eq!(font.first_unencodable("ab\u{3a9}c\u{3a8}"), Some('\u{3a9}')); + assert_eq!(font.first_unencodable(""), None); + } } From fd4d60ff4ae0e2f383ee57218ea554f37dd272d6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:04:39 +0100 Subject: [PATCH 19/21] CI: use the shared git-sources check (#7042) ci.yml ran its own copy of the git-sources job; it now calls craft-common-actions git-sources.yml, under the same full-ci label rule. --- .github/workflows/ci.yml | 48 ++-------------------------------------- 1 file changed, 2 insertions(+), 46 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 38ee53caf3..ebda82a2f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,52 +24,8 @@ jobs: # The shared gate doesn't check where git dependencies come from; release.yml runs the same job. git-sources: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' - name: Git dependencies come from storytold - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Windows font notice regressions - shell: pwsh - run: ./packaging/windows/test-font-notices.ps1 - - name: Git dependencies come from storytold - run: | - set -euo pipefail - test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } - # Source replacement, patches and path overrides in cargo config never show up - # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. - # Cargo still reads the legacy .cargo/config. - python3 - <<'PY' - import os, sys, tomllib - for path in (".cargo/config", ".cargo/config.toml"): - if not os.path.exists(path): - continue - config = tomllib.load(open(path, "rb")) - replaced = [name for name, source in config.get("source", {}).items() - if isinstance(source, dict) and "replace-with" in source] - if replaced or "patch" in config or "paths" in config: - print(f"{path} replaces, patches or overrides a source") - sys.exit(1) - PY - # Fails when Cargo.lock is out of date with the manifests. - cargo metadata --locked --format-version 1 > /dev/null - python3 - <<'PY' - import sys, tomllib - lock = tomllib.load(open("Cargo.lock", "rb")) - bad = sorted({p["source"] for p in lock.get("package", []) - if p.get("source", "").startswith("git+") - and not p["source"].startswith("git+https://github.com/storytold/")}) - if bad: - print("Git dependencies outside github.com/storytold:", *bad, sep="\n") - sys.exit(1) - PY + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main gate: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' From e6730be28976b474b8ac479bf87f1146578ef128 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:08:57 +0100 Subject: [PATCH 20/21] test: scope CPU override regressions to supported platforms --- apps/pdfcraft-cli/tests/it/cpu_override.rs | 3 +++ apps/pdfcraft/tests/help.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/apps/pdfcraft-cli/tests/it/cpu_override.rs b/apps/pdfcraft-cli/tests/it/cpu_override.rs index d5dc87c790..78922ae26d 100644 --- a/apps/pdfcraft-cli/tests/it/cpu_override.rs +++ b/apps/pdfcraft-cli/tests/it/cpu_override.rs @@ -2,6 +2,9 @@ //! its signing (#2916). aws-lc printed "Fatal Error: HW capability found: …" and aborted before //! `main`. Built to detect the CPU on first use, it would abort at the first signature instead. +// macOS intentionally does not relaunch: Finder delivers files to the original process. +#![cfg(not(target_os = "macos"))] + use std::process::{Command, Output}; /// CPUID leaf 1, EDX bit 10: reserved, so no x86 processor reports it. diff --git a/apps/pdfcraft/tests/help.rs b/apps/pdfcraft/tests/help.rs index 5c7782e0d8..282fd73500 100644 --- a/apps/pdfcraft/tests/help.rs +++ b/apps/pdfcraft/tests/help.rs @@ -50,6 +50,8 @@ fn version_prints_the_version_and_exits() { /// An `OPENSSL_ia32cap` that asks for a CPU feature the processor lacks (CPUID leaf 1, EDX bit /// 10, reserved on every x86) doesn't stop the app (#2916): aws-lc aborted before `main`, with no /// window and nothing in the log. +// macOS intentionally does not relaunch: Finder delivers files to the original process. +#[cfg(not(target_os = "macos"))] #[test] fn a_cpu_override_naming_a_missing_feature_does_not_stop_the_app() { let out = run_with(Command::new(BIN).arg("--version").env("OPENSSL_ia32cap", "0x400"), Stdio::piped()); From ec31c55763e8cd80fb134443bf48137501c4cc27 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:28:29 +0100 Subject: [PATCH 21/21] fix(ocr): main builds on Windows again: the executable check is its own function per platform (#7222) Since Rust 1.100, clippy's needless_bool refused program_is_executable on Windows: with the #[cfg(unix)] block gone it read if ... { return false; } true, and the Windows gate failed on every main commit since 13 Nov 09:38. The check is now one expression with the platform part in has_execute_permission; behaviour is unchanged on every platform. --- crates/ocr/src/tesseract.rs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/crates/ocr/src/tesseract.rs b/crates/ocr/src/tesseract.rs index a4e1407331..815a7dd537 100644 --- a/crates/ocr/src/tesseract.rs +++ b/crates/ocr/src/tesseract.rs @@ -130,18 +130,22 @@ pub fn program_is_usable(program: &Path) -> bool { /// executable FILE (on Unix the executable bits must be set; elsewhere being a file is what /// the OS requires). A directory or a missing file is simply unavailable — never a panic. fn program_is_executable(program: &Path) -> bool { - if !program.is_absolute() || !program.is_file() { - return false; - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::metadata(program).is_ok_and(|m| m.permissions().mode() & 0o111 != 0) - } - #[cfg(not(unix))] - { - true - } + program.is_absolute() && program.is_file() && has_execute_permission(program) +} + +/// Unix: an executable bit is set. +#[cfg(unix)] +fn has_execute_permission(program: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(program).is_ok_and(|m| m.permissions().mode() & 0o111 != 0) +} + +/// Elsewhere, being a file is what the OS requires. A function of its own: inlined above, the +/// Windows build reduced to `if … { return false; } true`, which clippy's `needless_bool` +/// refuses (Rust 1.100). +#[cfg(not(unix))] +fn has_execute_permission(_program: &Path) -> bool { + true } /// One row of Tesseract's TSV output. `level` 5 rows are the words; `conf` is −1 on the header