From d812cf8a5ca46a27756aaae5a10240ca63dec0d9 Mon Sep 17 00:00:00 2001 From: Mara Johnson Date: Sun, 11 Oct 2026 12:55:33 -0400 Subject: [PATCH 01/29] Windows MSI: notify Explorer of the PDF association so PdfCraft shows under Open with (#1080) The MSI already registers PdfCraft.Document in .pdf\OpenWithProgids, Capabilities and RegisteredApplications, but Windows Installer never sends SHCNE_ASSOCCHANGED, so Explorer's cached Open with list can miss PdfCraft until sign-out. Send it after install and uninstall from an immediate, ignore-result custom action; test-msi.ps1 checks the action and its order. --- packaging/windows/pdfcraft.wxs | 13 +++++++++++++ packaging/windows/test-msi.ps1 | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/packaging/windows/pdfcraft.wxs b/packaging/windows/pdfcraft.wxs index e8bb53734d..015631bdd8 100644 --- a/packaging/windows/pdfcraft.wxs +++ b/packaging/windows/pdfcraft.wxs @@ -53,11 +53,24 @@ + + + + + + + diff --git a/packaging/windows/test-msi.ps1 b/packaging/windows/test-msi.ps1 index 0b6fa7781e..841c3c4dea 100644 --- a/packaging/windows/test-msi.ps1 +++ b/packaging/windows/test-msi.ps1 @@ -148,6 +148,15 @@ if ($pdfCheckbox[2] -notmatch 'Edit with PdfCraft') { throw "Welcome PDF context $pdfChecked = Read-Row 'SELECT `Value` FROM `CheckBox` WHERE `Property` = ''INSTALLPDFCONTEXTMENU''' 1 Assert-Equal $pdfChecked[0] '1' 'Welcome PDF context-menu value' Assert-NoRow 'SELECT `Registry` FROM `Registry` WHERE `Key` = ''Software\Classes\.pdf'' AND `Name` IS NULL' '.pdf default app' +# #1080: Explorer is told the associations changed (SHCNE_ASSOCCHANGED) after install/uninstall, +# without ever failing setup. 34 = exe in a directory; 64 = ignore its exit code. +$notify = Read-Row 'SELECT `Type`, `Source`, `Target` FROM `CustomAction` WHERE `Action` = ''NotifyAssociationsChanged''' 3 +Assert-Equal $notify[0] '98' 'Association notify action type' +Assert-Equal $notify[1] 'SystemFolder' 'Association notify directory' +if ($notify[2] -notmatch 'SHChangeNotify\(0x8000000,0,0,0\)' -or $notify[2].Length -gt 255) { throw "Association notify command: '$($notify[2])'" } +$after = Read-Row 'SELECT `Sequence` FROM `InstallExecuteSequence` WHERE `Action` = ''NotifyAssociationsChanged''' 1 +$finalize = Read-Row 'SELECT `Sequence` FROM `InstallExecuteSequence` WHERE `Action` = ''InstallFinalize''' 1 +if ([int] $after[0] -le [int] $finalize[0]) { throw 'Association notify must run after InstallFinalize' } # Negative sequences are Windows Installer's success/user-exit/failure paths. Only full UI # shows these dialogs: an unattended /qn or /qb install must never wait for a Finish click. From ec429fdd90e8a75ed1eba4905913878156173eff Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Sat, 24 Oct 2026 16:50:45 +0200 Subject: [PATCH 02/29] fix(forms, xfdf): importing a value into same-named check boxes turns on the box it names --- crates/forms/src/lib.rs | 9 ++++++-- crates/xfdf/src/lib.rs | 3 +++ crates/xfdf/src/tests.rs | 50 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 75c3dbee00..977525d512 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -1068,13 +1068,18 @@ fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scripts: &mut redraw(doc, f, std::slice::from_ref(t), scripts) } (FieldKind::CheckBox, v) => { - let state = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into()); + let mut state = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into()); let on = match v { FieldValue::Check(on) => *on, // The on-state name or a yes/no word also work (agents, FDF-style data). FieldValue::Text(t) | FieldValue::Radio(Some(t)) => { let t = t.trim(); - if t == state || f.state_for(t).is_some() || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) { + // Same-named check boxes with different on states (/A, /B) are one field: a + // value naming another box's state turns that box on, not the first one. + if let Some(named) = f.state_for(t) { + state = named.to_string(); + true + } else if t == state || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) { true } else if t.is_empty() || ["no", "false", "off", "0", "unchecked"].contains(&t.to_lowercase().as_str()) { false diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index 6131c9c96b..e0d5b7d639 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -892,6 +892,9 @@ fn apply_values(doc: &mut Document, values: &[(String, Vec)], report: &m let first = vals.first().cloned().unwrap_or_default(); let v = match f.kind { FieldKind::Text => FieldValue::Text(first), + // A value that names one of the boxes' on states picks that box (same-named check + // boxes with different on states); anything else is just on or off. + FieldKind::CheckBox if f.state_for(&first).is_some() => FieldValue::Text(first), FieldKind::CheckBox => FieldValue::Check(!first.is_empty() && first != "Off"), FieldKind::Radio => FieldValue::Radio((!first.is_empty() && first != "Off").then_some(first)), // XML, CSV and text hold a multi-select list's values in one cell, joined by ", " diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs index 17c48c281b..a1bc0dfc23 100644 --- a/crates/xfdf/src/tests.rs +++ b/crates/xfdf/src/tests.rs @@ -1933,3 +1933,53 @@ fn annots_of(doc: &Document) -> Vec { .filter(|d| d.get(b"Subtype") != Some(&Object::name("Widget"))) .collect() } + +/// Check boxes sharing one name with different on states (`/A`, `/B`) are one field whose value +/// picks the box. Importing `B` turned on the first box's state instead, whatever the data said. +fn check_box_pair(value: &str) -> Document { + let objs = [ + "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".to_string(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".to_string(), + "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>".to_string(), + "<< /Fields [5 0 R] >>".to_string(), + format!("<< /FT /Btn /T (choice) /V /{value} /Kids [6 0 R 7 0 R] >>"), + format!( + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /P 3 0 R /Rect [50 700 64 714] /AS /{} /AP << /N << /A 8 0 R /Off 8 0 R >> >> >>", + if value == "A" { "A" } else { "Off" } + ), + format!( + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /P 3 0 R /Rect [80 700 94 714] /AS /{} /AP << /N << /B 8 0 R /Off 8 0 R >> >> >>", + if value == "B" { "B" } else { "Off" } + ), + "<< /Length 0 >>\nstream\n\nendstream".to_string(), + ]; + 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()); + Document::open(Arc::new(out)).unwrap() +} + +#[test] +fn a_check_box_group_value_selects_its_own_box_on_import() { + let src = check_box_pair("B"); + assert_eq!(values(&src), vec![("choice".to_string(), vec!["B".to_string()])]); + let exports = [ + ("xfdf", export_xfdf(&src, false, true, "form.pdf").into_bytes()), + ("fdf", export_fdf(&src, false, true, "form.pdf").unwrap()), + ("xml", export_data(&src, Format::Xml).into_bytes()), + ]; + for (format, data) in exports { + let mut dst = check_box_pair("Off"); + let report = import(&mut dst, &data); + assert_eq!(values(&dst), values(&src), "{format}: {report:?}: {}", String::from_utf8_lossy(&data)); + } +} From 2ec44a88acbadcdf07f04cc7e5038bd71160d8a8 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:42:03 +0200 Subject: [PATCH 03/29] Deduplicate the media option in spool jobs A duplicated media option can make the spooler or a virtual printer such as Microsoft Print to PDF reject or crash on the job instead of feeding the laid-out paper. Remove any existing media entry from the user options before appending the laid-out paper's media option, so the job carries exactly one media value. Test: spool_job_does_not_duplicate_media_option failed before the change and passes after. --- crates/automation/src/printing.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs index c0cf35f02c..a4f27031d9 100644 --- a/crates/automation/src/printing.rs +++ b/crates/automation/src/printing.rs @@ -143,7 +143,10 @@ fn spool_job( grey_pages: false, title, options: { - let mut options: Vec<(String, String)> = options.into_iter().chain(media.map(|m| ("media".to_string(), m.to_string()))).collect(); + let mut options: Vec<(String, String)> = options.into_iter().filter(|(k, _)| k != "media").collect(); + if let Some(m) = media { + options.push(("media".to_string(), m.to_string())); + } print::add_cups_orientation(&mut options, sheets); options }, @@ -581,4 +584,16 @@ mod tests { assert_eq!(paper_size(spec), None, "{spec}"); } } + + /// A user-supplied `media` option must not reach the spooler alongside the + /// laid-out paper's own `media` option: the job carries exactly one `media` + /// entry, and it is the paper the sheets were laid out on. + #[test] + fn spool_job_does_not_duplicate_media_option() { + let (index, _) = paper_named(None).unwrap(); + let job = spool_job(&Args(&json!({ "options": { "InputSlot": "Tray3", "media": "A4" } })), "Office", "a.pdf".into(), None, index).unwrap(); + let media: Vec<&(String, String)> = job.options.iter().filter(|(k, _)| k == "media").collect(); + assert_eq!(media, [print::media_option(index).as_ref().unwrap()]); + assert!(job.options.contains(&("InputSlot".to_string(), "Tray3".to_string()))); + } } From fc2fc39c74986872a737d0782f31956518e0dae7 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:21:35 +0200 Subject: [PATCH 04/29] Repair review branch integration --- crates/automation/src/printing.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs index a4f27031d9..b2971c752b 100644 --- a/crates/automation/src/printing.rs +++ b/crates/automation/src/printing.rs @@ -590,8 +590,18 @@ mod tests { /// entry, and it is the paper the sheets were laid out on. #[test] fn spool_job_does_not_duplicate_media_option() { - let (index, _) = paper_named(None).unwrap(); - let job = spool_job(&Args(&json!({ "options": { "InputSlot": "Tray3", "media": "A4" } })), "Office", "a.pdf".into(), None, index).unwrap(); + let index = 0; // US Letter + let media_name = print::cups_media(index).unwrap(); + let job = spool_job( + &Args(&json!({ "options": { "InputSlot": "Tray3", "media": "A4" } })), + "Office", + "a.pdf".into(), + None, + Some(media_name), + None, + &[], + ) + .unwrap(); let media: Vec<&(String, String)> = job.options.iter().filter(|(k, _)| k == "media").collect(); assert_eq!(media, [print::media_option(index).as_ref().unwrap()]); assert!(job.options.contains(&("InputSlot".to_string(), "Tray3".to_string()))); From ab178b25f8b38219f2ca48189aed9434d33ee4df Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:05:01 +0200 Subject: [PATCH 05/29] Address remaining review requests --- crates/automation/src/printing.rs | 2 +- crates/automation/src/tools.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs index b2971c752b..28e7721002 100644 --- a/crates/automation/src/printing.rs +++ b/crates/automation/src/printing.rs @@ -143,7 +143,7 @@ fn spool_job( grey_pages: false, title, options: { - let mut options: Vec<(String, String)> = options.into_iter().filter(|(k, _)| k != "media").collect(); + let mut options: Vec<(String, String)> = options.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("media")).collect(); if let Some(m) = media { options.push(("media".to_string(), m.to_string())); } diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index e4301f2f23..d9b71df537 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -767,7 +767,7 @@ pub fn tools() -> Vec { t( "doc_print", "Print", - "Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"x\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again.", + "Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"x\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again. Any caller-supplied `media` option is replaced by the paper the document was laid out on." ) .with(schema( json!({ From b007d8c01e2b07b65ef884659a55cf9f150e32ac Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:32:29 +0200 Subject: [PATCH 06/29] Address remaining review requests --- crates/automation/src/printing.rs | 3 ++- crates/automation/src/tools.rs | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs index 28e7721002..6583d479ac 100644 --- a/crates/automation/src/printing.rs +++ b/crates/automation/src/printing.rs @@ -111,7 +111,8 @@ fn resolve_paper(name: Option<&str>, printer: Option<&str>) -> Result<((f64, f64 /// naming none got (A4 under Letter sheets on the queue in #3752), and tells CUPS which way the /// laid-out `sheets` run, as the Print dialog does (#2713): an orientation the caller chose in /// `options` stands. It asks the driver for grayscale only when the pages aren't grey pictures -/// already ([`print::driver_needs_grayscale`]). +/// already ([`print::driver_needs_grayscale`]). Any caller-supplied `media` option (case-insensitive) +/// is replaced by the laid-out paper's media. fn spool_job( a: &Args, printer: &str, diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index d9b71df537..20872c4f3d 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -790,7 +790,7 @@ pub fn tools() -> Vec { "cut_marks": { "type": "boolean" }, "orientation": { "type": "string", "enum": ["auto", "portrait", "landscape"] }, "comments_forms": { "type": "string", "enum": ["document", "document-and-markups", "document-and-stamps", "form-fields-only"] }, - "paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side)." }, + "paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side). The paper the document is laid out on determines the `media` option sent to the printer; any `media` in `options` is replaced." }, "path": { "type": "string" }, "printer": { "type": "string" }, "copies": { "type": "integer", "minimum": 1, "maximum": 999 }, @@ -800,7 +800,7 @@ pub fn tools() -> Vec { "area": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Print a selected area: [x0, y0, x1, y1] in points from the top-left of the displayed page, of the one page in pages, sized by layout fit/actual/shrink/custom." }, "as_image": { "type": "boolean", "description": "Print as image (Acrobat's Advanced Print Setup): every page rendered to a picture at dpi before it is placed on the paper, for printers that skip text, shading or transparency; the print is no longer searchable text, and with grayscale the pictures are grey, so the printer isn't asked for grayscale (a driver without that setting still prints them)." }, "dpi": { "type": "number", "minimum": 72, "maximum": 600, "description": "Resolution for as_image (default 300)." }, - "options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value." }, + "options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value. Any caller-supplied `media` option is replaced by the paper the document was laid out on." }, "color_management": { "type": "string", "enum": ["printer", "app"], "description": "Who converts the colours: printer (default, the driver does) or app, which prints the pages as images (dpi, grayscale apply) converted from sRGB into color_profile." }, "color_profile": { "type": "string", "description": "For color_management app: a name or file name from print_color_profiles, or the path of an RGB or grey ICC printer profile." }, "rendering_intent": { "type": "string", "enum": ["perceptual", "relative", "saturation", "absolute"], "description": "For color_management app: how colours the printer can't reach are mapped (default relative colorimetric)." }, From 7d3262e7643670b86bb67b4f828f48f2ff6b551e Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:35:38 +0200 Subject: [PATCH 07/29] Address remaining review requests --- crates/automation/src/tools.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 20872c4f3d..93a376e4a8 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -790,7 +790,7 @@ pub fn tools() -> Vec { "cut_marks": { "type": "boolean" }, "orientation": { "type": "string", "enum": ["auto", "portrait", "landscape"] }, "comments_forms": { "type": "string", "enum": ["document", "document-and-markups", "document-and-stamps", "form-fields-only"] }, - "paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side). The paper the document is laid out on determines the `media` option sent to the printer; any `media` in `options` is replaced." }, + "paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side). The paper the document is laid out on determines the `media` option sent to the printer; any caller-supplied `media` option in `options` is replaced by this paper." }, "path": { "type": "string" }, "printer": { "type": "string" }, "copies": { "type": "integer", "minimum": 1, "maximum": 999 }, From a0e94e8d505f0e14e398a721d53089453c52fda5 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 20:06:29 +0530 Subject: [PATCH 08/29] Contributors: gmrmad1's name for the About window --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 06c98f6464..4c54055ec4 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -194,3 +194,6 @@ sync_github_name = false [people.enriquemelzer-bit] sync_github_name = true + +[people.gmrmad1] +real_name = "Madhav Agarwal" From 4e634e4b01492e4034768911886b35ade9b2ecbf Mon Sep 17 00:00:00 2001 From: bmh129 <11478682+bmh129@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:45:34 -0500 Subject: [PATCH 09/29] M3: hand the launcher's activation token back from the first window (Linux) A launcher with StartupNotify=true passes an activation token in XDG_ACTIVATION_TOKEN (Wayland) or DESKTOP_STARTUP_ID (X11) and shows a busy cursor until a window hands it back. winit hands back only a token given through with_activation_token, and eframe never gives one, so GNOME kept the busy cursor for 15 seconds after PdfCraft's window appeared, and a Wayland window opened without keyboard focus. Vendored winit patch 14: the first window created without a token takes the environment's. Later windows don't reuse the spent token; an empty or oversized (over 1,024 bytes) token is ignored, since on X11 an oversized one would fail window creation. The variable stays in the environment: removing it while other threads may read it is unsound. Tests: startup_token's policy tests in the vendored crate (three fail with the policy reverted) and apps/pdfcraft/tests/winit_startup_token.rs, which keeps the patch in the build (fails with the Window::new wiring reverted). --- ROADMAP.md | 1 + apps/pdfcraft/tests/winit_startup_token.rs | 30 +++++++ docs/roadmap.md | 3 +- vendor/README.md | 2 +- vendor/winit/src/platform/startup_notify.rs | 4 +- vendor/winit/src/platform_impl/linux/mod.rs | 9 ++- .../src/platform_impl/linux/startup_token.rs | 79 +++++++++++++++++++ 7 files changed, 123 insertions(+), 5 deletions(-) create mode 100644 apps/pdfcraft/tests/winit_startup_token.rs create mode 100644 vendor/winit/src/platform_impl/linux/startup_token.rs diff --git a/ROADMAP.md b/ROADMAP.md index 56bbcd4c74..9dbde6088d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -424,6 +424,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-13 (M10, OCR review, batch and two engines):** Scan & OCR gains a review step, a second engine and Unicode output. Recognition can clean the raster first (opt-in auto-rotate, deskew, denoise, binarize; word boxes map back to the scan) and read with the built-in ocrs engine, an installed tesseract program run as a fenced external process (a validated location that fails closed instead of falling back to the PATH, allow-listed languages, a private temp directory, timeout and output caps), or both: Automatic asks tesseract when the ocrs reading is weak or of unknown confidence, and a ROVER merge keeps the more confident word (an unscored ocrs word yields only to a tesseract word of 70 or more). The OCR Verify screen (Scan & OCR ▸ Correct recognized text) reviews a recognition before it is applied: confidence-coloured word boxes, corrections, a per-language user dictionary (a plain-text file in the preferences folder, so a word added from any document stays on disk after it closes), Re-OCR of a page or a region, Accept/Reject per page or whole. Pages accepted one by one each apply once; a region re-read moves the review marks of the words it keeps, and a whole-page re-read clears that page's marks (undoable in the panel). Output is searchable (an invisible layer, one undo step) or a NEW editable document of visible text. Words beyond WinAnsi are drawn in Type3 faces from craft-fonts with a ToUnicode map in the editable output (characters no bundled face has appear as '?'); the searchable layer writes them as Type3 fonts with empty character programs and a ToUnicode map, so extraction reads them back with no fonts and no substitutions; redaction removes that layer like any other text (tests in pdfcraft-redact; the end-to-end engine test needs the craft-fonts build input and is skipped without it). Batch runs skip pages that already have text unless forced, and skip whole files that have text only with the opt-in skip-files flag (off by default; Force OCR overrides both); they refuse two inputs of the same file name and existing outputs before reading anything, and report low-confidence pages at the settings' threshold. Headless: ocr_recognize (engine, strategy, preprocessing, region; the editable output goes to an `out` that must not exist yet, and `out` is refused for a searchable run), ocr_words, ocr_review_apply, ocr_dictionary, ocr_status and ocr_recognize_files. All 21 interface catalogs carry the new strings; the Lithuanian ones were added without native review. Reading with every cleaning step off passes the render through untouched, as on main (the 300 dpi normalization runs only when a cleaning step is on: enlarging a 72 dpi render 4x on its own made the models read "due: €250" as "ue: ?250"). Still missing: the deep scan clean-up options (descreen, background and edge-shadow removal), scan images in the editable output, matching the scanned typeface, and recognition quality beyond the tested English set. - **2026-10-13 (M10, #1757):** Office export keeps each dotted-leader contents entry in one paragraph, with its page number, instead of inferring table cells from its separate text objects. - **2026-10-22 (M6, calculation scripts):** The Calculate tab and a rename read simplified field notation only from a comment, where Acrobat writes it: a string that spells `BVCALC … EVCALC` is no longer taken for the notation, or rewritten by a rename. A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression, so a rename no longer rewrites a name inside one, and a quote inside one no longer hides the `getField` calls after it. Both found in review of #3550. A `//` comment ends at `\r`, U+2028 or U+2029 as well as `\n`, so in a script with `\r` line endings the code after one is no longer hidden from a rename, or taken for the notation. Estimates unchanged. +- **2026-10-21 (M3, startup notification on Linux):** Opened from the menu or dock with `StartupNotify=true`, PdfCraft hands the launcher's activation token back from its first window (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11). GNOME kept its busy cursor for 15 seconds after the window appeared, because eframe never gives winit the token; on Wayland the window should now also open with keyboard focus. Vendored winit patch 14, with unit tests of the policy (later windows don't reuse the spent token; an empty or oversized token is ignored). Estimates unchanged. - **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged. - **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged. - **2026-10-20 (M2, #3574):** Forms without Resources use page Properties for ActualText and layer visibility. Synthetic tests cover boundaries, nested/shared forms, and save/reopen. Estimates unchanged. diff --git a/apps/pdfcraft/tests/winit_startup_token.rs b/apps/pdfcraft/tests/winit_startup_token.rs new file mode 100644 index 0000000000..6d38633561 --- /dev/null +++ b/apps/pdfcraft/tests/winit_startup_token.rs @@ -0,0 +1,30 @@ +//! vendor/winit patch (14) (vendor/README.md). + +#[test] +fn winit_hands_the_launchers_activation_token_back() { + // A launcher with `StartupNotify=true` (the packaged desktop entry) passes an activation token + // in `XDG_ACTIVATION_TOKEN` (Wayland) or `DESKTOP_STARTUP_ID` (X11) and shows a busy cursor + // until a window hands it back. eframe never gives winit a token, so GNOME kept the busy + // cursor for 15 seconds and the window opened without focus. vendor/winit gives the first + // window the environment's token. The policy is tested beside it (`startup_token::tests`, run + // them in the vendored crate); this guards the copy, which workspace tests don't test. A + // re-vendored copy without the patch would silently bring the bug back: re-apply the patch, or + // drop the copy once winit or eframe hands the token back. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let linux = root.join("vendor/winit/src/platform_impl/linux"); + let module = std::fs::read_to_string(linux.join("mod.rs")).unwrap(); + assert!(module.contains("mod startup_token;")); + let (_, new) = module.split_once(" pub(crate) fn new(\n window_target: &ActiveEventLoop,").expect("Window::new moved"); + let new = new.split_once("\n }\n").map_or(new, |(body, _)| body); + assert!( + new.contains("startup_token::for_new_window(given, startup_notify::WAYLAND_VAR)"), + "a Wayland window no longer takes the launcher's token" + ); + assert!(new.contains("startup_token::for_new_window(given, startup_notify::X11_VAR)"), "an X11 window no longer takes the launcher's token"); + let policy = std::fs::read_to_string(linux.join("startup_token.rs")).unwrap(); + assert!(policy.contains("fn the_first_window_takes_the_launchers_token")); + assert!(policy.contains("fn a_later_window_does_not_reuse_the_spent_token")); + // The token reaches the app only when the launcher asks for startup notification. + let desktop = std::fs::read_to_string(root.join("packaging/linux/ai.storyteller.pdfcraft.desktop")).unwrap(); + assert!(desktop.contains("StartupNotify=true")); +} diff --git a/docs/roadmap.md b/docs/roadmap.md index 1ff189e481..2d105b6892 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -255,7 +255,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. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). 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). #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. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). Native Recent rows also offer Reveal in Finder / File Explorer (#5452). Opened from a launcher with startup notification (the Linux desktop entry), the first window hands the launcher's activation token back, so GNOME's busy cursor clears when the window appears instead of after 15 seconds. | | 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. | @@ -428,6 +428,7 @@ Estimates unchanged. | 2026-10-17 | minor | M8, gap 6 #2662: a filled cover that hides half of any one word of a long line counts as a redaction-audit finding, applied or not; a sliver under half of every word stays unflagged. Estimates unchanged. | | 2026-10-13 | minor | M10: dotted-leader contents entries retain titles and page numbers in separate paragraphs (#1757); estimates unchanged. | | 2026-10-22 | minor | M6: calculation scripts: simplified field notation is read only from a comment, and a regular expression after `if (…)`, `while (…)`, `for (…)` or `with (…)` as one, so a rename leaves strings and regular expressions alone; a `//` comment ends at any line terminator, not only `\n`. Estimates unchanged. | +| 2026-10-21 | minor | M3: on Linux, the first window takes the launcher's activation token (`XDG_ACTIVATION_TOKEN`, `DESKTOP_STARTUP_ID`) and hands it back, so the busy cursor clears when the window appears (vendored winit patch 14). Estimates unchanged. | | 2026-10-20 | minor | M6: Prepare a form ▸ Calculation order: formulas and values, what is wrong and Fix order, Up/Down, Alt+↑/↓ and drag, links on the page. Estimates unchanged. | | 2026-10-20 | minor | M6: `form_calculation_order` reads, checks, fixes and sets the calculation order; an edited formula keeps its place in `/CO`. Estimates unchanged. | | 2026-10-20 | minor | M12 #3673: Character encoding accepts Identity-H/V with Adobe CJK collections, or a predefined non-Identity CMap; unknown names and foreign registries do not establish a mapping route. Synthetic checker and read-only automation regressions passed after failing before the fix. Per-glyph validation and embedded-font extraction remain separate; estimates unchanged. | diff --git a/vendor/README.md b/vendor/README.md index 6db4c6dc55..6c4b9e584a 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -60,7 +60,7 @@ Other resource categories retain their existing parent-chain lookup. | 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, and a failed typed read through `flex_iter` leaves the slot in place, as at a value of another type; (47) a JPEG 2000 codestream whose SIZ marker gives more than 2^28 pixels (`jpx::MAX_PIXELS`, the cap `image_size_ok` applies to `/Width` × `/Height`) is not decoded, measured at full resolution (a `target_resolution` shrinks the reported size but not each tile's coefficient buffers): the size comes from the codestream, not the image dictionary, and the decoder allocated it infallibly, so a tiny file could ask for about 47 GB and abort the process (#5078) | (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); (47) `filter::jpx::tests::a_codestream_over_the_pixel_cap_is_refused`, `filter::jpx::tests::jpx_size_guard_uses_full_resolution_before_target_resolution` (hayro-syntax) | -| 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 | +| 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; (14) on Linux, the first window created without an activation token takes the one the launcher put in the environment (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and hands it back as a token given through `with_activation_token` would be (`startup_token.rs`). eframe never gives winit a token, so with `StartupNotify=true` GNOME kept its busy cursor for 15 seconds after the window appeared, and a Wayland window opened without focus. Later windows don't reuse the spent token, and an empty or oversized (over 1,024 bytes) token is ignored. The variable is left in the environment, unlike `reset_activation_token_env`: changing the environment while other threads may read it is unsound. PdfCraft patch | (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 ; (14) `pdfcraft` `tests/winit_startup_token.rs` keeps the patch in the build, and `startup_token.rs`'s own tests test the policy (run them in the vendored crate); the busy cursor itself needs a desktop session and a launcher with `StartupNotify=true` | | 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 | | vello_cpu | 0.0.8 | Apache-2.0 OR MIT | (1) the single-threaded dispatcher leaves out a fill, stroke, fast rectangle or layer clip once the scene has no room for one more path's coverage (`StripStorage::room_for_path_within`, vello_common patch 2), records it (`RenderContext::coverage_full`, cleared by `reset`) and can be kept to fewer values (`RenderContext::set_max_coverage`, kept across `reset`). Every path's coverage stays in one buffer until the scene is rasterized, so a page that painted one form 2^22 times over (PDFBOX-5415) grew it past 2^31 values at about 7 GB and panicked in `Strip::new` (`alpha_idx` too large); it now renders what fitted. The multi-threaded dispatcher is unchanged (PdfCraft renders single-threaded); the backport of linebender/vello#2000 is recorded under the KenM76 integration patches (#5199) | (1) `raster::tests::coverage_budget::a_page_past_its_coverage_leaves_the_rest_out_and_says_so` renders a page that fills a circle 2^10 times with the rasterizer kept to 200,000 values, and fails without the dispatcher's check; `strokes_past_the_coverage_are_left_out`, `fast_rectangles_past_the_coverage_are_left_out` and `layer_clips_past_the_coverage_are_left_out` (the last through `RenderContext` directly, as hayro pushes no clipped layers, with the first clip kept below the limit and its pixels checked) each fail without that path's check, and `a_layer_clip_past_the_coverage_is_itself_left_out` fails when the clip is generated without room; vello_cpu's own tests need upstream assets that are not vendored | diff --git a/vendor/winit/src/platform/startup_notify.rs b/vendor/winit/src/platform/startup_notify.rs index 6fab284e1a..e8f4287fcc 100644 --- a/vendor/winit/src/platform/startup_notify.rs +++ b/vendor/winit/src/platform/startup_notify.rs @@ -28,10 +28,10 @@ use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial}; use crate::window::{ActivationToken, Window, WindowAttributes}; /// The variable which is used mostly on X11. -const X11_VAR: &str = "DESKTOP_STARTUP_ID"; +pub(crate) const X11_VAR: &str = "DESKTOP_STARTUP_ID"; /// The variable which is used mostly on Wayland. -const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN"; +pub(crate) const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN"; pub trait EventLoopExtStartupNotify { /// Read the token from the environment. diff --git a/vendor/winit/src/platform_impl/linux/mod.rs b/vendor/winit/src/platform_impl/linux/mod.rs index bc0e71c80c..311e33dea0 100644 --- a/vendor/winit/src/platform_impl/linux/mod.rs +++ b/vendor/winit/src/platform_impl/linux/mod.rs @@ -25,6 +25,7 @@ use crate::event_loop::{ use crate::icon::Icon; use crate::keyboard::Key; use crate::platform::pump_events::PumpStatus; +use crate::platform::startup_notify; #[cfg(x11_platform)] use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook}; use crate::window::{ @@ -38,6 +39,7 @@ pub(crate) use crate::icon::RgbaIcon as PlatformIcon; pub(crate) use crate::platform_impl::Fullscreen; pub(crate) mod common; +mod startup_token; #[cfg(wayland_platform)] pub(crate) mod wayland; #[cfg(x11_platform)] @@ -290,15 +292,20 @@ impl Window { #[inline] pub(crate) fn new( window_target: &ActiveEventLoop, - attribs: WindowAttributes, + mut attribs: WindowAttributes, ) -> Result { + let given = attribs.platform_specific.activation_token.take(); match *window_target { #[cfg(wayland_platform)] ActiveEventLoop::Wayland(ref window_target) => { + attribs.platform_specific.activation_token = + startup_token::for_new_window(given, startup_notify::WAYLAND_VAR); wayland::Window::new(window_target, attribs).map(Window::Wayland) }, #[cfg(x11_platform)] ActiveEventLoop::X(ref window_target) => { + attribs.platform_specific.activation_token = + startup_token::for_new_window(given, startup_notify::X11_VAR); x11::Window::new(window_target, attribs).map(Window::X) }, } diff --git a/vendor/winit/src/platform_impl/linux/startup_token.rs b/vendor/winit/src/platform_impl/linux/startup_token.rs new file mode 100644 index 0000000000..5dda3ffe25 --- /dev/null +++ b/vendor/winit/src/platform_impl/linux/startup_token.rs @@ -0,0 +1,79 @@ +//! The launcher's activation token for the first window (PdfCraft patch). +//! +//! A launcher with `StartupNotify=true` passes an activation token in the environment +//! (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and shows a busy cursor +//! until a window hands it back. winit hands back only a token given through +//! `WindowAttributesExtStartupNotify::with_activation_token`, and eframe never gives one, so +//! GNOME kept the busy cursor until its 15-second timeout and the window opened without focus. +//! +//! The first window the process creates without a token now takes the one in the environment. +//! Later windows never do: the token is spent once a window has handed it back. The variable is +//! left in the environment, unlike `reset_activation_token_env`, because changing the +//! environment while other threads may read it is unsound, and an application can start +//! threads before its first window. + +use std::sync::atomic::{AtomicBool, Ordering}; + +use crate::window::ActivationToken; + +/// Longer tokens are ignored. Launchers make tokens of a few dozen bytes; on X11 the token is +/// written to a window property and sent to the window manager, and an oversized one would +/// fail window creation. +const MAX_TOKEN_LEN: usize = 1024; + +static TAKEN: AtomicBool = AtomicBool::new(false); + +/// The token for a window being created: `given` if there is one, else the environment's +/// value of `var` for the process's first window. +pub(crate) fn for_new_window(given: Option, var: &str) -> Option { + choose(given, &TAKEN, || std::env::var(var).ok()) +} + +fn choose(given: Option, taken: &AtomicBool, read: impl FnOnce() -> Option) -> Option { + // The first window spends the launcher's token, whether or not it was given one. + let first = !taken.swap(true, Ordering::Relaxed); + if given.is_some() || !first { + return given; + } + read().filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN).map(ActivationToken::from_raw) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn token(raw: &str) -> Option { + Some(ActivationToken::from_raw(raw.to_owned())) + } + + #[test] + fn the_first_window_takes_the_launchers_token() { + let taken = AtomicBool::new(false); + assert_eq!(choose(None, &taken, || Some("gnome-shell/PdfCraft/1234".into())), token("gnome-shell/PdfCraft/1234")); + } + + #[test] + fn a_later_window_does_not_reuse_the_spent_token() { + let taken = AtomicBool::new(false); + assert!(choose(None, &taken, || Some("t".into())).is_some()); + assert_eq!(choose(None, &taken, || Some("t".into())), None); + } + + #[test] + fn a_given_token_wins_and_still_spends_the_launchers() { + let taken = AtomicBool::new(false); + assert_eq!(choose(token("mine"), &taken, || Some("env".into())), token("mine")); + assert_eq!(choose(None, &taken, || Some("env".into())), None); + assert_eq!(choose(token("again"), &taken, || Some("env".into())), token("again")); + } + + #[test] + fn a_missing_empty_or_oversized_token_is_ignored() { + assert_eq!(choose(None, &AtomicBool::new(false), || None), None); + assert_eq!(choose(None, &AtomicBool::new(false), || Some(String::new())), None); + let long = "x".repeat(MAX_TOKEN_LEN + 1); + assert_eq!(choose(None, &AtomicBool::new(false), || Some(long)), None); + let limit = "x".repeat(MAX_TOKEN_LEN); + assert!(choose(None, &AtomicBool::new(false), || Some(limit)).is_some()); + } +} From bc2b4cc33df441f0c843070d29f0ff9a6159efcd Mon Sep 17 00:00:00 2001 From: bmh129 <11478682+bmh129@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:02:00 -0500 Subject: [PATCH 10/29] M3: record the by-hand check of the launcher's activation token on GNOME/Wayland --- ROADMAP.md | 2 +- vendor/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 9dbde6088d..3887b4c7ec 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -424,7 +424,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-13 (M10, OCR review, batch and two engines):** Scan & OCR gains a review step, a second engine and Unicode output. Recognition can clean the raster first (opt-in auto-rotate, deskew, denoise, binarize; word boxes map back to the scan) and read with the built-in ocrs engine, an installed tesseract program run as a fenced external process (a validated location that fails closed instead of falling back to the PATH, allow-listed languages, a private temp directory, timeout and output caps), or both: Automatic asks tesseract when the ocrs reading is weak or of unknown confidence, and a ROVER merge keeps the more confident word (an unscored ocrs word yields only to a tesseract word of 70 or more). The OCR Verify screen (Scan & OCR ▸ Correct recognized text) reviews a recognition before it is applied: confidence-coloured word boxes, corrections, a per-language user dictionary (a plain-text file in the preferences folder, so a word added from any document stays on disk after it closes), Re-OCR of a page or a region, Accept/Reject per page or whole. Pages accepted one by one each apply once; a region re-read moves the review marks of the words it keeps, and a whole-page re-read clears that page's marks (undoable in the panel). Output is searchable (an invisible layer, one undo step) or a NEW editable document of visible text. Words beyond WinAnsi are drawn in Type3 faces from craft-fonts with a ToUnicode map in the editable output (characters no bundled face has appear as '?'); the searchable layer writes them as Type3 fonts with empty character programs and a ToUnicode map, so extraction reads them back with no fonts and no substitutions; redaction removes that layer like any other text (tests in pdfcraft-redact; the end-to-end engine test needs the craft-fonts build input and is skipped without it). Batch runs skip pages that already have text unless forced, and skip whole files that have text only with the opt-in skip-files flag (off by default; Force OCR overrides both); they refuse two inputs of the same file name and existing outputs before reading anything, and report low-confidence pages at the settings' threshold. Headless: ocr_recognize (engine, strategy, preprocessing, region; the editable output goes to an `out` that must not exist yet, and `out` is refused for a searchable run), ocr_words, ocr_review_apply, ocr_dictionary, ocr_status and ocr_recognize_files. All 21 interface catalogs carry the new strings; the Lithuanian ones were added without native review. Reading with every cleaning step off passes the render through untouched, as on main (the 300 dpi normalization runs only when a cleaning step is on: enlarging a 72 dpi render 4x on its own made the models read "due: €250" as "ue: ?250"). Still missing: the deep scan clean-up options (descreen, background and edge-shadow removal), scan images in the editable output, matching the scanned typeface, and recognition quality beyond the tested English set. - **2026-10-13 (M10, #1757):** Office export keeps each dotted-leader contents entry in one paragraph, with its page number, instead of inferring table cells from its separate text objects. - **2026-10-22 (M6, calculation scripts):** The Calculate tab and a rename read simplified field notation only from a comment, where Acrobat writes it: a string that spells `BVCALC … EVCALC` is no longer taken for the notation, or rewritten by a rename. A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression, so a rename no longer rewrites a name inside one, and a quote inside one no longer hides the `getField` calls after it. Both found in review of #3550. A `//` comment ends at `\r`, U+2028 or U+2029 as well as `\n`, so in a script with `\r` line endings the code after one is no longer hidden from a rename, or taken for the notation. Estimates unchanged. -- **2026-10-21 (M3, startup notification on Linux):** Opened from the menu or dock with `StartupNotify=true`, PdfCraft hands the launcher's activation token back from its first window (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11). GNOME kept its busy cursor for 15 seconds after the window appeared, because eframe never gives winit the token; on Wayland the window should now also open with keyboard focus. Vendored winit patch 14, with unit tests of the policy (later windows don't reuse the spent token; an empty or oversized token is ignored). Estimates unchanged. +- **2026-10-21 (M3, startup notification on Linux):** Opened from the menu or dock with `StartupNotify=true`, PdfCraft hands the launcher's activation token back from its first window (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11). GNOME kept its busy cursor for 15 seconds after the window appeared, because eframe never gives winit the token, and the window opened without keyboard focus. Vendored winit patch 14, with unit tests of the policy (later windows don't reuse the spent token; an empty or oversized token is ignored). Checked by hand in a test build on GNOME 50 (Wayland): the busy cursor clears as the window appears, and the window has keyboard focus. Estimates unchanged. - **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged. - **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged. - **2026-10-20 (M2, #3574):** Forms without Resources use page Properties for ActualText and layer visibility. Synthetic tests cover boundaries, nested/shared forms, and save/reopen. Estimates unchanged. diff --git a/vendor/README.md b/vendor/README.md index 6c4b9e584a..45ea584683 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -60,7 +60,7 @@ Other resource categories retain their existing parent-chain lookup. | 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, and a failed typed read through `flex_iter` leaves the slot in place, as at a value of another type; (47) a JPEG 2000 codestream whose SIZ marker gives more than 2^28 pixels (`jpx::MAX_PIXELS`, the cap `image_size_ok` applies to `/Width` × `/Height`) is not decoded, measured at full resolution (a `target_resolution` shrinks the reported size but not each tile's coefficient buffers): the size comes from the codestream, not the image dictionary, and the decoder allocated it infallibly, so a tiny file could ask for about 47 GB and abort the process (#5078) | (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); (47) `filter::jpx::tests::a_codestream_over_the_pixel_cap_is_refused`, `filter::jpx::tests::jpx_size_guard_uses_full_resolution_before_target_resolution` (hayro-syntax) | -| 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; (14) on Linux, the first window created without an activation token takes the one the launcher put in the environment (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and hands it back as a token given through `with_activation_token` would be (`startup_token.rs`). eframe never gives winit a token, so with `StartupNotify=true` GNOME kept its busy cursor for 15 seconds after the window appeared, and a Wayland window opened without focus. Later windows don't reuse the spent token, and an empty or oversized (over 1,024 bytes) token is ignored. The variable is left in the environment, unlike `reset_activation_token_env`: changing the environment while other threads may read it is unsound. PdfCraft patch | (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 ; (14) `pdfcraft` `tests/winit_startup_token.rs` keeps the patch in the build, and `startup_token.rs`'s own tests test the policy (run them in the vendored crate); the busy cursor itself needs a desktop session and a launcher with `StartupNotify=true` | +| 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; (14) on Linux, the first window created without an activation token takes the one the launcher put in the environment (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and hands it back as a token given through `with_activation_token` would be (`startup_token.rs`). eframe never gives winit a token, so with `StartupNotify=true` GNOME kept its busy cursor for 15 seconds after the window appeared, and a Wayland window opened without focus. Later windows don't reuse the spent token, and an empty or oversized (over 1,024 bytes) token is ignored. The variable is left in the environment, unlike `reset_activation_token_env`: changing the environment while other threads may read it is unsound. PdfCraft patch | (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 ; (14) `pdfcraft` `tests/winit_startup_token.rs` keeps the patch in the build, and `startup_token.rs`'s own tests test the policy (run them in the vendored crate); the busy cursor itself needs a desktop session and a launcher with `StartupNotify=true`; checked by hand on GNOME 50 (Wayland), where the busy cursor clears as the window appears and the window has keyboard focus | | 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 | | vello_cpu | 0.0.8 | Apache-2.0 OR MIT | (1) the single-threaded dispatcher leaves out a fill, stroke, fast rectangle or layer clip once the scene has no room for one more path's coverage (`StripStorage::room_for_path_within`, vello_common patch 2), records it (`RenderContext::coverage_full`, cleared by `reset`) and can be kept to fewer values (`RenderContext::set_max_coverage`, kept across `reset`). Every path's coverage stays in one buffer until the scene is rasterized, so a page that painted one form 2^22 times over (PDFBOX-5415) grew it past 2^31 values at about 7 GB and panicked in `Strip::new` (`alpha_idx` too large); it now renders what fitted. The multi-threaded dispatcher is unchanged (PdfCraft renders single-threaded); the backport of linebender/vello#2000 is recorded under the KenM76 integration patches (#5199) | (1) `raster::tests::coverage_budget::a_page_past_its_coverage_leaves_the_rest_out_and_says_so` renders a page that fills a circle 2^10 times with the rasterizer kept to 200,000 values, and fails without the dispatcher's check; `strokes_past_the_coverage_are_left_out`, `fast_rectangles_past_the_coverage_are_left_out` and `layer_clips_past_the_coverage_are_left_out` (the last through `RenderContext` directly, as hayro pushes no clipped layers, with the first clip kept below the limit and its pixels checked) each fail without that path's check, and `a_layer_clip_past_the_coverage_is_itself_left_out` fails when the clip is generated without room; vello_cpu's own tests need upstream assets that are not vendored | From 63e821e3e3b21db4f0039244eb356e3974966803 Mon Sep 17 00:00:00 2001 From: bmh129 <11478682+bmh129@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:19:15 -0500 Subject: [PATCH 11/29] M3: release the launcher's activation token when the first window fails before handing it back The first window used to spend the launcher's token as soon as it was chosen. On X11, `UnownedWindow::new` can return an error before it reaches `remove_activation_token`, so a retry got no token and the launcher's busy cursor stayed until its timeout (CodeRabbit on #3972). The token is now reserved while the window is built. Each backend marks it spent just before handing it back (Wayland `xdg_activation.activate`, X11 `remove_activation_token`), a created window commits it, and a window that fails earlier releases it for the next one. A window created while the token is held neither takes nor releases it. --- apps/pdfcraft/tests/winit_startup_token.rs | 8 + vendor/README.md | 2 +- vendor/winit/src/platform_impl/linux/mod.rs | 16 +- .../src/platform_impl/linux/startup_token.rs | 152 ++++++++++++++---- .../platform_impl/linux/wayland/window/mod.rs | 1 + .../src/platform_impl/linux/x11/window.rs | 1 + 6 files changed, 144 insertions(+), 36 deletions(-) diff --git a/apps/pdfcraft/tests/winit_startup_token.rs b/apps/pdfcraft/tests/winit_startup_token.rs index 6d38633561..ab398605f1 100644 --- a/apps/pdfcraft/tests/winit_startup_token.rs +++ b/apps/pdfcraft/tests/winit_startup_token.rs @@ -21,9 +21,17 @@ fn winit_hands_the_launchers_activation_token_back() { "a Wayland window no longer takes the launcher's token" ); assert!(new.contains("startup_token::for_new_window(given, startup_notify::X11_VAR)"), "an X11 window no longer takes the launcher's token"); + assert_eq!(new.matches("reservation.commit();").count(), 2, "a created window no longer spends the launcher's token"); + // The backends mark the token spent where they hand it back, so a window that fails earlier + // releases it for a retry and one that fails later doesn't reuse it. + for backend in ["wayland/window/mod.rs", "x11/window.rs"] { + let source = std::fs::read_to_string(linux.join(backend)).unwrap(); + assert!(source.contains("startup_token::handing_back();"), "{backend} no longer marks the token spent at its handoff"); + } let policy = std::fs::read_to_string(linux.join("startup_token.rs")).unwrap(); assert!(policy.contains("fn the_first_window_takes_the_launchers_token")); assert!(policy.contains("fn a_later_window_does_not_reuse_the_spent_token")); + assert!(policy.contains("fn a_window_that_fails_before_handing_the_token_back_releases_it")); // The token reaches the app only when the launcher asks for startup notification. let desktop = std::fs::read_to_string(root.join("packaging/linux/ai.storyteller.pdfcraft.desktop")).unwrap(); assert!(desktop.contains("StartupNotify=true")); diff --git a/vendor/README.md b/vendor/README.md index 45ea584683..cb2aa41585 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -60,7 +60,7 @@ Other resource categories retain their existing parent-chain lookup. | 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, and a failed typed read through `flex_iter` leaves the slot in place, as at a value of another type; (47) a JPEG 2000 codestream whose SIZ marker gives more than 2^28 pixels (`jpx::MAX_PIXELS`, the cap `image_size_ok` applies to `/Width` × `/Height`) is not decoded, measured at full resolution (a `target_resolution` shrinks the reported size but not each tile's coefficient buffers): the size comes from the codestream, not the image dictionary, and the decoder allocated it infallibly, so a tiny file could ask for about 47 GB and abort the process (#5078) | (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); (47) `filter::jpx::tests::a_codestream_over_the_pixel_cap_is_refused`, `filter::jpx::tests::jpx_size_guard_uses_full_resolution_before_target_resolution` (hayro-syntax) | -| 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; (14) on Linux, the first window created without an activation token takes the one the launcher put in the environment (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and hands it back as a token given through `with_activation_token` would be (`startup_token.rs`). eframe never gives winit a token, so with `StartupNotify=true` GNOME kept its busy cursor for 15 seconds after the window appeared, and a Wayland window opened without focus. Later windows don't reuse the spent token, and an empty or oversized (over 1,024 bytes) token is ignored. The variable is left in the environment, unlike `reset_activation_token_env`: changing the environment while other threads may read it is unsound. PdfCraft patch | (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 ; (14) `pdfcraft` `tests/winit_startup_token.rs` keeps the patch in the build, and `startup_token.rs`'s own tests test the policy (run them in the vendored crate); the busy cursor itself needs a desktop session and a launcher with `StartupNotify=true`; checked by hand on GNOME 50 (Wayland), where the busy cursor clears as the window appears and the window has keyboard focus | +| 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; (14) on Linux, the first window created without an activation token takes the one the launcher put in the environment (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and hands it back as a token given through `with_activation_token` would be (`startup_token.rs`). eframe never gives winit a token, so with `StartupNotify=true` GNOME kept its busy cursor for 15 seconds after the window appeared, and a Wayland window opened without focus. Later windows don't reuse the spent token; a first window that fails before its backend hands the token back releases it for a retry, and one that fails after doesn't. An empty or oversized (over 1,024 bytes) token is ignored. The variable is left in the environment, unlike `reset_activation_token_env`: changing the environment while other threads may read it is unsound. PdfCraft patch | (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 ; (14) `pdfcraft` `tests/winit_startup_token.rs` keeps the patch in the build, and checks both backends mark the token spent at their handoff, and `startup_token.rs`'s own tests test the policy (run them with `cargo test --lib startup_token` in `vendor/winit`); the busy cursor itself needs a desktop session and a launcher with `StartupNotify=true`; checked by hand on GNOME 50 (Wayland), where the busy cursor clears as the window appears and the window has keyboard focus | | 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 | | vello_cpu | 0.0.8 | Apache-2.0 OR MIT | (1) the single-threaded dispatcher leaves out a fill, stroke, fast rectangle or layer clip once the scene has no room for one more path's coverage (`StripStorage::room_for_path_within`, vello_common patch 2), records it (`RenderContext::coverage_full`, cleared by `reset`) and can be kept to fewer values (`RenderContext::set_max_coverage`, kept across `reset`). Every path's coverage stays in one buffer until the scene is rasterized, so a page that painted one form 2^22 times over (PDFBOX-5415) grew it past 2^31 values at about 7 GB and panicked in `Strip::new` (`alpha_idx` too large); it now renders what fitted. The multi-threaded dispatcher is unchanged (PdfCraft renders single-threaded); the backport of linebender/vello#2000 is recorded under the KenM76 integration patches (#5199) | (1) `raster::tests::coverage_budget::a_page_past_its_coverage_leaves_the_rest_out_and_says_so` renders a page that fills a circle 2^10 times with the rasterizer kept to 200,000 values, and fails without the dispatcher's check; `strokes_past_the_coverage_are_left_out`, `fast_rectangles_past_the_coverage_are_left_out` and `layer_clips_past_the_coverage_are_left_out` (the last through `RenderContext` directly, as hayro pushes no clipped layers, with the first clip kept below the limit and its pixels checked) each fail without that path's check, and `a_layer_clip_past_the_coverage_is_itself_left_out` fails when the clip is generated without room; vello_cpu's own tests need upstream assets that are not vendored | diff --git a/vendor/winit/src/platform_impl/linux/mod.rs b/vendor/winit/src/platform_impl/linux/mod.rs index 311e33dea0..42b7820feb 100644 --- a/vendor/winit/src/platform_impl/linux/mod.rs +++ b/vendor/winit/src/platform_impl/linux/mod.rs @@ -298,15 +298,19 @@ impl Window { match *window_target { #[cfg(wayland_platform)] ActiveEventLoop::Wayland(ref window_target) => { - attribs.platform_specific.activation_token = - startup_token::for_new_window(given, startup_notify::WAYLAND_VAR); - wayland::Window::new(window_target, attribs).map(Window::Wayland) + let (token, reservation) = startup_token::for_new_window(given, startup_notify::WAYLAND_VAR); + attribs.platform_specific.activation_token = token; + let window = wayland::Window::new(window_target, attribs).map(Window::Wayland)?; + reservation.commit(); + Ok(window) }, #[cfg(x11_platform)] ActiveEventLoop::X(ref window_target) => { - attribs.platform_specific.activation_token = - startup_token::for_new_window(given, startup_notify::X11_VAR); - x11::Window::new(window_target, attribs).map(Window::X) + let (token, reservation) = startup_token::for_new_window(given, startup_notify::X11_VAR); + attribs.platform_specific.activation_token = token; + let window = x11::Window::new(window_target, attribs).map(Window::X)?; + reservation.commit(); + Ok(window) }, } } diff --git a/vendor/winit/src/platform_impl/linux/startup_token.rs b/vendor/winit/src/platform_impl/linux/startup_token.rs index 5dda3ffe25..934533fc76 100644 --- a/vendor/winit/src/platform_impl/linux/startup_token.rs +++ b/vendor/winit/src/platform_impl/linux/startup_token.rs @@ -7,12 +7,13 @@ //! GNOME kept the busy cursor until its 15-second timeout and the window opened without focus. //! //! The first window the process creates without a token now takes the one in the environment. -//! Later windows never do: the token is spent once a window has handed it back. The variable is -//! left in the environment, unlike `reset_activation_token_env`, because changing the -//! environment while other threads may read it is unsound, and an application can start -//! threads before its first window. +//! Later windows never do: the token is spent once a window has handed it back, or once the +//! first window exists. A window that fails before handing it back releases it, so a retry +//! still clears the busy cursor. The variable is left in the environment, unlike +//! `reset_activation_token_env`, because changing the environment while other threads may read +//! it is unsound, and an application can start threads before its first window. -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicU8, Ordering}; use crate::window::ActivationToken; @@ -21,21 +22,68 @@ use crate::window::ActivationToken; /// fail window creation. const MAX_TOKEN_LEN: usize = 1024; -static TAKEN: AtomicBool = AtomicBool::new(false); +/// No window has claimed the launcher's token. +const FREE: u8 = 0; +/// A window being created holds it. +const RESERVED: u8 = 1; +/// A window has handed it back, or the first window exists. +const SPENT: u8 = 2; -/// The token for a window being created: `given` if there is one, else the environment's -/// value of `var` for the process's first window. -pub(crate) fn for_new_window(given: Option, var: &str) -> Option { - choose(given, &TAKEN, || std::env::var(var).ok()) +static STATE: AtomicU8 = AtomicU8::new(FREE); + +/// The launcher's token held by a window being created. Dropping it before it is committed or +/// handed back releases the token for the next window. +pub(crate) struct Reservation<'a> { + state: &'a AtomicU8, + held: bool, } -fn choose(given: Option, taken: &AtomicBool, read: impl FnOnce() -> Option) -> Option { - // The first window spends the launcher's token, whether or not it was given one. - let first = !taken.swap(true, Ordering::Relaxed); - if given.is_some() || !first { - return given; +impl Reservation<'_> { + /// The window was created: later windows don't take the launcher's token. + pub(crate) fn commit(self) { + if self.held { + self.state.store(SPENT, Ordering::Relaxed); + } } - read().filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN).map(ActivationToken::from_raw) +} + +impl Drop for Reservation<'_> { + fn drop(&mut self) { + if self.held { + // Fails, leaving the token spent, once it was committed or handed back. + let _ = self.state.compare_exchange(RESERVED, FREE, Ordering::Relaxed, Ordering::Relaxed); + } + } +} + +/// The token for a window being created: `given` if there is one, else the environment's +/// value of `var` for the process's first window, with the reservation the caller commits +/// once the window exists. +pub(crate) fn for_new_window(given: Option, var: &str) -> (Option, Reservation<'static>) { + choose(given, &STATE, || std::env::var(var).ok()) +} + +/// A backend is handing a window's token back to the launcher or compositor: from here on the +/// launcher's token is spent even if creating the window fails. +pub(crate) fn handing_back() { + hand_back(&STATE); +} + +fn hand_back(state: &AtomicU8) { + // Windows are created one at a time on the event loop's thread, so a reservation, if any, + // is this window's. + let _ = state.compare_exchange(RESERVED, SPENT, Ordering::Relaxed, Ordering::Relaxed); +} + +fn choose(given: Option, state: &AtomicU8, read: impl FnOnce() -> Option) -> (Option, Reservation<'_>) { + // The first window holds the launcher's token, whether or not it was given one. + let held = state.compare_exchange(FREE, RESERVED, Ordering::Relaxed, Ordering::Relaxed).is_ok(); + let reservation = Reservation { state, held }; + if given.is_some() || !held { + return (given, reservation); + } + let token = read().filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN).map(ActivationToken::from_raw); + (token, reservation) } #[cfg(test)] @@ -46,34 +94,80 @@ mod tests { Some(ActivationToken::from_raw(raw.to_owned())) } + fn created(state: &AtomicU8, given: Option, env: &str) -> Option { + let (token, reservation) = choose(given, state, || Some(env.to_owned())); + reservation.commit(); + token + } + #[test] fn the_first_window_takes_the_launchers_token() { - let taken = AtomicBool::new(false); - assert_eq!(choose(None, &taken, || Some("gnome-shell/PdfCraft/1234".into())), token("gnome-shell/PdfCraft/1234")); + let state = AtomicU8::new(FREE); + assert_eq!(created(&state, None, "gnome-shell/PdfCraft/1234"), token("gnome-shell/PdfCraft/1234")); } #[test] fn a_later_window_does_not_reuse_the_spent_token() { - let taken = AtomicBool::new(false); - assert!(choose(None, &taken, || Some("t".into())).is_some()); - assert_eq!(choose(None, &taken, || Some("t".into())), None); + let state = AtomicU8::new(FREE); + assert!(created(&state, None, "t").is_some()); + assert_eq!(created(&state, None, "t"), None); } #[test] fn a_given_token_wins_and_still_spends_the_launchers() { - let taken = AtomicBool::new(false); - assert_eq!(choose(token("mine"), &taken, || Some("env".into())), token("mine")); - assert_eq!(choose(None, &taken, || Some("env".into())), None); - assert_eq!(choose(token("again"), &taken, || Some("env".into())), token("again")); + let state = AtomicU8::new(FREE); + assert_eq!(created(&state, token("mine"), "env"), token("mine")); + assert_eq!(created(&state, None, "env"), None); + assert_eq!(created(&state, token("again"), "env"), token("again")); + } + + #[test] + fn a_window_that_fails_before_handing_the_token_back_releases_it() { + let state = AtomicU8::new(FREE); + let (first, failed) = choose(None, &state, || Some("t".into())); + assert_eq!(first, token("t")); + drop(failed); + assert_eq!(created(&state, None, "t"), token("t")); + assert_eq!(created(&state, None, "t"), None); + } + + #[test] + fn a_window_given_a_token_that_fails_early_releases_the_launchers() { + let state = AtomicU8::new(FREE); + drop(choose(token("mine"), &state, || Some("env".into()))); + assert_eq!(created(&state, None, "env"), token("env")); + } + + #[test] + fn a_window_that_fails_after_handing_the_token_back_spends_it() { + let state = AtomicU8::new(FREE); + let (first, failed) = choose(None, &state, || Some("t".into())); + assert_eq!(first, token("t")); + hand_back(&state); + drop(failed); + assert_eq!(created(&state, None, "t"), None); + } + + #[test] + fn a_window_created_while_the_token_is_held_does_not_take_or_release_it() { + let state = AtomicU8::new(FREE); + let (first, holder) = choose(None, &state, || Some("t".into())); + assert_eq!(first, token("t")); + let (other, reservation) = choose(None, &state, || Some("t".into())); + assert_eq!(other, None); + drop(reservation); + assert_eq!(state.load(Ordering::Relaxed), RESERVED); + drop(holder); + assert_eq!(created(&state, None, "t"), token("t")); } #[test] fn a_missing_empty_or_oversized_token_is_ignored() { - assert_eq!(choose(None, &AtomicBool::new(false), || None), None); - assert_eq!(choose(None, &AtomicBool::new(false), || Some(String::new())), None); + assert_eq!(created(&AtomicU8::new(FREE), None, ""), None); + assert_eq!(choose(None, &AtomicU8::new(FREE), || None).0, None); let long = "x".repeat(MAX_TOKEN_LEN + 1); - assert_eq!(choose(None, &AtomicBool::new(false), || Some(long)), None); + assert_eq!(created(&AtomicU8::new(FREE), None, &long), None); let limit = "x".repeat(MAX_TOKEN_LEN); - assert!(choose(None, &AtomicBool::new(false), || Some(limit)).is_some()); + assert!(created(&AtomicU8::new(FREE), None, &limit).is_some()); } } diff --git a/vendor/winit/src/platform_impl/linux/wayland/window/mod.rs b/vendor/winit/src/platform_impl/linux/wayland/window/mod.rs index 6d29a5a5f0..f4c09da416 100644 --- a/vendor/winit/src/platform_impl/linux/wayland/window/mod.rs +++ b/vendor/winit/src/platform_impl/linux/wayland/window/mod.rs @@ -176,6 +176,7 @@ impl Window { if let (Some(xdg_activation), Some(token)) = (xdg_activation.as_ref(), attributes.platform_specific.activation_token) { + super::super::startup_token::handing_back(); xdg_activation.activate(token.token, &surface); } diff --git a/vendor/winit/src/platform_impl/linux/x11/window.rs b/vendor/winit/src/platform_impl/linux/x11/window.rs index 7e15d5f242..c82263875c 100644 --- a/vendor/winit/src/platform_impl/linux/x11/window.rs +++ b/vendor/winit/src/platform_impl/linux/x11/window.rs @@ -558,6 +558,7 @@ impl UnownedWindow { // Remove the startup notification if we have one. if let Some(startup) = window_attrs.platform_specific.activation_token.as_ref() { + super::super::startup_token::handing_back(); leap!(xconn.remove_activation_token(xwindow, &startup.token)); } From 1b9fa432f08be4b2bd18069b4fc6f1feebeeb5dd Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 14:59:31 -0500 Subject: [PATCH 12/29] feat(a11y): mark running headers and footers as pagination artifacts Auto-tag Apply finds text that repeats near the top or bottom edge of most pages before assigning roles: the same text, digits and lone roman numerals aside, within 4 units of the same height, on at least 40% of the pages and at least two. It wraps that text in /Artifact <> BDC ... EMC with no MCID instead of tagging it (ISO 32000-2 14.8.2.2). A group of changing, heading-sized text is left as headings. Running text is left out of the body style and heading levels, MCIDs number the tagged objects only, and AutoTagResult counts headers and footers. a11y::running_text lists the findings without changing the document; accessibility_autotag_apply returns them as running_text and running_count, and its note says so. Adapted from pdfcer (MIT, same author) at ccb49b46, block_layout.rs, with distinct pages counted instead of objects. Closes #7065 Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag.rs | 183 +++++++++---- crates/a11y/src/autotag_roles.rs | 60 ++++- crates/a11y/src/autotag_running.rs | 323 +++++++++++++++++++++++ crates/a11y/src/lib.rs | 3 +- crates/a11y/src/tests.rs | 122 ++++++++- crates/automation/src/a11y.rs | 22 +- crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/automation.rs | 62 +++++ crates/engine/src/autotag.rs | 8 + docs/gaps.md | 3 +- docs/roadmap.md | 2 +- parity/acrobat-features.toml | 4 +- 12 files changed, 725 insertions(+), 69 deletions(-) create mode 100644 crates/a11y/src/autotag_running.rs diff --git a/crates/a11y/src/autotag.rs b/crates/a11y/src/autotag.rs index bf3df8d0a4..24ae511657 100644 --- a/crates/a11y/src/autotag.rs +++ b/crates/a11y/src/autotag.rs @@ -2,7 +2,10 @@ //! //! Each text object becomes a paragraph, or a heading when its size or weight sets it apart from //! the body text ([`crate::autotag_roles`]); either can be retagged with the existing tag-property -//! tool after human review. Painted paths, shadings and images outside text objects +//! tool after human review. Running headers, footers and page numbers, found by repetition across +//! the pages ([`crate::autotag_running`]), are wrapped in +//! `/Artifact <> BDC … EMC` (or `/Footer`) instead of being +//! tagged. Painted paths, shadings and images outside text objects //! are wrapped in `/Artifact BMC … EMC` so the resulting page passes the tagged-content check. use std::collections::{HashMap, HashSet}; @@ -11,6 +14,7 @@ use pdfcraft_content::{Op, Pieces, serialize_ops}; use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream}; use crate::autotag_roles::{self, Evidence}; +use crate::autotag_running::{self, Edge, Frame, PageText}; const MAX_PAGES: usize = 1_000; const MAX_PAGE_BYTES: usize = 16 * 1024 * 1024; @@ -26,6 +30,21 @@ pub struct AutoTagResult { pub pages: usize, pub paragraphs: usize, pub headings: usize, + /// Text objects marked as running header artifacts. + pub headers: usize, + /// Text objects marked as running footer artifacts, page numbers included. + pub footers: usize, +} + +/// A text object auto-tag marks as a running header or footer instead of tagging it. +#[derive(Clone, Debug, PartialEq)] +pub struct RunningText { + /// 0-based page index. + pub page: usize, + /// `"Header"` or `"Footer"`, the artifact subtype written. + pub subtype: &'static str, + /// The text shown, at most 256 characters. + pub text: String, } #[derive(Debug, thiserror::Error, PartialEq)] @@ -50,6 +69,14 @@ struct Plan { spans: Vec<(usize, usize)>, evidence: Vec, artifacts: HashMap, + frame: Frame, +} + +/// What a text object's span is wrapped in. +#[derive(Clone, Copy)] +enum Mark { + Tag(usize, &'static str), + Running(Edge), } fn unsupported(page: usize, reason: impl Into) -> AutoTagError { @@ -269,7 +296,8 @@ fn plan_page( } let resources = page_fonts(doc, &page.dict); let evidence = autotag_roles::evidence(doc, fonts, &resources, &parsed.ops, &spans); - Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts }) + let frame = Frame { rotation: page.rotation(doc), crop: page.crop(doc) }; + Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts, frame }) } fn plan(doc: &Document) -> Result, AutoTagError> { @@ -301,21 +329,26 @@ fn plan(doc: &Document) -> Result, AutoTagError> { Ok(out) } -fn mark_ops( - ops: Vec, - starts: &HashMap, - ends: &HashSet, - artifacts: &HashMap, -) -> Result, AutoTagError> { +fn mark_ops(ops: Vec, starts: &HashMap, ends: &HashSet, artifacts: &HashMap) -> Result, AutoTagError> { let artifact_ends: HashSet = artifacts.values().copied().collect(); let extra = starts.len().saturating_add(artifacts.len()).saturating_mul(2); let mut marked = Vec::with_capacity(ops.len().saturating_add(extra)); for (at, op) in ops.into_iter().enumerate() { let is_artifact = artifacts.contains_key(&at); - if let Some(&(mcid, role)) = starts.get(&at) { + if let Some(&mark) = starts.get(&at) { let mut properties = Dict::new(); - properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); - marked.push(Op::new("BDC", vec![Object::name(role), Object::Dict(properties)])); + let tag = match mark { + Mark::Tag(mcid, role) => { + properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); + role + } + Mark::Running(edge) => { + properties.set(b"Type".to_vec(), Object::name("Pagination")); + properties.set(b"Subtype".to_vec(), Object::name(edge.subtype())); + "Artifact" + } + }; + marked.push(Op::new("BDC", vec![Object::name(tag), Object::Dict(properties)])); } else if is_artifact { marked.push(Op::new("BMC", vec![Object::name("Artifact")])); } @@ -361,54 +394,108 @@ fn write_structure( Ok(()) } -/// Tag every text object in an untagged PDF as a paragraph or a heading and mark painted paths, shadings and +/// The edge each planned text object repeats at, for running text, per page and span. +fn running(plans: &[Plan]) -> Vec>> { + let all: Vec = plans.iter().flat_map(|p| p.evidence.iter().cloned()).collect(); + let pages: Vec> = plans.iter().map(|p| PageText { frame: p.frame, objects: &p.evidence }).collect(); + autotag_running::find(&pages, autotag_roles::body_size(&all)) +} + +/// The running headers, footers and page numbers [`autotag_text`] would mark as artifacts, in page +/// order. Refuses what `autotag_text` refuses, and changes nothing. +pub fn running_text(doc: &Document) -> Result, AutoTagError> { + let plans = plan(doc)?; + let mut out = Vec::new(); + for (page, (plan, edges)) in plans.iter().zip(running(&plans)).enumerate() { + for (evidence, edge) in plan.evidence.iter().zip(edges) { + if let Some(edge) = edge { + out.push(RunningText { page, subtype: edge.subtype(), text: evidence.text.clone() }); + } + } + } + Ok(out) +} + +/// What [`autotag_text`] has written so far. +struct Written { + children: Vec, + numbers: Vec, + result: AutoTagResult, +} + +/// Tag or mark one page's text objects, and write its marked content. +fn tag_page( + next: &mut Document, + document: ObjRef, + page: Plan, + edges: &[Option], + roles: &mut impl Iterator, + written: &mut Written, +) -> Result<(), AutoTagError> { + let (mut starts, mut ends, mut parents) = (HashMap::new(), HashSet::new(), Vec::new()); + let key = i64::try_from(written.result.pages).map_err(|_| AutoTagError::TooManyPages)?; + for (at, &(first, last)) in page.spans.iter().enumerate() { + ends.insert(last); + if let Some(edge) = edges.get(at).copied().flatten() { + starts.insert(first, Mark::Running(edge)); + let count = if edge == Edge::Top { &mut written.result.headers } else { &mut written.result.footers }; + *count = count.saturating_add(1); + continue; + } + let role = roles.next().unwrap_or("P"); + let mcid = parents.len(); + let mut element = Dict::new(); + element.set(b"Type".to_vec(), Object::name("StructElem")); + element.set(b"S".to_vec(), Object::name(role)); + element.set(b"P".to_vec(), Object::Ref(document)); + element.set(b"Pg".to_vec(), Object::Ref(page.page)); + element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); + let reference = next.add(element); + parents.push(Object::Ref(reference)); + written.children.push(Object::Ref(reference)); + starts.insert(first, Mark::Tag(mcid, role)); + let count = if role == "P" { &mut written.result.paragraphs } else { &mut written.result.headings }; + *count = count.saturating_add(1); + } + if !parents.is_empty() { + next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?; + written.numbers.extend([Object::Int(key), Object::Array(parents)]); + written.result.pages = written.result.pages.saturating_add(1); + } + let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?; + let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked))); + next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?; + Ok(()) +} + +/// Tag every text object in an untagged PDF as a paragraph or a heading, mark running headers, +/// footers and page numbers as pagination artifacts, and mark painted paths, shadings and /// images outside text objects as artifacts. The full structure tree, parent tree and /// marked-content IDs are written together. Unsupported operators are refused before any /// mutation. On success the caller can use tag-property edits to correct the roles after review. pub fn autotag_text(doc: &mut Document) -> Result { let plans = plan(doc)?; - let all: Vec = plans.iter().flat_map(|p| p.evidence.iter().copied()).collect(); - let mut roles = autotag_roles::roles(&all).into_iter(); + let running = running(&plans); + // Running text is left out of the body style and the heading levels, as it is out of the tags. + let tagged: Vec = plans + .iter() + .zip(&running) + .flat_map(|(p, edges)| p.evidence.iter().zip(edges).filter(|(_, edge)| edge.is_none()).map(|(e, _)| e.clone())) + .collect(); + let mut roles = autotag_roles::roles(&tagged).into_iter(); let mut next = doc.clone(); let catalog = next.root().ok_or(AutoTagError::NoCatalog)?; let (root, document) = (next.add(Object::Null), next.add(Object::Null)); - let (mut children, mut numbers, mut tagged_pages, mut paragraphs, mut headings) = (Vec::new(), Vec::new(), 0usize, 0usize, 0usize); - for page in plans { + let result = AutoTagResult { pages: 0, paragraphs: 0, headings: 0, headers: 0, footers: 0 }; + let mut written = Written { children: Vec::new(), numbers: Vec::new(), result }; + for (page, edges) in plans.into_iter().zip(running) { if page.spans.is_empty() && page.artifacts.is_empty() { continue; } - let (mut starts, mut ends) = (HashMap::new(), HashSet::new()); - if !page.spans.is_empty() { - let key = i64::try_from(tagged_pages).map_err(|_| AutoTagError::TooManyPages)?; - let mut parents = Vec::with_capacity(page.spans.len()); - for (mcid, (first, last)) in page.spans.iter().enumerate() { - let role = roles.next().unwrap_or("P"); - let mut element = Dict::new(); - element.set(b"Type".to_vec(), Object::name("StructElem")); - element.set(b"S".to_vec(), Object::name(role)); - element.set(b"P".to_vec(), Object::Ref(document)); - element.set(b"Pg".to_vec(), Object::Ref(page.page)); - element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); - let reference = next.add(element); - parents.push(Object::Ref(reference)); - children.push(Object::Ref(reference)); - starts.insert(*first, (mcid, role)); - ends.insert(*last); - if role == "P" { - paragraphs = paragraphs.saturating_add(1); - } else { - headings = headings.saturating_add(1); - } - } - next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?; - numbers.extend([Object::Int(key), Object::Array(parents)]); - tagged_pages += 1; - } - let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?; - let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked))); - next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?; + tag_page(&mut next, document, page, &edges, &mut roles, &mut written)?; } - write_structure(&mut next, catalog, root, document, children, numbers, tagged_pages)?; + let Written { children, numbers, result } = written; + write_structure(&mut next, catalog, root, document, children, numbers, result.pages)?; *doc = next; - Ok(AutoTagResult { pages: tagged_pages, paragraphs, headings }) + Ok(result) } diff --git a/crates/a11y/src/autotag_roles.rs b/crates/a11y/src/autotag_roles.rs index a72e14a417..0c9db76e15 100644 --- a/crates/a11y/src/autotag_roles.rs +++ b/crates/a11y/src/autotag_roles.rs @@ -15,7 +15,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object}; use pdfcraft_fonts::pdf::Metrics; /// A line this much larger than body text reads as a heading. -const HEADING_SIZE_RATIO: f64 = 1.15; +pub(crate) const HEADING_SIZE_RATIO: f64 = 1.15; /// Bold text this much of the body size or more can be a heading by weight. const WEIGHT_SIZE_RATIO: f64 = 0.9; const MAX_LINES: usize = 3; @@ -25,9 +25,12 @@ const MAX_CHARS: usize = 200; const MAX_SAVED: usize = 64; /// Distinct fonts measured per document; text in any further font counts as unstyled. const MAX_FONTS: usize = 256; +/// Characters of an object's text kept for finding running headers and footers; longer text is +/// body text. +pub(crate) const MAX_KEPT_CHARS: usize = 256; /// What one text object shows. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct Evidence { /// The size, in user space, carrying the most of the object's characters. pub size: f64, @@ -37,6 +40,11 @@ pub(crate) struct Evidence { /// Characters shown, whitespace excluded. pub chars: usize, pub letters: bool, + /// The text shown, at most [`MAX_KEPT_CHARS`] characters, with a space at each line move. + pub text: String, + /// `[x0, y0, x1, y1]` in user space around each shown string's origin and the point one font + /// size above it. + pub extent: Option<[f64; 4]>, } /// The structure type for each text object, in document order: `H1`–`H6` or `P`. @@ -73,6 +81,11 @@ fn half_points(size: f64) -> i64 { (size * 2.0).round() as i64 } +/// The body text size: the size carrying the most characters. +pub(crate) fn body_size(objects: &[Evidence]) -> Option { + body_style(objects).map(|(size, _)| size) +} + /// The size carrying the most characters, and whether most of them are bold. fn body_style(objects: &[Evidence]) -> Option<(f64, bool)> { let mut by_size: HashMap = HashMap::new(); @@ -136,6 +149,9 @@ struct Shown { shown: bool, moved: bool, letters: bool, + text: String, + kept: usize, + extent: Option<[f64; 4]>, } impl Shown { @@ -151,13 +167,17 @@ impl Shown { (self.shown, self.lines) = (true, 1); } else if self.moved { self.lines = self.lines.saturating_add(1); + self.keep(" "); } self.moved = false; - let [_, _, c, d, _, _] = state.tm.then(&state.ctm).0; + let [_, _, c, d, e, f] = state.tm.then(&state.ctm).0; let size = (state.size * c.hypot(d)).abs(); if !size.is_finite() || size <= 0.0 || size > 1e6 { return; } + self.keep(&text); + self.reach(e, f); + self.reach(e + state.size * c, f + state.size * d); let entry = self.by_size.entry(half_points(size)).or_default(); entry.0 = entry.0.saturating_add(chars); if metrics.bold { @@ -165,6 +185,21 @@ impl Shown { } } + fn keep(&mut self, text: &str) { + for ch in text.chars().take(MAX_KEPT_CHARS.saturating_sub(self.kept)) { + self.text.push(ch); + self.kept = self.kept.saturating_add(1); + } + } + + fn reach(&mut self, x: f64, y: f64) { + if !x.is_finite() || !y.is_finite() { + return; + } + let [x0, y0, x1, y1] = self.extent.unwrap_or([x, y, x, y]); + self.extent = Some([x0.min(x), y0.min(y), x1.max(x), y1.max(y)]); + } + /// A line move counts once text is shown after it, so blank lines and trailing moves do not. fn new_line(&mut self) { self.moved = self.shown; @@ -175,7 +210,15 @@ impl Shown { let Some((size, (count, bold))) = self.by_size.into_iter().max_by_key(|&(s, (n, _))| (n, s)) else { return Evidence::default(); }; - Evidence { size: size as f64 / 2.0, bold: bold.saturating_mul(2) > count, lines: self.lines, chars, letters: self.letters } + Evidence { + size: size as f64 / 2.0, + bold: bold.saturating_mul(2) > count, + lines: self.lines, + chars, + letters: self.letters, + text: self.text, + extent: self.extent, + } } } @@ -283,7 +326,7 @@ mod tests { use super::*; fn text(size: f64, chars: usize) -> Evidence { - Evidence { size, bold: false, lines: 1, chars, letters: true } + Evidence { size, bold: false, lines: 1, chars, letters: true, ..Evidence::default() } } fn bold(e: Evidence) -> Evidence { @@ -363,8 +406,11 @@ mod tests { let found = walk( b"q 2 0 0 2 0 0 cm BT /F1 1 Tf 9 0 0 9 10 10 Tm (Title) Tj ET Q BT /F1 12 Tf 10 50 Td (one) Tj T* (two) ' 0 -14 Td (three) Tj ET BT ET", ); - assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true }); - assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true }); + assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true, ..found[0].clone() }); + assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true, ..found[1].clone() }); + assert_eq!(found[0].text, "Title"); + assert_eq!(found[0].extent, Some([20.0, 20.0, 20.0, 38.0]), "origin and one font size above it, through Tm and cm"); + assert_eq!(found[1].text, "one two three"); assert_eq!(found[2], Evidence::default()); assert_eq!(found.len(), 3); } diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs new file mode 100644 index 0000000000..d6ef9732c4 --- /dev/null +++ b/crates/a11y/src/autotag_running.rs @@ -0,0 +1,323 @@ +//! Running headers, footers and page numbers among auto-tagged text objects, found by repetition. +//! +//! A text object is running text when it lies wholly inside the top or bottom 15% of the page as +//! displayed, and the same text appears within 4 units of the same distance from that edge on at +//! least 40% of the pages, and at least two. Text is compared lowercase with whitespace collapsed, +//! each run of digits, and a roman numeral standing alone or after `Page`, matching any number, so +//! page numbers repeat. 40% lets alternating left- and right-page headers qualify. A group whose +//! text changes from page to page and is all heading-sized (`Chapter 1`, `Chapter 2`) is a +//! sequence of headings, not running text. Position alone never makes running text. + +use std::collections::HashMap; + +use crate::autotag_roles::{Evidence, HEADING_SIZE_RATIO, MAX_KEPT_CHARS}; + +/// Depth of the top and bottom bands, as a fraction of the page height. +const BAND: f64 = 0.15; +/// How far, in user-space units, the same running text may move from page to page. +const TOLERANCE: f64 = 4.0; + +/// The page edge running text repeats at. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Edge { + Top, + Bottom, +} + +impl Edge { + /// The artifact subtype (ISO 32000-2 Table 363) for running text at this edge. + pub(crate) fn subtype(self) -> &'static str { + match self { + Edge::Top => "Header", + Edge::Bottom => "Footer", + } + } +} + +/// How a page is displayed: its `/Rotate` (0, 90, 180 or 270) and its crop box in user space. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Frame { + pub rotation: i64, + pub crop: [f64; 4], +} + +/// One page's text objects, in the order of its `(BT, ET)` spans. +pub(crate) struct PageText<'a> { + pub frame: Frame, + pub objects: &'a [Evidence], +} + +struct Member<'a> { + page: usize, + object: usize, + distance: f64, + evidence: &'a Evidence, +} + +/// The edge each text object repeats at, for running text, per page and object. +pub(crate) fn find(pages: &[PageText<'_>], body: Option) -> Vec>> { + let mut out: Vec>> = pages.iter().map(|p| vec![None; p.objects.len()]).collect(); + if pages.len() < 2 { + return out; + } + let needed = pages.len().saturating_mul(2).div_ceil(5).max(2); + for ((edge, _), mut members) in groups(pages) { + members.sort_by(|a, b| a.distance.total_cmp(&b.distance)); + let (best, distinct) = best_window(&members); + if distinct < needed { + continue; + } + let texts_differ = best.windows(2).any(|w| matches!(w, [a, b] if a.evidence.text != b.evidence.text)); + let heading_sized = body.is_some_and(|body| best.iter().all(|m| m.evidence.size >= body * HEADING_SIZE_RATIO)); + if texts_differ && heading_sized { + continue; + } + for m in best { + if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) { + *slot = Some(edge); + } + } + } + out +} + +/// Text objects inside a band, grouped by edge and normalised text. +fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec>> { + let mut groups: HashMap<(Edge, String), Vec>> = HashMap::new(); + for (page, text) in pages.iter().enumerate() { + let (low, high) = vertical(text.frame.rotation, text.frame.crop); + let band = (high - low) * BAND; + for (object, evidence) in text.objects.iter().enumerate() { + let Some(extent) = evidence.extent.filter(|_| evidence.chars > 0 && evidence.text.chars().count() < MAX_KEPT_CHARS) else { + continue; + }; + let (bottom, top) = vertical(text.frame.rotation, extent); + let (edge, distance) = if bottom >= high - band && top <= high { + (Edge::Top, high - top) + } else if top <= low + band && bottom >= low { + (Edge::Bottom, bottom - low) + } else { + continue; + }; + let key = normalise(&evidence.text); + if key.is_empty() || !distance.is_finite() { + continue; + } + groups.entry((edge, key)).or_default().push(Member { page, object, distance, evidence }); + } + } + groups +} + +/// The run of `members` (sorted by distance) spanning at most [`TOLERANCE`] that covers the most +/// pages, and that number of pages. +fn best_window<'m, 'a>(members: &'m [Member<'a>]) -> (&'m [Member<'a>], usize) { + let mut on_page: HashMap = HashMap::new(); + let (mut low, mut best, mut most) = (0usize, (0usize, 0usize), 0usize); + for (high, member) in members.iter().enumerate() { + let n = on_page.entry(member.page).or_default(); + *n = n.saturating_add(1); + while let Some(first) = members.get(low).filter(|m| member.distance - m.distance > TOLERANCE) { + if let Some(n) = on_page.get_mut(&first.page) { + *n = n.saturating_sub(1); + if *n == 0 { + on_page.remove(&first.page); + } + } + low = low.saturating_add(1); + } + if on_page.len() > most { + (most, best) = (on_page.len(), (low, high.saturating_add(1))); + } + } + (members.get(best.0..best.1).unwrap_or(&[]), most) +} + +/// The bottom and top of a user-space box as the page displays it. +fn vertical(rotation: i64, [x0, y0, x1, y1]: [f64; 4]) -> (f64, f64) { + let (a, b) = match rotation { + 90 => (-x0, -x1), + 180 => (-y0, -y1), + 270 => (x0, x1), + _ => (y0, y1), + }; + (a.min(b), a.max(b)) +} + +/// Lowercase, whitespace collapsed, and each digit run, and a roman numeral standing alone or +/// after `page`, replaced by `#`. +fn normalise(text: &str) -> String { + let lower = text.to_lowercase(); + let words: Vec<&str> = lower.split_whitespace().collect(); + let roman_alone = match words.as_slice() { + [w] | ["page", w] => is_roman(w), + _ => false, + }; + let mut out = String::new(); + for (i, w) in words.iter().enumerate() { + if i > 0 { + out.push(' '); + } + if roman_alone && i + 1 == words.len() { + out.push('#'); + continue; + } + let mut in_digits = false; + for c in w.chars() { + if c.is_ascii_digit() { + if !in_digits { + out.push('#'); + } + in_digits = true; + } else { + out.push(c); + in_digits = false; + } + } + } + out +} + +/// A canonical lowercase roman numeral from 1 to 3999 (`mid` and `iiii` are not). +fn is_roman(s: &str) -> bool { + const UNITS: [(u32, &str); 13] = [ + (1000, "m"), + (900, "cm"), + (500, "d"), + (400, "cd"), + (100, "c"), + (90, "xc"), + (50, "l"), + (40, "xl"), + (10, "x"), + (9, "ix"), + (5, "v"), + (4, "iv"), + (1, "i"), + ]; + if s.is_empty() || s.len() > 15 { + return false; + } + let (mut rest, mut value) = (s, 0u32); + for (v, sym) in UNITS { + let mut repeats = 0; + while let Some(r) = rest.strip_prefix(sym) { + (rest, value, repeats) = (r, value.saturating_add(v), repeats + 1); + if repeats > 3 { + return false; + } + } + } + if !rest.is_empty() || value == 0 { + return false; + } + let mut canonical = String::new(); + for (v, sym) in UNITS { + while value >= v { + canonical.push_str(sym); + value = value.saturating_sub(v); + } + } + canonical == s +} + +#[cfg(test)] +mod tests { + use super::*; + + const LETTER: Frame = Frame { rotation: 0, crop: [0.0, 0.0, 612.0, 792.0] }; + + /// One line of 10-unit text at baseline `y`. + fn line(text: &str, y: f64) -> Evidence { + Evidence { + size: 10.0, + lines: 1, + chars: text.chars().filter(|c| !c.is_whitespace()).count(), + letters: true, + text: text.into(), + extent: Some([72.0, y, 72.0, y + 10.0]), + ..Evidence::default() + } + } + + fn run(pages: &[Vec], body: Option) -> Vec>> { + let text: Vec> = pages.iter().map(|objects| PageText { frame: LETTER, objects }).collect(); + find(&text, body) + } + + #[test] + fn digits_and_roman_numerals_match_any_number() { + assert_eq!(normalise("Page 12 of 30"), "page # of #"); + assert_eq!(normalise("Annual Report 2026"), "annual report #"); + assert_eq!(normalise("xiv"), "#"); + assert_eq!(normalise("Page IX"), "page #"); + assert_eq!(normalise("mid"), "mid", "not a canonical numeral"); + assert_eq!(normalise("Chapter iv"), "chapter iv", "a numeral after another word is a word"); + assert!(is_roman("mmmcmxcix") && !is_roman("iiii") && !is_roman("ic") && !is_roman("")); + } + + #[test] + fn a_header_and_a_numbered_footer_repeat_but_a_body_line_does_not() { + let page = |n: usize| vec![line("Annual report", 760.0), line("Repeated body line", 400.0), line(&format!("Page {n}"), 30.0)]; + let found = run(&[page(1), page(2), page(3)], Some(10.0)); + for page in found { + assert_eq!(page, [Some(Edge::Top), None, Some(Edge::Bottom)]); + } + } + + #[test] + fn a_single_page_has_no_running_text() { + let found = run(&[vec![line("Annual report", 760.0), line("1", 30.0)]], Some(10.0)); + assert_eq!(found, [[None, None]]); + } + + #[test] + fn text_on_too_few_pages_or_at_another_height_is_not_running() { + // Five pages: the footer on one of them, the header 20 units lower on each. + let pages: Vec> = (0..5u32) + .map(|i| { + let mut page = vec![line("Header", 760.0 - f64::from(i) * 20.0)]; + if i < 1 { + page.push(line("Draft", 30.0)); + } + page + }) + .collect(); + assert!(run(&pages, None).iter().flatten().all(Option::is_none)); + // Within the tolerance, alternate headers on two of five pages qualify. + let pages: Vec> = (0..5u32).map(|i| vec![line(if i % 2 == 0 { "Left" } else { "Right" }, 760.0 + f64::from(i))]).collect(); + let found = run(&pages, None); + assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}"); + } + + #[test] + fn distinct_pages_are_counted_not_objects() { + // Six pages need three. Copies at 30 and 32 on the first page and one at 31 on the second + // are three objects in a row by height, but only two pages. + let note = |y: f64| line("Note", y); + let mut pages = vec![vec![note(30.0), note(32.0)], vec![note(31.0)], Vec::new(), Vec::new(), Vec::new(), Vec::new()]; + assert!(run(&pages, None).iter().flatten().all(Option::is_none)); + pages[2].push(note(31.0)); + assert!(run(&pages, None).iter().flatten().any(Option::is_some), "on three pages it runs"); + } + + #[test] + fn heading_sized_text_that_changes_is_a_heading_not_a_header() { + let big = |text: &str| Evidence { size: 20.0, ..line(text, 750.0) }; + let found = run(&[vec![big("Chapter 1")], vec![big("Chapter 2")]], Some(10.0)); + assert_eq!(found, [[None], [None]]); + let found = run(&[vec![big("Annual report")], vec![big("Annual report")]], Some(10.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "the same large text on every page is still a header"); + } + + #[test] + fn the_bands_follow_the_displayed_page() { + // Turned 90° clockwise, the displayed top is the user-space left edge (x = 0). + let turned = Frame { rotation: 90, crop: [0.0, 0.0, 612.0, 792.0] }; + let side = Evidence { extent: Some([20.0, 300.0, 30.0, 300.0]), ..line("Side title", 0.0) }; + let objects = vec![side]; + let pages = [PageText { frame: turned, objects: &objects }, PageText { frame: turned, objects: &objects }]; + assert_eq!(find(&pages, None), [[Some(Edge::Top)], [Some(Edge::Top)]]); + assert_eq!(run(&[objects.clone(), objects], None), [[None], [None]], "upright, it sits mid-page"); + } +} diff --git a/crates/a11y/src/lib.rs b/crates/a11y/src/lib.rs index d3492f50e7..131900a76a 100644 --- a/crates/a11y/src/lib.rs +++ b/crates/a11y/src/lib.rs @@ -16,6 +16,7 @@ mod alt; mod autotag; mod autotag_fields; mod autotag_roles; +mod autotag_running; mod content; mod headings; mod layout_table; @@ -40,7 +41,7 @@ fn count_mark_reads(_n: usize) { } pub use alt::{AltError, ArtifactError, Figure, figures, mark_decorative, mark_tag_artifact, set_alt}; -pub use autotag::{AutoTagError, AutoTagResult, autotag_text}; +pub use autotag::{AutoTagError, AutoTagResult, RunningText, autotag_text, running_text}; pub use autotag_fields::tag_form_fields; pub use headings::{Heading, headings}; pub use layout_table::{LayoutTableError, layout_table_to_blocks}; diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index 4a981aaf5b..14c550ae53 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -50,7 +50,7 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() { "", ); let result = autotag_text(&mut doc).unwrap(); - assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1 }); + assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1, headers: 0, footers: 0 }); let catalog = doc.get(doc.root().unwrap()); let root = catalog.as_dict().unwrap().reference(b"StructTreeRoot").unwrap(); let tree = doc.get(root); @@ -83,6 +83,122 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() { assert_eq!(status(&check(&reopened, &Options::default()), Rule::TaggedContent), Status::Passed); } +/// Three pages with a running header, a numbered footer and a body line repeated mid-page +/// (#7065): the header and footer become pagination artifacts without MCIDs, the rest is tagged. +fn running_text_pdf() -> Document { + let page = |n: usize| { + stream(&format!( + "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text on page {n} that is long enough to set the body size) Tj ET \ + BT /F1 12 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /F1 9 Tf 300 30 Td (Page {n}) Tj ET" + )) + }; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /F1 9 0 R >> >> >>".into(), + leaf(6), + leaf(7), + leaf(8), + page(1), + page(2), + page(3), + FONT.into(), + ], + "", + ) +} + +#[test] +fn autotag_text_marks_running_headers_and_footers_as_pagination_artifacts() { + let mut doc = running_text_pdf(); + let found = running_text(&doc).unwrap(); + let listed: Vec<(usize, &str, &str)> = found.iter().map(|r| (r.page, r.subtype, r.text.as_str())).collect(); + assert_eq!( + listed, + [ + (0, "Header", "Annual report"), + (0, "Footer", "Page 1"), + (1, "Header", "Annual report"), + (1, "Footer", "Page 2"), + (2, "Header", "Annual report"), + (2, "Footer", "Page 3") + ] + ); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!(result, AutoTagResult { pages: 3, paragraphs: 6, headings: 0, headers: 3, footers: 3 }); + for page in pdfcraft_model::pages(&doc) { + let content = doc.resolve(page.dict.get(b"Contents").unwrap()); + let Object::Stream(stream) = &*content else { panic!("marked page content") }; + let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap(); + // Each BDC in order: the artifact subtype, or the tag and its MCID. + let marks: Vec = pdfcraft_content::parse(text.as_bytes()) + .ops + .iter() + .filter(|op| op.op == b"BDC") + .map(|op| { + let d = op.operands.get(1).and_then(Object::as_dict).unwrap(); + match op.name(0).unwrap() { + b"Artifact" => { + assert_eq!(d.name(b"Type"), Some(&b"Pagination"[..])); + assert!(!d.contains(b"MCID"), "an artifact has no MCID"); + String::from_utf8(d.name(b"Subtype").unwrap().to_vec()).unwrap() + } + tag => format!("{} {}", String::from_utf8_lossy(tag), d.get(b"MCID").and_then(Object::as_int).unwrap()), + } + }) + .collect(); + assert_eq!(marks, ["Header", "P 0", "P 1", "Footer"], "{text}"); + } + let kinds: Vec = tags(&doc).iter().map(|t| t.kind.clone()).collect(); + assert_eq!(kinds, ["Document", "P", "P", "P", "P", "P", "P"]); + assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed); +} + +/// Roles are assigned over the tagged text only: a running header before a heading does not +/// shift the heading's role onto the next object. +#[test] +fn autotag_text_assigns_roles_past_running_headers() { + let body = "BT /F1 12 Tf 72 640 Td (Body text that is long enough to set the body size of the document) Tj ET"; + let page = |extra: &str| stream(&format!("BT /F1 9 Tf 72 760 Td (Annual report) Tj ET {extra} {body}")); + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + page("BT /F1 18 Tf 72 700 Td (Introduction) Tj ET"), + page(""), + FONT.into(), + ], + "", + ); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!((result.headers, result.headings, result.paragraphs), (2, 1, 2)); + let kinds: Vec = tags(&doc).iter().map(|t| t.kind.clone()).collect(); + assert_eq!(kinds, ["Document", "H1", "P", "P"]); +} + +#[test] +fn autotag_text_leaves_a_single_page_header_tagged() { + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(), + stream( + "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text long enough to set the body size) Tj ET BT /F1 9 Tf 300 30 Td (1) Tj ET", + ), + FONT.into(), + ], + "", + ); + assert_eq!(running_text(&doc).unwrap(), []); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 3)); +} + /// Page content behind a predictor whose `/DecodeParms` are given by reference is read through /// them: autotagging writes the text back as it was, marked, not with the predictor's tag bytes in /// it (a `\0` every eight bytes, which split `24` into `2 4`). @@ -108,7 +224,7 @@ fn autotag_text_reads_content_with_parameters_given_by_reference() { let mut predicted = pdfcraft_cos::Stream::flate(Dict::new(), &rows); predicted.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms)); doc.set(ObjRef::new(4, 0), predicted); - assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1, headings: 0 }); + assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 }); let page = &pdfcraft_model::pages(&doc)[0]; let written = doc.resolve(page.dict.get(b"Contents").unwrap()); let Object::Stream(written) = &*written else { panic!("page content") }; @@ -161,7 +277,7 @@ fn autotag_text_marks_vector_graphics_and_images_as_artifacts() { "", ); let result = autotag_text(&mut doc).unwrap(); - assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0 }); + assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 }); let report = check(&doc, &Options { rules: [Rule::TaggedPdf, Rule::TaggedContent].into(), pages: None }); assert_eq!(status(&report, Rule::TaggedPdf), Status::Passed); assert_eq!(status(&report, Rule::TaggedContent), Status::Passed); diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rs index cab0fb9a61..2dedaade5b 100644 --- a/crates/automation/src/a11y.rs +++ b/crates/automation/src/a11y.rs @@ -206,19 +206,31 @@ fn review_html(record: &Value) -> Result { Ok(html) } +/// Running headers and footers listed by `accessibility_autotag_apply`, at most. +const MAX_RUNNING_LISTED: usize = 200; + /// Tags in one page of `accessibility_tags`, by default and at most. const TAG_PAGE: usize = 200; const MAX_TAG_PAGE: usize = 1000; impl Automation { pub(crate) fn accessibility_autotag_apply(&mut self, a: &Args) -> Result { - let id = self.doc(a)?.id; + let doc = self.doc(a)?; + let id = doc.id; + // Read before applying: once tagged, the document is refused. A refusal here is Apply's too. + let running = doc.autotag_running_text().unwrap_or_default(); let warnings = self.apply_with_warnings(id, pdfcraft_engine::Edit::AutoTagText)?; let tags = self.accessibility_tags(a)?; - let out = json!({ - "tags": tags["tags"], "count": tags["count"], - "note": "Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. Review heading roles, reading order and remaining accessibility findings manually.", - }); + let listed: Vec = + running.iter().take(MAX_RUNNING_LISTED).map(|r| json!({ "page": r.page + 1, "subtype": r.subtype, "text": r.text })).collect(); + let note = format!( + "Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. \ + {} text objects repeating at the top or bottom of the pages were marked as running header or footer artifacts \ + instead (listed in running_text{}). Review heading roles, the running text, reading order and remaining accessibility findings manually.", + running.len(), + if running.len() > MAX_RUNNING_LISTED { format!(", first {MAX_RUNNING_LISTED}") } else { String::new() }, + ); + let out = json!({ "tags": tags["tags"], "count": tags["count"], "running_text": listed, "running_count": running.len(), "note": note }); Ok(with_warnings(out, warnings)) } diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index d058c18309..729fb87d41 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1313,7 +1313,7 @@ pub fn tools() -> Vec { t("accessibility_autotag_preview", "Preview automatic tags", "Propose paragraph and heading tags for visible text blocks on one page. Returns page bounds, tentative roles and reasons. Does not change the PDF or claim accessibility compliance. Images, tables, lists, annotations and existing structure require separate review.") .ro() .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])), - t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.") + t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, heading and paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Text repeating at the top or bottom of most pages (running headers, footers and page numbers) is marked as pagination artifacts instead and listed in running_text. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.") .with(schema(json!({ "doc": doc() }), &["doc"])), t("accessibility_autotag_form_fields", "Tag form fields", "Write `/Form` tags, widget structure-parent keys, and a parent tree for all page widgets in an untagged AcroForm. Existing tag trees are refused for review. Text, figures, links, and other content are not tagged.") .cmd("a11y.autotag_fields") diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 4674667382..c2bda33e06 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -554,6 +554,68 @@ fn autotag_apply_tags_headings_by_size_across_pages() { assert_eq!(nesting["status"], "passed", "{check}"); } +/// #7065: Apply marks a running header and a numbered footer as pagination artifacts and lists +/// them, and tags a body line that repeats mid-page like any other text. +#[test] +fn autotag_apply_marks_running_headers_and_footers_as_artifacts() { + let dir = workdir("autotag-running"); + let page = |n: usize| { + format!( + "BT /FR 9 Tf 72 760 Td (Annual report) Tj ET BT /FR 11 Tf 72 640 Td (Body text on page {n} that runs long enough to set the body size) Tj ET \ + BT /FR 11 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /FR 9 Tf 300 30 Td (Page {n}) Tj ET" + ) + }; + let mut objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /FR 9 0 R >> >> >>".into(), + ]; + objs.extend((6..9).map(|c| format!("<< /Type /Page /Parent 2 0 R /Contents {c} 0 R >>"))); + objs.extend((1..4).map(|n| { + let content = page(n); + format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()) + })); + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into()); + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + std::fs::write(dir.join("running.pdf"), bytes).unwrap(); + + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "running.pdf" }))["doc"].as_u64().unwrap(); + let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc })); + let types: Vec<&str> = applied["tags"].as_array().unwrap().iter().map(|t| t["type"].as_str().unwrap()).collect(); + assert_eq!(types, ["Document", "P", "P", "P", "P", "P", "P"], "only the body text is tagged: {applied}"); + assert_eq!(applied["running_count"], 6); + let listed: Vec<(u64, &str, &str)> = applied["running_text"] + .as_array() + .unwrap() + .iter() + .map(|r| (r["page"].as_u64().unwrap(), r["subtype"].as_str().unwrap(), r["text"].as_str().unwrap())) + .collect(); + assert_eq!(listed[..2], [(1, "Header", "Annual report"), (1, "Footer", "Page 1")]); + assert_eq!(listed[5], (3, "Footer", "Page 3")); + assert!(applied["note"].as_str().unwrap().contains("6 text objects"), "{applied}"); + let check = ok(&mut a, "accessibility_check", json!({ "doc": doc, "rules": ["tagged-content"] })); + let content = check["results"].as_array().unwrap().iter().find(|r| r["rule"] == "tagged-content").unwrap(); + assert_eq!(content["status"], "passed", "{check}"); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" })); + let reopened = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("tagged.pdf")).unwrap())).unwrap(); + let first = pdfcraft_model::pages(&reopened).into_iter().next().unwrap(); + let pdfcraft_cos::Object::Stream(stream) = &*reopened.resolve(first.dict.get(b"Contents").unwrap()) else { panic!("page content") }; + let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap(); + assert!(text.contains("/Artifact <> BDC"), "{text}"); + assert!(text.contains("/Artifact <> BDC"), "{text}"); +} + #[test] fn autotag_form_fields_writes_reviewable_widget_tags() { let dir = workdir("autotag-form-fields"); diff --git a/crates/engine/src/autotag.rs b/crates/engine/src/autotag.rs index 07b5d2dcff..2aba97aacb 100644 --- a/crates/engine/src/autotag.rs +++ b/crates/engine/src/autotag.rs @@ -83,4 +83,12 @@ impl Document { .collect(); Ok(Preview { candidates, unclassified_images: self.page_images(page).len(), unclassified_text_blocks, existing_structure }) } + + /// The running headers, footers and page numbers that applying auto-tag would mark as + /// pagination artifacts. Reads the working PDF and does not alter it; refuses what auto-tag + /// refuses. + pub fn autotag_running_text(&self) -> Result, String> { + let editor = self.editor.as_ref().ok_or("the document can't be read")?; + crate::a11y::running_text(&editor.cos).map_err(|e| e.to_string()) + } } diff --git a/docs/gaps.md b/docs/gaps.md index 6f2ab13219..b522ccdfc6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -250,7 +250,8 @@ update the numbers. Read Out Loud; full keyboard operation of PdfCraft itself and a screen-reader audit. - **Evidence:** all 32 checker rules, figure alt text, tag property and sibling order edits, and a bounded auto-tag preview exist. Apply writes valid structure and parent-tree links for - text-only files, tagging headings by size and weight; it refuses mixed content and existing tags; + text-only files, tagging headings by size and weight and marking running headers and footers + as pagination artifacts; it refuses mixed content and existing tags; `a11y.keyboard-only` (P0) planned, `a11y.app-screen-reader` partial. - **Impact:** most untagged files still need another editor to build their structure; PdfCraft itself is not yet usable without a mouse. diff --git a/docs/roadmap.md b/docs/roadmap.md index fd12d39615..bf76833e02 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -299,7 +299,7 @@ total matches the parity estimate. | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | | M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Reading colours: pending page backgrounds follow the configured colour (#2059). | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, heading and paragraph tags and a parent tree, then opens the Tags panel for review. Missing: mixed-content and field autotag, list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).
Reading colours: pending page backgrounds follow the configured colour (#2059). | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, heading and paragraph tags and a parent tree, marks running headers and footers as pagination artifacts, then opens the Tags panel for review. Missing: mixed-content and field autotag, list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).
Reading colours: pending page backgrounds follow the configured colour (#2059). | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. | | M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Local customization: adjustable, floating or side-docked hotbar with optional full-side strip and persistent tool picker; freehand highlighting is grouped with Highlight. Estimates unchanged. Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian and Arabic (logical catalog; explicit right-to-left labels and mirrored stock chrome; end-to-end RTL workflows unqualified); the 2,674-entry Brazilian Portuguese catalog covers the current key union; Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Norwegian Bokmål adds a catalog and date names (terminology reviewed by a native speaker). Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Candidate #2383 clamps GPU requests to supported limits while retaining the adapter texture extent; synthetic V3D/downlevel and Windows GPU-required tests pass, but Raspberry Pi startup is unverified. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, file-backed input and global memory budgets, performance budgets, keyboard-only operation Linux/Unix UI fallback fonts also use Fontconfig directories, including Nix store paths, with bounded discovery and the existing candidate allowlist; relative includes and digit-prefixed config filtering have isolated regressions. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, file-backed input and global memory budgets, performance budgets, keyboard-only operation XDG desktops use the configuration base for preferences with non-overwriting migration and original-data preservation (#1395). Traditional Chinese accessibility statuses, rule semantics and Taiwan form/table terms have catalog regressions. Long main-menu lists scroll in short windows (#3373). Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, file-backed input and global memory budgets, performance budgets, keyboard-only operation. Candidate #3558: bounded-worker macOS per-file PDFCraft association recovery after desktop open/save/sign; metadata-only watcher handling and upstream #3042 shared-writer preservation; recovery parser limits do not narrow save limits. Native workflow qualified on macOS 27.0.1; other versions and physical SMB/FUSE volumes remain unqualified. Estimates unchanged. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation. | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index acf720af7d..1b7ef6ff3f 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -9158,8 +9158,8 @@ milestone = "M12" status = "partial" commands = ["a11y.autotag"] tools = ["accessibility_autotag_preview", "accessibility_autotag_apply"] -evidence = ["crates/automation/tests/it/automation.rs::autotag_preview_proposes_text_without_changing_the_pdf", "crates/automation/tests/it/automation.rs::autotag_apply_writes_reviewable_tags_and_survives_save_reopen", "crates/automation/tests/it/automation.rs::autotag_apply_tags_headings_by_size_across_pages", "crates/a11y/src/autotag_roles.rs::levels_rank_styles_largest_first_and_never_skip_a_level", "crates/ui-egui/tests/it/accessibility.rs::automatic_text_tagging_opens_reviewable_tags"] -notes = "Auto-tag writes real marked content, a Document structure element, H1-H6 and P tags and a parent tree for text-only PDFs, with undo and Tags-panel review. A text object is a heading when it is short and larger or bolder than the body text; levels rank those styles across the document and never skip a level. It refuses mixed content, forms, annotations and existing tags. The preview still proposes headings by its own single-line rule, so it can differ from Apply. Running headers and footers can still become headings (#7065); invisible text (render mode 3) is ignored. Images, tables, lists, links and fields are not classified or tagged by Apply." +evidence = ["crates/automation/tests/it/automation.rs::autotag_preview_proposes_text_without_changing_the_pdf", "crates/automation/tests/it/automation.rs::autotag_apply_writes_reviewable_tags_and_survives_save_reopen", "crates/automation/tests/it/automation.rs::autotag_apply_tags_headings_by_size_across_pages", "crates/automation/tests/it/automation.rs::autotag_apply_marks_running_headers_and_footers_as_artifacts", "crates/a11y/src/autotag_roles.rs::levels_rank_styles_largest_first_and_never_skip_a_level", "crates/ui-egui/tests/it/accessibility.rs::automatic_text_tagging_opens_reviewable_tags"] +notes = "Auto-tag writes real marked content, a Document structure element, H1-H6 and P tags and a parent tree for text-only PDFs, with undo and Tags-panel review. A text object is a heading when it is short and larger or bolder than the body text; levels rank those styles across the document and never skip a level. It refuses mixed content, forms, annotations and existing tags. The preview still proposes headings by its own single-line rule, so it can differ from Apply. Text repeating near the top or bottom edge of most pages (the same text, digits aside, at about the same height) is marked as a /Pagination /Header or /Footer artifact instead of tagged, and Apply lists it for review; invisible text (render mode 3) is ignored. Images, tables, lists, links and fields are not classified or tagged by Apply." [[feature]] id = "a11y.autotag-fields" From 699d9647195d3e12bcae1bd7ec90d54f9cf78566 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 15:12:51 -0500 Subject: [PATCH 13/29] fix(a11y): keep large page numbers as footers, test crop and rotation A heading-sized group that changes only in its number is still a page number unless it has words ("Chapter 1"). Pin the bands against an offset crop box and 180 and 270 degree pages, a text origin that overflows to infinity, and a page whose only text is running text. body_size reads the evidence without cloning it. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag.rs | 3 +-- crates/a11y/src/autotag_roles.rs | 14 ++++++++++--- crates/a11y/src/autotag_running.rs | 32 +++++++++++++++++++++++++++++- crates/a11y/src/tests.rs | 25 +++++++++++++++++++++++ 4 files changed, 68 insertions(+), 6 deletions(-) diff --git a/crates/a11y/src/autotag.rs b/crates/a11y/src/autotag.rs index 24ae511657..42dc37b978 100644 --- a/crates/a11y/src/autotag.rs +++ b/crates/a11y/src/autotag.rs @@ -396,9 +396,8 @@ fn write_structure( /// The edge each planned text object repeats at, for running text, per page and span. fn running(plans: &[Plan]) -> Vec>> { - let all: Vec = plans.iter().flat_map(|p| p.evidence.iter().cloned()).collect(); let pages: Vec> = plans.iter().map(|p| PageText { frame: p.frame, objects: &p.evidence }).collect(); - autotag_running::find(&pages, autotag_roles::body_size(&all)) + autotag_running::find(&pages, autotag_roles::body_size(plans.iter().flat_map(|p| &p.evidence))) } /// The running headers, footers and page numbers [`autotag_text`] would mark as artifacts, in page diff --git a/crates/a11y/src/autotag_roles.rs b/crates/a11y/src/autotag_roles.rs index 0c9db76e15..5d5d264ade 100644 --- a/crates/a11y/src/autotag_roles.rs +++ b/crates/a11y/src/autotag_roles.rs @@ -82,14 +82,14 @@ fn half_points(size: f64) -> i64 { } /// The body text size: the size carrying the most characters. -pub(crate) fn body_size(objects: &[Evidence]) -> Option { +pub(crate) fn body_size<'a>(objects: impl IntoIterator) -> Option { body_style(objects).map(|(size, _)| size) } /// The size carrying the most characters, and whether most of them are bold. -fn body_style(objects: &[Evidence]) -> Option<(f64, bool)> { +fn body_style<'a>(objects: impl IntoIterator) -> Option<(f64, bool)> { let mut by_size: HashMap = HashMap::new(); - for e in objects.iter().filter(|e| e.chars > 0) { + for e in objects.into_iter().filter(|e| e.chars > 0) { let entry = by_size.entry(half_points(e.size)).or_default(); entry.0 = entry.0.saturating_add(e.chars); if e.bold { @@ -415,6 +415,14 @@ mod tests { assert_eq!(found.len(), 3); } + #[test] + fn an_origin_past_f64_leaves_no_extent() { + // Two translations near f64::MAX add up to infinity; the text is kept, its position is not. + let far = format!("{}.0", "9".repeat(308)); + let found = walk(format!("q 1 0 0 1 {far} 0 cm BT /F1 10 Tf 1 0 0 1 {far} 0 Tm (far) Tj ET Q").as_bytes()); + assert_eq!((found[0].text.as_str(), found[0].extent), ("far", None)); + } + #[test] fn line_moves_leading_invisible_text_and_absurd_sizes() { let found = walk( diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs index d6ef9732c4..6499679e07 100644 --- a/crates/a11y/src/autotag_running.rs +++ b/crates/a11y/src/autotag_running.rs @@ -67,9 +67,11 @@ pub(crate) fn find(pages: &[PageText<'_>], body: Option) -> Vec= body * HEADING_SIZE_RATIO)); - if texts_differ && heading_sized { + let worded = best.iter().all(|m| m.evidence.letters && normalise(&m.evidence.text) != "#"); + if texts_differ && heading_sized && worded { continue; } for m in best { @@ -308,6 +310,11 @@ mod tests { assert_eq!(found, [[None], [None]]); let found = run(&[vec![big("Annual report")], vec![big("Annual report")]], Some(10.0)); assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "the same large text on every page is still a header"); + let number = |text: &str| Evidence { letters: false, ..big(text) }; + let found = run(&[vec![number("12")], vec![number("13")]], Some(10.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "a large page number is still a page number"); + let found = run(&[vec![big("xii")], vec![big("xiii")]], Some(10.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "so is a large roman one"); } #[test] @@ -319,5 +326,28 @@ mod tests { let pages = [PageText { frame: turned, objects: &objects }, PageText { frame: turned, objects: &objects }]; assert_eq!(find(&pages, None), [[Some(Edge::Top)], [Some(Edge::Top)]]); assert_eq!(run(&[objects.clone(), objects], None), [[None], [None]], "upright, it sits mid-page"); + // Upside down the displayed top is the user-space bottom; turned 270° it is the right edge. + let upside = Frame { rotation: 180, ..turned }; + let low = vec![line("Upside down", 30.0)]; + assert_eq!( + find(&[PageText { frame: upside, objects: &low }, PageText { frame: upside, objects: &low }], None), + [[Some(Edge::Top)], [Some(Edge::Top)]] + ); + let left = Frame { rotation: 270, ..turned }; + let right = vec![Evidence { extent: Some([590.0, 300.0, 600.0, 300.0]), ..line("Turned left", 0.0) }]; + assert_eq!( + find(&[PageText { frame: left, objects: &right }, PageText { frame: left, objects: &right }], None), + [[Some(Edge::Top)], [Some(Edge::Top)]] + ); + } + + #[test] + fn the_bands_follow_the_crop_box() { + // Cropped to y 100..892, text at 860 is in the top band and text at 760 is not. + let cropped = Frame { rotation: 0, crop: [0.0, 100.0, 612.0, 892.0] }; + let objects = vec![line("Inside", 860.0), line("Below the band", 760.0)]; + let pages = [PageText { frame: cropped, objects: &objects }, PageText { frame: cropped, objects: &objects }]; + assert_eq!(find(&pages, None), [[Some(Edge::Top), None], [Some(Edge::Top), None]]); + assert_eq!(run(&[objects.clone(), objects], None)[0], [None, Some(Edge::Top)], "against the media box it is the other way"); } } diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index 14c550ae53..f2ea34210e 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -180,6 +180,31 @@ fn autotag_text_assigns_roles_past_running_headers() { assert_eq!(kinds, ["Document", "H1", "P", "P"]); } +/// A page whose only text is running text has nothing in the parent tree and gets no +/// `StructParents`; the next tagged page takes the next key. +#[test] +fn autotag_text_gives_a_page_of_running_text_alone_no_struct_parents() { + let header = "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET"; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + stream(header), + stream(&format!("{header} BT /F1 12 Tf 72 640 Td (Body) Tj ET")), + FONT.into(), + ], + "", + ); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 2, footers: 0 }); + let keys: Vec> = pdfcraft_model::pages(&doc).iter().map(|p| p.dict.get(b"StructParents").and_then(Object::as_int)).collect(); + assert_eq!(keys, [None, Some(0)]); + assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed); +} + #[test] fn autotag_text_leaves_a_single_page_header_tagged() { let mut doc = pdf( From 0ed3ad3655b1024900c34d5f2945522d67867c14 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 16:13:03 -0500 Subject: [PATCH 14/29] fix(a11y): text rise, every height cluster, labelled page numbers Apply the Ts text rise to a text object's extent, through the text matrix and CTM, so raised or lowered text is placed where it shows. Mark every qualifying height cluster of a running-text group, not only the best one: the window search repeats on the runs either side of each qualifying window, at most 8 clusters per group. A window now takes every member within the tolerance of its first, so further copies on pages it already covers are marked too. Treat a labelled page number (Page 3, p. 3, 3 of 9, 3/9, in dashes or brackets) like a bare one in the heading exception, so large labelled page numbers are footers while Chapter 1 / Chapter 2 stay headings. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag_roles.rs | 29 ++++++++-- crates/a11y/src/autotag_running.rs | 91 +++++++++++++++++++++++------- 2 files changed, 96 insertions(+), 24 deletions(-) diff --git a/crates/a11y/src/autotag_roles.rs b/crates/a11y/src/autotag_roles.rs index 5d5d264ade..43a0c6929f 100644 --- a/crates/a11y/src/autotag_roles.rs +++ b/crates/a11y/src/autotag_roles.rs @@ -107,6 +107,8 @@ struct State { tlm: Matrix, size: f64, leading: f64, + /// `Ts`, in unscaled text space units. + rise: f64, /// Text render mode 3 or 7: shown text that paints nothing, such as an OCR layer or a /// clip-only object. invisible: bool, @@ -176,8 +178,9 @@ impl Shown { return; } self.keep(&text); - self.reach(e, f); - self.reach(e + state.size * c, f + state.size * d); + let (low, high) = (state.rise, state.rise + state.size); + self.reach(e + low * c, f + low * d); + self.reach(e + high * c, f + high * d); let entry = self.by_size.entry(half_points(size)).or_default(); entry.0 = entry.0.saturating_add(chars); if metrics.bold { @@ -226,8 +229,16 @@ impl Shown { /// `/Font` resource dictionary; `fonts` is shared by the document's pages. pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: &[Op], spans: &[(usize, usize)]) -> Vec { let mut by_name: HashMap, Option>> = HashMap::new(); - let mut state = - State { ctm: Matrix::IDENTITY, tm: Matrix::IDENTITY, tlm: Matrix::IDENTITY, size: 0.0, leading: 0.0, invisible: false, metrics: None }; + let mut state = State { + ctm: Matrix::IDENTITY, + tm: Matrix::IDENTITY, + tlm: Matrix::IDENTITY, + size: 0.0, + leading: 0.0, + rise: 0.0, + invisible: false, + metrics: None, + }; let (mut saved, mut unsaved) = (Vec::new(), 0usize); let mut out = Vec::with_capacity(spans.len()); let mut spans = spans.iter().peekable(); @@ -259,6 +270,7 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: .and_then(|name| by_name.entry(name.to_vec()).or_insert_with(|| resources.get(name).and_then(|f| fonts.get(doc, f))).clone()); } b"TL" => state.leading = op.num(0).unwrap_or(state.leading), + b"Ts" => state.rise = op.num(0).unwrap_or(state.rise), b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0), b"Td" | b"TD" => { if let Some([x, y]) = op.nums::<2>() { @@ -415,6 +427,15 @@ mod tests { assert_eq!(found.len(), 3); } + #[test] + fn text_rise_moves_the_extent() { + // Ts is text space, so a 2x Tm doubles it; it outlives BT and is undone by Q. + let found = walk(b"q BT /F1 10 Tf 2 0 0 2 72 760 Tm -180 Ts (Body) Tj ET BT /F1 10 Tf 1 0 0 1 72 760 Tm (Still) Tj ET Q BT /F1 10 Tf 1 0 0 1 72 760 Tm (Back) Tj ET"); + assert_eq!(found[0].extent, Some([72.0, 400.0, 72.0, 420.0])); + assert_eq!(found[1].extent, Some([72.0, 580.0, 72.0, 590.0])); + assert_eq!(found[2].extent, Some([72.0, 760.0, 72.0, 770.0])); + } + #[test] fn an_origin_past_f64_leaves_no_extent() { // Two translations near f64::MAX add up to infinity; the text is kept, its position is not. diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs index 6499679e07..f696e4addd 100644 --- a/crates/a11y/src/autotag_running.rs +++ b/crates/a11y/src/autotag_running.rs @@ -6,7 +6,8 @@ //! each run of digits, and a roman numeral standing alone or after `Page`, matching any number, so //! page numbers repeat. 40% lets alternating left- and right-page headers qualify. A group whose //! text changes from page to page and is all heading-sized (`Chapter 1`, `Chapter 2`) is a -//! sequence of headings, not running text. Position alone never makes running text. +//! sequence of headings, not running text, unless it reads as a page number (`Page 3`, `3 of 9`). +//! Each separate cluster of heights that qualifies counts. Position alone never makes running text. use std::collections::HashMap; @@ -16,6 +17,8 @@ use crate::autotag_roles::{Evidence, HEADING_SIZE_RATIO, MAX_KEPT_CHARS}; const BAND: f64 = 0.15; /// How far, in user-space units, the same running text may move from page to page. const TOLERANCE: f64 = 4.0; +/// Height clusters kept per group of the same text, so the search stays linear in its size. +const MAX_CLUSTERS: usize = 8; /// The page edge running text repeats at. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -61,28 +64,49 @@ pub(crate) fn find(pages: &[PageText<'_>], body: Option) -> Vec= body * HEADING_SIZE_RATIO)); - let worded = best.iter().all(|m| m.evidence.letters && normalise(&m.evidence.text) != "#"); - if texts_differ && heading_sized && worded { - continue; - } - for m in best { - if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) { - *slot = Some(edge); + // Each qualifying window splits what is left into the runs on either side of it, so every + // separate cluster of heights is found; a run that does not qualify holds none. + let mut pending: Vec<&[Member<'_>]> = vec![&members]; + let mut clusters = 0usize; + while let Some(run) = pending.pop().filter(|_| clusters < MAX_CLUSTERS) { + let (start, end, distinct) = best_window(run); + let (Some(before), Some(window), Some(after)) = (run.get(..start), run.get(start..end), run.get(end..)) else { + continue; + }; + if distinct < needed || window.is_empty() { + continue; + } + pending.extend([before, after]); + clusters = clusters.saturating_add(1); + if !is_heading_sequence(window, &key, body) { + for m in window { + if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) { + *slot = Some(edge); + } + } } } } out } +/// `Chapter 1`, `Chapter 2`: heading-sized text that changes, unless it reads as a page number. +fn is_heading_sequence(window: &[Member<'_>], key: &str, body: Option) -> bool { + let texts_differ = window.windows(2).any(|w| matches!(w, [a, b] if a.evidence.text != b.evidence.text)); + let heading_sized = body.is_some_and(|body| window.iter().all(|m| m.evidence.size >= body * HEADING_SIZE_RATIO)); + let worded = window.iter().all(|m| m.evidence.letters) && !is_page_number(key); + texts_differ && heading_sized && worded +} + +/// A normalised key that is a page number alone or with its label: `#`, `page #`, `p. #`, +/// `# of #`, `page # of #`, `#/#`, optionally in dashes or brackets. +fn is_page_number(key: &str) -> bool { + let bare = key.trim_matches(|c: char| matches!(c, '-' | '\u{2013}' | '\u{2014}' | '[' | ']' | '(' | ')' | ' ')); + matches!(bare, "#" | "page #" | "p. #" | "# of #" | "page # of #" | "#/#" | "# / #") +} + /// Text objects inside a band, grouped by edge and normalised text. fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec>> { let mut groups: HashMap<(Edge, String), Vec>> = HashMap::new(); @@ -111,9 +135,10 @@ fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec(members: &'m [Member<'a>]) -> (&'m [Member<'a>], usize) { +/// The run `start..end` of `members` (sorted by distance) spanning at most [`TOLERANCE`] that +/// covers the most pages, and that number of pages. The run takes every member within the +/// tolerance of its first, so further copies on pages it already covers belong to it. +fn best_window(members: &[Member<'_>]) -> (usize, usize, usize) { let mut on_page: HashMap = HashMap::new(); let (mut low, mut best, mut most) = (0usize, (0usize, 0usize), 0usize); for (high, member) in members.iter().enumerate() { @@ -132,7 +157,14 @@ fn best_window<'m, 'a>(members: &'m [Member<'a>]) -> (&'m [Member<'a>], usize) { (most, best) = (on_page.len(), (low, high.saturating_add(1))); } } - (members.get(best.0..best.1).unwrap_or(&[]), most) + let (start, mut end) = best; + while let (Some(first), Some(next)) = (members.get(start), members.get(end)) { + if next.distance - first.distance > TOLERANCE { + break; + } + end = end.saturating_add(1); + } + (start, end, most) } /// The bottom and top of a user-space box as the page displays it. @@ -255,6 +287,8 @@ mod tests { assert_eq!(normalise("Page IX"), "page #"); assert_eq!(normalise("mid"), "mid", "not a canonical numeral"); assert_eq!(normalise("Chapter iv"), "chapter iv", "a numeral after another word is a word"); + assert!(is_page_number("#") && is_page_number("page # of #") && is_page_number("- # -") && is_page_number("[p. #]")); + assert!(!is_page_number("chapter #") && !is_page_number("page") && !is_page_number("annual report #")); assert!(is_roman("mmmcmxcix") && !is_roman("iiii") && !is_roman("ic") && !is_roman("")); } @@ -303,6 +337,21 @@ mod tests { assert!(run(&pages, None).iter().flatten().any(Option::is_some), "on three pages it runs"); } + #[test] + fn each_qualifying_cluster_of_heights_counts() { + // Six pages need three: "Note" 20 units below the top on three pages and 40 below on the + // other three, plus a second copy on the first page just inside the first cluster. + let at = |distance: f64| line("Note", 792.0 - 10.0 - distance); + let pages = vec![vec![at(20.0), at(21.0)], vec![at(20.0)], vec![at(20.0)], vec![at(40.0)], vec![at(40.0)], vec![at(40.0)]]; + let found = run(&pages, None); + assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}"); + // On two pages, a copy every 10 units from 20 down puts 9 clusters in the band, past the cap. + let column: Vec = (0..12u32).map(|i| at(20.0 + f64::from(i) * 10.0)).collect(); + let found = run(&[column.clone(), column], None); + let marked = found.iter().flatten().filter(|e| e.is_some()).count(); + assert_eq!(marked, 16, "8 clusters on 2 pages: {found:?}"); + } + #[test] fn heading_sized_text_that_changes_is_a_heading_not_a_header() { let big = |text: &str| Evidence { size: 20.0, ..line(text, 750.0) }; @@ -315,6 +364,8 @@ mod tests { assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "a large page number is still a page number"); let found = run(&[vec![big("xii")], vec![big("xiii")]], Some(10.0)); assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "so is a large roman one"); + let found = run(&[vec![big("Page 1")], vec![big("Page 2")], vec![big("- 3 of 9 -")], vec![big("- 4 of 9 -")]], Some(10.0)); + assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "a labelled page number is too: {found:?}"); } #[test] From 3a8fbb8c62bd56f6f29fced37f1040241d10a35a Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 16:44:45 -0500 Subject: [PATCH 15/29] feat(bookmarks): suggest an outline for review (#6020) bookmark_suggest proposes a bookmark tree for the whole document without changing it: the tagged headings when there are some, or else headings found from the text's size and weight by Auto-tag's heading rules, with wrapped headings joined and captions left out. The result is in bookmark_export's form, so it is reviewed as data and applied with bookmark_import in one undoable step. Part of #6020. Adapted from pdfcer (MIT, same author) at ccb49b46. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/heading_levels.rs | 56 ++++ crates/a11y/src/lib.rs | 2 + crates/automation/src/bookmark_io.rs | 28 +- crates/automation/src/dispatch.rs | 1 + crates/automation/src/tools.rs | 7 + crates/automation/tests/it/main.rs | 1 + crates/automation/tests/it/suggest_outline.rs | 134 ++++++++++ crates/engine/src/document.rs | 10 + crates/engine/src/edit/run.rs | 6 +- crates/engine/src/lib.rs | 1 + crates/engine/src/suggest_outline.rs | 249 ++++++++++++++++++ crates/engine/src/text_style_bookmarks.rs | 50 ++-- parity/acrobat-features.toml | 12 + 13 files changed, 528 insertions(+), 29 deletions(-) create mode 100644 crates/a11y/src/heading_levels.rs create mode 100644 crates/automation/tests/it/suggest_outline.rs create mode 100644 crates/engine/src/suggest_outline.rs diff --git a/crates/a11y/src/heading_levels.rs b/crates/a11y/src/heading_levels.rs new file mode 100644 index 0000000000..9934ec17f5 --- /dev/null +++ b/crates/a11y/src/heading_levels.rs @@ -0,0 +1,56 @@ +//! Heading levels for blocks of text laid out on the page, by the rules Auto-tag uses for text +//! objects ([`crate::autotag_text`]): the body style is the size carrying the most characters, +//! a block is a heading when it is short and larger than the body (or bold where the body is +//! not), and levels rank the heading styles over the whole document without skipping a level. + +use crate::autotag_roles::{Evidence, roles}; + +/// What one block of text shows: a run of lines set in one style, such as a heading that wraps. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct TextBlock { + /// The size it is shown at, in user space. + pub size: f64, + pub bold: bool, + pub lines: usize, + /// Characters shown, whitespace excluded. + pub chars: usize, + /// Whether it includes a letter: a number alone is never a heading. + pub letters: bool, +} + +/// The heading level of each block, in document order: `Some(1)` to `Some(6)`, or `None` for a +/// block that is not a heading. A heading's level is at most one deeper than the heading before. +pub fn heading_levels(blocks: &[TextBlock]) -> Vec> { + let evidence: Vec = + blocks.iter().map(|b| Evidence { size: b.size, bold: b.bold, lines: b.lines, chars: b.chars, letters: b.letters }).collect(); + roles(&evidence).into_iter().map(|role| role.strip_prefix('H').and_then(|n| n.parse().ok())).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn block(size: f64, bold: bool, lines: usize, chars: usize) -> TextBlock { + TextBlock { size, bold, lines, chars, letters: true } + } + + #[test] + fn blocks_take_the_levels_auto_tag_gives_text_objects() { + let blocks = [ + block(18.0, true, 1, 12), + block(11.0, false, 8, 600), + block(14.0, true, 2, 30), + block(11.0, false, 6, 500), + block(18.0, true, 1, 9), + block(11.0, true, 1, 20), + TextBlock { letters: false, ..block(30.0, false, 1, 2) }, + ]; + assert_eq!(heading_levels(&blocks), [Some(1), None, Some(2), None, Some(1), Some(2), None]); + } + + #[test] + fn no_text_has_no_headings() { + assert!(heading_levels(&[]).is_empty()); + assert_eq!(heading_levels(&[TextBlock::default()]), [None]); + } +} diff --git a/crates/a11y/src/lib.rs b/crates/a11y/src/lib.rs index d3492f50e7..09d96bd345 100644 --- a/crates/a11y/src/lib.rs +++ b/crates/a11y/src/lib.rs @@ -17,6 +17,7 @@ mod autotag; mod autotag_fields; mod autotag_roles; mod content; +mod heading_levels; mod headings; mod layout_table; mod report; @@ -42,6 +43,7 @@ fn count_mark_reads(_n: usize) { pub use alt::{AltError, ArtifactError, Figure, figures, mark_decorative, mark_tag_artifact, set_alt}; pub use autotag::{AutoTagError, AutoTagResult, autotag_text}; pub use autotag_fields::tag_form_fields; +pub use heading_levels::{TextBlock, heading_levels}; pub use headings::{Heading, headings}; pub use layout_table::{LayoutTableError, layout_table_to_blocks}; pub use report::{REPORT_WORDS, report_html}; diff --git a/crates/automation/src/bookmark_io.rs b/crates/automation/src/bookmark_io.rs index 2a06d912f4..3e1f07009b 100644 --- a/crates/automation/src/bookmark_io.rs +++ b/crates/automation/src/bookmark_io.rs @@ -1,4 +1,5 @@ -//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`. +//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`, +//! and `bookmark_suggest`, which proposes a tree for review before `bookmark_import` applies it. //! //! The portable form is JSON: `{"bookmarks": [node, …]}`, where a node is `title`, `page` //! (1-based, or `null` for one that goes nowhere), `view` (`{"type", "values"}`: a destination @@ -60,6 +61,31 @@ impl Automation { Ok(out) } + pub(crate) fn bookmark_suggest(&self, a: &Args) -> Result { + // The titles are the document's text, as text_lines is. + let doc = self.doc_to_copy(a)?; + let id = doc.id.0; + let s = doc.suggest_outline().ok_or_else(|| failed(format!("document {id} can't be read for editing")))?; + let source = match s.source { + pdfcraft_engine::suggest_outline::OutlineSource::Structure => "structure", + pdfcraft_engine::suggest_outline::OutlineSource::Layout => "layout", + }; + let mut out = json!({ + "source": source, + "bookmarks": s.tree().iter().map(node_json).collect::>(), + "headings": s.entries.len(), + "pages": s.pages, + "pages_read": s.pages_read, + "truncated": s.pages_read < s.pages, + }); + if s.entries.is_empty() { + out["note"] = json!( + "no headings found: the text may be in one style; text_styles lists the styles, and bookmark_from_text_styles makes bookmarks from chosen ones" + ); + } + Ok(out) + } + fn outline_of(&self, id: DocId, path: &[usize]) -> Result { match self.session.outline_tree(id, path) { // The engine names the path 0-based; the caller gave it 1-based. diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 212664a37a..2d28e8c3ae 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -202,6 +202,7 @@ impl Automation { "bookmark_export" => self.bookmark_export(&a)?, "bookmark_import" => self.bookmark_import(&a)?, "bookmark_copy" => self.bookmark_copy(&a)?, + "bookmark_suggest" => self.bookmark_suggest(&a)?, "bookmark_add" => { let page = self.page(&a)?; let parent = a.opt_path("parent")?.unwrap_or_default(); diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index d058c18309..b7778f1088 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -487,6 +487,13 @@ pub fn tools() -> Vec { "Make bookmarks from the document's tagged headings (H, H1-H6), nested by level under a new first bookmark titled \"Untitled\". Fails if the document has no tagged headings. Returns the first page of the bookmark tree (see bookmark_list). Undoable.", ) .with(schema(json!({ "doc": doc() }), &["doc"])), + t( + "bookmark_suggest", + "Suggest bookmarks", + "Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion (pages_read; truncated is true when the document has more). Changes nothing: bookmarks is in bookmark_export's form, so edit titles, levels or remove entries, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.", + ) + .ro() + .with(schema(json!({ "doc": doc() }), &["doc"])), t( "text_styles", "List text styles", diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index c8caff969f..12d635233f 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -25,6 +25,7 @@ mod portfolio_info; mod redact_after_stray_q_form; mod redact_text_after_q; mod render_warnings; +mod suggest_outline; mod text_copy; mod timesheet_compat; mod unreadable_objects; diff --git a/crates/automation/tests/it/suggest_outline.rs b/crates/automation/tests/it/suggest_outline.rs new file mode 100644 index 0000000000..24efb56a9a --- /dev/null +++ b/crates/automation/tests/it/suggest_outline.rs @@ -0,0 +1,134 @@ +//! #6020: `bookmark_suggest` proposes an outline for an untagged document from how its text looks, +//! uses the tags once there are some, and its proposal goes back in through `bookmark_import`. + +use std::path::PathBuf; + +use pdfcraft_automation::{Automation, Content}; +use serde_json::{Value, json}; + +fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("pdfcraft-suggest-outline-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn ok(a: &mut Automation, tool: &str, args: Value) -> Value { + match a.call(tool, &args) { + Ok(mut c) => match c.remove(0) { + Content::Json(v) => v, + other => panic!("{tool}: expected JSON, got {other:?}"), + }, + Err(e) => panic!("{tool} {args}: {e}"), + } +} + +const BODY: &str = "Body text runs on for a good many characters across the page."; + +/// A chapter heading (Helvetica-Bold 20) set on two lines, body text (Helvetica 11), a bold +/// caption, a section heading (Helvetica-Bold 14), and a second chapter on page 2. +fn report_pdf() -> Vec { + let body = |y: u32| format!("BT /FR 11 Tf 72 {y} Td ({BODY}) Tj ET "); + let page1 = format!( + "BT /FB 20 Tf 72 740 Td (Getting started) Tj 0 -22 Td (with the toolkit) Tj ET {}{}\ + BT /FB 14 Tf 72 640 Td (Figure 1 The toolkit) Tj ET {}\ + BT /FB 14 Tf 72 590 Td (Installing) Tj ET {}{}", + body(690), + body(676), + body(620), + body(566), + body(552) + ); + let page2 = format!("BT /FB 20 Tf 72 740 Td (Reference) Tj ET {}{}", body(700), body(686)); + two_pages(&page1, &page2) +} + +/// Two untagged pages drawing `page1` and `page2` with `/FB` (Helvetica-Bold) and `/FR` +/// (Helvetica). +fn two_pages(page1: &str, page2: &str) -> Vec { + let contents = [page1, page2]; + let mut objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /FB 7 0 R /FR 8 0 R >> >> >>".into(), + "<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".into(), + "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>".into(), + ]; + objs.extend(contents.iter().map(|c| format!("<< /Length {} >>\nstream\n{c}\nendstream", c.len()))); + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>".into()); + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into()); + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + bytes +} + +/// (title, page, children's titles) for each top-level node. +fn outline(nodes: &Value) -> Vec<(String, u64, Vec)> { + let title = |n: &Value| n["title"].as_str().unwrap().to_string(); + nodes + .as_array() + .unwrap() + .iter() + .map(|n| (title(n), n["page"].as_u64().unwrap(), n["children"].as_array().map_or(Vec::new(), |c| c.iter().map(title).collect()))) + .collect() +} + +#[test] +fn suggest_from_layout_then_import_and_undo() { + let dir = tmp("layout"); + std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap(); + let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc })); + assert_eq!(s["source"], "layout"); + assert_eq!(s["truncated"], false); + assert_eq!((s["headings"].as_u64(), s["pages"].as_u64(), s["pages_read"].as_u64()), (Some(3), Some(2), Some(2))); + let expected = + vec![("Getting started with the toolkit".to_string(), 1, vec!["Installing".to_string()]), ("Reference".to_string(), 2, Vec::new())]; + assert_eq!(outline(&s["bookmarks"]), expected, "the caption is left out and the wrapped heading is one bookmark"); + let view = &s["bookmarks"][0]["view"]; + assert_eq!(view["type"], "XYZ"); + assert_eq!(view["values"][2], Value::Null, "the zoom is the reader's"); + assert!(view["values"][1].as_f64().is_some_and(|top| top > 740.0), "goes to the top of the heading: {view}"); + // It changed nothing; the reviewed list goes in as one undoable step. + assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([])); + ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": s["bookmarks"], "replace": true })); + let back = ok(&mut a, "bookmark_export", json!({ "doc": doc })); + assert_eq!(outline(&back["bookmarks"]), expected); + ok(&mut a, "edit_undo", json!({ "doc": doc })); + assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([])); +} + +#[test] +fn suggest_uses_the_tags_once_there_are_some() { + let dir = tmp("structure"); + std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc })); + let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc })); + assert_eq!(s["source"], "structure"); + let titles: Vec<&str> = s["bookmarks"].as_array().unwrap().iter().map(|n| n["title"].as_str().unwrap()).collect(); + assert!(titles.first().is_some_and(|t| t.starts_with("Getting started")), "{s}"); +} + +#[test] +fn text_in_one_style_gets_no_suggestion_and_a_note() { + let dir = tmp("plain"); + let page = format!("BT /FR 11 Tf 72 700 Td ({BODY}) Tj 0 -14 Td ({BODY}) Tj ET"); + std::fs::write(dir.join("plain.pdf"), two_pages(&page, &page)).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "plain.pdf" }))["doc"].as_u64().unwrap(); + let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc })); + assert_eq!((s["source"].as_str(), s["headings"].as_u64(), &s["bookmarks"]), (Some("layout"), Some(0), &json!([]))); + assert!(s["note"].as_str().is_some_and(|n| n.contains("bookmark_from_text_styles")), "{s}"); +} diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 98a7e45009..e1235ea290 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -420,6 +420,16 @@ impl Document { self.editor.as_ref().map(|e| crate::text_style_bookmarks::styles(&e.cos)).unwrap_or_default() } + /// Suggest outline (#6020): the bookmark tree proposed for the document, from its tagged + /// headings or else from how its text looks. `None` when the document doesn't allow copying + /// (the titles are its text) or can't be read for editing. + pub fn suggest_outline(&self) -> Option { + if !self.allows_copying() { + return None; + } + self.editor.as_ref().map(|e| crate::suggest_outline::suggest(&e.cos)) + } + /// Edit a PDF ▸ Edit text: the lines of existing text on `page` (0-based). pub fn text_lines(&self, page: usize) -> Vec { self.editor.as_ref().and_then(|e| pdfcraft_edit::text_lines(&e.cos, page).ok()).unwrap_or_default() diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index 58a2609db6..aa12ca4ea8 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -609,11 +609,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E pdfcraft_organize::import_outline(doc, parent, *index, bookmarks, *replace)?; } Edit::BookmarksFromStructure => { - let entries: Vec<_> = pdfcraft_a11y::headings(doc) - .into_iter() - .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }) - .collect(); - pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?; + pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &crate::suggest_outline::structure_entries(doc))?; } Edit::BookmarksFromTextStyles { levels } => { if levels.is_empty() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 02fb1c588a..279ddca5e5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -59,6 +59,7 @@ pub mod signature_scan; mod sources; pub mod spooler; mod stamp_preview; +pub mod suggest_outline; #[cfg(test)] mod test_hooks; pub mod text_fonts; diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs new file mode 100644 index 0000000000..2681ac286f --- /dev/null +++ b/crates/engine/src/suggest_outline.rs @@ -0,0 +1,249 @@ +//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before +//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the +//! headings are inferred from how the text looks, by the rules Auto-tag uses +//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page +//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the +//! most characters, a short block larger than the body (or bold where the body is not) is a +//! heading, and levels rank the heading styles over the document without skipping a level. +//! Captions (`Figure 3`, `Table 2`) are not headings. Each inferred bookmark goes to the top of +//! its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); tagged ones go to their page. + +use pdfcraft_a11y::TextBlock; +use pdfcraft_cos::Document; +use pdfcraft_organize::{OutlineEntry, OutlineNode}; + +use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_PAGES, MAX_TITLE_CHARS, lines}; + +/// Blocks looked back over for one a line continues: a heading's next line can come after lines +/// of other columns on the same row. +const LOOKBACK: usize = 8; +/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent. +const MAX_DEPTH: usize = 32; + +/// Where the suggested headings come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineSource { + /// The structure tree's headings. + Structure, + /// The size and weight of the text. + Layout, +} + +/// A suggested outline. +#[derive(Clone, Debug, PartialEq)] +pub struct OutlineSuggestion { + pub source: OutlineSource, + /// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]). + pub entries: Vec, + /// Pages in the document. + pub pages: usize, + /// Pages whose text was read: at most [`MAX_PAGES`] for a suggestion from layout. + pub pages_read: usize, +} + +impl OutlineSuggestion { + /// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the + /// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth. + pub fn tree(&self) -> Vec { + nest(&self.entries, &mut 0, 0, 0) + } +} + +/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion +/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't. +fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec { + let mut out = Vec::new(); + while let Some(e) = entries.get(*at) { + if depth > 0 && e.level <= above { + break; + } + *at = at.saturating_add(1); + let mut n = node(e); + if depth.saturating_add(1) < MAX_DEPTH { + n.children = nest(entries, at, e.level, depth.saturating_add(1)); + } + out.push(n); + } + out +} + +fn node(e: &OutlineEntry) -> OutlineNode { + let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None])); + OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() } +} + +/// The tagged headings as outline entries, each linked to its element (`/SE`). +pub(crate) fn structure_entries(doc: &Document) -> Vec { + pdfcraft_a11y::headings(doc) + .into_iter() + .map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }) + .collect() +} + +/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the +/// first [`MAX_PAGES`] pages' text. Empty when neither finds a heading. +pub fn suggest(doc: &Document) -> OutlineSuggestion { + let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); + let tagged = structure_entries(doc); + if !tagged.is_empty() { + return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages }; + } + OutlineSuggestion { source: OutlineSource::Layout, entries: inferred(lines(doc)), pages, pages_read: pages.min(MAX_PAGES) } +} + +/// Lines in one style, one after another down a page. +struct Block { + first: Line, + last: Line, + title: String, + lines: usize, + chars: usize, + letters: bool, +} + +impl Block { + fn new(line: Line) -> Block { + let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false }; + b.count(&b.first.text.clone()); + b + } + + fn add(&mut self, line: Line) { + if self.title.chars().count() < MAX_TITLE_CHARS { + self.title.push(' '); + } + self.count(&line.text); + self.last = line; + } + + fn count(&mut self, text: &str) { + self.lines = self.lines.saturating_add(1); + self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count()); + self.letters |= text.chars().any(char::is_alphabetic); + let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count()); + self.title.extend(text.chars().take(room)); + } + + fn evidence(&self) -> TextBlock { + let s = &self.first.style; + TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters } + } +} + +/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last +/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]). +fn blocks(lines: Vec) -> Vec { + let mut out: Vec = Vec::new(); + for line in lines { + let start = out.len().saturating_sub(LOOKBACK); + let found = out.get_mut(start..).and_then(|recent| { + recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last)) + }); + match found { + Some(b) => b.add(line), + None => out.push(Block::new(line)), + } + } + out +} + +/// A caption's lead: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a number. +fn is_caption(text: &str) -> bool { + let t = text.trim_start(); + ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"] + .iter() + .any(|lead| t.strip_prefix(lead).is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit()))) +} + +/// The headings among `lines`, as outline entries. +fn inferred(lines: Vec) -> Vec { + let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); + let evidence: Vec = blocks.iter().map(Block::evidence).collect(); + blocks + .iter() + .zip(pdfcraft_a11y::heading_levels(&evidence)) + .filter_map(|(b, level)| { + let [left, top] = b.first.anchor; + Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top }) + }) + .take(MAX_BOOKMARKS) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text_style_bookmarks::TextStyle; + + /// A line at `top` (its box 0.8 of its size tall) from x 72 to 400. + fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line { + let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false }; + Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] } + } + + fn body(page: usize, top: f64) -> Line { + line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.") + } + + fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> { + entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect() + } + + #[test] + fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() { + let lines = vec![ + line(0, 760.0, 20.0, true, "Getting started"), + line(0, 738.0, 20.0, true, "with the toolkit"), + body(0, 700.0), + body(0, 686.0), + body(0, 672.0), + body(0, 658.0), + line(0, 630.0, 11.0, true, "Installing"), + body(0, 610.0), + body(0, 596.0), + line(1, 760.0, 20.0, true, "Reference"), + body(1, 730.0), + body(1, 716.0), + ]; + let found = inferred(lines); + assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]); + assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line"); + } + + #[test] + fn a_wrapped_heading_joins_across_a_line_of_another_column() { + let mut right = body(0, 760.0); + (right.left, right.right) = (420.0, 560.0); + let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)]; + assert_eq!(titles(&inferred(lines)), [(1, "Two column heading", 0)]); + } + + #[test] + fn captions_and_numbers_are_not_headings() { + let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).is_empty()); + assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); + } + + #[test] + fn the_tree_nests_by_level_and_caps_the_depth() { + let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; + let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")]; + let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1 }; + let tree = s.tree(); + assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::>(), ["A", "B"]); + assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::>(), ["A.1", "A.2"]); + assert_eq!(tree[0].children[0].children[0].title, "A.1.a"); + assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None]))); + // A tagged H nested in 40 sections stops at the deepest level bookmark_import takes. + entries = (1..=40).map(|l| entry(l, "deep")).collect(); + let deep = OutlineSuggestion { entries, ..s }.tree(); + let mut depth = 0; + let mut at = &deep; + while let Some(n) = at.first() { + depth += 1; + at = &n.children; + } + assert_eq!(depth, MAX_DEPTH); + } +} diff --git a/crates/engine/src/text_style_bookmarks.rs b/crates/engine/src/text_style_bookmarks.rs index 05ca9223f0..329b578420 100644 --- a/crates/engine/src/text_style_bookmarks.rs +++ b/crates/engine/src/text_style_bookmarks.rs @@ -49,29 +49,41 @@ pub const MAX_PAGES: usize = 5000; /// The most bookmarks made at once. pub const MAX_BOOKMARKS: usize = 10_000; /// The longest bookmark title kept, in characters (a heading run on into a paragraph). -const MAX_TITLE_CHARS: usize = 300; +pub(crate) const MAX_TITLE_CHARS: usize = 300; /// The longest sample shown for a style. const SAMPLE_CHARS: usize = 60; /// The most styles listed, the largest first. const MAX_STYLES: usize = 200; /// One line of text in reading order. -struct Line { - page: usize, - text: String, - style: TextStyle, +#[derive(Clone)] +pub(crate) struct Line { + pub(crate) page: usize, + pub(crate) text: String, + pub(crate) style: TextStyle, /// Top, bottom, left and right of its box as displayed (after the page's `/Rotate`, y up), so /// reading order and the join of a heading's lines are right on a turned page. Only /// differences between these values are used: they are offset from points on the page. - top: f64, - bottom: f64, - left: f64, - right: f64, + pub(crate) top: f64, + pub(crate) bottom: f64, + pub(crate) left: f64, + pub(crate) right: f64, /// The `/XYZ` position `[left, top]` (user space) that puts the top of the line as displayed /// at the top of the window. The box edge displayed on top depends on the rotation: the top /// edge, the left edge (90), the bottom edge (180) or the right edge (270). On a page turned /// a quarter it is a user-space x, so it is `left`, and `top` stays unspecified. - anchor: [Option; 2], + pub(crate) anchor: [Option; 2], +} + +impl Line { + /// Whether this line goes on with a heading whose last line is `above`: on the same page, on + /// the next row down, close below it and under it. A line on the same row (two headings side + /// by side), or in another column, starts a heading of its own. + pub(crate) fn continues(&self, above: &Line) -> bool { + let size = self.style.size; + let under = self.left < above.right && above.left < self.right; + self.page == above.page && self.top < above.top - size * 0.5 && above.bottom - self.top < size * 0.6 && under + } } /// A box in user space `[x0, y0, x1, y1]` on a page turned `rotation` degrees clockwise → its @@ -96,7 +108,7 @@ fn without_subset_tag(name: &str) -> &str { /// The text lines of `doc`'s first [`MAX_PAGES`] pages, each page's in reading order. Text that /// is only whitespace, or whose size can't be read, is left out. -fn lines(doc: &Document) -> Vec { +pub(crate) fn lines(doc: &Document) -> Vec { let pages = pdfcraft_organize::page_count(doc).unwrap_or(0).min(MAX_PAGES); let rotations = pdfcraft_organize::page_rotations(doc).unwrap_or_default(); let mut out = Vec::new(); @@ -183,22 +195,14 @@ pub fn styles(doc: &Document) -> Vec { /// is one bookmark. Each goes to the top of its heading as displayed, also on a turned page. pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec { let mut entries: Vec = Vec::new(); - // The heading the previous line belonged to: its level, and the top, bottom, left and right - // of its last line. - let mut open: Option<(usize, f64, f64, f64, f64)> = None; + // The heading the previous line belonged to: its level and its last line. + let mut open: Option<(usize, Line)> = None; for line in lines(doc) { let Some(level) = levels.iter().position(|s| s.matches(&line.style)) else { open = None; continue; }; - // A heading goes on to the next row down, close below its last line and under it. A line - // on the same row (two headings side by side), or in another column, is a heading of - // its own. - let continues = open.is_some_and(|(l, top, bottom, left, right)| { - let size = line.style.size; - let under = line.left < right && left < line.right; - l == level && line.top < top - size * 0.5 && bottom - line.top < size * 0.6 && under - }) && entries.last().is_some_and(|e| e.page == line.page); + let continues = open.as_ref().is_some_and(|(l, above)| *l == level && line.continues(above)); if continues { if let Some(e) = entries.last_mut() && e.title.chars().count() < MAX_TITLE_CHARS @@ -217,7 +221,7 @@ pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec { let [left, top] = line.anchor; entries.push(OutlineEntry { level, title: line.text.chars().take(MAX_TITLE_CHARS).collect(), page: line.page, element: None, left, top }); } - open = Some((level, line.top, line.bottom, line.left, line.right)); + open = Some((level, line)); } entries } diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index acf720af7d..83a5d62102 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -3433,6 +3433,18 @@ tools = ["text_styles", "bookmark_from_text_styles"] evidence = ["crates/engine/src/tests.rs::bookmarks_from_text_styles_nest_the_headings_and_undo", "crates/engine/src/text_style_bookmarks.rs::subset_tags_are_left_out_of_the_font_name", "crates/engine/src/text_style_bookmarks.rs::styles_match_within_a_quarter_point", "crates/automation/tests/it/automation.rs::bookmarks_from_text_styles_through_tools", "crates/ui-egui/tests/it/bookmarks.rs::new_bookmarks_from_text_styles_from_the_bookmark_options"] notes = "Bookmark options (and Pages) ▸ New bookmarks from text styles…, for documents whose headings aren't tagged (#1693): the dialog lists the document's text styles (font without its subset tag, the size shown at, bold, italic, line count and a sample), the largest first and offered for level 1; one style per level, up to four levels (nine headlessly). Every line in a level's style becomes a bookmark of that level under a new first \"Untitled\" bookmark, a heading set on several rows is one bookmark, and each goes to the top of its heading (/XYZ). Lines are read down each page, then left to right, so a multi-column page's headings are taken row by row across the columns; sizes within a quarter point match. Not yet: several styles for one level, colour as part of a style, and the first 5000 pages only. Acrobat has no such command (its bookmarks come from structure); this is beyond it" +[[feature]] +id = "organize.suggest-outline" +title = "Suggest bookmarks for review" +area = "D" +tier = "P2" +milestone = "M4" +status = "partial" +commands = [] +tools = ["bookmark_suggest"] +evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] +notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) are left out. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" + [[feature]] id = "organize.bookmarks-import-export" title = "Export, import and copy bookmarks" From 2980cfca6a407bbaff9dd6150cf3e7bdcb7982e6 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 18:01:56 -0500 Subject: [PATCH 16/29] fix(bookmarks): report every way a suggested outline can miss headings bookmark_suggest's pages_read counted a page whose text could not be read (its content past the page decode allowance) as read, and the layout cap of 10,000 bookmarks dropped headings without setting truncated. read_lines now counts the pages it read; the suggestion carries truncated when pages were not read or more headings than the cap were found, and the tool returns that. Caption leads (Figure, Fig., Table, Chart, Exhibit, Plate) now match in any case, so "FIGURE 3:" is not suggested as a heading. Tests: captions_match_in_any_case, more_headings_than_the_cap_are_reported, a_page_whose_text_cant_be_read_is_not_counted; each fails with its fix reverted. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/bookmark_io.rs | 2 +- crates/automation/src/tools.rs | 2 +- crates/engine/src/suggest_outline.rs | 98 ++++++++++++++++++----- crates/engine/src/text_style_bookmarks.rs | 10 ++- parity/acrobat-features.toml | 2 +- 5 files changed, 92 insertions(+), 22 deletions(-) diff --git a/crates/automation/src/bookmark_io.rs b/crates/automation/src/bookmark_io.rs index 3e1f07009b..b3b626ad1b 100644 --- a/crates/automation/src/bookmark_io.rs +++ b/crates/automation/src/bookmark_io.rs @@ -76,7 +76,7 @@ impl Automation { "headings": s.entries.len(), "pages": s.pages, "pages_read": s.pages_read, - "truncated": s.pages_read < s.pages, + "truncated": s.truncated, }); if s.entries.is_empty() { out["note"] = json!( diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index b7778f1088..ac9e4091ce 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -490,7 +490,7 @@ pub fn tools() -> Vec { t( "bookmark_suggest", "Suggest bookmarks", - "Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion (pages_read; truncated is true when the document has more). Changes nothing: bookmarks is in bookmark_export's form, so edit titles, levels or remove entries, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.", + "Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion; pages_read counts the pages whose text was read. truncated is true when headings may be missing: the document has more pages, a page's text could not be read, or there were more than 10000 headings (the first 10000 are given). Changes nothing: bookmarks is in bookmark_export's form, so edit titles, levels or remove entries, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.", ) .ro() .with(schema(json!({ "doc": doc() }), &["doc"])), diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index 2681ac286f..5765615417 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -12,7 +12,7 @@ use pdfcraft_a11y::TextBlock; use pdfcraft_cos::Document; use pdfcraft_organize::{OutlineEntry, OutlineNode}; -use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_PAGES, MAX_TITLE_CHARS, lines}; +use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, read_lines}; /// Blocks looked back over for one a line continues: a heading's next line can come after lines /// of other columns on the same row. @@ -37,8 +37,11 @@ pub struct OutlineSuggestion { pub entries: Vec, /// Pages in the document. pub pages: usize, - /// Pages whose text was read: at most [`MAX_PAGES`] for a suggestion from layout. + /// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) + /// for a suggestion from layout, fewer when a page's text can't be read. pub pages_read: usize, + /// Headings were left out: pages weren't read, or layout found more than [`MAX_BOOKMARKS`]. + pub truncated: bool, } impl OutlineSuggestion { @@ -81,14 +84,17 @@ pub(crate) fn structure_entries(doc: &Document) -> Vec { } /// The outline suggested for `doc`: its tagged headings, or else headings inferred from the -/// first [`MAX_PAGES`] pages' text. Empty when neither finds a heading. +/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither +/// finds a heading. pub fn suggest(doc: &Document) -> OutlineSuggestion { let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); let tagged = structure_entries(doc); if !tagged.is_empty() { - return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages }; + return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: false }; } - OutlineSuggestion { source: OutlineSource::Layout, entries: inferred(lines(doc)), pages, pages_read: pages.min(MAX_PAGES) } + let (lines, pages_read) = read_lines(doc); + let (entries, capped) = inferred(lines); + OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: capped || pages_read < pages } } /// Lines in one style, one after another down a page. @@ -147,27 +153,33 @@ fn blocks(lines: Vec) -> Vec { out } -/// A caption's lead: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a number. +/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a +/// number. fn is_caption(text: &str) -> bool { let t = text.trim_start(); - ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"] - .iter() - .any(|lead| t.strip_prefix(lead).is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit()))) + ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| { + let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..)); + rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit())) + }) } -/// The headings among `lines`, as outline entries. -fn inferred(lines: Vec) -> Vec { +/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there +/// were more. +fn inferred(lines: Vec) -> (Vec, bool) { let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); let evidence: Vec = blocks.iter().map(Block::evidence).collect(); - blocks + let mut entries: Vec = blocks .iter() .zip(pdfcraft_a11y::heading_levels(&evidence)) .filter_map(|(b, level)| { let [left, top] = b.first.anchor; Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top }) }) - .take(MAX_BOOKMARKS) - .collect() + .take(MAX_BOOKMARKS.saturating_add(1)) + .collect(); + let capped = entries.len() > MAX_BOOKMARKS; + entries.truncate(MAX_BOOKMARKS); + (entries, capped) } #[cfg(test)] @@ -205,7 +217,8 @@ mod tests { body(1, 730.0), body(1, 716.0), ]; - let found = inferred(lines); + let (found, capped) = inferred(lines); + assert!(!capped); assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]); assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line"); } @@ -215,21 +228,70 @@ mod tests { let mut right = body(0, 760.0); (right.left, right.right) = (420.0, 560.0); let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)]; - assert_eq!(titles(&inferred(lines)), [(1, "Two column heading", 0)]); + assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]); } #[test] fn captions_and_numbers_are_not_headings() { let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)]; - assert!(inferred(lines).is_empty()); + assert!(inferred(lines).0.is_empty()); assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); } + #[test] + fn captions_match_in_any_case() { + let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading"); + assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3")); + } + + #[test] + fn more_headings_than_the_cap_are_reported() { + // Each heading on a page of its own, with a line of body text under it. + let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::>(); + let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS)); + assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false)); + let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1)); + assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported"); + } + + /// A page past the page decode allowance (two compressed streams of spaces, each just over + /// half of it) can't be read: it doesn't count as read, and the suggestion says headings + /// may be missing. + #[test] + fn a_page_whose_text_cant_be_read_is_not_counted() { + let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]); + let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(), + stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"), + stream("/Filter /FlateDecode", &packed), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), + ]; + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + let s = suggest(&Document::open(std::sync::Arc::new(bytes)).unwrap()); + assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); + } + #[test] fn the_tree_nests_by_level_and_caps_the_depth() { let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")]; - let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1 }; + let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false }; let tree = s.tree(); assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::>(), ["A", "B"]); assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::>(), ["A.1", "A.2"]); diff --git a/crates/engine/src/text_style_bookmarks.rs b/crates/engine/src/text_style_bookmarks.rs index 329b578420..22a9c1fb5c 100644 --- a/crates/engine/src/text_style_bookmarks.rs +++ b/crates/engine/src/text_style_bookmarks.rs @@ -109,12 +109,20 @@ fn without_subset_tag(name: &str) -> &str { /// The text lines of `doc`'s first [`MAX_PAGES`] pages, each page's in reading order. Text that /// is only whitespace, or whose size can't be read, is left out. pub(crate) fn lines(doc: &Document) -> Vec { + read_lines(doc).0 +} + +/// [`lines`], and how many pages' text was read: a page whose text can't be read (its content +/// past the page's decode allowance, say) is skipped and not counted. +pub(crate) fn read_lines(doc: &Document) -> (Vec, usize) { let pages = pdfcraft_organize::page_count(doc).unwrap_or(0).min(MAX_PAGES); let rotations = pdfcraft_organize::page_rotations(doc).unwrap_or_default(); let mut out = Vec::new(); + let mut read = 0usize; for page in 0..pages { let rotation = rotations.get(page).copied().unwrap_or(0); let Ok(found) = pdfcraft_edit::text_lines(doc, page) else { continue }; + read = read.saturating_add(1); let mut on_page: Vec = found .into_iter() .filter_map(|l| { @@ -147,7 +155,7 @@ pub(crate) fn lines(doc: &Document) -> Vec { on_page.sort_by(|a, b| (b.top * 10.0).round().total_cmp(&(a.top * 10.0).round()).then(a.left.total_cmp(&b.left))); out.extend(on_page); } - out + (out, read) } /// The styles `doc`'s text is set in, the largest size first (then the most used): headings diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 83a5d62102..58277abb15 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -3442,7 +3442,7 @@ milestone = "M4" status = "partial" commands = [] tools = ["bookmark_suggest"] -evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] +evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) are left out. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" [[feature]] From d3c615dd9b124e440eafb770757c131ad4cba63f Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 19:43:07 -0500 Subject: [PATCH 17/29] fix(bookmarks): report tagged headings cut by a limit; renest through children bookmark_suggest's structure path always said truncated: false, though pdfcraft_a11y::headings stops silently at 10000 headings, at a tree nested past 256 levels and after a million visits. headings_with_truncation returns the same list and whether one of those limits stopped the walk where a heading could have been; headings keeps its signature and output. The heading cap is now checked when a heading is met, so exactly 10000 headings is not reported as cut. The tool description told callers to edit levels; a suggested bookmark has no level and bookmark_import refuses one. It now says to move bookmarks into or out of children. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/headings.rs | 23 ++++++-- crates/a11y/src/lib.rs | 2 +- crates/a11y/src/tests.rs | 37 +++++++++++++ crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/suggest_outline.rs | 23 ++++++++ crates/engine/src/edit/run.rs | 2 +- crates/engine/src/suggest_outline.rs | 52 +++++++++++++++---- 7 files changed, 123 insertions(+), 18 deletions(-) diff --git a/crates/a11y/src/headings.rs b/crates/a11y/src/headings.rs index a9de970b65..5f31523bc8 100644 --- a/crates/a11y/src/headings.rs +++ b/crates/a11y/src/headings.rs @@ -10,7 +10,8 @@ use pdfcraft_model::Page; use crate::alt::{page_content, standard, tree_root}; -const MAX_HEADINGS: usize = 10_000; +/// The most headings [`headings`] returns. +pub const MAX_HEADINGS: usize = 10_000; const MAX_VISITS: usize = 1_000_000; const MAX_DEPTH: usize = 256; /// Characters kept of a heading's title. @@ -40,6 +41,8 @@ struct Walker<'a> { /// What is left of [`MAX_TITLE_SOURCE_BYTES`]. title_left: usize, out: Vec, + /// A limit stopped the walk where a heading could have been. + cut: bool, } /// Bytes of `/ActualText`, `/Alt` and `/T` strings the headings of one document decode in all. @@ -49,7 +52,13 @@ const MAX_TITLE_SOURCE_BYTES: usize = 32 << 20; /// The headings, in document order. Headings without text or a page are left out. pub fn headings(doc: &Document) -> Vec { - let Some(root) = tree_root(doc) else { return Vec::new() }; + headings_with_truncation(doc).0 +} + +/// [`headings`], and whether headings may be missing from it: there were more than +/// [`MAX_HEADINGS`], or the structure tree nests or branches past the walk's limits. +pub fn headings_with_truncation(doc: &Document) -> (Vec, bool) { + let Some(root) = tree_root(doc) else { return (Vec::new(), false) }; let pages = pdfcraft_model::pages(doc); let mut w = Walker { doc, @@ -61,18 +70,19 @@ pub fn headings(doc: &Document) -> Vec { texts: HashMap::new(), title_left: MAX_TITLE_SOURCE_BYTES, out: Vec::new(), + cut: false, }; if let Some(k) = root.get(b"K") { w.walk(k, None, 0, 0); } - w.out + (w.out, w.cut) } impl Walker<'_> { /// Whether `k` may be visited (bounded depth and size, each object once). fn enter(&mut self, k: &Object, depth: usize) -> bool { self.visits += 1; - depth <= MAX_DEPTH && self.visits <= MAX_VISITS && self.out.len() < MAX_HEADINGS && !matches!(k, Object::Ref(r) if !self.seen.insert(*r)) + !self.cut && depth <= MAX_DEPTH && self.visits <= MAX_VISITS && !matches!(k, Object::Ref(r) if !self.seen.insert(*r)) } fn element_of(&self, k: &Object) -> Option<(Option, Dict)> { @@ -86,6 +96,7 @@ impl Walker<'_> { fn walk(&mut self, k: &Object, pg: Option, sections: u8, depth: usize) { if !self.enter(k, depth) { + self.cut |= depth > MAX_DEPTH || self.visits > MAX_VISITS; return; } if let Object::Array(a) = k { @@ -101,6 +112,10 @@ impl Walker<'_> { _ => None, }; if let Some(level) = level { + if self.out.len() >= MAX_HEADINGS { + self.cut = true; + return; + } self.heading(obj, &d, pg, level, depth); return; } diff --git a/crates/a11y/src/lib.rs b/crates/a11y/src/lib.rs index 09d96bd345..ab6a1fe3c0 100644 --- a/crates/a11y/src/lib.rs +++ b/crates/a11y/src/lib.rs @@ -44,7 +44,7 @@ pub use alt::{AltError, ArtifactError, Figure, figures, mark_decorative, mark_ta pub use autotag::{AutoTagError, AutoTagResult, autotag_text}; pub use autotag_fields::tag_form_fields; pub use heading_levels::{TextBlock, heading_levels}; -pub use headings::{Heading, headings}; +pub use headings::{Heading, MAX_HEADINGS, headings, headings_with_truncation}; pub use layout_table::{LayoutTableError, layout_table_to_blocks}; pub use report::{REPORT_WORDS, report_html}; pub use tags::{TagContentItem, TagError, TagInfo, TagPlacement, TagProperty, move_tag, set_tag_property, tag_content, tags}; diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index 4a981aaf5b..65ec1db9fc 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -1684,6 +1684,43 @@ fn headings_naming_one_large_string_stop_decoding_it_at_the_allowance() { assert!(!found.is_empty() && found.len() < count, "{}", found.len()); } +/// A tree of `count` H1 elements, each with its text and page. +fn many_headings(count: usize) -> Vec { + let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 7)).collect(); + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R >>".to_string(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(), + stream("BT ET"), + "<< /Type /StructTreeRoot /K 6 0 R >>".to_string(), + format!("<< /S /Document /P 5 0 R /K [{kids}] >>"), + ]; + objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText (Head) >>".to_string())); + objects +} + +#[test] +fn headings_past_the_cap_are_reported() { + let (at_cap, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS), "")); + assert_eq!((at_cap.len(), cut), (MAX_HEADINGS, false)); + let (over, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS + 1), "")); + assert_eq!((over.len(), cut), (MAX_HEADINGS, true), "a heading past the cap was dropped unreported"); +} + +#[test] +fn a_heading_nested_past_the_depth_limit_is_reported() { + let mut objs = headings_doc(); + let (found, cut) = headings_with_truncation(&pdf(&objs, "")); + assert!(!found.is_empty() && !cut); + // Element 17 opens a chain of 300 sections, each holding the next, around one H1. + let first = objs.len() + 1; + objs[9] = format!("<< /S /Document /K [12 0 R {first} 0 R] >>"); + objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i))); + objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into()); + let (found, cut) = headings_with_truncation(&pdf(&objs, "")); + assert!(found.iter().all(|h| h.title != "Deep") && cut, "a heading too deep to reach was dropped unreported"); +} + #[test] fn an_untagged_document_has_no_headings() { let mut objs = headings_doc(); diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index ac9e4091ce..c061c7f766 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -490,7 +490,7 @@ pub fn tools() -> Vec { t( "bookmark_suggest", "Suggest bookmarks", - "Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion; pages_read counts the pages whose text was read. truncated is true when headings may be missing: the document has more pages, a page's text could not be read, or there were more than 10000 headings (the first 10000 are given). Changes nothing: bookmarks is in bookmark_export's form, so edit titles, levels or remove entries, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.", + "Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion; pages_read counts the pages whose text was read. truncated is true when headings may be missing: the document has more pages, a page's text could not be read, there were more than 10000 headings (the first 10000 are given), or the structure tree nests or branches too far to read whole. Changes nothing: bookmarks is in bookmark_export's form, so edit titles, remove entries or move them into or out of a bookmark's children to change the nesting, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.", ) .ro() .with(schema(json!({ "doc": doc() }), &["doc"])), diff --git a/crates/automation/tests/it/suggest_outline.rs b/crates/automation/tests/it/suggest_outline.rs index 24efb56a9a..41b1dbe257 100644 --- a/crates/automation/tests/it/suggest_outline.rs +++ b/crates/automation/tests/it/suggest_outline.rs @@ -132,3 +132,26 @@ fn text_in_one_style_gets_no_suggestion_and_a_note() { assert_eq!((s["source"].as_str(), s["headings"].as_u64(), &s["bookmarks"]), (Some("layout"), Some(0), &json!([]))); assert!(s["note"].as_str().is_some_and(|n| n.contains("bookmark_from_text_styles")), "{s}"); } + +/// A suggested bookmark has no level to edit: bookmark_import refuses one, and the nesting changes +/// by moving a bookmark into or out of another's children, as the tool description says. +#[test] +fn a_suggestion_is_renested_through_children_not_levels() { + let dir = tmp("renest"); + std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap(); + let mut bookmarks = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }))["bookmarks"].clone(); + let mut leveled = bookmarks.clone(); + leveled[0]["level"] = json!(2); + let refused = a.call("bookmark_import", &json!({ "doc": doc, "bookmarks": leveled, "replace": true })); + assert!(refused.is_err_and(|e| e.to_string().contains("unknown key")), "a level was taken"); + let child = bookmarks[0]["children"].as_array_mut().unwrap().remove(0); + bookmarks.as_array_mut().unwrap().push(child); + ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": bookmarks, "replace": true })); + let back = ok(&mut a, "bookmark_export", json!({ "doc": doc })); + let top: Vec = outline(&back["bookmarks"]).into_iter().map(|(t, _, _)| t).collect(); + assert_eq!(top, ["Getting started with the toolkit", "Reference", "Installing"]); + let tool = pdfcraft_automation::tools().into_iter().find(|t| t.name == "bookmark_suggest").unwrap(); + assert!(tool.description.contains("children") && !tool.description.contains("levels or"), "{}", tool.description); +} diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index aa12ca4ea8..498c85ed95 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -609,7 +609,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E pdfcraft_organize::import_outline(doc, parent, *index, bookmarks, *replace)?; } Edit::BookmarksFromStructure => { - pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &crate::suggest_outline::structure_entries(doc))?; + pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &crate::suggest_outline::structure_entries(doc).0)?; } Edit::BookmarksFromTextStyles { levels } => { if levels.is_empty() { diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index 5765615417..ea7924a959 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -40,7 +40,9 @@ pub struct OutlineSuggestion { /// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) /// for a suggestion from layout, fewer when a page's text can't be read. pub pages_read: usize, - /// Headings were left out: pages weren't read, or layout found more than [`MAX_BOOKMARKS`]. + /// Headings may have been left out: pages weren't read, layout found more than + /// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of + /// [`pdfcraft_a11y::headings_with_truncation`]. pub truncated: bool, } @@ -75,12 +77,13 @@ fn node(e: &OutlineEntry) -> OutlineNode { OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() } } -/// The tagged headings as outline entries, each linked to its element (`/SE`). -pub(crate) fn structure_entries(doc: &Document) -> Vec { - pdfcraft_a11y::headings(doc) - .into_iter() - .map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }) - .collect() +/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether +/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]). +pub(crate) fn structure_entries(doc: &Document) -> (Vec, bool) { + let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc); + let entries = + found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect(); + (entries, cut) } /// The outline suggested for `doc`: its tagged headings, or else headings inferred from the @@ -88,9 +91,9 @@ pub(crate) fn structure_entries(doc: &Document) -> Vec { /// finds a heading. pub fn suggest(doc: &Document) -> OutlineSuggestion { let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); - let tagged = structure_entries(doc); + let (tagged, cut) = structure_entries(doc); if !tagged.is_empty() { - return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: false }; + return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut }; } let (lines, pages_read) = read_lines(doc); let (entries, capped) = inferred(lines); @@ -271,6 +274,12 @@ mod tests { stream("/Filter /FlateDecode", &packed), b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), ]; + let s = suggest(&doc_of(&objs)); + assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); + } + + /// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog. + fn doc_of(objs: &[Vec]) -> Document { let mut bytes = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); for (i, o) in objs.iter().enumerate() { @@ -283,8 +292,29 @@ mod tests { bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); } bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); - let s = suggest(&Document::open(std::sync::Arc::new(bytes)).unwrap()); - assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); + Document::open(std::sync::Arc::new(bytes)).unwrap() + } + + /// More tagged headings than the structure reader returns: the suggestion says some are missing. + #[test] + fn tagged_headings_past_the_cap_are_reported() { + let tagged = |count: usize| { + let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect(); + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + format!("<< /S /Document /K [{kids}] >>").into_bytes(), + ]; + objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec())); + suggest(&doc_of(&objs)) + }; + let cap = pdfcraft_a11y::MAX_HEADINGS; + let at_cap = tagged(cap); + assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false)); + let over = tagged(cap + 1); + assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported"); } #[test] From d148ea61f74d031c7073b8260a8e89528aa25c4c Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 20:24:13 -0500 Subject: [PATCH 18/29] Bound running text by each string's whole run The extent of a text object now covers each shown string from its origin to where it advances (widths, Tc, Tw, Tz, TJ) and from its baseline to one font size above, in any orientation of Tm and cm, so text turned to run out of a band no longer counts as lying inside it. An object with a glyph whose width the font does not declare, text with no font, or a non-finite corner has no extent and is never running text. Metrics::width_declared tells /Widths, /W, explicit /DW and a named standard-14 face from /MissingWidth, the implied DW and guessed faces. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag_roles.rs | 229 ++++++++++++++++++++--------- crates/a11y/src/autotag_running.rs | 1 + crates/a11y/src/tests.rs | 21 +++ crates/fonts/src/pdf.rs | 25 +++- crates/fonts/src/pdf/tests.rs | 39 +++++ parity/acrobat-features.toml | 4 +- 6 files changed, 246 insertions(+), 73 deletions(-) diff --git a/crates/a11y/src/autotag_roles.rs b/crates/a11y/src/autotag_roles.rs index 43a0c6929f..22bb379ecb 100644 --- a/crates/a11y/src/autotag_roles.rs +++ b/crates/a11y/src/autotag_roles.rs @@ -42,8 +42,9 @@ pub(crate) struct Evidence { pub letters: bool, /// The text shown, at most [`MAX_KEPT_CHARS`] characters, with a space at each line move. pub text: String, - /// `[x0, y0, x1, y1]` in user space around each shown string's origin and the point one font - /// size above it. + /// `[x0, y0, x1, y1]` in user space around each shown string's run from its origin to where + /// it advances to, and from its baseline to one font size above. `None` when any of it is in + /// glyphs whose widths the font does not declare ([`Metrics::width_declared`]). pub extent: Option<[f64; 4]>, } @@ -109,6 +110,8 @@ struct State { leading: f64, /// `Ts`, in unscaled text space units. rise: f64, + /// `Tc`, `Tw` and `Tz` / 100. + spacing: [f64; 3], /// Text render mode 3 or 7: shown text that paints nothing, such as an OCR layer or a /// clip-only object. invisible: bool, @@ -154,11 +157,16 @@ struct Shown { text: String, kept: usize, extent: Option<[f64; 4]>, + /// Text shown whose run is not known: in glyphs without a declared width, or out of range. + unbounded: bool, } impl Shown { fn show(&mut self, state: &State, bytes: &[u8]) { - let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else { return }; + let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else { + self.unbounded |= state.metrics.is_none(); + return; + }; let text = metrics.decode(bytes); let chars = text.chars().filter(|c| !c.is_whitespace()).count(); if chars == 0 { @@ -172,15 +180,20 @@ impl Shown { self.keep(" "); } self.moved = false; - let [_, _, c, d, e, f] = state.tm.then(&state.ctm).0; + let [a, b, c, d, e, f] = state.tm.then(&state.ctm).0; let size = (state.size * c.hypot(d)).abs(); if !size.is_finite() || size <= 0.0 || size > 1e6 { return; } self.keep(&text); + let (run, declared) = advance(state, metrics, bytes); + self.unbounded |= !declared; let (low, high) = (state.rise, state.rise + state.size); - self.reach(e + low * c, f + low * d); - self.reach(e + high * c, f + high * d); + for along in [0.0, run] { + let (x, y) = (e + along * a, f + along * b); + self.reach(x + low * c, y + low * d); + self.reach(x + high * c, y + high * d); + } let entry = self.by_size.entry(half_points(size)).or_default(); entry.0 = entry.0.saturating_add(chars); if metrics.bold { @@ -197,6 +210,7 @@ impl Shown { fn reach(&mut self, x: f64, y: f64) { if !x.is_finite() || !y.is_finite() { + self.unbounded = true; return; } let [x0, y0, x1, y1] = self.extent.unwrap_or([x, y, x, y]); @@ -220,11 +234,105 @@ impl Shown { chars, letters: self.letters, text: self.text, - extent: self.extent, + extent: self.extent.filter(|_| !self.unbounded), } } } +/// The text width `bytes` advances by, in unscaled text space (§9.4.4), and whether the font +/// declares every glyph's width. +fn advance(state: &State, metrics: &Metrics, bytes: &[u8]) -> (f64, bool) { + let [char_spacing, word_spacing, scale] = state.spacing; + let (width, declared) = metrics.codes(bytes).into_iter().fold((0.0, true), |(sum, declared), (code, len)| { + let word = if metrics.is_space(code, len) { word_spacing } else { 0.0 }; + (sum + metrics.width(code) * state.size + char_spacing + word, declared && metrics.width_declared(code)) + }); + (width * scale, declared) +} + +/// Shows `bytes` in `object`, if any, then moves the text matrix past them. +fn show(state: &mut State, object: Option<&mut Shown>, bytes: &[u8]) { + if let Some(o) = object { + o.show(state, bytes); + } + let moved = state.metrics.as_ref().map_or(0.0, |m| advance(state, m, bytes).0); + state.tm = Matrix::translate(moved, 0.0).then(&state.tm); +} + +/// The text state and text-showing operators other than `Tf`. +fn text_op(state: &mut State, object: Option<&mut Shown>, op: &Op) { + match op.op.as_slice() { + b"TL" => state.leading = op.num(0).unwrap_or(state.leading), + b"Ts" => state.rise = op.num(0).unwrap_or(state.rise), + b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0), + b"Tc" => state.spacing[0] = op.num(0).unwrap_or(state.spacing[0]), + b"Tw" => state.spacing[1] = op.num(0).unwrap_or(state.spacing[1]), + b"Tz" => state.spacing[2] = op.num(0).map_or(state.spacing[2], |z| z / 100.0), + b"Td" | b"TD" => { + if let Some([x, y]) = op.nums::<2>() { + if op.op == b"TD" { + state.leading = -y; + } + state.tlm = Matrix::translate(x, y).then(&state.tlm); + state.tm = state.tlm; + if y != 0.0 + && let Some(o) = object + { + o.new_line(); + } + } + } + b"Tm" => { + if let Some(m) = op.nums::<6>() { + let moved = m[5] != state.tlm.0[5]; + (state.tm, state.tlm) = (Matrix(m), Matrix(m)); + if moved && let Some(o) = object { + o.new_line(); + } + } + } + b"T*" | b"'" | b"\"" => { + if op.op == b"\"" + && let (Some(word), Some(char)) = (op.num(0), op.num(1)) + { + state.spacing = [char, word, state.spacing[2]]; + } + state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm); + state.tm = state.tlm; + let mut object = object; + if let Some(o) = object.as_deref_mut() { + o.new_line(); + } + if op.op != b"T*" + && let Some(Object::String(s)) = op.operands.last() + { + show(state, object, &s.bytes); + } + } + b"Tj" => { + if let Some(Object::String(s)) = op.operands.first() { + show(state, object, &s.bytes); + } + } + b"TJ" => { + if let Some(Object::Array(items)) = op.operands.first() { + let mut object = object; + for item in items { + match item { + Object::String(s) => show(state, object.as_deref_mut(), &s.bytes), + other => { + let n = other.as_f64().unwrap_or(0.0); + let moved = -n / 1000.0 * state.size * state.spacing[2]; + state.tm = Matrix::translate(moved, 0.0).then(&state.tm); + } + } + } + } + } + _ => {} + } +} + /// The evidence for each `(BT, ET)` operator span of a page, in order. `resources` is the page's /// `/Font` resource dictionary; `fonts` is shared by the document's pages. pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: &[Op], spans: &[(usize, usize)]) -> Vec { @@ -236,6 +344,7 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: size: 0.0, leading: 0.0, rise: 0.0, + spacing: [0.0, 0.0, 1.0], invisible: false, metrics: None, }; @@ -269,59 +378,7 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: .name(0) .and_then(|name| by_name.entry(name.to_vec()).or_insert_with(|| resources.get(name).and_then(|f| fonts.get(doc, f))).clone()); } - b"TL" => state.leading = op.num(0).unwrap_or(state.leading), - b"Ts" => state.rise = op.num(0).unwrap_or(state.rise), - b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0), - b"Td" | b"TD" => { - if let Some([x, y]) = op.nums::<2>() { - if op.op == b"TD" { - state.leading = -y; - } - state.tlm = Matrix::translate(x, y).then(&state.tlm); - state.tm = state.tlm; - if y != 0.0 - && let Some(o) = object - { - o.new_line(); - } - } - } - b"Tm" => { - if let Some(m) = op.nums::<6>() { - let moved = m[5] != state.tlm.0[5]; - (state.tm, state.tlm) = (Matrix(m), Matrix(m)); - if moved && let Some(o) = object { - o.new_line(); - } - } - } - b"T*" | b"'" | b"\"" => { - state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm); - state.tm = state.tlm; - if let Some(o) = object { - o.new_line(); - if op.op != b"T*" - && let Some(Object::String(s)) = op.operands.last() - { - o.show(&state, &s.bytes); - } - } - } - b"Tj" => { - if let (Some(o), Some(Object::String(s))) = (object, op.operands.first()) { - o.show(&state, &s.bytes); - } - } - b"TJ" => { - if let (Some(o), Some(Object::Array(items))) = (object, op.operands.first()) { - for item in items { - if let Object::String(s) = item { - o.show(&state, &s.bytes); - } - } - } - } - _ => {} + _ => text_op(&mut state, object, op), } if current.as_ref().is_some_and(|c| c.0 == at) && let Some((_, o)) = current.take() @@ -398,15 +455,23 @@ mod tests { assert!(roles(&[]).is_empty()); } - /// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`. + /// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`, a font + /// with no widths whose name is no standard face as `/F2`, and one whose `/Widths` covers + /// only `a` as `/F3`. fn walk(content: &[u8]) -> Vec { let doc = Document::new_empty(); - let mut font = Dict::new(); - font.set(b"Type".to_vec(), Object::name("Font")); - font.set(b"Subtype".to_vec(), Object::name("Type1")); - font.set(b"BaseFont".to_vec(), Object::name("Helvetica-Bold")); let mut resources = Dict::new(); - resources.set(b"F1".to_vec(), Object::Dict(font)); + for (name, base, widths) in [("F1", "Helvetica-Bold", None), ("F2", "HouseFont", None), ("F3", "HouseFont", Some(500))] { + let mut font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type1")); + font.set(b"BaseFont".to_vec(), Object::name(base)); + if let Some(w) = widths { + font.set(b"FirstChar".to_vec(), Object::Int(97)); + font.set(b"Widths".to_vec(), Object::Array(vec![Object::Int(w)])); + } + resources.set(name.as_bytes().to_vec(), Object::Dict(font)); + } let ops = pdfcraft_content::parse(content).ops; let at = |name: &[u8]| -> Vec { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() }; let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect(); @@ -421,7 +486,8 @@ mod tests { assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true, ..found[0].clone() }); assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true, ..found[1].clone() }); assert_eq!(found[0].text, "Title"); - assert_eq!(found[0].extent, Some([20.0, 20.0, 20.0, 38.0]), "origin and one font size above it, through Tm and cm"); + // "Title" is 2.056 em wide in Helvetica-Bold, at 18 units from x 20. + assert_eq!(rounded(found[0].extent), Some([20.0, 20.0, 57.008, 38.0]), "the run and one font size above it, through Tm and cm"); assert_eq!(found[1].text, "one two three"); assert_eq!(found[2], Evidence::default()); assert_eq!(found.len(), 3); @@ -431,9 +497,32 @@ mod tests { fn text_rise_moves_the_extent() { // Ts is text space, so a 2x Tm doubles it; it outlives BT and is undone by Q. let found = walk(b"q BT /F1 10 Tf 2 0 0 2 72 760 Tm -180 Ts (Body) Tj ET BT /F1 10 Tf 1 0 0 1 72 760 Tm (Still) Tj ET Q BT /F1 10 Tf 1 0 0 1 72 760 Tm (Back) Tj ET"); - assert_eq!(found[0].extent, Some([72.0, 400.0, 72.0, 420.0])); - assert_eq!(found[1].extent, Some([72.0, 580.0, 72.0, 590.0])); - assert_eq!(found[2].extent, Some([72.0, 760.0, 72.0, 770.0])); + // Body, Still and Back are 2.5, 1.834 and 2.39 em wide in Helvetica-Bold. + assert_eq!(rounded(found[0].extent), Some([72.0, 400.0, 122.0, 420.0])); + assert_eq!(rounded(found[1].extent), Some([72.0, 580.0, 90.34, 590.0])); + assert_eq!(rounded(found[2].extent), Some([72.0, 760.0, 95.9, 770.0])); + } + + fn rounded(extent: Option<[f64; 4]>) -> Option<[f64; 4]> { + extent.map(|p| p.map(|v| (v * 1000.0).round() / 1000.0)) + } + + #[test] + fn the_extent_follows_the_run_in_any_direction_with_spacing() { + // Turned to run down the page, "Body" reaches 30 units below its origin; one font size + // up is to the right. Tc 1 adds 4, TJ -500 adds 6, and Tz 50 halves the whole run. + let found = walk(b"q BT /F1 12 Tf 0 -1 1 0 72 760 Tm (Body) Tj ET BT /F1 12 Tf 1 Tc 50 Tz 1 0 0 1 72 700 Tm [(Bo) -500 (dy)] TJ ET Q"); + assert_eq!(rounded(found[0].extent), Some([72.0, 730.0, 84.0, 760.0])); + assert_eq!(rounded(found[1].extent), Some([72.0, 700.0, 92.0, 712.0])); + } + + #[test] + fn text_in_widths_the_font_does_not_declare_has_no_extent() { + let found = walk(b"BT /F2 10 Tf (a) Tj ET BT /F3 10 Tf (ab) Tj ET BT /F3 10 Tf (a) Tj ET BT /F1 10 Tf (a) Tj /F9 10 Tf (b) Tj ET"); + assert_eq!(found[0].extent, None, "no /Widths, and Helvetica only a guess"); + assert_eq!(found[1].extent, None, "b is past /Widths"); + assert_eq!(rounded(found[2].extent), Some([0.0, 0.0, 5.0, 10.0]), "a is in /Widths"); + assert_eq!(found[3].extent, None, "part of it has no font"); } #[test] diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs index f696e4addd..b2bc34cd6d 100644 --- a/crates/a11y/src/autotag_running.rs +++ b/crates/a11y/src/autotag_running.rs @@ -8,6 +8,7 @@ //! text changes from page to page and is all heading-sized (`Chapter 1`, `Chapter 2`) is a //! sequence of headings, not running text, unless it reads as a page number (`Page 3`, `3 of 9`). //! Each separate cluster of heights that qualifies counts. Position alone never makes running text. +//! A text object whose extent is not known (see [`Evidence::extent`]) is never running text. use std::collections::HashMap; diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index f2ea34210e..842157a12a 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -205,6 +205,27 @@ fn autotag_text_gives_a_page_of_running_text_alone_no_struct_parents() { assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed); } +/// A body line turned to run down from the top of each page starts in the header band but does +/// not lie inside it: it is not running text. +#[test] +fn autotag_text_leaves_turned_text_that_runs_out_of_the_band_tagged() { + let body = "BT /F1 12 Tf 0 -1 1 0 72 760 Tm (A body line set turned so that it runs down the page) Tj ET"; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + stream(body), + stream(body), + FONT.into(), + ], + "", + ); + assert_eq!(running_text(&doc).unwrap(), []); +} + #[test] fn autotag_text_leaves_a_single_page_header_tagged() { let mut doc = pdf( diff --git a/crates/fonts/src/pdf.rs b/crates/fonts/src/pdf.rs index 4ff8feb722..a75b1ab0b6 100644 --- a/crates/fonts/src/pdf.rs +++ b/crates/fonts/src/pdf.rs @@ -42,6 +42,8 @@ pub struct Metrics { explicit_default: bool, /// The standard-14 face to measure with when the dictionary carries no `/Widths`. std14: Option, + /// [`Metrics::std14`] is the face `/BaseFont` names (or a common alias of it), not a guess. + std14_named: bool, /// Glyph units → text space (0.001, or `/FontMatrix[0]` for Type 3). pub scale: f64, /// Glyph box in text space per unit of font size. @@ -899,6 +901,7 @@ impl Metrics { default: 500.0, explicit_default: false, std14: Some(crate::Std14::Helvetica), + std14_named: false, scale: 0.001, ascent: 0.9, descent: -0.25, @@ -1067,7 +1070,9 @@ impl Metrics { let base = String::from_utf8_lossy(font.name(b"BaseFont").unwrap_or(b"")).into_owned(); // The real face, bold and italic included: the published metrics differ by style, // so Times-Bold is not Times-Roman and neither is Helvetica scaled. - m.std14 = crate::Std14::from_base_font(&base).or(Some(crate::Std14::Helvetica)); + let recognised = crate::Std14::recognise(&base); + m.std14_named = matches!(recognised, Some((_, crate::Std14Match::Alias))); + m.std14 = recognised.map(|(face, _)| face).or(Some(crate::Std14::Helvetica)); } } if let Some(d) = descriptor { @@ -1144,6 +1149,24 @@ impl Metrics { } } + /// Whether [`Metrics::width`] of `code` is a width the font declares: a `/Widths` entry (or + /// the embedded program's advance where `/Widths` is absent), a `/W` entry or an explicit + /// `/DW`, or the published metrics of the standard-14 face `/BaseFont` names. It is not for a + /// `/MissingWidth`, the implied `/DW` of 1000, or a standard-14 face guessed from the name. + pub fn width_declared(&self, code: u32) -> bool { + if self.composite { + let cid = self.cid(code); + return self.explicit_default || self.cid_widths.contains_key(&cid) || self.cid_ranges.find(cid).is_some(); + } + if code.checked_sub(self.first).and_then(|i| self.widths.get(i as usize)).is_some() { + return true; + } + match self.std14.filter(|_| self.std14_named) { + Some(f) => u8::try_from(self.std14_code(f, code)).is_ok_and(|c| f.width(c) != 0.0), + None => false, + } + } + /// Where the standard-14 table, indexed by WinAnsi, holds the glyph `code` draws in this font: /// its encoding (base and `/Differences`) names the glyph, so a remapped code is measured as /// the glyph it now shows (#2894). Symbol and ZapfDingbats are indexed by their own encodings, diff --git a/crates/fonts/src/pdf/tests.rs b/crates/fonts/src/pdf/tests.rs index e85870d4a7..a93718048b 100644 --- a/crates/fonts/src/pdf/tests.rs +++ b/crates/fonts/src/pdf/tests.rs @@ -2165,3 +2165,42 @@ fn a_dropped_codespace_range_is_reported() { assert!(parse_cmap(b"1 begincodespacerange <00> endcodespacerange").2); assert!(!parse_cmap(b"2 begincodespacerange <0000> <0000> endcodespacerange").2); } + +#[test] +fn widths_the_font_declares_are_told_from_fallbacks() { + let mut doc = Document::new_empty(); + let simple = |doc: &mut Document, base: &str, widths: Option>| { + let mut entries = vec![("Subtype", Object::name("Type1")), ("BaseFont", Object::name(base))]; + if let Some(w) = widths { + entries.extend([("FirstChar", Object::Int(65)), ("Widths", Object::Array(w))]); + } + let dict = font(doc, entries); + Metrics::from_dict(doc, &dict) + }; + let listed = simple(&mut doc, "HouseFont", Some(vec![Object::Int(500)])); + assert!(listed.width_declared(65)); + assert!(!listed.width_declared(66), "a code past /Widths takes /MissingWidth"); + assert!(simple(&mut doc, "Helvetica", None).width_declared(65)); + assert!(simple(&mut doc, "Arial", None).width_declared(65), "a common alias names the face"); + assert!(!simple(&mut doc, "HouseSerif", None).width_declared(65), "Times is a guess from the name"); + assert!(!simple(&mut doc, "HouseFont", None).width_declared(65), "Helvetica is a guess"); + let cid = |doc: &mut Document, dw: Option| { + let mut desc = Dict::new(); + desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2")); + desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600)])])); + if let Some(dw) = dw { + desc.set(b"DW".to_vec(), Object::Int(dw)); + } + let entries = vec![ + ("Subtype", Object::name("Type0")), + ("Encoding", Object::name("Identity-H")), + ("DescendantFonts", Object::Array(vec![Object::Dict(desc)])), + ]; + let dict = font(doc, entries); + Metrics::from_dict(doc, &dict) + }; + let implied = cid(&mut doc, None); + assert!(implied.width_declared(1)); + assert!(!implied.width_declared(2), "a CID /W leaves out, with no /DW, takes the implied 1000"); + assert!(cid(&mut doc, Some(500)).width_declared(2)); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 6fdfead89c..f4d699999f 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -9158,8 +9158,8 @@ milestone = "M12" status = "partial" commands = ["a11y.autotag"] tools = ["accessibility_autotag_preview", "accessibility_autotag_apply"] -evidence = ["crates/automation/tests/it/automation.rs::autotag_preview_proposes_text_without_changing_the_pdf", "crates/automation/tests/it/automation.rs::autotag_apply_writes_reviewable_tags_and_survives_save_reopen", "crates/automation/tests/it/automation.rs::autotag_apply_tags_headings_by_size_across_pages", "crates/automation/tests/it/automation.rs::autotag_apply_marks_running_headers_and_footers_as_artifacts", "crates/a11y/src/autotag_roles.rs::levels_rank_styles_largest_first_and_never_skip_a_level", "crates/ui-egui/tests/it/accessibility.rs::automatic_text_tagging_opens_reviewable_tags"] -notes = "Auto-tag writes real marked content, a Document structure element, H1-H6 and P tags and a parent tree for text-only PDFs, with undo and Tags-panel review. A text object is a heading when it is short and larger or bolder than the body text; levels rank those styles across the document and never skip a level. It refuses mixed content, forms, annotations and existing tags. The preview still proposes headings by its own single-line rule, so it can differ from Apply. Text repeating near the top or bottom edge of most pages (the same text, digits aside, at about the same height) is marked as a /Pagination /Header or /Footer artifact instead of tagged, and Apply lists it for review; invisible text (render mode 3) is ignored. Images, tables, lists, links and fields are not classified or tagged by Apply." +evidence = ["crates/automation/tests/it/automation.rs::autotag_preview_proposes_text_without_changing_the_pdf", "crates/automation/tests/it/automation.rs::autotag_apply_writes_reviewable_tags_and_survives_save_reopen", "crates/automation/tests/it/automation.rs::autotag_apply_tags_headings_by_size_across_pages", "crates/automation/tests/it/automation.rs::autotag_apply_marks_running_headers_and_footers_as_artifacts", "crates/a11y/src/tests.rs::autotag_text_leaves_turned_text_that_runs_out_of_the_band_tagged", "crates/a11y/src/autotag_roles.rs::levels_rank_styles_largest_first_and_never_skip_a_level", "crates/ui-egui/tests/it/accessibility.rs::automatic_text_tagging_opens_reviewable_tags"] +notes = "Auto-tag writes real marked content, a Document structure element, H1-H6 and P tags and a parent tree for text-only PDFs, with undo and Tags-panel review. A text object is a heading when it is short and larger or bolder than the body text; levels rank those styles across the document and never skip a level. It refuses mixed content, forms, annotations and existing tags. The preview still proposes headings by its own single-line rule, so it can differ from Apply. Text repeating near the top or bottom edge of most pages (the same text, digits aside, at about the same height, its whole run from origin to advance inside the band) is marked as a /Pagination /Header or /Footer artifact instead of tagged, and Apply lists it for review; text in glyphs whose widths the font does not declare (no /Widths entry, not a standard-14 face it names) is never marked; invisible text (render mode 3) is ignored. Images, tables, lists, links and fields are not classified or tagged by Apply." [[feature]] id = "a11y.autotag-fields" From b758feda055c75646e42cd474377fc35ccb11462 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 22:03:05 -0500 Subject: [PATCH 19/29] fix(a11y): a depth limit skips a branch instead of ending the walk A branch past the depth or visit limit set `cut`, which then refused every later node, so a shallow heading after a deep branch was lost. The limits now only skip the node and report it; only the heading cap still ends the walk. Marked content past the limit is reported too. When no tagged heading is found and the suggestion falls back to layout, the structure walk's truncation is kept in `truncated`. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/headings.rs | 14 +++++++++--- crates/a11y/src/tests.rs | 32 ++++++++++++++++++++++++++++ crates/engine/src/suggest_outline.rs | 22 ++++++++++++++++++- 3 files changed, 64 insertions(+), 4 deletions(-) diff --git a/crates/a11y/src/headings.rs b/crates/a11y/src/headings.rs index 5f31523bc8..88932522e3 100644 --- a/crates/a11y/src/headings.rs +++ b/crates/a11y/src/headings.rs @@ -43,6 +43,8 @@ struct Walker<'a> { out: Vec, /// A limit stopped the walk where a heading could have been. cut: bool, + /// [`MAX_HEADINGS`] were found and one more was met: the walk stops. + full: bool, } /// Bytes of `/ActualText`, `/Alt` and `/T` strings the headings of one document decode in all. @@ -71,6 +73,7 @@ pub fn headings_with_truncation(doc: &Document) -> (Vec, bool) { title_left: MAX_TITLE_SOURCE_BYTES, out: Vec::new(), cut: false, + full: false, }; if let Some(k) = root.get(b"K") { w.walk(k, None, 0, 0); @@ -79,10 +82,15 @@ pub fn headings_with_truncation(doc: &Document) -> (Vec, bool) { } impl Walker<'_> { - /// Whether `k` may be visited (bounded depth and size, each object once). + /// Whether `k` may be visited (bounded depth and size, each object once). A depth or size + /// limit only skips `k`, and is reported in `cut`. fn enter(&mut self, k: &Object, depth: usize) -> bool { self.visits += 1; - !self.cut && depth <= MAX_DEPTH && self.visits <= MAX_VISITS && !matches!(k, Object::Ref(r) if !self.seen.insert(*r)) + if depth > MAX_DEPTH || self.visits > MAX_VISITS { + self.cut = true; + return false; + } + !self.full && !matches!(k, Object::Ref(r) if !self.seen.insert(*r)) } fn element_of(&self, k: &Object) -> Option<(Option, Dict)> { @@ -96,7 +104,6 @@ impl Walker<'_> { fn walk(&mut self, k: &Object, pg: Option, sections: u8, depth: usize) { if !self.enter(k, depth) { - self.cut |= depth > MAX_DEPTH || self.visits > MAX_VISITS; return; } if let Object::Array(a) = k { @@ -114,6 +121,7 @@ impl Walker<'_> { if let Some(level) = level { if self.out.len() >= MAX_HEADINGS { self.cut = true; + self.full = true; return; } self.heading(obj, &d, pg, level, depth); diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index 65ec1db9fc..7ae2d2d6ba 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -1721,6 +1721,38 @@ fn a_heading_nested_past_the_depth_limit_is_reported() { assert!(found.iter().all(|h| h.title != "Deep") && cut, "a heading too deep to reach was dropped unreported"); } +/// A branch too deep to walk is skipped, not the end of the walk: a heading after it is found. +#[test] +fn a_heading_after_a_branch_past_the_depth_limit_is_found() { + let mut objs = headings_doc(); + let first = objs.len() + 1; + objs[9] = format!("<< /S /Document /K [{first} 0 R 12 0 R] >>"); + objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i))); + objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into()); + let (found, cut) = headings_with_truncation(&pdf(&objs, "")); + let titles: Vec<&str> = found.iter().map(|h| h.title.as_str()).collect(); + assert_eq!((titles, cut), (vec!["Chapter One"], true), "the deep branch stopped the walk"); +} + +/// An H1 `sects + 1` elements down whose title is only its marked content. +fn heading_under_sections(sects: usize) -> (Vec, bool) { + let mut objs = headings_doc(); + let first = objs.len() + 1; + objs[9] = format!("<< /S /Document /K {first} 0 R >>"); + objs.extend((1..=sects).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i))); + objs.push("<< /S /H1 /Pg 3 0 R /K 0 >>".into()); + headings_with_truncation(&pdf(&objs, "")) +} + +/// Marked content past the depth limit is reported too: the H1 whose title it holds is lost. +#[test] +fn marked_content_past_the_depth_limit_is_reported() { + let (found, cut) = heading_under_sections(254); + assert_eq!((found.iter().map(|h| h.title.as_str()).collect::>(), cut), (vec!["Chapter One"], false)); + let (found, cut) = heading_under_sections(255); + assert!(found.is_empty() && cut, "a heading whose text was too deep was dropped unreported"); +} + #[test] fn an_untagged_document_has_no_headings() { let mut objs = headings_doc(); diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index ea7924a959..12ff79a5bc 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -97,7 +97,7 @@ pub fn suggest(doc: &Document) -> OutlineSuggestion { } let (lines, pages_read) = read_lines(doc); let (entries, capped) = inferred(lines); - OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: capped || pages_read < pages } + OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages } } /// Lines in one style, one after another down a page. @@ -317,6 +317,26 @@ mod tests { assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported"); } + /// A tagged heading too deep for the structure walk, on a page without text: layout finds + /// nothing either, and the suggestion still says a heading may be missing. The same page + /// untagged is not truncated. + #[test] + fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() { + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + ]; + objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes())); + objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec()); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped"); + objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false)); + } + #[test] fn the_tree_nests_by_level_and_caps_the_depth() { let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; From 1cbc487caf9909e358a191c2f562515c4b0d84da Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 22:18:03 -0500 Subject: [PATCH 20/29] fix(a11y): no extent for unmapped or vertical text; fold case in heading check Text shown in codes without a Unicode mapping still paints glyphs, and a vertical font's glyphs advance down the page, so neither gives the object a known extent; both now mark it unbounded instead of being measured short or sideways. Vertical is a Type 0 font whose /Encoding name ends in -V or whose embedded CMap has /WMode 1, as the redaction interpreter reads it. The heading-sequence check compares text lowercased with whitespace collapsed, so a running header set once in capitals is not mistaken for a sequence of headings. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag_roles.rs | 88 ++++++++++++++++++++++++++++-- crates/a11y/src/autotag_running.rs | 15 ++++- crates/a11y/src/tests.rs | 4 +- 3 files changed, 98 insertions(+), 9 deletions(-) diff --git a/crates/a11y/src/autotag_roles.rs b/crates/a11y/src/autotag_roles.rs index 22bb379ecb..cd974c8369 100644 --- a/crates/a11y/src/autotag_roles.rs +++ b/crates/a11y/src/autotag_roles.rs @@ -44,7 +44,8 @@ pub(crate) struct Evidence { pub text: String, /// `[x0, y0, x1, y1]` in user space around each shown string's run from its origin to where /// it advances to, and from its baseline to one font size above. `None` when any of it is in - /// glyphs whose widths the font does not declare ([`Metrics::width_declared`]). + /// glyphs whose widths the font does not declare ([`Metrics::width_declared`]) or that have no + /// Unicode mapping, or in a font that writes vertically. pub extent: Option<[f64; 4]>, } @@ -116,6 +117,8 @@ struct State { /// clip-only object. invisible: bool, metrics: Option>, + /// The font writes vertically, which the extents do not measure. + vertical: bool, } /// Font metrics for a whole document, measured once per font object and capped at @@ -157,7 +160,8 @@ struct Shown { text: String, kept: usize, extent: Option<[f64; 4]>, - /// Text shown whose run is not known: in glyphs without a declared width, or out of range. + /// Text shown whose run is not known: in glyphs without a declared width or a Unicode mapping, + /// in a vertical font, or out of range. unbounded: bool, } @@ -167,6 +171,10 @@ impl Shown { self.unbounded |= state.metrics.is_none(); return; }; + // Codes without a Unicode mapping still paint glyphs, and a vertical font's glyphs + // advance down the page: either way the text's extent is not known. + let unmapped = metrics.codes(bytes).iter().any(|&(code, _)| metrics.text_of(code).is_none()); + self.unbounded |= state.vertical || unmapped; let text = metrics.decode(bytes); let chars = text.chars().filter(|c| !c.is_whitespace()).count(); if chars == 0 { @@ -250,6 +258,21 @@ fn advance(state: &State, metrics: &Metrics, bytes: &[u8]) -> (f64, bool) { (width * scale, declared) } +/// Whether `font` writes vertically: a Type 0 font whose `/Encoding` is a predefined CMap name +/// ending in `-V`, or an embedded CMap whose `/WMode` is 1 (§9.7.5). +fn vertical(doc: &Document, font: &Object) -> bool { + let font = doc.resolve(font); + let Some(font) = font.as_dict() else { return false }; + if font.get(b"Subtype").map(|s| doc.resolve(s)).as_deref().and_then(Object::as_name) != Some(b"Type0".as_slice()) { + return false; + } + match font.get(b"Encoding").map(|e| doc.resolve(e)).as_deref() { + Some(Object::Name(n)) => n.ends_with(b"-V"), + Some(Object::Stream(s)) => s.dict.int(b"WMode") == Some(1), + _ => false, + } +} + /// Shows `bytes` in `object`, if any, then moves the text matrix past them. fn show(state: &mut State, object: Option<&mut Shown>, bytes: &[u8]) { if let Some(o) = object { @@ -336,7 +359,7 @@ fn text_op(state: &mut State, object: Option<&mut Shown>, op: &Op) { /// The evidence for each `(BT, ET)` operator span of a page, in order. `resources` is the page's /// `/Font` resource dictionary; `fonts` is shared by the document's pages. pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: &[Op], spans: &[(usize, usize)]) -> Vec { - let mut by_name: HashMap, Option>> = HashMap::new(); + let mut by_name: HashMap, (Option>, bool)> = HashMap::new(); let mut state = State { ctm: Matrix::IDENTITY, tm: Matrix::IDENTITY, @@ -347,6 +370,7 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: spacing: [0.0, 0.0, 1.0], invisible: false, metrics: None, + vertical: false, }; let (mut saved, mut unsaved) = (Vec::new(), 0usize); let mut out = Vec::with_capacity(spans.len()); @@ -374,9 +398,13 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: b"BT" => (state.tm, state.tlm) = (Matrix::IDENTITY, Matrix::IDENTITY), b"Tf" => { state.size = op.num(1).unwrap_or(state.size); - state.metrics = op - .name(0) - .and_then(|name| by_name.entry(name.to_vec()).or_insert_with(|| resources.get(name).and_then(|f| fonts.get(doc, f))).clone()); + (state.metrics, state.vertical) = op.name(0).map_or((None, false), |name| { + let font = || resources.get(name); + by_name + .entry(name.to_vec()) + .or_insert_with(|| (font().and_then(|f| fonts.get(doc, f)), font().is_some_and(|f| vertical(doc, f)))) + .clone() + }); } _ => text_op(&mut state, object, op), } @@ -543,4 +571,52 @@ mod tests { assert_eq!(found[2].chars, 5, "render mode 3 and 7 text is not counted"); assert_eq!(found[3], Evidence::default(), "a size past 1e6 is dropped"); } + + /// The evidence for each `BT`..`ET` of `content` in two-byte Type 0 fonts declaring every + /// width as 1000: `/H` and `/V` map their codes to Unicode and write horizontally and + /// vertically, and `/U` has no Unicode mapping; with `/F1` as in [`walk`]. + fn walk_type0(content: &[u8]) -> Vec { + let cmap = "begincmap 1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0020> <007E> <0020> endbfrange endcmap"; + let type0 = |encoding: &str, unicode: &str| { + format!("<< /Type /Font /Subtype /Type0 /BaseFont /House /Encoding /{encoding} /DescendantFonts [2 0 R] {unicode} >>") + }; + let doc = crate::tests::pdf( + &[ + "<< /Type /Catalog >>".into(), + "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /House /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /DW 1000 >>".into(), + crate::tests::stream(cmap), + type0("Identity-H", "/ToUnicode 3 0 R"), + type0("Identity-V", "/ToUnicode 3 0 R"), + type0("Identity-H", ""), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>".into(), + ], + "", + ); + let mut resources = Dict::new(); + for (name, n) in [("H", 4), ("V", 5), ("U", 6), ("F1", 7)] { + resources.set(name.as_bytes().to_vec(), Object::Ref(ObjRef::new(n, 0))); + } + let ops = pdfcraft_content::parse(content).ops; + let at = |name: &[u8]| -> Vec { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() }; + let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect(); + evidence(&doc, &mut Fonts::default(), &resources, &ops, &spans) + } + + #[test] + fn text_in_glyphs_without_a_unicode_mapping_has_no_extent() { + // A mapped header and, in the same object, unmapped glyphs further down the page: the + // object reaches the body, though its text is only the header's. + let found = walk_type0(b"BT /F1 12 Tf 72 760 Td (Header) Tj /U 12 Tf 0 -360 Td <00410042> Tj ET BT /H 12 Tf 72 760 Td <00410042> Tj ET"); + assert_eq!((found[0].text.as_str(), found[0].extent), ("Header", None)); + assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 96.0, 772.0]), "mapped Type 0 text keeps its extent"); + } + + #[test] + fn text_in_a_vertical_font_has_no_extent() { + // Thirty glyphs at 12 run 360 units down the page in a vertical font, not along x. + let glyphs = format!("<{}>", "0041".repeat(30)); + let found = walk_type0(format!("BT /V 12 Tf 72 760 Td {glyphs} Tj ET BT /H 12 Tf 72 760 Td {glyphs} Tj ET").as_bytes()); + assert_eq!((found[0].chars, found[0].extent), (30, None)); + assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 432.0, 772.0])); + } } diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs index b2bc34cd6d..67d0d844a3 100644 --- a/crates/a11y/src/autotag_running.rs +++ b/crates/a11y/src/autotag_running.rs @@ -95,12 +95,18 @@ pub(crate) fn find(pages: &[PageText<'_>], body: Option) -> Vec], key: &str, body: Option) -> bool { - let texts_differ = window.windows(2).any(|w| matches!(w, [a, b] if a.evidence.text != b.evidence.text)); + let texts_differ = window.windows(2).any(|w| matches!(w, [a, b] if folded(&a.evidence.text) != folded(&b.evidence.text))); let heading_sized = body.is_some_and(|body| window.iter().all(|m| m.evidence.size >= body * HEADING_SIZE_RATIO)); let worded = window.iter().all(|m| m.evidence.letters) && !is_page_number(key); texts_differ && heading_sized && worded } +/// Lowercase with whitespace collapsed, digits kept: `ANNUAL REPORT` and `Annual report` are the +/// same heading, `Chapter 1` and `Chapter 2` are not. +fn folded(text: &str) -> String { + text.to_lowercase().split_whitespace().collect::>().join(" ") +} + /// A normalised key that is a page number alone or with its label: `#`, `page #`, `p. #`, /// `# of #`, `page # of #`, `#/#`, optionally in dashes or brackets. fn is_page_number(key: &str) -> bool { @@ -369,6 +375,13 @@ mod tests { assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "a labelled page number is too: {found:?}"); } + #[test] + fn a_heading_differing_only_in_case_or_spacing_does_not_change() { + let big = |text: &str| Evidence { size: 18.0, ..line(text, 750.0) }; + let found = run(&[vec![big("ANNUAL REPORT")], vec![big("Annual report")]], Some(12.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]]); + } + #[test] fn the_bands_follow_the_displayed_page() { // Turned 90° clockwise, the displayed top is the user-space left edge (x = 0). diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index 842157a12a..bc91fa8407 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -5,7 +5,7 @@ use pdfcraft_cos::{Document, Object}; use super::*; /// A PDF from object bodies (object n = bodies[n - 1]) and extra trailer entries. -fn pdf(bodies: &[String], trailer: &str) -> Document { +pub(crate) fn pdf(bodies: &[String], trailer: &str) -> Document { let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); for (i, b) in bodies.iter().enumerate() { @@ -21,7 +21,7 @@ fn pdf(bodies: &[String], trailer: &str) -> Document { Document::open(Arc::new(out)).unwrap() } -fn stream(data: &str) -> String { +pub(crate) fn stream(data: &str) -> String { format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()) } From 67f6269142961b7d7222820e03298062aa02b4fd Mon Sep 17 00:00:00 2001 From: KenM76 Date: Sat, 21 Nov 2026 14:08:44 -0500 Subject: [PATCH 21/29] fix(engine): a bold word inside a sentence is not a suggested heading A bold run inside a paragraph is a text line of its own, so the layout fallback saw a short bold block where the body is regular and proposed it as a bookmark. A line now counts as set inside a sentence when prose sits beside it on the same row: boxes sharing at least half the shorter one's height, side by side, at most half an em apart, at the same size, in another style, with a lower-case letter. Such blocks are left out like captions. The lower-case test keeps a bold title after its section number, the half-height overlap keeps a heading over tightly set text, and the half-em gap keeps a heading across a narrow gutter. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/suggest_outline.rs | 106 ++++++++++++++++++++-- crates/engine/src/text_style_bookmarks.rs | 2 +- parity/acrobat-features.toml | 4 +- 3 files changed, 99 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index 12ff79a5bc..133e3b7103 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -5,20 +5,28 @@ //! are one block (a heading that wraps is one bookmark), the body style is the size carrying the //! most characters, a short block larger than the body (or bold where the body is not) is a //! heading, and levels rank the heading styles over the document without skipping a level. -//! Captions (`Figure 3`, `Table 2`) are not headings. Each inferred bookmark goes to the top of -//! its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); tagged ones go to their page. +//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each +//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); +//! tagged ones go to their page. use pdfcraft_a11y::TextBlock; use pdfcraft_cos::Document; use pdfcraft_organize::{OutlineEntry, OutlineNode}; -use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, read_lines}; +use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines}; /// Blocks looked back over for one a line continues: a heading's next line can come after lines /// of other columns on the same row. const LOOKBACK: usize = 8; /// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent. const MAX_DEPTH: usize = 32; +/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is +/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can +/// be under an em, so this stays below it. +const BESIDE_GAP: f64 = 0.5; +/// The most lines looked at on either side of a line for text beside it, which bounds the work on +/// a page with many runs on one row. +const MAX_BESIDE: usize = 64; /// Where the suggested headings come from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -108,16 +116,19 @@ struct Block { lines: usize, chars: usize, letters: bool, + /// Whether any of its lines is set inside a sentence ([`set_inline`]). + inline: bool, } impl Block { - fn new(line: Line) -> Block { - let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false }; + fn new(line: Line, inline: bool) -> Block { + let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline }; b.count(&b.first.text.clone()); b } - fn add(&mut self, line: Line) { + fn add(&mut self, line: Line, inline: bool) { + self.inline |= inline; if self.title.chars().count() < MAX_TITLE_CHARS { self.title.push(' '); } @@ -142,20 +153,57 @@ impl Block { /// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last /// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]). fn blocks(lines: Vec) -> Vec { + let flags = set_inline(&lines); let mut out: Vec = Vec::new(); - for line in lines { + for (line, inline) in lines.into_iter().zip(flags) { let start = out.len().saturating_sub(LOOKBACK); let found = out.get_mut(start..).and_then(|recent| { recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last)) }); match found { - Some(b) => b.add(line), - None => out.push(Block::new(line)), + Some(b) => b.add(line, inline), + None => out.push(Block::new(line, inline)), } } out } +/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another +/// style at the same size sits right beside it on its row. A bold word in a paragraph (a +/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only +/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`) +/// leaves the title a heading. +fn set_inline(lines: &[Line]) -> Vec { + lines + .iter() + .enumerate() + .map(|(i, l)| { + // Lines are sorted down each page, so those on its row are next to it. + let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size; + let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near); + let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near); + before.chain(after).any(|o| beside(l, o)) + }) + .collect() +} + +/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at +/// least half the shorter one's height, since a box runs from the font's ascent to its descent +/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the +/// other, at the same size, in another style, at most [`BESIDE_GAP`] ems apart. +fn beside(l: &Line, o: &Line) -> bool { + let size = l.style.size; + let shared = l.top.min(o.top) - l.bottom.max(o.bottom); + let shorter = (l.top - l.bottom).min(o.top - o.bottom); + let gap = l.left.max(o.left) - l.right.min(o.right); + shared >= shorter * 0.5 + && gap >= -size * 0.25 + && gap <= size * BESIDE_GAP + && (o.style.size - size).abs() <= SIZE_TOLERANCE + && !o.style.matches(&l.style) + && o.text.chars().any(char::is_lowercase) +} + /// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a /// number. fn is_caption(text: &str) -> bool { @@ -169,7 +217,7 @@ fn is_caption(text: &str) -> bool { /// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there /// were more. fn inferred(lines: Vec) -> (Vec, bool) { - let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); + let blocks: Vec = blocks(lines).into_iter().filter(|b| !b.inline && !is_caption(&b.title)).collect(); let evidence: Vec = blocks.iter().map(Block::evidence).collect(); let mut entries: Vec = blocks .iter() @@ -241,6 +289,44 @@ mod tests { assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); } + /// A line of `text` in `style` from `left` to `right` at `top`. + fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line { + Line { left, right, ..line(0, top, 11.0, bold, text) } + } + + #[test] + fn a_bold_word_inside_a_sentence_is_not_a_heading() { + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient", 72.0, 130.0), + run(726.0, true, "MUST", 133.0, 165.0), + run(726.0, false, "ignore the field.", 168.0, 400.0), + body(0, 712.0), + run(690.0, false, "2.3", 72.0, 88.0), + run(690.0, true, "Numbered title", 96.0, 180.0), + body(0, 670.0), + body(0, 656.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]); + } + + #[test] + fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() { + let lines = vec![ + // Its box overlaps the first body line's by 1.5 pt. + run(760.0, true, "Tight heading", 72.0, 180.0), + body(0, 752.7), + body(0, 740.0), + // A gutter of 9 pt, under an em: prose ends the left column on the heading's row. + run(700.0, false, "ends the left column here", 72.0, 291.0), + run(700.0, true, "Right column heading", 300.0, 520.0), + body(0, 686.0), + body(0, 672.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]); + } + #[test] fn captions_match_in_any_case() { let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)]; diff --git a/crates/engine/src/text_style_bookmarks.rs b/crates/engine/src/text_style_bookmarks.rs index 22a9c1fb5c..4ec843aacd 100644 --- a/crates/engine/src/text_style_bookmarks.rs +++ b/crates/engine/src/text_style_bookmarks.rs @@ -30,7 +30,7 @@ impl TextStyle { } /// How far apart two sizes may be and still be one style. -const SIZE_TOLERANCE: f64 = 0.25; +pub(crate) const SIZE_TOLERANCE: f64 = 0.25; /// A style and how much text is set in it. #[derive(Clone, Debug, PartialEq)] diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 85b7322bac..fca6d58164 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -3442,8 +3442,8 @@ milestone = "M4" status = "partial" commands = [] tools = ["bookmark_suggest"] -evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] -notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) are left out. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" +evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] +notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) and bold words inside a sentence (prose in another style at the same size right beside them on the row) are left out, which also leaves out a run-in heading set on the same line as its paragraph, a heading after a label with lower-case letters in another style (Appendix, then A Title in bold), and a wrapped heading any of whose lines has prose beside it. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" [[feature]] id = "organize.bookmarks-import-export" From 7f153466a3024934d5748e3237278a28b7e2827f Mon Sep 17 00:00:00 2001 From: KenM76 Date: Sat, 21 Nov 2026 14:43:38 -0500 Subject: [PATCH 22/29] fix(engine): text beside an italic word still sets the body size Blocks set inside a sentence were removed before the heading rules ran. The check is symmetric, so prose beside an italic word was removed too, and a page of such paragraphs lost its body text: the body size became the heading's, and the heading was dropped. Inline blocks now stay in the evidence, counting toward the body style, but marked as having no letters, which the rules never take as a heading. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/suggest_outline.rs | 26 ++++++++++++++++++++++++-- parity/acrobat-features.toml | 2 +- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index 133e3b7103..64781585c4 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -144,9 +144,12 @@ impl Block { self.title.extend(text.chars().take(room)); } + /// What the heading rules see. A block set inside a sentence still counts toward the body + /// style, since it is the paragraph's text, but is never a heading: the rules take no block + /// without letters as one. fn evidence(&self) -> TextBlock { let s = &self.first.style; - TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters } + TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline } } } @@ -217,7 +220,7 @@ fn is_caption(text: &str) -> bool { /// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there /// were more. fn inferred(lines: Vec) -> (Vec, bool) { - let blocks: Vec = blocks(lines).into_iter().filter(|b| !b.inline && !is_caption(&b.title)).collect(); + let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); let evidence: Vec = blocks.iter().map(Block::evidence).collect(); let mut entries: Vec = blocks .iter() @@ -311,6 +314,25 @@ mod tests { assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]); } + #[test] + fn text_beside_an_italic_word_still_sets_the_body_size() { + let italic = |top: f64| { + let mut l = run(top, false, "term", 252.0, 275.0); + l.style.italic = true; + l.style.font = "Helvetica-Oblique".into(); + l + }; + let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")]; + for top in [750.0, 736.0, 722.0, 708.0] { + lines.extend([ + run(top, false, "The first part of the row runs to", 72.0, 250.0), + italic(top), + run(top, false, "and the rest of it follows on.", 277.0, 400.0), + ]); + } + assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]); + } + #[test] fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() { let lines = vec![ diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index fca6d58164..a63b4b874b 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -3442,7 +3442,7 @@ milestone = "M4" status = "partial" commands = [] tools = ["bookmark_suggest"] -evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] +evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::text_beside_an_italic_word_still_sets_the_body_size", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) and bold words inside a sentence (prose in another style at the same size right beside them on the row) are left out, which also leaves out a run-in heading set on the same line as its paragraph, a heading after a label with lower-case letters in another style (Appendix, then A Title in bold), and a wrapped heading any of whose lines has prose beside it. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" [[feature]] From d8e0bc1e90fff2101f42671ad0368225c09b2064 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Sun, 22 Nov 2026 00:48:02 -0500 Subject: [PATCH 23/29] fix(engine): a bold word set smaller than its sentence is not a heading The beside test required the same size, so a 9 pt bold keyword in 10 pt prose (RFC 9110 page 16, reported on #6020) was suggested again. A line now counts as inside a sentence when the prose beside it is no smaller than it; a heading set larger than run-in text beside it stays a heading. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/suggest_outline.rs | 961 ++++++++++++++------------- parity/acrobat-features.toml | 4 +- 2 files changed, 494 insertions(+), 471 deletions(-) diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index 64781585c4..cfd7d41a08 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -1,469 +1,492 @@ -//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before -//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the -//! headings are inferred from how the text looks, by the rules Auto-tag uses -//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page -//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the -//! most characters, a short block larger than the body (or bold where the body is not) is a -//! heading, and levels rank the heading styles over the document without skipping a level. -//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each -//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); -//! tagged ones go to their page. - -use pdfcraft_a11y::TextBlock; -use pdfcraft_cos::Document; -use pdfcraft_organize::{OutlineEntry, OutlineNode}; - -use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines}; - -/// Blocks looked back over for one a line continues: a heading's next line can come after lines -/// of other columns on the same row. -const LOOKBACK: usize = 8; -/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent. -const MAX_DEPTH: usize = 32; -/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is -/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can -/// be under an em, so this stays below it. -const BESIDE_GAP: f64 = 0.5; -/// The most lines looked at on either side of a line for text beside it, which bounds the work on -/// a page with many runs on one row. -const MAX_BESIDE: usize = 64; - -/// Where the suggested headings come from. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OutlineSource { - /// The structure tree's headings. - Structure, - /// The size and weight of the text. - Layout, -} - -/// A suggested outline. -#[derive(Clone, Debug, PartialEq)] -pub struct OutlineSuggestion { - pub source: OutlineSource, - /// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]). - pub entries: Vec, - /// Pages in the document. - pub pages: usize, - /// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) - /// for a suggestion from layout, fewer when a page's text can't be read. - pub pages_read: usize, - /// Headings may have been left out: pages weren't read, layout found more than - /// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of - /// [`pdfcraft_a11y::headings_with_truncation`]. - pub truncated: bool, -} - -impl OutlineSuggestion { - /// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the - /// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth. - pub fn tree(&self) -> Vec { - nest(&self.entries, &mut 0, 0, 0) - } -} - -/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion -/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't. -fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec { - let mut out = Vec::new(); - while let Some(e) = entries.get(*at) { - if depth > 0 && e.level <= above { - break; - } - *at = at.saturating_add(1); - let mut n = node(e); - if depth.saturating_add(1) < MAX_DEPTH { - n.children = nest(entries, at, e.level, depth.saturating_add(1)); - } - out.push(n); - } - out -} - -fn node(e: &OutlineEntry) -> OutlineNode { - let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None])); - OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() } -} - -/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether -/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]). -pub(crate) fn structure_entries(doc: &Document) -> (Vec, bool) { - let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc); - let entries = - found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect(); - (entries, cut) -} - -/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the -/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither -/// finds a heading. -pub fn suggest(doc: &Document) -> OutlineSuggestion { - let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); - let (tagged, cut) = structure_entries(doc); - if !tagged.is_empty() { - return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut }; - } - let (lines, pages_read) = read_lines(doc); - let (entries, capped) = inferred(lines); - OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages } -} - -/// Lines in one style, one after another down a page. -struct Block { - first: Line, - last: Line, - title: String, - lines: usize, - chars: usize, - letters: bool, - /// Whether any of its lines is set inside a sentence ([`set_inline`]). - inline: bool, -} - -impl Block { - fn new(line: Line, inline: bool) -> Block { - let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline }; - b.count(&b.first.text.clone()); - b - } - - fn add(&mut self, line: Line, inline: bool) { - self.inline |= inline; - if self.title.chars().count() < MAX_TITLE_CHARS { - self.title.push(' '); - } - self.count(&line.text); - self.last = line; - } - - fn count(&mut self, text: &str) { - self.lines = self.lines.saturating_add(1); - self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count()); - self.letters |= text.chars().any(char::is_alphabetic); - let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count()); - self.title.extend(text.chars().take(room)); - } - - /// What the heading rules see. A block set inside a sentence still counts toward the body - /// style, since it is the paragraph's text, but is never a heading: the rules take no block - /// without letters as one. - fn evidence(&self) -> TextBlock { - let s = &self.first.style; - TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline } - } -} - -/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last -/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]). -fn blocks(lines: Vec) -> Vec { - let flags = set_inline(&lines); - let mut out: Vec = Vec::new(); - for (line, inline) in lines.into_iter().zip(flags) { - let start = out.len().saturating_sub(LOOKBACK); - let found = out.get_mut(start..).and_then(|recent| { - recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last)) - }); - match found { - Some(b) => b.add(line, inline), - None => out.push(Block::new(line, inline)), - } - } - out -} - -/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another -/// style at the same size sits right beside it on its row. A bold word in a paragraph (a -/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only -/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`) -/// leaves the title a heading. -fn set_inline(lines: &[Line]) -> Vec { - lines - .iter() - .enumerate() - .map(|(i, l)| { - // Lines are sorted down each page, so those on its row are next to it. - let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size; - let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near); - let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near); - before.chain(after).any(|o| beside(l, o)) - }) - .collect() -} - -/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at -/// least half the shorter one's height, since a box runs from the font's ascent to its descent -/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the -/// other, at the same size, in another style, at most [`BESIDE_GAP`] ems apart. -fn beside(l: &Line, o: &Line) -> bool { - let size = l.style.size; - let shared = l.top.min(o.top) - l.bottom.max(o.bottom); - let shorter = (l.top - l.bottom).min(o.top - o.bottom); - let gap = l.left.max(o.left) - l.right.min(o.right); - shared >= shorter * 0.5 - && gap >= -size * 0.25 - && gap <= size * BESIDE_GAP - && (o.style.size - size).abs() <= SIZE_TOLERANCE - && !o.style.matches(&l.style) - && o.text.chars().any(char::is_lowercase) -} - -/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a -/// number. -fn is_caption(text: &str) -> bool { - let t = text.trim_start(); - ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| { - let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..)); - rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit())) - }) -} - -/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there -/// were more. -fn inferred(lines: Vec) -> (Vec, bool) { - let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); - let evidence: Vec = blocks.iter().map(Block::evidence).collect(); - let mut entries: Vec = blocks - .iter() - .zip(pdfcraft_a11y::heading_levels(&evidence)) - .filter_map(|(b, level)| { - let [left, top] = b.first.anchor; - Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top }) - }) - .take(MAX_BOOKMARKS.saturating_add(1)) - .collect(); - let capped = entries.len() > MAX_BOOKMARKS; - entries.truncate(MAX_BOOKMARKS); - (entries, capped) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::text_style_bookmarks::TextStyle; - - /// A line at `top` (its box 0.8 of its size tall) from x 72 to 400. - fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line { - let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false }; - Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] } - } - - fn body(page: usize, top: f64) -> Line { - line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.") - } - - fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> { - entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect() - } - - #[test] - fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() { - let lines = vec![ - line(0, 760.0, 20.0, true, "Getting started"), - line(0, 738.0, 20.0, true, "with the toolkit"), - body(0, 700.0), - body(0, 686.0), - body(0, 672.0), - body(0, 658.0), - line(0, 630.0, 11.0, true, "Installing"), - body(0, 610.0), - body(0, 596.0), - line(1, 760.0, 20.0, true, "Reference"), - body(1, 730.0), - body(1, 716.0), - ]; - let (found, capped) = inferred(lines); - assert!(!capped); - assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]); - assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line"); - } - - #[test] - fn a_wrapped_heading_joins_across_a_line_of_another_column() { - let mut right = body(0, 760.0); - (right.left, right.right) = (420.0, 560.0); - let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)]; - assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]); - } - - #[test] - fn captions_and_numbers_are_not_headings() { - let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)]; - assert!(inferred(lines).0.is_empty()); - assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); - } - - /// A line of `text` in `style` from `left` to `right` at `top`. - fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line { - Line { left, right, ..line(0, top, 11.0, bold, text) } - } - - #[test] - fn a_bold_word_inside_a_sentence_is_not_a_heading() { - let lines = vec![ - line(0, 760.0, 11.0, true, "MUST"), - body(0, 740.0), - run(726.0, false, "A recipient", 72.0, 130.0), - run(726.0, true, "MUST", 133.0, 165.0), - run(726.0, false, "ignore the field.", 168.0, 400.0), - body(0, 712.0), - run(690.0, false, "2.3", 72.0, 88.0), - run(690.0, true, "Numbered title", 96.0, 180.0), - body(0, 670.0), - body(0, 656.0), - ]; - assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]); - } - - #[test] - fn text_beside_an_italic_word_still_sets_the_body_size() { - let italic = |top: f64| { - let mut l = run(top, false, "term", 252.0, 275.0); - l.style.italic = true; - l.style.font = "Helvetica-Oblique".into(); - l - }; - let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")]; - for top in [750.0, 736.0, 722.0, 708.0] { - lines.extend([ - run(top, false, "The first part of the row runs to", 72.0, 250.0), - italic(top), - run(top, false, "and the rest of it follows on.", 277.0, 400.0), - ]); - } - assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]); - } - - #[test] - fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() { - let lines = vec![ - // Its box overlaps the first body line's by 1.5 pt. - run(760.0, true, "Tight heading", 72.0, 180.0), - body(0, 752.7), - body(0, 740.0), - // A gutter of 9 pt, under an em: prose ends the left column on the heading's row. - run(700.0, false, "ends the left column here", 72.0, 291.0), - run(700.0, true, "Right column heading", 300.0, 520.0), - body(0, 686.0), - body(0, 672.0), - ]; - assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]); - } - - #[test] - fn captions_match_in_any_case() { - let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)]; - assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading"); - assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3")); - } - - #[test] - fn more_headings_than_the_cap_are_reported() { - // Each heading on a page of its own, with a line of body text under it. - let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::>(); - let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS)); - assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false)); - let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1)); - assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported"); - } - - /// A page past the page decode allowance (two compressed streams of spaces, each just over - /// half of it) can't be read: it doesn't count as read, and the suggestion says headings - /// may be missing. - #[test] - fn a_page_whose_text_cant_be_read_is_not_counted() { - let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]); - let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(); - let objs: Vec> = vec![ - b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), - b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(), - stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"), - stream("/Filter /FlateDecode", &packed), - b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), - ]; - let s = suggest(&doc_of(&objs)); - assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); - } - - /// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog. - fn doc_of(objs: &[Vec]) -> Document { - let mut bytes = b"%PDF-1.7\n".to_vec(); - let mut offsets = Vec::new(); - for (i, o) in objs.iter().enumerate() { - offsets.push(bytes.len()); - bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat()); - } - let xref = bytes.len(); - bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); - for o in offsets { - bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); - } - bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); - Document::open(std::sync::Arc::new(bytes)).unwrap() - } - - /// More tagged headings than the structure reader returns: the suggestion says some are missing. - #[test] - fn tagged_headings_past_the_cap_are_reported() { - let tagged = |count: usize| { - let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect(); - let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), - b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), - b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), - format!("<< /S /Document /K [{kids}] >>").into_bytes(), - ]; - objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec())); - suggest(&doc_of(&objs)) - }; - let cap = pdfcraft_a11y::MAX_HEADINGS; - let at_cap = tagged(cap); - assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false)); - let over = tagged(cap + 1); - assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported"); - } - - /// A tagged heading too deep for the structure walk, on a page without text: layout finds - /// nothing either, and the suggestion still says a heading may be missing. The same page - /// untagged is not truncated. - #[test] - fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() { - let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), - b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), - b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), - ]; - objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes())); - objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec()); - let s = suggest(&doc_of(&objs)); - assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped"); - objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(); - let s = suggest(&doc_of(&objs)); - assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false)); - } - - #[test] - fn the_tree_nests_by_level_and_caps_the_depth() { - let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; - let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")]; - let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false }; - let tree = s.tree(); - assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::>(), ["A", "B"]); - assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::>(), ["A.1", "A.2"]); - assert_eq!(tree[0].children[0].children[0].title, "A.1.a"); - assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None]))); - // A tagged H nested in 40 sections stops at the deepest level bookmark_import takes. - entries = (1..=40).map(|l| entry(l, "deep")).collect(); - let deep = OutlineSuggestion { entries, ..s }.tree(); - let mut depth = 0; - let mut at = &deep; - while let Some(n) = at.first() { - depth += 1; - at = &n.children; - } - assert_eq!(depth, MAX_DEPTH); - } -} +//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before +//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the +//! headings are inferred from how the text looks, by the rules Auto-tag uses +//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page +//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the +//! most characters, a short block larger than the body (or bold where the body is not) is a +//! heading, and levels rank the heading styles over the document without skipping a level. +//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each +//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); +//! tagged ones go to their page. + +use pdfcraft_a11y::TextBlock; +use pdfcraft_cos::Document; +use pdfcraft_organize::{OutlineEntry, OutlineNode}; + +use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines}; + +/// Blocks looked back over for one a line continues: a heading's next line can come after lines +/// of other columns on the same row. +const LOOKBACK: usize = 8; +/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent. +const MAX_DEPTH: usize = 32; +/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is +/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can +/// be under an em, so this stays below it. +const BESIDE_GAP: f64 = 0.5; +/// The most lines looked at on either side of a line for text beside it, which bounds the work on +/// a page with many runs on one row. +const MAX_BESIDE: usize = 64; + +/// Where the suggested headings come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineSource { + /// The structure tree's headings. + Structure, + /// The size and weight of the text. + Layout, +} + +/// A suggested outline. +#[derive(Clone, Debug, PartialEq)] +pub struct OutlineSuggestion { + pub source: OutlineSource, + /// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]). + pub entries: Vec, + /// Pages in the document. + pub pages: usize, + /// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) + /// for a suggestion from layout, fewer when a page's text can't be read. + pub pages_read: usize, + /// Headings may have been left out: pages weren't read, layout found more than + /// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of + /// [`pdfcraft_a11y::headings_with_truncation`]. + pub truncated: bool, +} + +impl OutlineSuggestion { + /// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the + /// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth. + pub fn tree(&self) -> Vec { + nest(&self.entries, &mut 0, 0, 0) + } +} + +/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion +/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't. +fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec { + let mut out = Vec::new(); + while let Some(e) = entries.get(*at) { + if depth > 0 && e.level <= above { + break; + } + *at = at.saturating_add(1); + let mut n = node(e); + if depth.saturating_add(1) < MAX_DEPTH { + n.children = nest(entries, at, e.level, depth.saturating_add(1)); + } + out.push(n); + } + out +} + +fn node(e: &OutlineEntry) -> OutlineNode { + let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None])); + OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() } +} + +/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether +/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]). +pub(crate) fn structure_entries(doc: &Document) -> (Vec, bool) { + let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc); + let entries = + found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect(); + (entries, cut) +} + +/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the +/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither +/// finds a heading. +pub fn suggest(doc: &Document) -> OutlineSuggestion { + let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); + let (tagged, cut) = structure_entries(doc); + if !tagged.is_empty() { + return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut }; + } + let (lines, pages_read) = read_lines(doc); + let (entries, capped) = inferred(lines); + OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages } +} + +/// Lines in one style, one after another down a page. +struct Block { + first: Line, + last: Line, + title: String, + lines: usize, + chars: usize, + letters: bool, + /// Whether any of its lines is set inside a sentence ([`set_inline`]). + inline: bool, +} + +impl Block { + fn new(line: Line, inline: bool) -> Block { + let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline }; + b.count(&b.first.text.clone()); + b + } + + fn add(&mut self, line: Line, inline: bool) { + self.inline |= inline; + if self.title.chars().count() < MAX_TITLE_CHARS { + self.title.push(' '); + } + self.count(&line.text); + self.last = line; + } + + fn count(&mut self, text: &str) { + self.lines = self.lines.saturating_add(1); + self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count()); + self.letters |= text.chars().any(char::is_alphabetic); + let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count()); + self.title.extend(text.chars().take(room)); + } + + /// What the heading rules see. A block set inside a sentence still counts toward the body + /// style, since it is the paragraph's text, but is never a heading: the rules take no block + /// without letters as one. + fn evidence(&self) -> TextBlock { + let s = &self.first.style; + TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline } + } +} + +/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last +/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]). +fn blocks(lines: Vec) -> Vec { + let flags = set_inline(&lines); + let mut out: Vec = Vec::new(); + for (line, inline) in lines.into_iter().zip(flags) { + let start = out.len().saturating_sub(LOOKBACK); + let found = out.get_mut(start..).and_then(|recent| { + recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last)) + }); + match found { + Some(b) => b.add(line, inline), + None => out.push(Block::new(line, inline)), + } + } + out +} + +/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another +/// style, no smaller than it, sits right beside it on its row. A bold word in a paragraph (a +/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only +/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`) +/// leaves the title a heading. +fn set_inline(lines: &[Line]) -> Vec { + lines + .iter() + .enumerate() + .map(|(i, l)| { + // Lines are sorted down each page, so those on its row are next to it. + let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size; + let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near); + let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near); + before.chain(after).any(|o| beside(l, o)) + }) + .collect() +} + +/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at +/// least half the shorter one's height, since a box runs from the font's ascent to its descent +/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the +/// other, no smaller than `l`, in another style, at most [`BESIDE_GAP`] ems apart. A heading set +/// beside text more than [`SIZE_TOLERANCE`] smaller is still a heading; a word set smaller than +/// the prose around it is not. +fn beside(l: &Line, o: &Line) -> bool { + let size = l.style.size; + let shared = l.top.min(o.top) - l.bottom.max(o.bottom); + let shorter = (l.top - l.bottom).min(o.top - o.bottom); + let gap = l.left.max(o.left) - l.right.min(o.right); + shared >= shorter * 0.5 + && gap >= -size * 0.25 + && gap <= size * BESIDE_GAP + && size <= o.style.size + SIZE_TOLERANCE + && !o.style.matches(&l.style) + && o.text.chars().any(char::is_lowercase) +} + +/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a +/// number. +fn is_caption(text: &str) -> bool { + let t = text.trim_start(); + ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| { + let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..)); + rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit())) + }) +} + +/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there +/// were more. +fn inferred(lines: Vec) -> (Vec, bool) { + let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); + let evidence: Vec = blocks.iter().map(Block::evidence).collect(); + let mut entries: Vec = blocks + .iter() + .zip(pdfcraft_a11y::heading_levels(&evidence)) + .filter_map(|(b, level)| { + let [left, top] = b.first.anchor; + Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top }) + }) + .take(MAX_BOOKMARKS.saturating_add(1)) + .collect(); + let capped = entries.len() > MAX_BOOKMARKS; + entries.truncate(MAX_BOOKMARKS); + (entries, capped) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text_style_bookmarks::TextStyle; + + /// A line at `top` (its box 0.8 of its size tall) from x 72 to 400. + fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line { + let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false }; + Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] } + } + + fn body(page: usize, top: f64) -> Line { + line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.") + } + + fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> { + entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect() + } + + #[test] + fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() { + let lines = vec![ + line(0, 760.0, 20.0, true, "Getting started"), + line(0, 738.0, 20.0, true, "with the toolkit"), + body(0, 700.0), + body(0, 686.0), + body(0, 672.0), + body(0, 658.0), + line(0, 630.0, 11.0, true, "Installing"), + body(0, 610.0), + body(0, 596.0), + line(1, 760.0, 20.0, true, "Reference"), + body(1, 730.0), + body(1, 716.0), + ]; + let (found, capped) = inferred(lines); + assert!(!capped); + assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]); + assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line"); + } + + #[test] + fn a_wrapped_heading_joins_across_a_line_of_another_column() { + let mut right = body(0, 760.0); + (right.left, right.right) = (420.0, 560.0); + let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)]; + assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]); + } + + #[test] + fn captions_and_numbers_are_not_headings() { + let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).0.is_empty()); + assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); + } + + /// A line of `text` in `style` from `left` to `right` at `top`. + fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line { + Line { left, right, ..line(0, top, 11.0, bold, text) } + } + + #[test] + fn a_bold_word_inside_a_sentence_is_not_a_heading() { + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient", 72.0, 130.0), + run(726.0, true, "MUST", 133.0, 165.0), + run(726.0, false, "ignore the field.", 168.0, 400.0), + body(0, 712.0), + run(690.0, false, "2.3", 72.0, 88.0), + run(690.0, true, "Numbered title", 96.0, 180.0), + body(0, 670.0), + body(0, 656.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]); + } + + #[test] + fn a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is() { + let mut small = run(726.0, true, "MUST", 133.0, 163.0); + small.style.size = 10.0; + small.top = 725.2; + small.bottom = small.top - 8.0; + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient", 72.0, 130.0), + small, + run(726.0, false, "ignore the field.", 166.0, 400.0), + body(0, 712.0), + Line { left: 72.0, right: 110.0, ..line(0, 690.0, 14.0, true, "Scope") }, + run(688.8, false, "covers the rest of this page.", 113.0, 400.0), + body(0, 670.0), + body(0, 656.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Scope", 0)]); + } + + #[test] + fn text_beside_an_italic_word_still_sets_the_body_size() { + let italic = |top: f64| { + let mut l = run(top, false, "term", 252.0, 275.0); + l.style.italic = true; + l.style.font = "Helvetica-Oblique".into(); + l + }; + let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")]; + for top in [750.0, 736.0, 722.0, 708.0] { + lines.extend([ + run(top, false, "The first part of the row runs to", 72.0, 250.0), + italic(top), + run(top, false, "and the rest of it follows on.", 277.0, 400.0), + ]); + } + assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]); + } + + #[test] + fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() { + let lines = vec![ + // Its box overlaps the first body line's by 1.5 pt. + run(760.0, true, "Tight heading", 72.0, 180.0), + body(0, 752.7), + body(0, 740.0), + // A gutter of 9 pt, under an em: prose ends the left column on the heading's row. + run(700.0, false, "ends the left column here", 72.0, 291.0), + run(700.0, true, "Right column heading", 300.0, 520.0), + body(0, 686.0), + body(0, 672.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]); + } + + #[test] + fn captions_match_in_any_case() { + let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading"); + assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3")); + } + + #[test] + fn more_headings_than_the_cap_are_reported() { + // Each heading on a page of its own, with a line of body text under it. + let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::>(); + let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS)); + assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false)); + let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1)); + assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported"); + } + + /// A page past the page decode allowance (two compressed streams of spaces, each just over + /// half of it) can't be read: it doesn't count as read, and the suggestion says headings + /// may be missing. + #[test] + fn a_page_whose_text_cant_be_read_is_not_counted() { + let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]); + let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(), + stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"), + stream("/Filter /FlateDecode", &packed), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), + ]; + let s = suggest(&doc_of(&objs)); + assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); + } + + /// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog. + fn doc_of(objs: &[Vec]) -> Document { + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + Document::open(std::sync::Arc::new(bytes)).unwrap() + } + + /// More tagged headings than the structure reader returns: the suggestion says some are missing. + #[test] + fn tagged_headings_past_the_cap_are_reported() { + let tagged = |count: usize| { + let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect(); + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + format!("<< /S /Document /K [{kids}] >>").into_bytes(), + ]; + objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec())); + suggest(&doc_of(&objs)) + }; + let cap = pdfcraft_a11y::MAX_HEADINGS; + let at_cap = tagged(cap); + assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false)); + let over = tagged(cap + 1); + assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported"); + } + + /// A tagged heading too deep for the structure walk, on a page without text: layout finds + /// nothing either, and the suggestion still says a heading may be missing. The same page + /// untagged is not truncated. + #[test] + fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() { + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + ]; + objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes())); + objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec()); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped"); + objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false)); + } + + #[test] + fn the_tree_nests_by_level_and_caps_the_depth() { + let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; + let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")]; + let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false }; + let tree = s.tree(); + assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::>(), ["A", "B"]); + assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::>(), ["A.1", "A.2"]); + assert_eq!(tree[0].children[0].children[0].title, "A.1.a"); + assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None]))); + // A tagged H nested in 40 sections stops at the deepest level bookmark_import takes. + entries = (1..=40).map(|l| entry(l, "deep")).collect(); + let deep = OutlineSuggestion { entries, ..s }.tree(); + let mut depth = 0; + let mut at = &deep; + while let Some(n) = at.first() { + depth += 1; + at = &n.children; + } + assert_eq!(depth, MAX_DEPTH); + } +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index a63b4b874b..773550c15a 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -3442,8 +3442,8 @@ milestone = "M4" status = "partial" commands = [] tools = ["bookmark_suggest"] -evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::text_beside_an_italic_word_still_sets_the_body_size", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] -notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) and bold words inside a sentence (prose in another style at the same size right beside them on the row) are left out, which also leaves out a run-in heading set on the same line as its paragraph, a heading after a label with lower-case letters in another style (Appendix, then A Title in bold), and a wrapped heading any of whose lines has prose beside it. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" +evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::text_beside_an_italic_word_still_sets_the_body_size", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] +notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) and bold words inside a sentence (prose in another style, no smaller than them, right beside them on the row) are left out, which also leaves out a run-in heading set on the same line as its paragraph, a side head no larger than the body text half an em beside it, a heading after a label with lower-case letters in another style (Appendix, then A Title in bold), and a wrapped heading any of whose lines has prose beside it. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" [[feature]] id = "organize.bookmarks-import-export" From 1a25e882c543a14b8609b28301e6d8dab68519b6 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Sun, 22 Nov 2026 01:48:09 -0500 Subject: [PATCH 24/29] style(engine): restore LF line endings in suggest_outline.rs The previous commit rewrote the file with CRLF endings. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/suggest_outline.rs | 984 +++++++++++++-------------- 1 file changed, 492 insertions(+), 492 deletions(-) diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index cfd7d41a08..47a12c3fe1 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -1,492 +1,492 @@ -//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before -//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the -//! headings are inferred from how the text looks, by the rules Auto-tag uses -//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page -//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the -//! most characters, a short block larger than the body (or bold where the body is not) is a -//! heading, and levels rank the heading styles over the document without skipping a level. -//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each -//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); -//! tagged ones go to their page. - -use pdfcraft_a11y::TextBlock; -use pdfcraft_cos::Document; -use pdfcraft_organize::{OutlineEntry, OutlineNode}; - -use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines}; - -/// Blocks looked back over for one a line continues: a heading's next line can come after lines -/// of other columns on the same row. -const LOOKBACK: usize = 8; -/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent. -const MAX_DEPTH: usize = 32; -/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is -/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can -/// be under an em, so this stays below it. -const BESIDE_GAP: f64 = 0.5; -/// The most lines looked at on either side of a line for text beside it, which bounds the work on -/// a page with many runs on one row. -const MAX_BESIDE: usize = 64; - -/// Where the suggested headings come from. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OutlineSource { - /// The structure tree's headings. - Structure, - /// The size and weight of the text. - Layout, -} - -/// A suggested outline. -#[derive(Clone, Debug, PartialEq)] -pub struct OutlineSuggestion { - pub source: OutlineSource, - /// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]). - pub entries: Vec, - /// Pages in the document. - pub pages: usize, - /// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) - /// for a suggestion from layout, fewer when a page's text can't be read. - pub pages_read: usize, - /// Headings may have been left out: pages weren't read, layout found more than - /// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of - /// [`pdfcraft_a11y::headings_with_truncation`]. - pub truncated: bool, -} - -impl OutlineSuggestion { - /// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the - /// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth. - pub fn tree(&self) -> Vec { - nest(&self.entries, &mut 0, 0, 0) - } -} - -/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion -/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't. -fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec { - let mut out = Vec::new(); - while let Some(e) = entries.get(*at) { - if depth > 0 && e.level <= above { - break; - } - *at = at.saturating_add(1); - let mut n = node(e); - if depth.saturating_add(1) < MAX_DEPTH { - n.children = nest(entries, at, e.level, depth.saturating_add(1)); - } - out.push(n); - } - out -} - -fn node(e: &OutlineEntry) -> OutlineNode { - let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None])); - OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() } -} - -/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether -/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]). -pub(crate) fn structure_entries(doc: &Document) -> (Vec, bool) { - let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc); - let entries = - found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect(); - (entries, cut) -} - -/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the -/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither -/// finds a heading. -pub fn suggest(doc: &Document) -> OutlineSuggestion { - let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); - let (tagged, cut) = structure_entries(doc); - if !tagged.is_empty() { - return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut }; - } - let (lines, pages_read) = read_lines(doc); - let (entries, capped) = inferred(lines); - OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages } -} - -/// Lines in one style, one after another down a page. -struct Block { - first: Line, - last: Line, - title: String, - lines: usize, - chars: usize, - letters: bool, - /// Whether any of its lines is set inside a sentence ([`set_inline`]). - inline: bool, -} - -impl Block { - fn new(line: Line, inline: bool) -> Block { - let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline }; - b.count(&b.first.text.clone()); - b - } - - fn add(&mut self, line: Line, inline: bool) { - self.inline |= inline; - if self.title.chars().count() < MAX_TITLE_CHARS { - self.title.push(' '); - } - self.count(&line.text); - self.last = line; - } - - fn count(&mut self, text: &str) { - self.lines = self.lines.saturating_add(1); - self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count()); - self.letters |= text.chars().any(char::is_alphabetic); - let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count()); - self.title.extend(text.chars().take(room)); - } - - /// What the heading rules see. A block set inside a sentence still counts toward the body - /// style, since it is the paragraph's text, but is never a heading: the rules take no block - /// without letters as one. - fn evidence(&self) -> TextBlock { - let s = &self.first.style; - TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline } - } -} - -/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last -/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]). -fn blocks(lines: Vec) -> Vec { - let flags = set_inline(&lines); - let mut out: Vec = Vec::new(); - for (line, inline) in lines.into_iter().zip(flags) { - let start = out.len().saturating_sub(LOOKBACK); - let found = out.get_mut(start..).and_then(|recent| { - recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last)) - }); - match found { - Some(b) => b.add(line, inline), - None => out.push(Block::new(line, inline)), - } - } - out -} - -/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another -/// style, no smaller than it, sits right beside it on its row. A bold word in a paragraph (a -/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only -/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`) -/// leaves the title a heading. -fn set_inline(lines: &[Line]) -> Vec { - lines - .iter() - .enumerate() - .map(|(i, l)| { - // Lines are sorted down each page, so those on its row are next to it. - let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size; - let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near); - let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near); - before.chain(after).any(|o| beside(l, o)) - }) - .collect() -} - -/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at -/// least half the shorter one's height, since a box runs from the font's ascent to its descent -/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the -/// other, no smaller than `l`, in another style, at most [`BESIDE_GAP`] ems apart. A heading set -/// beside text more than [`SIZE_TOLERANCE`] smaller is still a heading; a word set smaller than -/// the prose around it is not. -fn beside(l: &Line, o: &Line) -> bool { - let size = l.style.size; - let shared = l.top.min(o.top) - l.bottom.max(o.bottom); - let shorter = (l.top - l.bottom).min(o.top - o.bottom); - let gap = l.left.max(o.left) - l.right.min(o.right); - shared >= shorter * 0.5 - && gap >= -size * 0.25 - && gap <= size * BESIDE_GAP - && size <= o.style.size + SIZE_TOLERANCE - && !o.style.matches(&l.style) - && o.text.chars().any(char::is_lowercase) -} - -/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a -/// number. -fn is_caption(text: &str) -> bool { - let t = text.trim_start(); - ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| { - let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..)); - rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit())) - }) -} - -/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there -/// were more. -fn inferred(lines: Vec) -> (Vec, bool) { - let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); - let evidence: Vec = blocks.iter().map(Block::evidence).collect(); - let mut entries: Vec = blocks - .iter() - .zip(pdfcraft_a11y::heading_levels(&evidence)) - .filter_map(|(b, level)| { - let [left, top] = b.first.anchor; - Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top }) - }) - .take(MAX_BOOKMARKS.saturating_add(1)) - .collect(); - let capped = entries.len() > MAX_BOOKMARKS; - entries.truncate(MAX_BOOKMARKS); - (entries, capped) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::text_style_bookmarks::TextStyle; - - /// A line at `top` (its box 0.8 of its size tall) from x 72 to 400. - fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line { - let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false }; - Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] } - } - - fn body(page: usize, top: f64) -> Line { - line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.") - } - - fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> { - entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect() - } - - #[test] - fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() { - let lines = vec![ - line(0, 760.0, 20.0, true, "Getting started"), - line(0, 738.0, 20.0, true, "with the toolkit"), - body(0, 700.0), - body(0, 686.0), - body(0, 672.0), - body(0, 658.0), - line(0, 630.0, 11.0, true, "Installing"), - body(0, 610.0), - body(0, 596.0), - line(1, 760.0, 20.0, true, "Reference"), - body(1, 730.0), - body(1, 716.0), - ]; - let (found, capped) = inferred(lines); - assert!(!capped); - assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]); - assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line"); - } - - #[test] - fn a_wrapped_heading_joins_across_a_line_of_another_column() { - let mut right = body(0, 760.0); - (right.left, right.right) = (420.0, 560.0); - let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)]; - assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]); - } - - #[test] - fn captions_and_numbers_are_not_headings() { - let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)]; - assert!(inferred(lines).0.is_empty()); - assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); - } - - /// A line of `text` in `style` from `left` to `right` at `top`. - fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line { - Line { left, right, ..line(0, top, 11.0, bold, text) } - } - - #[test] - fn a_bold_word_inside_a_sentence_is_not_a_heading() { - let lines = vec![ - line(0, 760.0, 11.0, true, "MUST"), - body(0, 740.0), - run(726.0, false, "A recipient", 72.0, 130.0), - run(726.0, true, "MUST", 133.0, 165.0), - run(726.0, false, "ignore the field.", 168.0, 400.0), - body(0, 712.0), - run(690.0, false, "2.3", 72.0, 88.0), - run(690.0, true, "Numbered title", 96.0, 180.0), - body(0, 670.0), - body(0, 656.0), - ]; - assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]); - } - - #[test] - fn a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is() { - let mut small = run(726.0, true, "MUST", 133.0, 163.0); - small.style.size = 10.0; - small.top = 725.2; - small.bottom = small.top - 8.0; - let lines = vec![ - line(0, 760.0, 11.0, true, "MUST"), - body(0, 740.0), - run(726.0, false, "A recipient", 72.0, 130.0), - small, - run(726.0, false, "ignore the field.", 166.0, 400.0), - body(0, 712.0), - Line { left: 72.0, right: 110.0, ..line(0, 690.0, 14.0, true, "Scope") }, - run(688.8, false, "covers the rest of this page.", 113.0, 400.0), - body(0, 670.0), - body(0, 656.0), - ]; - assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Scope", 0)]); - } - - #[test] - fn text_beside_an_italic_word_still_sets_the_body_size() { - let italic = |top: f64| { - let mut l = run(top, false, "term", 252.0, 275.0); - l.style.italic = true; - l.style.font = "Helvetica-Oblique".into(); - l - }; - let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")]; - for top in [750.0, 736.0, 722.0, 708.0] { - lines.extend([ - run(top, false, "The first part of the row runs to", 72.0, 250.0), - italic(top), - run(top, false, "and the rest of it follows on.", 277.0, 400.0), - ]); - } - assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]); - } - - #[test] - fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() { - let lines = vec![ - // Its box overlaps the first body line's by 1.5 pt. - run(760.0, true, "Tight heading", 72.0, 180.0), - body(0, 752.7), - body(0, 740.0), - // A gutter of 9 pt, under an em: prose ends the left column on the heading's row. - run(700.0, false, "ends the left column here", 72.0, 291.0), - run(700.0, true, "Right column heading", 300.0, 520.0), - body(0, 686.0), - body(0, 672.0), - ]; - assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]); - } - - #[test] - fn captions_match_in_any_case() { - let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)]; - assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading"); - assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3")); - } - - #[test] - fn more_headings_than_the_cap_are_reported() { - // Each heading on a page of its own, with a line of body text under it. - let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::>(); - let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS)); - assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false)); - let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1)); - assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported"); - } - - /// A page past the page decode allowance (two compressed streams of spaces, each just over - /// half of it) can't be read: it doesn't count as read, and the suggestion says headings - /// may be missing. - #[test] - fn a_page_whose_text_cant_be_read_is_not_counted() { - let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]); - let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(); - let objs: Vec> = vec![ - b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), - b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(), - stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"), - stream("/Filter /FlateDecode", &packed), - b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), - ]; - let s = suggest(&doc_of(&objs)); - assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); - } - - /// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog. - fn doc_of(objs: &[Vec]) -> Document { - let mut bytes = b"%PDF-1.7\n".to_vec(); - let mut offsets = Vec::new(); - for (i, o) in objs.iter().enumerate() { - offsets.push(bytes.len()); - bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat()); - } - let xref = bytes.len(); - bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); - for o in offsets { - bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); - } - bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); - Document::open(std::sync::Arc::new(bytes)).unwrap() - } - - /// More tagged headings than the structure reader returns: the suggestion says some are missing. - #[test] - fn tagged_headings_past_the_cap_are_reported() { - let tagged = |count: usize| { - let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect(); - let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), - b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), - b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), - format!("<< /S /Document /K [{kids}] >>").into_bytes(), - ]; - objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec())); - suggest(&doc_of(&objs)) - }; - let cap = pdfcraft_a11y::MAX_HEADINGS; - let at_cap = tagged(cap); - assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false)); - let over = tagged(cap + 1); - assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported"); - } - - /// A tagged heading too deep for the structure walk, on a page without text: layout finds - /// nothing either, and the suggestion still says a heading may be missing. The same page - /// untagged is not truncated. - #[test] - fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() { - let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), - b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), - b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), - ]; - objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes())); - objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec()); - let s = suggest(&doc_of(&objs)); - assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped"); - objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(); - let s = suggest(&doc_of(&objs)); - assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false)); - } - - #[test] - fn the_tree_nests_by_level_and_caps_the_depth() { - let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; - let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")]; - let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false }; - let tree = s.tree(); - assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::>(), ["A", "B"]); - assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::>(), ["A.1", "A.2"]); - assert_eq!(tree[0].children[0].children[0].title, "A.1.a"); - assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None]))); - // A tagged H nested in 40 sections stops at the deepest level bookmark_import takes. - entries = (1..=40).map(|l| entry(l, "deep")).collect(); - let deep = OutlineSuggestion { entries, ..s }.tree(); - let mut depth = 0; - let mut at = &deep; - while let Some(n) = at.first() { - depth += 1; - at = &n.children; - } - assert_eq!(depth, MAX_DEPTH); - } -} +//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before +//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the +//! headings are inferred from how the text looks, by the rules Auto-tag uses +//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page +//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the +//! most characters, a short block larger than the body (or bold where the body is not) is a +//! heading, and levels rank the heading styles over the document without skipping a level. +//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each +//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); +//! tagged ones go to their page. + +use pdfcraft_a11y::TextBlock; +use pdfcraft_cos::Document; +use pdfcraft_organize::{OutlineEntry, OutlineNode}; + +use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines}; + +/// Blocks looked back over for one a line continues: a heading's next line can come after lines +/// of other columns on the same row. +const LOOKBACK: usize = 8; +/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent. +const MAX_DEPTH: usize = 32; +/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is +/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can +/// be under an em, so this stays below it. +const BESIDE_GAP: f64 = 0.5; +/// The most lines looked at on either side of a line for text beside it, which bounds the work on +/// a page with many runs on one row. +const MAX_BESIDE: usize = 64; + +/// Where the suggested headings come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineSource { + /// The structure tree's headings. + Structure, + /// The size and weight of the text. + Layout, +} + +/// A suggested outline. +#[derive(Clone, Debug, PartialEq)] +pub struct OutlineSuggestion { + pub source: OutlineSource, + /// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]). + pub entries: Vec, + /// Pages in the document. + pub pages: usize, + /// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) + /// for a suggestion from layout, fewer when a page's text can't be read. + pub pages_read: usize, + /// Headings may have been left out: pages weren't read, layout found more than + /// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of + /// [`pdfcraft_a11y::headings_with_truncation`]. + pub truncated: bool, +} + +impl OutlineSuggestion { + /// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the + /// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth. + pub fn tree(&self) -> Vec { + nest(&self.entries, &mut 0, 0, 0) + } +} + +/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion +/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't. +fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec { + let mut out = Vec::new(); + while let Some(e) = entries.get(*at) { + if depth > 0 && e.level <= above { + break; + } + *at = at.saturating_add(1); + let mut n = node(e); + if depth.saturating_add(1) < MAX_DEPTH { + n.children = nest(entries, at, e.level, depth.saturating_add(1)); + } + out.push(n); + } + out +} + +fn node(e: &OutlineEntry) -> OutlineNode { + let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None])); + OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() } +} + +/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether +/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]). +pub(crate) fn structure_entries(doc: &Document) -> (Vec, bool) { + let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc); + let entries = + found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect(); + (entries, cut) +} + +/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the +/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither +/// finds a heading. +pub fn suggest(doc: &Document) -> OutlineSuggestion { + let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); + let (tagged, cut) = structure_entries(doc); + if !tagged.is_empty() { + return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut }; + } + let (lines, pages_read) = read_lines(doc); + let (entries, capped) = inferred(lines); + OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages } +} + +/// Lines in one style, one after another down a page. +struct Block { + first: Line, + last: Line, + title: String, + lines: usize, + chars: usize, + letters: bool, + /// Whether any of its lines is set inside a sentence ([`set_inline`]). + inline: bool, +} + +impl Block { + fn new(line: Line, inline: bool) -> Block { + let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline }; + b.count(&b.first.text.clone()); + b + } + + fn add(&mut self, line: Line, inline: bool) { + self.inline |= inline; + if self.title.chars().count() < MAX_TITLE_CHARS { + self.title.push(' '); + } + self.count(&line.text); + self.last = line; + } + + fn count(&mut self, text: &str) { + self.lines = self.lines.saturating_add(1); + self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count()); + self.letters |= text.chars().any(char::is_alphabetic); + let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count()); + self.title.extend(text.chars().take(room)); + } + + /// What the heading rules see. A block set inside a sentence still counts toward the body + /// style, since it is the paragraph's text, but is never a heading: the rules take no block + /// without letters as one. + fn evidence(&self) -> TextBlock { + let s = &self.first.style; + TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline } + } +} + +/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last +/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]). +fn blocks(lines: Vec) -> Vec { + let flags = set_inline(&lines); + let mut out: Vec = Vec::new(); + for (line, inline) in lines.into_iter().zip(flags) { + let start = out.len().saturating_sub(LOOKBACK); + let found = out.get_mut(start..).and_then(|recent| { + recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last)) + }); + match found { + Some(b) => b.add(line, inline), + None => out.push(Block::new(line, inline)), + } + } + out +} + +/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another +/// style, no smaller than it, sits right beside it on its row. A bold word in a paragraph (a +/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only +/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`) +/// leaves the title a heading. +fn set_inline(lines: &[Line]) -> Vec { + lines + .iter() + .enumerate() + .map(|(i, l)| { + // Lines are sorted down each page, so those on its row are next to it. + let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size; + let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near); + let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near); + before.chain(after).any(|o| beside(l, o)) + }) + .collect() +} + +/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at +/// least half the shorter one's height, since a box runs from the font's ascent to its descent +/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the +/// other, no smaller than `l`, in another style, at most [`BESIDE_GAP`] ems apart. A heading set +/// beside text more than [`SIZE_TOLERANCE`] smaller is still a heading; a word set smaller than +/// the prose around it is not. +fn beside(l: &Line, o: &Line) -> bool { + let size = l.style.size; + let shared = l.top.min(o.top) - l.bottom.max(o.bottom); + let shorter = (l.top - l.bottom).min(o.top - o.bottom); + let gap = l.left.max(o.left) - l.right.min(o.right); + shared >= shorter * 0.5 + && gap >= -size * 0.25 + && gap <= size * BESIDE_GAP + && size <= o.style.size + SIZE_TOLERANCE + && !o.style.matches(&l.style) + && o.text.chars().any(char::is_lowercase) +} + +/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a +/// number. +fn is_caption(text: &str) -> bool { + let t = text.trim_start(); + ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| { + let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..)); + rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit())) + }) +} + +/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there +/// were more. +fn inferred(lines: Vec) -> (Vec, bool) { + let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); + let evidence: Vec = blocks.iter().map(Block::evidence).collect(); + let mut entries: Vec = blocks + .iter() + .zip(pdfcraft_a11y::heading_levels(&evidence)) + .filter_map(|(b, level)| { + let [left, top] = b.first.anchor; + Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top }) + }) + .take(MAX_BOOKMARKS.saturating_add(1)) + .collect(); + let capped = entries.len() > MAX_BOOKMARKS; + entries.truncate(MAX_BOOKMARKS); + (entries, capped) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text_style_bookmarks::TextStyle; + + /// A line at `top` (its box 0.8 of its size tall) from x 72 to 400. + fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line { + let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false }; + Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] } + } + + fn body(page: usize, top: f64) -> Line { + line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.") + } + + fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> { + entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect() + } + + #[test] + fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() { + let lines = vec![ + line(0, 760.0, 20.0, true, "Getting started"), + line(0, 738.0, 20.0, true, "with the toolkit"), + body(0, 700.0), + body(0, 686.0), + body(0, 672.0), + body(0, 658.0), + line(0, 630.0, 11.0, true, "Installing"), + body(0, 610.0), + body(0, 596.0), + line(1, 760.0, 20.0, true, "Reference"), + body(1, 730.0), + body(1, 716.0), + ]; + let (found, capped) = inferred(lines); + assert!(!capped); + assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]); + assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line"); + } + + #[test] + fn a_wrapped_heading_joins_across_a_line_of_another_column() { + let mut right = body(0, 760.0); + (right.left, right.right) = (420.0, 560.0); + let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)]; + assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]); + } + + #[test] + fn captions_and_numbers_are_not_headings() { + let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).0.is_empty()); + assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); + } + + /// A line of `text` in `style` from `left` to `right` at `top`. + fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line { + Line { left, right, ..line(0, top, 11.0, bold, text) } + } + + #[test] + fn a_bold_word_inside_a_sentence_is_not_a_heading() { + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient", 72.0, 130.0), + run(726.0, true, "MUST", 133.0, 165.0), + run(726.0, false, "ignore the field.", 168.0, 400.0), + body(0, 712.0), + run(690.0, false, "2.3", 72.0, 88.0), + run(690.0, true, "Numbered title", 96.0, 180.0), + body(0, 670.0), + body(0, 656.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]); + } + + #[test] + fn a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is() { + let mut small = run(726.0, true, "MUST", 133.0, 163.0); + small.style.size = 10.0; + small.top = 725.2; + small.bottom = small.top - 8.0; + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient", 72.0, 130.0), + small, + run(726.0, false, "ignore the field.", 166.0, 400.0), + body(0, 712.0), + Line { left: 72.0, right: 110.0, ..line(0, 690.0, 14.0, true, "Scope") }, + run(688.8, false, "covers the rest of this page.", 113.0, 400.0), + body(0, 670.0), + body(0, 656.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Scope", 0)]); + } + + #[test] + fn text_beside_an_italic_word_still_sets_the_body_size() { + let italic = |top: f64| { + let mut l = run(top, false, "term", 252.0, 275.0); + l.style.italic = true; + l.style.font = "Helvetica-Oblique".into(); + l + }; + let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")]; + for top in [750.0, 736.0, 722.0, 708.0] { + lines.extend([ + run(top, false, "The first part of the row runs to", 72.0, 250.0), + italic(top), + run(top, false, "and the rest of it follows on.", 277.0, 400.0), + ]); + } + assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]); + } + + #[test] + fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() { + let lines = vec![ + // Its box overlaps the first body line's by 1.5 pt. + run(760.0, true, "Tight heading", 72.0, 180.0), + body(0, 752.7), + body(0, 740.0), + // A gutter of 9 pt, under an em: prose ends the left column on the heading's row. + run(700.0, false, "ends the left column here", 72.0, 291.0), + run(700.0, true, "Right column heading", 300.0, 520.0), + body(0, 686.0), + body(0, 672.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]); + } + + #[test] + fn captions_match_in_any_case() { + let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading"); + assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3")); + } + + #[test] + fn more_headings_than_the_cap_are_reported() { + // Each heading on a page of its own, with a line of body text under it. + let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::>(); + let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS)); + assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false)); + let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1)); + assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported"); + } + + /// A page past the page decode allowance (two compressed streams of spaces, each just over + /// half of it) can't be read: it doesn't count as read, and the suggestion says headings + /// may be missing. + #[test] + fn a_page_whose_text_cant_be_read_is_not_counted() { + let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]); + let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(), + stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"), + stream("/Filter /FlateDecode", &packed), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), + ]; + let s = suggest(&doc_of(&objs)); + assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); + } + + /// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog. + fn doc_of(objs: &[Vec]) -> Document { + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + Document::open(std::sync::Arc::new(bytes)).unwrap() + } + + /// More tagged headings than the structure reader returns: the suggestion says some are missing. + #[test] + fn tagged_headings_past_the_cap_are_reported() { + let tagged = |count: usize| { + let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect(); + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + format!("<< /S /Document /K [{kids}] >>").into_bytes(), + ]; + objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec())); + suggest(&doc_of(&objs)) + }; + let cap = pdfcraft_a11y::MAX_HEADINGS; + let at_cap = tagged(cap); + assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false)); + let over = tagged(cap + 1); + assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported"); + } + + /// A tagged heading too deep for the structure walk, on a page without text: layout finds + /// nothing either, and the suggestion still says a heading may be missing. The same page + /// untagged is not truncated. + #[test] + fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() { + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + ]; + objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes())); + objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec()); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped"); + objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false)); + } + + #[test] + fn the_tree_nests_by_level_and_caps_the_depth() { + let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; + let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")]; + let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false }; + let tree = s.tree(); + assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::>(), ["A", "B"]); + assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::>(), ["A.1", "A.2"]); + assert_eq!(tree[0].children[0].children[0].title, "A.1.a"); + assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None]))); + // A tagged H nested in 40 sections stops at the deepest level bookmark_import takes. + entries = (1..=40).map(|l| entry(l, "deep")).collect(); + let deep = OutlineSuggestion { entries, ..s }.tree(); + let mut depth = 0; + let mut at = &deep; + while let Some(n) = at.first() { + depth += 1; + at = &n.children; + } + assert_eq!(depth, MAX_DEPTH); + } +} From 6481545e4a46b30b8762c1c514c47d13c36ee278 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 23 Nov 2026 02:31:07 -0500 Subject: [PATCH 25/29] fix(engine): treat a bold word inside one run of prose as emphasis A producer may draw a sentence as one text run with a gap and paint the bold word into it. The prose box then spans the word instead of ending beside it, so the overlap limit rejected it and the word was suggested as a heading. Prose whose box spans the line on its row now counts as beside it; the row, size, style and lower-case conditions are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/suggest_outline.rs | 22 ++++++++++++++++++++-- parity/acrobat-features.toml | 4 ++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs index 47a12c3fe1..1f55536887 100644 --- a/crates/engine/src/suggest_outline.rs +++ b/crates/engine/src/suggest_outline.rs @@ -195,14 +195,16 @@ fn set_inline(lines: &[Line]) -> Vec { /// and tight leading makes stacked lines' boxes touch), side by side rather than one over the /// other, no smaller than `l`, in another style, at most [`BESIDE_GAP`] ems apart. A heading set /// beside text more than [`SIZE_TOLERANCE`] smaller is still a heading; a word set smaller than -/// the prose around it is not. +/// the prose around it is not. Prose whose box spans `l` on its row also counts: a producer may +/// set a sentence as one run with a gap, and paint the bold word into the gap. fn beside(l: &Line, o: &Line) -> bool { let size = l.style.size; let shared = l.top.min(o.top) - l.bottom.max(o.bottom); let shorter = (l.top - l.bottom).min(o.top - o.bottom); let gap = l.left.max(o.left) - l.right.min(o.right); + let spans = o.left <= l.left && l.right <= o.right; shared >= shorter * 0.5 - && gap >= -size * 0.25 + && (spans || gap >= -size * 0.25) && gap <= size * BESIDE_GAP && size <= o.style.size + SIZE_TOLERANCE && !o.style.matches(&l.style) @@ -337,6 +339,22 @@ mod tests { assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Scope", 0)]); } + #[test] + fn a_bold_word_painted_into_a_gap_in_one_run_of_prose_is_not_a_heading() { + let mut word = run(725.2, true, "MUST", 192.0, 219.0); + word.style.size = 10.0; + word.bottom = word.top - 8.0; + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient ignore the field.", 72.0, 400.0), + word, + body(0, 712.0), + body(0, 698.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0)]); + } + #[test] fn text_beside_an_italic_word_still_sets_the_body_size() { let italic = |top: f64| { diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 773550c15a..40a47cc26f 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -3442,8 +3442,8 @@ milestone = "M4" status = "partial" commands = [] tools = ["bookmark_suggest"] -evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::text_beside_an_italic_word_still_sets_the_body_size", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] -notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) and bold words inside a sentence (prose in another style, no smaller than them, right beside them on the row) are left out, which also leaves out a run-in heading set on the same line as its paragraph, a side head no larger than the body text half an em beside it, a heading after a label with lower-case letters in another style (Appendix, then A Title in bold), and a wrapped heading any of whose lines has prose beside it. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" +evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is", "crates/engine/src/suggest_outline.rs::a_bold_word_painted_into_a_gap_in_one_run_of_prose_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::text_beside_an_italic_word_still_sets_the_body_size", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"] +notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) and bold words inside a sentence (prose in another style, no smaller than them, right beside them on the row or in one run spanning them) are left out, which also leaves out a run-in heading set on the same line as its paragraph, a side head no larger than the body text half an em beside it, a heading after a label with lower-case letters in another style (Appendix, then A Title in bold), a wrapped heading any of whose lines has prose beside it, and a heading drawn inside the box of a wider run of prose on its row. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it" [[feature]] id = "organize.bookmarks-import-export" From 3ee649eeeae01f14fb5b1f2dfea117e0ac219b55 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 23 Nov 2026 04:47:36 -0500 Subject: [PATCH 26/29] fix(a11y): report headings whose title the allowance turned away When the title-source allowance declined a heading's only title string, the heading was dropped as if it had no text and `truncated` stayed false. Note the decline per heading and report it in the truncation flag when no other title is found. The allowance and the walk are unchanged; a heading that falls back to another title is kept and not reported. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/headings.rs | 16 +++++++++++++--- crates/a11y/src/tests.rs | 22 +++++++++++++++++++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/a11y/src/headings.rs b/crates/a11y/src/headings.rs index 88932522e3..933597ee55 100644 --- a/crates/a11y/src/headings.rs +++ b/crates/a11y/src/headings.rs @@ -40,8 +40,10 @@ struct Walker<'a> { texts: HashMap>, /// What is left of [`MAX_TITLE_SOURCE_BYTES`]. title_left: usize, + /// [`Walker::attr`] declined a string the allowance could not hold, since the last reset. + declined: bool, out: Vec, - /// A limit stopped the walk where a heading could have been. + /// A limit left out a heading that could have been found. cut: bool, /// [`MAX_HEADINGS`] were found and one more was met: the walk stops. full: bool, @@ -58,7 +60,8 @@ pub fn headings(doc: &Document) -> Vec { } /// [`headings`], and whether headings may be missing from it: there were more than -/// [`MAX_HEADINGS`], or the structure tree nests or branches past the walk's limits. +/// [`MAX_HEADINGS`], the structure tree nests or branches past the walk's limits, or a heading's +/// only title source was past the title allowance. pub fn headings_with_truncation(doc: &Document) -> (Vec, bool) { let Some(root) = tree_root(doc) else { return (Vec::new(), false) }; let pages = pdfcraft_model::pages(doc); @@ -71,6 +74,7 @@ pub fn headings_with_truncation(doc: &Document) -> (Vec, bool) { visits: 0, texts: HashMap::new(), title_left: MAX_TITLE_SOURCE_BYTES, + declined: false, out: Vec::new(), cut: false, full: false, @@ -162,6 +166,7 @@ impl Walker<'_> { self.marks(kids, pg, depth + 1, &mut marks); } let Some(page) = pg.or_else(|| marks.iter().find_map(|m| m.0)).and_then(|p| self.page_index.get(&p).copied()) else { return }; + self.declined = false; let title = match self.attr(d, b"ActualText") { Some(t) => Some(t), None => match self.marked_text(&marks, page) { @@ -169,7 +174,11 @@ impl Walker<'_> { None => self.attr(d, b"Alt").or_else(|| self.attr(d, b"T")), }, }; - let Some(title) = title else { return }; + let Some(title) = title else { + // A title the allowance turned away is a heading left out, not one without text. + self.cut |= self.declined; + return; + }; let title: String = title.split_whitespace().collect::>().join(" ").chars().take(MAX_TITLE).collect(); self.out.push(Heading { obj, level, title, page }); } @@ -183,6 +192,7 @@ impl Walker<'_> { // not fit the remaining allowance is never decoded: the raw check alone let a string at // the raw limit decode to three times it before the allowance was reduced. if s.bytes.len().saturating_mul(3) > self.title_left { + self.declined = true; return None; } let text = s.to_text(); diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index 7ae2d2d6ba..d9f1e96653 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -1680,8 +1680,28 @@ fn headings_naming_one_large_string_stop_decoding_it_at_the_allowance() { format!("({})", "a".repeat(512 << 10)), ]; objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R >>".to_string())); - let found = headings(&pdf(&objects, "")); + let (found, cut) = headings_with_truncation(&pdf(&objects, "")); assert!(!found.is_empty() && found.len() < count, "{}", found.len()); + assert!(cut, "headings whose title the allowance turned away were dropped unreported"); +} + +/// A title source too large for the allowance is passed over for the next one, and the heading +/// it names is kept and not reported as missing. +#[test] +fn a_title_too_large_for_the_allowance_falls_back_without_truncation() { + let objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >>".to_string(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(), + stream("BT ET"), + "<< /Type /StructTreeRoot /K 6 0 R >>".to_string(), + "<< /S /Document /P 5 0 R /K [8 0 R] >>".to_string(), + format!("({})", "a".repeat((32 << 20) / 3 + 1)), + "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R /Alt (Short) >>".to_string(), + ]; + let (found, cut) = headings_with_truncation(&pdf(&objects, "")); + let titles: Vec = found.into_iter().map(|h| h.title).collect(); + assert_eq!((titles, cut), (vec!["Short".to_string()], false)); } /// A tree of `count` H1 elements, each with its text and page. From b2d5085dc5d176514a729bc52edf9b257ac4c7f0 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 23 Nov 2026 05:31:25 -0500 Subject: [PATCH 27/29] fix(a11y): bound running-text extents by every glyph, not the run's ends Negative character spacing can pull a string's advance back to zero while its glyphs still travel far along the line, so taking the extent at the origin and the advance alone let turned body text starting in the header band look like running text. The extent now spans the lowest and highest point any glyph or the advance reaches. A non-finite spacing leaves the extent unknown instead of being dropped by min/max, and text in a vertical font leaves it unknown even when invisible, since it still moves the text down the page. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag_roles.rs | 64 +++++++++++++++++++++++++------- crates/a11y/src/tests.rs | 26 +++++++++++++ 2 files changed, 76 insertions(+), 14 deletions(-) diff --git a/crates/a11y/src/autotag_roles.rs b/crates/a11y/src/autotag_roles.rs index cd974c8369..516726f45d 100644 --- a/crates/a11y/src/autotag_roles.rs +++ b/crates/a11y/src/autotag_roles.rs @@ -167,14 +167,16 @@ struct Shown { impl Shown { fn show(&mut self, state: &State, bytes: &[u8]) { + // A vertical font's glyphs advance down the page, invisible or not, so the text after + // them is placed where the extents do not follow. + self.unbounded |= state.vertical; let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else { self.unbounded |= state.metrics.is_none(); return; }; - // Codes without a Unicode mapping still paint glyphs, and a vertical font's glyphs - // advance down the page: either way the text's extent is not known. + // Codes without a Unicode mapping still paint glyphs: the text's extent is not known. let unmapped = metrics.codes(bytes).iter().any(|&(code, _)| metrics.text_of(code).is_none()); - self.unbounded |= state.vertical || unmapped; + self.unbounded |= unmapped; let text = metrics.decode(bytes); let chars = text.chars().filter(|c| !c.is_whitespace()).count(); if chars == 0 { @@ -194,10 +196,10 @@ impl Shown { return; } self.keep(&text); - let (run, declared) = advance(state, metrics, bytes); - self.unbounded |= !declared; + let run = advance(state, metrics, bytes); + self.unbounded |= !run.declared; let (low, high) = (state.rise, state.rise + state.size); - for along in [0.0, run] { + for along in run.span { let (x, y) = (e + along * a, f + along * b); self.reach(x + low * c, y + low * d); self.reach(x + high * c, y + high * d); @@ -247,15 +249,31 @@ impl Shown { } } -/// The text width `bytes` advances by, in unscaled text space (§9.4.4), and whether the font -/// declares every glyph's width. -fn advance(state: &State, metrics: &Metrics, bytes: &[u8]) -> (f64, bool) { +/// How far a string's glyphs move and reach along the text line, in unscaled text space (§9.4.4). +struct Run { + /// The advance past the string. + width: f64, + /// The lowest and highest points any glyph or the advance reaches: negative spacing can + /// pull glyphs back over each other, so the ends of the run alone do not bound them. + /// Non-finite when the spacing or size is. + span: [f64; 2], + /// Whether the font declares every glyph's width. + declared: bool, +} + +fn advance(state: &State, metrics: &Metrics, bytes: &[u8]) -> Run { let [char_spacing, word_spacing, scale] = state.spacing; - let (width, declared) = metrics.codes(bytes).into_iter().fold((0.0, true), |(sum, declared), (code, len)| { + let (mut at, mut low, mut high, mut declared) = (0.0f64, 0.0f64, 0.0f64, true); + for (code, len) in metrics.codes(bytes) { + let glyph = metrics.width(code) * state.size; + (low, high) = (low.min(at).min(at + glyph), high.max(at).max(at + glyph)); let word = if metrics.is_space(code, len) { word_spacing } else { 0.0 }; - (sum + metrics.width(code) * state.size + char_spacing + word, declared && metrics.width_declared(code)) - }); - (width * scale, declared) + at += glyph + char_spacing + word; + declared &= metrics.width_declared(code); + } + // `min` and `max` drop a NaN, but once `at` is not finite it stays so: pass it on instead. + let span = if at.is_finite() { [low.min(at), high.max(at)] } else { [at, at] }; + Run { width: at * scale, span: span.map(|v| v * scale), declared } } /// Whether `font` writes vertically: a Type 0 font whose `/Encoding` is a predefined CMap name @@ -278,7 +296,7 @@ fn show(state: &mut State, object: Option<&mut Shown>, bytes: &[u8]) { if let Some(o) = object { o.show(state, bytes); } - let moved = state.metrics.as_ref().map_or(0.0, |m| advance(state, m, bytes).0); + let moved = state.metrics.as_ref().map_or(0.0, |m| advance(state, m, bytes).width); state.tm = Matrix::translate(moved, 0.0).then(&state.tm); } @@ -611,6 +629,24 @@ mod tests { assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 96.0, 772.0]), "mapped Type 0 text keeps its extent"); } + #[test] + fn text_after_invisible_vertical_text_has_no_extent() { + // The invisible glyph moves the text 360 units down the page before "Body" is shown. + let found = walk_type0(b"BT /V 360 Tf 3 Tr 72 760 Td <0041> Tj /F1 12 Tf 0 Tr (Body) Tj ET BT /F1 12 Tf 72 760 Td (Body) Tj ET"); + assert_eq!((found[0].text.as_str(), found[0].extent), ("Body", None)); + assert!(found[1].extent.is_some()); + } + + #[test] + fn spacing_past_f64_leaves_no_extent() { + // Tc and Tw near f64::MAX each overflow to infinity and cancel to NaN on the first space. + let big = format!("1.0e{}", 999); + let found = + walk(format!("BT /F1 10 Tf {big} Tc -{big} Tw 72 760 Td ( Body) Tj ET BT /F1 10 Tf 0 Tc 0 Tw 72 760 Td ( Body) Tj ET").as_bytes()); + assert_eq!((found[0].text.as_str(), found[0].extent), (" Body", None)); + assert!(found[1].extent.is_some()); + } + #[test] fn text_in_a_vertical_font_has_no_extent() { // Thirty glyphs at 12 run 360 units down the page in a vertical font, not along x. diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index bc91fa8407..02aed586c5 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -226,6 +226,32 @@ fn autotag_text_leaves_turned_text_that_runs_out_of_the_band_tagged() { assert_eq!(running_text(&doc).unwrap(), []); } +/// Turned body text whose negative character spacing brings each line's advance back to zero +/// still has glyphs running down the page from the header band: it is not running text. +#[test] +fn autotag_text_leaves_turned_text_pulled_back_by_negative_spacing_tagged() { + // A is 12 units wide and advances 6 at Tc -6; B is 0 wide and advances -6. Thirty of each + // end where they began, but the A glyphs reach 186 units down from y 760. + let body = format!("BT /F1 12 Tf -6 Tc 0 -1 1 0 72 760 Tm ({}{}) Tj ET", "A".repeat(30), "B".repeat(30)); + let font = "<< /Type /Font /Subtype /Type1 /BaseFont /HouseFont /FirstChar 65 /LastChar 66 /Widths [1000 0] >>"; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + stream(&body), + stream(&body), + font.into(), + ], + "", + ); + assert_eq!(running_text(&doc).unwrap(), []); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 2)); +} + #[test] fn autotag_text_leaves_a_single_page_header_tagged() { let mut doc = pdf( From e99a8130ccf43cbd97115a2445353fe3cec0e506 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 23 Nov 2026 06:51:24 -0500 Subject: [PATCH 28/29] fix(a11y): mark every qualifying span of running-text heights A chosen window split the rest into the runs either side of it, so a second window sharing a copy with the first lost that copy and fell below the page count. One sliding pass now keeps every window that covers enough pages, joining windows that share a copy into one cluster; the cluster cap and the heading-sequence check are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag_running.rs | 95 ++++++++++++++++-------------- 1 file changed, 52 insertions(+), 43 deletions(-) diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs index 67d0d844a3..2caf490670 100644 --- a/crates/a11y/src/autotag_running.rs +++ b/crates/a11y/src/autotag_running.rs @@ -7,7 +7,8 @@ //! page numbers repeat. 40% lets alternating left- and right-page headers qualify. A group whose //! text changes from page to page and is all heading-sized (`Chapter 1`, `Chapter 2`) is a //! sequence of headings, not running text, unless it reads as a page number (`Page 3`, `3 of 9`). -//! Each separate cluster of heights that qualifies counts. Position alone never makes running text. +//! Every object in some qualifying span of distances counts, so spans that overlap and spans that +//! lie apart are each marked. Position alone never makes running text. //! A text object whose extent is not known (see [`Evidence::extent`]) is never running text. use std::collections::HashMap; @@ -18,7 +19,7 @@ use crate::autotag_roles::{Evidence, HEADING_SIZE_RATIO, MAX_KEPT_CHARS}; const BAND: f64 = 0.15; /// How far, in user-space units, the same running text may move from page to page. const TOLERANCE: f64 = 4.0; -/// Height clusters kept per group of the same text, so the search stays linear in its size. +/// Height clusters marked per group of the same text; copies at further heights stay content. const MAX_CLUSTERS: usize = 8; /// The page edge running text repeats at. @@ -67,25 +68,13 @@ pub(crate) fn find(pages: &[PageText<'_>], body: Option) -> Vec]> = vec![&members]; - let mut clusters = 0usize; - while let Some(run) = pending.pop().filter(|_| clusters < MAX_CLUSTERS) { - let (start, end, distinct) = best_window(run); - let (Some(before), Some(window), Some(after)) = (run.get(..start), run.get(start..end), run.get(end..)) else { - continue; - }; - if distinct < needed || window.is_empty() { + for cluster in clusters(&members, needed) { + if is_heading_sequence(cluster, &key, body) { continue; } - pending.extend([before, after]); - clusters = clusters.saturating_add(1); - if !is_heading_sequence(window, &key, body) { - for m in window { - if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) { - *slot = Some(edge); - } + for m in cluster { + if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) { + *slot = Some(edge); } } } @@ -142,36 +131,46 @@ fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec]) -> (usize, usize, usize) { +/// The clusters of `members` (sorted by distance) that run: the union of every window of members +/// within [`TOLERANCE`] of the window's first that covers at least `needed` pages, with windows that +/// share a member joined into one cluster. At most [`MAX_CLUSTERS`] are returned, nearest the edge +/// first. +fn clusters<'m, 'a>(members: &'m [Member<'a>], needed: usize) -> Vec<&'m [Member<'a>]> { let mut on_page: HashMap = HashMap::new(); - let (mut low, mut best, mut most) = (0usize, (0usize, 0usize), 0usize); - for (high, member) in members.iter().enumerate() { - let n = on_page.entry(member.page).or_default(); - *n = n.saturating_add(1); - while let Some(first) = members.get(low).filter(|m| member.distance - m.distance > TOLERANCE) { - if let Some(n) = on_page.get_mut(&first.page) { - *n = n.saturating_sub(1); - if *n == 0 { - on_page.remove(&first.page); + let mut found: Vec<&'m [Member<'a>]> = Vec::new(); + let mut current: Option<(usize, usize)> = None; + let mut end = 0usize; + for (start, first) in members.iter().enumerate() { + while let Some(next) = members.get(end).filter(|m| m.distance - first.distance <= TOLERANCE) { + let n = on_page.entry(next.page).or_default(); + *n = n.saturating_add(1); + end = end.saturating_add(1); + } + if on_page.len() >= needed { + current = match current { + Some((from, to)) if start < to => Some((from, to.max(end))), + done => { + if let Some(cluster) = done.and_then(|(from, to)| members.get(from..to)) { + found.push(cluster); + } + if found.len() >= MAX_CLUSTERS { + return found; + } + Some((start, end)) } + }; + } + if let Some(n) = on_page.get_mut(&first.page) { + *n = n.saturating_sub(1); + if *n == 0 { + on_page.remove(&first.page); } - low = low.saturating_add(1); - } - if on_page.len() > most { - (most, best) = (on_page.len(), (low, high.saturating_add(1))); } } - let (start, mut end) = best; - while let (Some(first), Some(next)) = (members.get(start), members.get(end)) { - if next.distance - first.distance > TOLERANCE { - break; - } - end = end.saturating_add(1); + if let Some(cluster) = current.and_then(|(from, to)| members.get(from..to)) { + found.push(cluster); } - (start, end, most) + found } /// The bottom and top of a user-space box as the page displays it. @@ -359,6 +358,16 @@ mod tests { assert_eq!(marked, 16, "8 clusters on 2 pages: {found:?}"); } + #[test] + fn overlapping_qualifying_spans_of_heights_both_count() { + // Six pages need three: "Note" 20 units below the top on two pages, 24 on one and 28 on + // two. 20..24 and 24..28 each cover three pages and share the copy at 24. + let at = |distance: f64| line("Note", 792.0 - 10.0 - distance); + let pages = vec![vec![at(20.0)], vec![at(20.0)], vec![at(24.0)], vec![at(28.0)], vec![at(28.0)], Vec::new()]; + let found = run(&pages, None); + assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}"); + } + #[test] fn heading_sized_text_that_changes_is_a_heading_not_a_header() { let big = |text: &str| Evidence { size: 20.0, ..line(text, 750.0) }; From 4cdc28869472b1dccca942ebbce183756bbd616a Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 23 Nov 2026 06:57:18 -0500 Subject: [PATCH 29/29] test(a11y): count the marked copies; say joined clusters may widen Co-Authored-By: Claude Opus 5.5 --- crates/a11y/src/autotag_running.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs index 2caf490670..91de5cff02 100644 --- a/crates/a11y/src/autotag_running.rs +++ b/crates/a11y/src/autotag_running.rs @@ -133,8 +133,9 @@ fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec(members: &'m [Member<'a>], needed: usize) -> Vec<&'m [Member<'a>]> { let mut on_page: HashMap = HashMap::new(); let mut found: Vec<&'m [Member<'a>]> = Vec::new(); @@ -365,7 +366,7 @@ mod tests { let at = |distance: f64| line("Note", 792.0 - 10.0 - distance); let pages = vec![vec![at(20.0)], vec![at(20.0)], vec![at(24.0)], vec![at(28.0)], vec![at(28.0)], Vec::new()]; let found = run(&pages, None); - assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}"); + assert_eq!(found.iter().flatten().filter(|e| **e == Some(Edge::Top)).count(), 5, "{found:?}"); } #[test]