Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(annot): extend each page's annotation list once when adding many links

aionggc2e96de0b240
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs
index 61dd5ff1c..d1d74ce41 100644
--- a/crates/annot/src/lib.rs
+++ b/crates/annot/src/lib.rs
@@ -728,7 +728,16 @@ fn page_ref(doc: &Document, page: usize) -> Result<ObjRef, AnnotError> {
fn annots(doc: &Document, page: ObjRef) -> Vec<Object> {
let obj = doc.get(page);
let Some(a) = obj.as_dict().and_then(|d| d.get(b"Annots")) else { return Vec::new() };
- doc.resolve(a).as_array().cloned().unwrap_or_default()
+ let list = doc.resolve(a).as_array().cloned().unwrap_or_default();
+ #[cfg(test)]
+ ANNOTS_ENTRIES_COPIED.with(|n| n.set(n.get() + list.len()));
+ list
+}
+
+#[cfg(test)]
+thread_local! {
+ /// Entries copied out of pages' `/Annots` arrays.
+ static ANNOTS_ENTRIES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Replace a page's `/Annots`, writing into the shared array object when it is indirect.
diff --git a/crates/annot/src/links.rs b/crates/annot/src/links.rs
index 4d3eef632..f11eecbd8 100644
--- a/crates/annot/src/links.rs
+++ b/crates/annot/src/links.rs
@@ -232,6 +232,16 @@ fn checked_rect(rect: [f64; 4]) -> Result<[f64; 4], AnnotError> {
/// Add a link over `rect` (user space). Returns its index in the page's `/Annots`.
pub fn add(doc: &mut Document, page: usize, rect: [f64; 4], action: &LinkAction, style: &LinkStyle) -> Result<usize, AnnotError> {
let p = page_ref(doc, page)?;
+ let obj = new_link(doc, p, rect, action, style)?;
+ let mut list = annots(doc, p);
+ list.push(Object::Ref(obj));
+ let index = list.len() - 1;
+ set_annots(doc, p, list)?;
+ Ok(index)
+}
+
+/// A link annotation object for page `p`, not yet on the page's `/Annots`.
+fn new_link(doc: &mut Document, p: ObjRef, rect: [f64; 4], action: &LinkAction, style: &LinkStyle) -> Result<ObjRef, AnnotError> {
let r = checked_rect(rect)?;
if matches!(action, LinkAction::Other(_)) {
return Err(AnnotError::Invalid("choose a page or a web address".into()));
@@ -244,12 +254,7 @@ pub fn add(doc: &mut Document, page: usize, rect: [f64; 4], action: &LinkAction,
d.set(b"F".to_vec(), Object::Int(4));
write_style(&mut d, style);
write_action(doc, &mut d, action)?;
- let obj = doc.add(Object::Dict(d));
- let mut list = annots(doc, p);
- list.push(Object::Ref(obj));
- let index = list.len() - 1;
- set_annots(doc, p, list)?;
- Ok(index)
+ Ok(doc.add(Object::Dict(d)))
}
fn link_at(doc: &Document, page: usize, index: usize) -> Result<(ObjRef, ObjRef), AnnotError> {
@@ -414,12 +419,30 @@ pub fn find_urls(chars: &[char]) -> Vec<(std::ops::Range<usize>, String)> {
/// Create links for found URLs: `(page, quads, uri)` with quads in user space (one link per
/// line rectangle). Returns how many links were added.
pub fn add_many(doc: &mut Document, links: &[(usize, Vec<[f64; 4]>, String)], style: &LinkStyle) -> Result<usize, AnnotError> {
+ let pages = page_refs(doc)?;
+ // Each page's `/Annots` is extended once, with its new links in the order given.
+ let mut added: Vec<(ObjRef, Vec<Object>)> = Vec::new();
+ let mut slot: std::collections::HashMap<ObjRef, usize> = std::collections::HashMap::new();
let mut n = 0;
for (page, rects, uri) in links {
+ let p = pages.get(*page).copied().ok_or(AnnotError::NoSuchPage(*page))?;
+ let action = LinkAction::Uri(uri.clone());
for r in rects {
- add(doc, *page, *r, &LinkAction::Uri(uri.clone()), style)?;
+ let obj = new_link(doc, p, *r, &action, style)?;
+ let k = *slot.entry(p).or_insert_with(|| {
+ added.push((p, Vec::new()));
+ added.len() - 1
+ });
+ if let Some((_, list)) = added.get_mut(k) {
+ list.push(Object::Ref(obj));
+ }
n += 1;
}
}
+ for (p, new) in added {
+ let mut list = annots(doc, p);
+ list.extend(new);
+ set_annots(doc, p, list)?;
+ }
Ok(n)
}
diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs
index 44328bbd0..cfd80093e 100644
--- a/crates/annot/src/tests.rs
+++ b/crates/annot/src/tests.rs
@@ -1526,3 +1526,18 @@ fn page_walk_reads_a_shared_kids_array_once() {
assert_eq!(pages, [first, second]);
assert!(walk.examined <= 10_000, "{} kids entries read", walk.examined);
}
+
+/// Adding many links to a page extends its `/Annots` once, not once per link.
+#[test]
+fn many_links_extend_a_page_annotation_list_once() {
+ let mut doc = fixture();
+ let before = annots(&doc, page_refs(&doc).unwrap()[0]).len();
+ let n = 2_000;
+ let rects: Vec<[f64; 4]> = (0..n).map(|i| [10.0, i as f64 * 0.1, 50.0, i as f64 * 0.1 + 5.0]).collect();
+ ANNOTS_ENTRIES_COPIED.with(|c| c.set(0));
+ let added = links::add_many(&mut doc, &[(0, rects, "https://example.com".into())], &links::LinkStyle::default()).unwrap();
+ let copied = ANNOTS_ENTRIES_COPIED.with(std::cell::Cell::get);
+ assert_eq!(added, n);
+ assert_eq!(annots(&doc, page_refs(&doc).unwrap()[0]).len(), before + n);
+ assert!(copied <= 4 * n, "{copied} annotation entries copied for {n} links");
+}