Bookmarks from text styles open at the heading top on turned pages (#7443)

* Style bookmarks go to the displayed heading top on turned pages

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Read and join style-bookmark headings in displayed order on turned pages

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Read page rotations once per document for style bookmarks

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Test style bookmarks on cropped turned pages and after save and reopen

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Valentin KleinandClaude Sonnet 5.5 authored and GitHub committed 2026-11-18 00:24:31 -06:00
1 parent 7895411b03
commit c4e174675e
6 files changed
+207 -18

No files matched your search

+1 -1
View File
@@ -581,7 +581,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
Edit::BookmarksFromStructure => {
let entries: Vec<_> = pdfcraft_a11y::headings(doc)
.into_iter()
.map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, top: None })
.map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None })
.collect();
pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?;
}
+159
View File
@@ -2472,6 +2472,165 @@ fn headings_in_two_columns_are_two_bookmarks() {
assert_eq!(outline_titles(&s.get(id).unwrap().info.outline), ["Untitled→0[Left heading→1,Right heading→1]"]);
}
/// #7415: a heading's bookmark goes to the top of the heading as displayed. The same heading is
/// shown at the same place on four pages turned 0, 90, 180 and 270 degrees; on a quarter turn the
/// displayed top is a user-space x, so it is the destination's `left` and `top` stays unspecified.
#[test]
fn style_bookmarks_go_to_the_displayed_heading_top_on_turned_pages() {
// (rotation, media box, text matrix): each shows "Birch Survey" at 90 pt from the left and
// 130 pt (baseline) from the top of a 400 x 600 displayed page.
let pages = [
(0, "0 0 400 600", "1 0 0 1 90 470"),
(90, "0 0 600 400", "0 1 -1 0 130 90"),
(180, "0 0 400 600", "-1 0 0 -1 310 130"),
(270, "0 0 600 400", "0 -1 1 0 470 310"),
];
let mut pdf =
pdfcraft_testkit::Pdf::new().obj("<< /Type /Catalog /Pages 2 0 R >>").obj("<< /Type /Pages /Kids [3 0 R 5 0 R 7 0 R 9 0 R] /Count 4 >>");
for (i, (rotate, media, tm)) in pages.iter().enumerate() {
let content = format!("BT /F1 20 Tf {tm} Tm (Birch Survey) Tj ET");
pdf = pdf
.obj(format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [{media}] /Rotate {rotate} /Resources << /Font << /F1 11 0 R >> >> /Contents {} 0 R >>",
4 + 2 * i
))
.stream("", &content);
}
let bytes = pdf.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>").build();
let mut s = Session::new();
let id = s.open("turned.pdf", None, Arc::new(bytes), None).unwrap();
let style = s.get(id).unwrap().text_styles()[0].style.clone();
s.apply(id, Edit::BookmarksFromTextStyles { levels: vec![style] }).unwrap();
let doc = s.get(id).unwrap();
let kids = &doc.info.outline[0].children;
assert_eq!(kids.len(), 4);
// The displayed top of the heading, from the upright page.
let top_of_heading = {
let cos = pdfcraft_cos::Document::open(doc.bytes.clone()).unwrap();
let line = &pdfcraft_edit::text_lines(&cos, 0).unwrap()[0];
600.0 - line.rect[1].max(line.rect[3]) as f32
};
assert!((110.0..115.0).contains(&top_of_heading), "{top_of_heading}");
for (i, kid) in kids.iter().enumerate() {
let page = &doc.info.pages[i];
assert_eq!(page.rotation, pages[i].0);
let [want_left, want_top] = page.xyz_for_view(None, Some(top_of_heading));
match kid.view {
pdfcraft_render::DestView::Xyz { left, top, zoom: None } => {
let near = |got: Option<f32>, want: Option<f32>| match (got, want) {
(None, None) => true,
(Some(g), Some(w)) => (g - w).abs() < 1.0,
_ => false,
};
assert!(near(left, want_left) && near(top, want_top), "rotate {}: got {left:?} {top:?}, want {want_left:?} {want_top:?}", pages[i].0);
}
ref v => panic!("{v:?}"),
}
}
}
/// #7415: on a turned page the headings are read in displayed order (top to bottom), a heading
/// set on two lines is one bookmark, and each goes to the top of its first displayed line. One
/// layout (two headings and a two-line heading, written to the file out of order) on pages turned
/// 0, 90, 180 and 270 degrees must give the same bookmarks at the same displayed tops, with and
/// without a crop box whose origin is not the page's.
#[test]
fn style_bookmarks_read_and_join_headings_as_displayed_on_turned_pages() {
for cropped in [false, true] {
let (mut s, id) = turned_headings_session(cropped);
let style = s.get(id).unwrap().text_styles()[0].style.clone();
s.apply(id, Edit::BookmarksFromTextStyles { levels: vec![style] }).unwrap();
check_turned_headings(&s, id, cropped);
// The destinations survive a save and reopen (`/XYZ left null` on the quarter turns).
let bytes = s.save_bytes(id).unwrap();
let mut s2 = Session::new();
let id2 = s2.open("saved.pdf", None, bytes, None).unwrap();
check_turned_headings(&s2, id2, cropped);
}
}
/// A document of four pages turned 0, 90, 180 and 270, each showing the same three headings at the
/// same displayed places on a displayed page of 400 x 600 (or 600 x 600 with `cropped`, where
/// the crop box does not start at the page's origin), written in an order that is not reading order.
fn turned_headings_session(cropped: bool) -> (Session, DocId) {
// Displayed baselines (x, y from the top).
let lines = [("Gamma Three", 50.0, 450.0), ("Beta Cont", 50.0, 274.0), ("Alpha One", 50.0, 100.0), ("Beta Two", 50.0, 250.0)];
// (rotation, page boxes, text matrix prefix, user position of a displayed (x, y)).
type Place = fn(f64, f64) -> (f64, f64);
let plain: [(i32, &str, &str, Place); 4] = [
(0, "/MediaBox [0 0 400 600]", "1 0 0 1", |x, y| (x, 600.0 - y)),
(90, "/MediaBox [0 0 600 400]", "0 1 -1 0", |x, y| (y, x)),
(180, "/MediaBox [0 0 400 600]", "-1 0 0 -1", |x, y| (400.0 - x, y)),
(270, "/MediaBox [0 0 600 400]", "0 -1 1 0", |x, y| (600.0 - y, 400.0 - x)),
];
let boxes = "/MediaBox [0 0 700 700] /CropBox [50 40 650 640]";
let crop: [(i32, &str, &str, Place); 4] = [
(0, boxes, "1 0 0 1", |x, y| (50.0 + x, 640.0 - y)),
(90, boxes, "0 1 -1 0", |x, y| (50.0 + y, 40.0 + x)),
(180, boxes, "-1 0 0 -1", |x, y| (650.0 - x, 40.0 + y)),
(270, boxes, "0 -1 1 0", |x, y| (650.0 - y, 640.0 - x)),
];
let mut pdf =
pdfcraft_testkit::Pdf::new().obj("<< /Type /Catalog /Pages 2 0 R >>").obj("<< /Type /Pages /Kids [3 0 R 5 0 R 7 0 R 9 0 R] /Count 4 >>");
for (i, (rotate, boxes, prefix, place)) in (if cropped { crop } else { plain }).iter().enumerate() {
let content: String = lines
.iter()
.map(|(text, x, y)| {
let (ux, uy) = place(*x, *y);
format!("BT /F1 20 Tf {prefix} {ux} {uy} Tm ({text}) Tj ET\n")
})
.collect();
pdf = pdf
.obj(format!(
"<< /Type /Page /Parent 2 0 R {boxes} /Rotate {rotate} /Resources << /Font << /F1 11 0 R >> >> /Contents {} 0 R >>",
4 + 2 * i
))
.stream("", &content);
}
let bytes = pdf.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>").build();
let mut s = Session::new();
let id = s.open("turned.pdf", None, Arc::new(bytes), None).unwrap();
(s, id)
}
/// The bookmarks of [`turned_headings_session`] after "from text styles": displayed order, the
/// two-line heading joined, each at the displayed top of its first line.
fn check_turned_headings(s: &Session, id: DocId, cropped: bool) {
let doc = s.get(id).unwrap();
let kids = &doc.info.outline[0].children;
let titles: Vec<_> = kids.iter().map(|k| k.title.as_str()).collect();
let per_page = ["Alpha One", "Beta Two Beta Cont", "Gamma Three"];
assert_eq!(titles, per_page.repeat(4), "displayed order, the two-line heading joined (cropped: {cropped})");
// The displayed tops of the three headings, from the text of the upright page.
let cos = pdfcraft_cos::Document::open(doc.bytes.clone()).unwrap();
let upright = &doc.info.pages[0];
let mut found: Vec<_> =
pdfcraft_edit::text_lines(&cos, 0).unwrap().into_iter().map(|l| upright.user_to_view(0.0, l.rect[3].max(l.rect[1]) as f32)[1]).collect();
found.sort_by(f32::total_cmp);
// Alpha, Beta Two (the upper line of its heading), Gamma: three of the four lines.
let tops = [found[0], found[1], found[3]];
for (i, kid) in kids.iter().enumerate() {
let (page, n) = (&doc.info.pages[i / 3], i % 3);
let [want_left, want_top] = page.xyz_for_view(None, Some(tops[n]));
let near = |got: Option<f32>, want: Option<f32>| match (got, want) {
(None, None) => true,
(Some(g), Some(w)) => (g - w).abs() < 1.0,
_ => false,
};
match kid.view {
pdfcraft_render::DestView::Xyz { left, top, .. } => {
assert!(
near(left, want_left) && near(top, want_top),
"rotate {} {} (cropped: {cropped}): got {left:?} {top:?}, want {want_left:?} {want_top:?}",
page.rotation,
kid.title
)
}
ref v => panic!("{v:?}"),
}
}
}
/// `style` at another size.
fn pdfcraft_engine_style(style: &text_style_bookmarks::TextStyle, size: f64) -> text_style_bookmarks::TextStyle {
text_style_bookmarks::TextStyle { size, ..style.clone() }
+31 -13
View File
@@ -60,11 +60,30 @@ struct Line {
page: usize,
text: String,
style: TextStyle,
/// Top, bottom, left and right of its box in user space.
/// Top, bottom, left and right of its box as displayed (after the page's `/Rotate`, y up), so
/// reading order and the join of a heading's lines are right on a turned page. Only
/// differences between these values are used: they are offset from points on the page.
top: f64,
bottom: f64,
left: f64,
right: f64,
/// The `/XYZ` position `[left, top]` (user space) that puts the top of the line as displayed
/// at the top of the window. The box edge displayed on top depends on the rotation: the top
/// edge, the left edge (90), the bottom edge (180) or the right edge (270). On a page turned
/// a quarter it is a user-space x, so it is `left`, and `top` stays unspecified.
anchor: [Option<f64>; 2],
}
/// A box in user space `[x0, y0, x1, y1]` on a page turned `rotation` degrees clockwise → its
/// displayed top, bottom, left and right (y up), and the `/XYZ` anchor of its displayed top.
fn displayed(rotation: i64, [x0, y0, x1, y1]: [f64; 4]) -> ([f64; 4], [Option<f64>; 2]) {
let (xl, xh, yl, yh) = (x0.min(x1), x0.max(x1), y0.min(y1), y0.max(y1));
match rotation {
90 => ([-xl, -xh, yl, yh], [Some(xl), None]),
180 => ([-yl, -yh, -xh, -xl], [None, Some(yl)]),
270 => ([xh, xl, -yh, -yl], [Some(xh), None]),
_ => ([yh, yl, xl, xh], [None, Some(yh)]),
}
}
/// `name` without a subset tag: six capital letters and a `+` (ISO 32000-2 §9.9.2).
@@ -79,8 +98,10 @@ fn without_subset_tag(name: &str) -> &str {
/// is only whitespace, or whose size can't be read, is left out.
fn lines(doc: &Document) -> Vec<Line> {
let pages = pdfcraft_organize::page_count(doc).unwrap_or(0).min(MAX_PAGES);
let rotations = pdfcraft_organize::page_rotations(doc).unwrap_or_default();
let mut out = Vec::new();
for page in 0..pages {
let rotation = rotations.get(page).copied().unwrap_or(0);
let Ok(found) = pdfcraft_edit::text_lines(doc, page) else { continue };
let mut on_page: Vec<Line> = found
.into_iter()
@@ -91,6 +112,7 @@ fn lines(doc: &Document) -> Vec<Line> {
let size = l.size;
let [x0, y0, x1, y1] = l.rect;
let ok = !text.is_empty() && size.is_finite() && size > 0.0 && [x0, y0, x1, y1].iter().all(|v| v.is_finite());
let ([top, bottom, left, right], anchor) = displayed(rotation, l.rect);
ok.then(|| Line {
page,
text,
@@ -100,10 +122,11 @@ fn lines(doc: &Document) -> Vec<Line> {
bold: l.bold,
italic: l.italic,
},
top: y0.max(y1),
bottom: y0.min(y1),
left: x0.min(x1),
right: x0.max(x1),
top,
bottom,
left,
right,
anchor,
})
})
.collect();
@@ -157,7 +180,7 @@ pub fn styles(doc: &Document) -> Vec<TextStyleUse> {
/// The bookmarks for the lines in `levels`' styles: a line in `levels[0]`'s style is a level-1
/// bookmark, `levels[1]`'s a level-2 one under the level-1 bookmark before it, and so on. A
/// heading set on several lines (one after another in the same style, close below each other)
/// is one bookmark. Each goes to the top of its heading.
/// is one bookmark. Each goes to the top of its heading as displayed, also on a turned page.
pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec<OutlineEntry> {
let mut entries: Vec<OutlineEntry> = Vec::new();
// The heading the previous line belonged to: its level, and the top, bottom, left and right
@@ -191,13 +214,8 @@ pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec<OutlineEntry> {
// The level counts from 1; the position in `levels` is at most its length, which a
// caller keeps small (a few levels), so it fits a u8.
let level = u8::try_from(level.saturating_add(1)).unwrap_or(u8::MAX);
entries.push(OutlineEntry {
level,
title: line.text.chars().take(MAX_TITLE_CHARS).collect(),
page: line.page,
element: None,
top: Some(line.top),
});
let [left, top] = line.anchor;
entries.push(OutlineEntry { level, title: line.text.chars().take(MAX_TITLE_CHARS).collect(), page: line.page, element: None, left, top });
}
open = Some((level, line.top, line.bottom, line.left, line.right));
}
+6
View File
@@ -160,6 +160,12 @@ pub fn page_rotation(doc: &Document, index: usize) -> Result<i64, OrganizeError>
Ok(resolved_rotation(doc, attrs).rem_euclid(360))
}
/// Effective inherited rotation of every leaf page, clockwise in degrees, from one walk of the
/// page tree (what [`page_rotation`] gives per page).
pub fn page_rotations(doc: &Document) -> Result<Vec<i64>, OrganizeError> {
Ok(walk(doc)?.iter().map(|(_, attrs)| resolved_rotation(doc, attrs).rem_euclid(360)).collect())
}
pub fn page_count(doc: &Document) -> Result<usize, OrganizeError> {
Ok(walk(doc)?.len())
}
+7 -3
View File
@@ -584,8 +584,12 @@ pub struct OutlineEntry {
pub page: usize,
/// The structure element it stands for (`/SE`).
pub element: Option<ObjRef>,
/// Where on the page it goes: this height (user space) at the top of the window, at the
/// reader's zoom. `None` goes to the page, keeping the reader's position.
/// Where on the page it goes: this x (user space) at the left of the window, at the reader's
/// zoom. `None` keeps the reader's horizontal position.
pub left: Option<f64>,
/// This height (user space) at the top of the window. `None` keeps the reader's vertical
/// position. A bookmark to the top of what is displayed on a page turned a quarter gives
/// `left`, not `top`.
pub top: Option<f64>,
}
@@ -610,7 +614,7 @@ pub fn add_bookmark_tree(doc: &mut Document, parent_title: &str, entries: &[Outl
for (e, page) in entries.iter().zip(targets) {
let mut d = Dict::new();
d.set(b"Title".to_vec(), Object::String(PdfString::text(&e.title)));
d.set(b"Dest".to_vec(), go_to_at(page, None, e.top));
d.set(b"Dest".to_vec(), go_to_at(page, e.left, e.top));
if let Some(se) = e.element {
d.set(b"SE".to_vec(), Object::Ref(se));
}
+3 -1
View File
@@ -14,6 +14,8 @@ fn page_rotation_resolves_inheritance_overrides_and_missing_pages() {
assert_eq!(page_rotation(&doc, 1).unwrap(), 270);
assert_eq!(page_rotation(&doc, 0).unwrap(), 90);
assert_eq!(page_rotation(&doc, 3), Err(OrganizeError::NoSuchPage(3)));
// One walk gives each page's rotation, as the per-page call does.
assert_eq!(crate::page_rotations(&doc).unwrap(), [90, 270, 90]);
}
#[test]
@@ -2000,7 +2002,7 @@ fn bookmarks_add_rename_move_delete() {
fn a_bookmark_tree_nests_entries_by_level_under_a_new_first_bookmark() {
let mut d = doc_a();
crate::add_bookmark(&mut d, &[], 0, "Existing", 0).unwrap();
let e = |level, title: &str, page, element| crate::OutlineEntry { level, title: title.into(), page, element, top: None };
let e = |level, title: &str, page, element| crate::OutlineEntry { level, title: title.into(), page, element, left: None, top: None };
let se = ObjRef::new(4242, 0);
let entries = [e(1, "One", 0, Some(se)), e(3, "Deep", 1, None), e(2, "Two", 1, None), e(1, "Next", 2, None)];
assert_eq!(crate::add_bookmark_tree(&mut d, "Untitled", &entries).unwrap(), vec![0]);