From 3a8fbb8c62bd56f6f29fced37f1040241d10a35a Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 16:44:45 -0500 Subject: [PATCH 01/10] 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 02/10] 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 03/10] 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 b758feda055c75646e42cd474377fc35ccb11462 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Wed, 18 Nov 2026 22:03:05 -0500 Subject: [PATCH 04/10] 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 67f6269142961b7d7222820e03298062aa02b4fd Mon Sep 17 00:00:00 2001 From: KenM76 Date: Sat, 21 Nov 2026 14:08:44 -0500 Subject: [PATCH 05/10] 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 06/10] 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 07/10] 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 08/10] 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 09/10] 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 10/10] 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.