mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-02 20:20:35 -05:00
Merge pull request #7818 from KenM76/feat/suggest-outline
feat(bookmarks): suggest an outline for review (#6020)
This commit is contained in:
15 files changed
+952
-39
No files matched your search
@@ -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<Option<u8>> {
|
||||
let evidence: Vec<Evidence> =
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -39,7 +40,13 @@ struct Walker<'a> {
|
||||
texts: HashMap<usize, HashMap<i64, String>>,
|
||||
/// 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<Heading>,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// Bytes of `/ActualText`, `/Alt` and `/T` strings the headings of one document decode in all.
|
||||
@@ -49,7 +56,14 @@ 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<Heading> {
|
||||
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`], 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<Heading>, bool) {
|
||||
let Some(root) = tree_root(doc) else { return (Vec::new(), false) };
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
let mut w = Walker {
|
||||
doc,
|
||||
@@ -60,19 +74,27 @@ pub fn headings(doc: &Document) -> Vec<Heading> {
|
||||
visits: 0,
|
||||
texts: HashMap::new(),
|
||||
title_left: MAX_TITLE_SOURCE_BYTES,
|
||||
declined: false,
|
||||
out: Vec::new(),
|
||||
cut: false,
|
||||
full: 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).
|
||||
/// 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;
|
||||
depth <= MAX_DEPTH && self.visits <= MAX_VISITS && self.out.len() < MAX_HEADINGS && !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<ObjRef>, Dict)> {
|
||||
@@ -101,6 +123,11 @@ impl Walker<'_> {
|
||||
_ => None,
|
||||
};
|
||||
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);
|
||||
return;
|
||||
}
|
||||
@@ -139,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) {
|
||||
@@ -146,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::<Vec<_>>().join(" ").chars().take(MAX_TITLE).collect();
|
||||
self.out.push(Heading { obj, level, title, page });
|
||||
}
|
||||
@@ -160,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();
|
||||
|
||||
@@ -18,6 +18,7 @@ mod autotag_fields;
|
||||
mod autotag_roles;
|
||||
mod autotag_running;
|
||||
mod content;
|
||||
mod heading_levels;
|
||||
mod headings;
|
||||
mod layout_table;
|
||||
mod report;
|
||||
@@ -43,7 +44,8 @@ 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, RunningText, autotag_text, running_text};
|
||||
pub use autotag_fields::tag_form_fields;
|
||||
pub use headings::{Heading, headings};
|
||||
pub use heading_levels::{TextBlock, heading_levels};
|
||||
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};
|
||||
|
||||
@@ -1868,8 +1868,97 @@ 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<String> = 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.
|
||||
fn many_headings(count: usize) -> Vec<String> {
|
||||
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");
|
||||
}
|
||||
|
||||
/// 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<Heading>, 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::<Vec<_>>(), 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]
|
||||
|
||||
@@ -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<Value> {
|
||||
// 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::<Vec<_>>(),
|
||||
"headings": s.entries.len(),
|
||||
"pages": s.pages,
|
||||
"pages_read": s.pages_read,
|
||||
"truncated": s.truncated,
|
||||
});
|
||||
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<pdfcraft_engine::OutlineTree> {
|
||||
match self.session.outline_tree(id, path) {
|
||||
// The engine names the path 0-based; the caller gave it 1-based.
|
||||
|
||||
@@ -203,6 +203,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();
|
||||
|
||||
@@ -494,6 +494,13 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"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 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"])),
|
||||
t(
|
||||
"text_styles",
|
||||
"List text styles",
|
||||
|
||||
@@ -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;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! #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<u8> {
|
||||
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<u8> {
|
||||
let contents = [page1, page2];
|
||||
let mut objs: Vec<String> = 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<String>)> {
|
||||
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}");
|
||||
}
|
||||
|
||||
/// 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<String> = 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);
|
||||
}
|
||||
@@ -437,6 +437,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<crate::suggest_outline::OutlineSuggestion> {
|
||||
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<pdfcraft_edit::TextLine> {
|
||||
self.editor.as_ref().and_then(|e| pdfcraft_edit::text_lines(&e.cos, page).ok()).unwrap_or_default()
|
||||
|
||||
@@ -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).0)?;
|
||||
}
|
||||
Edit::BookmarksFromTextStyles { levels } => {
|
||||
if levels.is_empty() {
|
||||
|
||||
@@ -60,6 +60,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;
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
//! 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<OutlineEntry>,
|
||||
/// 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<OutlineNode> {
|
||||
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<OutlineNode> {
|
||||
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<OutlineEntry>, 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<Line>) -> Vec<Block> {
|
||||
let flags = set_inline(&lines);
|
||||
let mut out: Vec<Block> = 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<bool> {
|
||||
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. 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
|
||||
&& (spans || 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<Line>) -> (Vec<OutlineEntry>, bool) {
|
||||
let blocks: Vec<Block> = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect();
|
||||
let evidence: Vec<TextBlock> = blocks.iter().map(Block::evidence).collect();
|
||||
let mut entries: Vec<OutlineEntry> = 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 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| {
|
||||
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::<Vec<_>>();
|
||||
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<u8>> = 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<u8>]) -> 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::<Vec<_>>(), ["A", "B"]);
|
||||
assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::<Vec<_>>(), ["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);
|
||||
}
|
||||
}
|
||||
@@ -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)]
|
||||
@@ -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<f64>; 2],
|
||||
pub(crate) anchor: [Option<f64>; 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,13 +108,21 @@ 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<Line> {
|
||||
pub(crate) fn lines(doc: &Document) -> Vec<Line> {
|
||||
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<Line>, 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<Line> = found
|
||||
.into_iter()
|
||||
.filter_map(|l| {
|
||||
@@ -135,7 +155,7 @@ fn lines(doc: &Document) -> Vec<Line> {
|
||||
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
|
||||
@@ -183,22 +203,14 @@ pub fn styles(doc: &Document) -> Vec<TextStyleUse> {
|
||||
/// 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<OutlineEntry> {
|
||||
let mut entries: Vec<OutlineEntry> = 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 +229,7 @@ pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec<OutlineEntry> {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -3427,6 +3427,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::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"
|
||||
title = "Export, import and copy bookmarks"
|
||||
|
||||
Reference in new issue
Block a user