PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(annot): list a repeated link once and cap its web-address text
aiongg1695106f98e0
diff --git a/crates/annot/src/links.rs b/crates/annot/src/links.rsindex 4d3eef632..b6a2c7575 100644--- a/crates/annot/src/links.rs+++ b/crates/annot/src/links.rs@@ -78,11 +78,14 @@ pub struct LinkItem {pub style: LinkStyle,}+/// Web-address text one listing keeps; past it a link lists as [`LinkAction::Other`].+pub(crate) const MAX_URI_BYTES: usize = 16 << 20;+fn nums(doc: &Document, o: Option<&Object>) -> Vec<f64> {o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect())).unwrap_or_default()}-fn action_of(doc: &Document, d: &Dict, pages: &[ObjRef]) -> LinkAction {+fn action_of(doc: &Document, d: &Dict, pages: &[ObjRef], uri_budget: &mut usize) -> LinkAction {let dest_page = |dest: &Object| -> Option<usize> {let a = doc.resolve(dest);let first = a.as_array()?.first()?.clone();@@ -97,9 +100,17 @@ fn action_of(doc: &Document, d: &Dict, pages: &[ObjRef]) -> LinkAction {}let Some(a) = d.get(b"A").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()) else { return LinkAction::Other("no action".into()) };match a.name(b"S") {- Some(b"URI") => LinkAction::Uri(- a.get(b"URI").and_then(|u| doc.resolve(u).as_string().map(|s| String::from_utf8_lossy(&s.bytes).into_owned())).unwrap_or_default(),- ),+ Some(b"URI") => {+ let uri = a.get(b"URI").map(|u| doc.resolve(u));+ let bytes = uri.as_ref().and_then(|u| u.as_string()).map_or(&[][..], |s| &s.bytes[..]);+ match uri_budget.checked_sub(bytes.len()) {+ Some(left) => {+ *uri_budget = left;+ LinkAction::Uri(String::from_utf8_lossy(bytes).into_owned())+ }+ None => LinkAction::Other("web address too long".into()),+ }+ }Some(b"GoTo") => a.get(b"D").and_then(dest_page).map_or_else(|| LinkAction::Other("named destination".into()), LinkAction::Page),Some(s) => LinkAction::Other(String::from_utf8_lossy(s).into_owned()),None => LinkAction::Other("no action".into()),@@ -133,8 +144,16 @@ fn style_of(doc: &Document, d: &Dict) -> LinkStyle {pub fn list(doc: &Document) -> Vec<LinkItem> {let Ok(pages) = page_refs(doc) else { return Vec::new() };let mut out = Vec::new();+ let mut seen = std::collections::HashSet::new();+ let mut uri_budget = MAX_URI_BYTES;for (pi, p) in pages.iter().enumerate() {for (k, a) in annots(doc, *p).iter().enumerate() {+ // One annotation object listed under several entries or pages is one link.+ if let Some(r) = a.as_ref()+ && !seen.insert(r)+ {+ continue;+ }let Some(d) = doc.resolve(a).as_dict().cloned() else { continue };if d.name(b"Subtype") != Some(b"Link") {continue;@@ -148,7 +167,7 @@ pub fn list(doc: &Document) -> Vec<LinkItem> {index: k,obj: a.as_ref(),rect: [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])],- action: action_of(doc, &d, &pages),+ action: action_of(doc, &d, &pages, &mut uri_budget),style: style_of(doc, &d),});}diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rsindex 201fe0e08..c52732ea8 100644--- a/crates/annot/src/tests.rs+++ b/crates/annot/src/tests.rs@@ -1505,6 +1505,42 @@ fn typed_signature_uses_nonzero_winding_fill() {assert!(!ap.contains("f*"), "must not use even-odd fill (`f*`): {ap}");}+fn doc_of(objs: &[String]) -> Document {+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ Document::open(Arc::new(out)).expect("opens")+}++#[test]+fn link_listing_skips_repeated_refs_and_caps_web_address_text() {+ // One link referenced 1000 times, and 300 small links sharing one 64 KiB address.+ let annots = format!("{}{}", " 4 0 R".repeat(1000), "<< /Subtype /Link /Rect [0 0 1 1] /A 5 0 R >>".repeat(300));+ let doc = doc_of(&[+ "<< /Type /Catalog /Pages 2 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),+ format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),+ "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A 5 0 R >>".into(),+ "<< /S /URI /URI 6 0 R >>".into(),+ format!("({})", "u".repeat(64 << 10)),+ ]);+ let all = links::list(&doc);+ assert_eq!(all.iter().filter(|l| l.obj == Some(ObjRef::new(4, 0))).count(), 1);+ assert_eq!(all.len(), 301, "every distinct link is still listed");+ let kept: usize = all.iter().map(|l| if let links::LinkAction::Uri(u) = &l.action { u.len() } else { 0 }).sum();+ assert!(kept <= links::MAX_URI_BYTES, "{kept} bytes of web addresses kept");+ assert!(matches!(&all[0].action, links::LinkAction::Uri(u) if u.len() == 64 << 10));+}+#[test]fn cloud_outline_has_a_bump_budget() {// 50 long edges would each ask for 10,000 bumps of radius 1.