Skip to content

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

Perf: defer marker and link index scans until first use (#1434)

cyfung1031416c85579bea
diff --git a/crates/automation/src/content.rs b/crates/automation/src/content.rs
index 0e97aa8b6..710952d7c 100644
--- a/crates/automation/src/content.rs
+++ b/crates/automation/src/content.rs
@@ -69,7 +69,7 @@ impl Automation {
let doc = self.doc(a)?;
let mut per_page: std::collections::HashMap<usize, usize> = Default::default();
let items: Vec<Value> = doc
- .added
+ .added()
.iter()
.map(|it| {
let index = per_page.entry(it.page).or_default();
@@ -110,7 +110,7 @@ impl Automation {
let mut t = AddedText { rect, text: a.str("text")?.to_string(), ..AddedText::default() };
style(a, &mut t)?;
let mut out = self.apply(a, Edit::AddText { page, text: t })?;
- out["index"] = json!(self.doc(a)?.added.iter().filter(|x| x.page == page).count());
+ out["index"] = json!(self.doc(a)?.added().iter().filter(|x| x.page == page).count());
Ok(out)
}
@@ -123,7 +123,7 @@ impl Automation {
let rect = rect_arg(a, "rect")?.map(|r| to_display(r, ph));
let mut out = self.apply(a, Edit::AddImage { page, rect, name, bytes: std::sync::Arc::new(bytes) })?;
let doc = self.doc(a)?;
- let mine: Vec<_> = doc.added.iter().filter(|x| x.page == page).collect();
+ let mine: Vec<_> = doc.added().iter().filter(|x| x.page == page).collect();
out["index"] = json!(mine.len());
out["rect"] = json!(mine.last().map(|x| to_view(x.content.rect(), ph)));
Ok(out)
@@ -135,7 +135,7 @@ impl Automation {
let index = a.int("index")?;
let ph = doc.info.pages[page].height as f64;
let it = doc
- .added
+ .added()
.iter()
.filter(|x| x.page == page)
.nth((index - 1).max(0) as usize)
diff --git a/crates/automation/src/links.rs b/crates/automation/src/links.rs
index 9a810ed1c..cd0fb9da0 100644
--- a/crates/automation/src/links.rs
+++ b/crates/automation/src/links.rs
@@ -67,7 +67,7 @@ impl Automation {
let doc = self.doc(a)?;
let targets: std::collections::HashMap<(usize, usize), &LinkTarget> = doc.info.links.iter().map(|t| ((t.page, t.index), &t.target)).collect();
let items: Vec<Value> = doc
- .links
+ .links()
.iter()
.map(|l| {
let p = &doc.info.pages[l.page];
@@ -179,7 +179,7 @@ impl Automation {
let index = a.int("index")?;
let doc = self.doc(a)?;
let l = doc
- .links
+ .links()
.iter()
.find(|l| l.page == page && l.index as i64 + 1 == index)
.ok_or_else(|| failed(format!("page {} has no link {index} (see link_list)", page + 1)))?;
@@ -217,8 +217,8 @@ impl Automation {
None => None,
};
let before = match &pages {
- Some(ps) => self.doc(a)?.links.iter().filter(|l| ps.contains(&l.page)).count(),
- None => self.doc(a)?.links.len(),
+ Some(ps) => self.doc(a)?.links().iter().filter(|l| ps.contains(&l.page)).count(),
+ None => self.doc(a)?.links().len(),
};
let mut out = self.apply(a, Edit::RemoveLinks { pages })?;
out["removed"] = json!(before);
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index f5068b476..6e03f7231 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -3557,7 +3557,7 @@ fn text_styling_on_an_image_is_refused_without_an_edit() {
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "saved.pdf" }));
let state = |a: &Automation| {
let d = a.session().docs().iter().find(|d| d.id.0 == doc).unwrap();
- (format!("{:?}", d.added), d.dirty, d.edit_generation(), d.can_undo().map(str::to_owned), d.can_redo().map(str::to_owned))
+ (format!("{:?}", d.added()), d.dirty, d.edit_generation(), d.can_undo().map(str::to_owned), d.can_redo().map(str::to_owned))
};
let before = state(&a);
assert!(!before.1 && before.4.is_some(), "a clean document with a step to redo: {before:?}");
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 45c58302e..e3dd581f2 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -396,7 +396,7 @@ pub fn is_enabled(spec: &CommandSpec, session: &Session, active: Option<DocId>)
Annotate => doc.is_some_and(|d| d.allows_annotation()),
Copying => doc.is_some_and(|d| d.allows_copying()),
FillForms => doc.is_some_and(|d| d.allows_form_filling() && !d.form.is_empty()),
- Marks(k) => doc.is_some_and(|d| d.allows_modification() && d.marks.contains(&k)),
+ Marks(k) => doc.is_some_and(|d| d.allows_modification() && d.marks().contains(&k)),
HasComments => doc.is_some_and(|d| d.allows_modification() && !d.info.annotations.is_empty()),
HasFields => doc.is_some_and(|d| d.allows_modification() && !d.form.is_empty()),
HasRedactions => doc.is_some_and(|d| d.allows_modification() && d.redaction_marks() > 0),
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index cfbec3b7f..2bca86ab2 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -165,7 +165,38 @@ pub fn merge_data_files(files: &[(String, Vec<u8>)]) -> Result<String, String> {
pub type SplitPart = (usize, usize, Arc<Vec<u8>>);
-use std::sync::Arc;
+use std::sync::{Arc, OnceLock};
+
+#[cfg(test)]
+thread_local! {
+ static SECONDARY_SCAN_COUNTS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
+}
+
+#[cfg(test)]
+fn reset_secondary_scan_counts() {
+ SECONDARY_SCAN_COUNTS.with(|counts| counts.set((0, 0)));
+}
+
+#[cfg(test)]
+fn secondary_scan_counts() -> (usize, usize) {
+ SECONDARY_SCAN_COUNTS.with(std::cell::Cell::get)
+}
+
+#[cfg(test)]
+fn record_marker_scan() {
+ SECONDARY_SCAN_COUNTS.with(|counts| {
+ let (markers, links) = counts.get();
+ counts.set((markers + 1, links));
+ });
+}
+
+#[cfg(test)]
+fn record_link_scan() {
+ SECONDARY_SCAN_COUNTS.with(|counts| {
+ let (markers, links) = counts.get();
+ counts.set((markers, links + 1));
+ });
+}
use pdfcraft_cos::{SaveOptions, write_full, write_incremental};
use pdfcraft_render::{DocInfo, Layer, LayerOp, OpenError, ReadingColors, RenderConfig, RenderPool, inspect};
@@ -197,6 +228,8 @@ enum Scope {
Comments,
/// Only form field values (and their widget appearances).
Form,
+ /// Link annotations; the full inspection is refreshed, but page-content indexes stay valid.
+ Links,
/// Only page content streams, resources and added content/marks: the page tree,
/// annotations, form fields, links, outline and fonts are unchanged, so the full
/// re-inspection is skipped (seconds on very large files).
@@ -234,6 +267,7 @@ fn scope_of(edit: &Edit) -> Scope {
| Edit::FillAnnotation { .. }
| Edit::FontSizeAnnotation { .. }
| Edit::SetAnnotationInfo { .. } => Scope::Comments,
+ Edit::AddLink { .. } | Edit::SetLink { .. } | Edit::DeleteLink { .. } | Edit::RemoveLinks { .. } | Edit::AddLinks { .. } => Scope::Links,
Edit::SetFieldValue { .. } | Edit::ResetForm { .. } | Edit::SetFieldImage { .. } | Edit::ApplyScriptChanges { .. } => Scope::Form,
// Page content, resources and added content/marks only: the page tree, annotations,
// fields, links and document metadata are untouched (see `refresh_content`).
@@ -344,12 +378,8 @@ pub struct Document {
pub read_only_reason: Option<String>,
/// Interactive form fields of the current state (empty without a form).
pub form: Arc<Vec<pdfcraft_forms::Field>>,
- /// Page marks present (headers and footers, watermarks, backgrounds), for Update/Remove.
- pub marks: Vec<MarkKind>,
- /// Text and images added with Edit a PDF ▸ Add content (still editable).
- pub added: Vec<pdfcraft_edit::Added>,
- /// Link annotations, for Edit a PDF ▸ Link.
- pub links: Vec<pdfcraft_annot::links::LinkItem>,
+ marker_scan: OnceLock<pdfcraft_edit::MarkerScan>,
+ links: OnceLock<Vec<pdfcraft_annot::links::LinkItem>>,
/// Signature fields, validated against the session's trust store (Signatures panel).
pub signatures: Arc<Vec<SignatureInfo>>,
trust: Arc<TrustStore>,
@@ -660,6 +690,54 @@ impl Document {
self.info.annotations.iter().filter(|a| a.subtype == "Redact").count()
}
+ /// Page marks present (headers and footers, watermarks, backgrounds), for Update/Remove.
+ pub fn marks(&self) -> &[MarkKind] {
+ &self
+ .marker_scan
+ .get_or_init(|| {
+ self.editor
+ .as_ref()
+ .map(|e| {
+ #[cfg(test)]
+ record_marker_scan();
+ pdfcraft_edit::scan_markers(&e.cos)
+ })
+ .unwrap_or_default()
+ })
+ .marks
+ }
+
+ /// Text and images added with Edit a PDF ▸ Add content (still editable).
+ pub fn added(&self) -> &[pdfcraft_edit::Added] {
+ &self
+ .marker_scan
+ .get_or_init(|| {
+ self.editor
+ .as_ref()
+ .map(|e| {
+ #[cfg(test)]
+ record_marker_scan();
+ pdfcraft_edit::scan_markers(&e.cos)
+ })
+ .unwrap_or_default()
+ })
+ .added
+ }
+
+ /// Link annotations, for Edit a PDF ▸ Link.
+ pub fn links(&self) -> &[pdfcraft_annot::links::LinkItem] {
+ self.links.get_or_init(|| {
+ self.editor
+ .as_ref()
+ .map(|e| {
+ #[cfg(test)]
+ record_link_scan();
+ pdfcraft_annot::links::list(&e.cos)
+ })
+ .unwrap_or_default()
+ })
+ }
+
/// Changes to content and document information are allowed.
pub fn allows_modification(&self) -> bool {
self.editable() && self.permissions().is_none_or(|p| p.modify())
@@ -3431,14 +3509,6 @@ impl Session {
};
e.cos.note_repair(line);
}
- let (marks, added) = editor
- .as_ref()
- .map(|e| {
- let scan = pdfcraft_edit::scan_markers(&e.cos);
- (scan.marks, scan.added)
- })
- .unwrap_or_default();
- let links = editor.as_ref().map(|e| pdfcraft_annot::links::list(&e.cos)).unwrap_or_default();
let sig_cache = Arc::new(pdfcraft_sign::DigestCache::default());
let signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, trust, &sig_cache)).unwrap_or_default();
Document {
@@ -3455,9 +3525,8 @@ impl Session {
snapshot_generation: 0,
read_only_reason,
form: Arc::new(form),
- marks,
- added,
- links,
+ marker_scan: OnceLock::new(),
+ links: OnceLock::new(),
signatures,
trust: trust.clone(),
sig_cache,
@@ -3725,6 +3794,9 @@ impl Session {
if scope == Scope::Content {
return Self::refresh_content(doc, None);
}
+ if scope == Scope::Links {
+ return Self::refresh_links(doc);
+ }
// Metadata edits keep the renderer, which holds the working file anyway.
if scope != Scope::Metadata {
Self::release_working(doc);
@@ -3762,7 +3834,11 @@ impl Session {
let form = Arc::new(form);
match scope {
Scope::Metadata => return Ok(()),
- Scope::Comments => doc.info.annotations = comment_list(&editor.cos),
+ Scope::Comments => {
+ doc.info.annotations = comment_list(&editor.cos);
+ // Link indexes are positions in /Annots, so comment insertion/deletion can move them.
+ doc.links = OnceLock::new();
+ }
Scope::Form => {
// PERF: keystroke path, index once. A linear find per field is O(F^2);
// forms reach 10k fields.
@@ -3783,6 +3859,7 @@ impl Session {
}
}
}
+ Scope::Links => return Self::refresh_links(doc),
// Handled above; kept as a full refresh so the match stays total.
Scope::Full => return Self::refresh(doc),
// Handled above (content-only refresh); the arm keeps the match total.
@@ -3832,11 +3909,8 @@ impl Session {
// The edit must still leave a file the viewer can open; anything else rolls back above.
pdfcraft_render::check_pages(bytes.clone(), doc.password.as_deref(), doc.info.pages.len()).map_err(|e| EditError::Reopen(e.to_string()))?;
let (touches_added, touches_marks) = Self::content_refresh_lists(edit);
- if touches_added {
- doc.added = pdfcraft_edit::list_added(&editor.cos);
- }
- if touches_marks {
- doc.marks = pdfcraft_edit::marks_present(&editor.cos);
+ if touches_added || touches_marks {
+ doc.marker_scan = OnceLock::new();
}
doc.info.file_size = bytes.len();
if !doc.signatures.is_empty() {
@@ -3873,6 +3947,15 @@ impl Session {
/// Rebuild working bytes, inspection and renderer from the current edit state.
fn refresh(doc: &mut Document) -> Result<(), EditError> {
+ Self::refresh_with_indexes(doc, true, true)
+ }
+
+ /// Reinspect a link edit while preserving the page-content marker scan cache.
+ fn refresh_links(doc: &mut Document) -> Result<(), EditError> {
+ Self::refresh_with_indexes(doc, false, true)
+ }
+
+ fn refresh_with_indexes(doc: &mut Document, invalidate_markers: bool, invalidate_links: bool) -> Result<(), EditError> {
// A full refresh may follow structural or annotation changes: cached appearances
// may be stale, so they are rebuilt below.
if let Some(editor) = doc.editor.as_mut() {
@@ -3900,10 +3983,12 @@ impl Session {
let mut form = pdfcraft_forms::fields(&editor.cos);
xfa::mark_script_buttons(&editor.cos, &mut form);
doc.form = Arc::new(form);
- let marker_scan = pdfcraft_edit::scan_markers(&editor.cos);
- doc.marks = marker_scan.marks;
- doc.added = marker_scan.added;
- doc.links = pdfcraft_annot::links::list(&editor.cos);
+ if invalidate_markers {
+ doc.marker_scan = OnceLock::new();
+ }
+ if invalidate_links {
+ doc.links = OnceLock::new();
+ }
doc.signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
doc.display = display_bytes(Some(editor), &bytes);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone());
@@ -4441,7 +4526,7 @@ impl Session {
]
})
.filter(|r| {
- !doc.links.iter().any(|l| l.page == page && l.rect[0] < r[2] && r[0] < l.rect[2] && l.rect[1] < r[3] && r[1] < l.rect[3])
+ !doc.links().iter().any(|l| l.page == page && l.rect[0] < r[2] && r[0] < l.rect[2] && l.rect[1] < r[3] && r[1] < l.rect[3])
})
.collect();
if !rects.is_empty() {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 167ae0078..d61c82d9d 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -2070,7 +2070,7 @@ fn headers_footers_watermarks_and_backgrounds_show_update_and_remove() {
s.apply(id, Edit::AddHeaderFooter { pages: vec![0, 1], settings: hf.clone(), replace: false }).unwrap();
// The session clock is 2023-11-14.
assert_eq!(page_texts(&s, id)[1], "Page 2\nPage 2 of 2 · 2023-11-14");
- assert_eq!(s.get(id).unwrap().marks, [MarkKind::HeaderFooter]);
+ assert_eq!(s.get(id).unwrap().marks(), [MarkKind::HeaderFooter]);
hf.text[4] = "Draft".into();
s.apply(id, Edit::AddHeaderFooter { pages: vec![0, 1], settings: hf, replace: true }).unwrap();
assert_eq!(page_texts(&s, id)[0], "Page 1\nDraft");
@@ -2089,19 +2089,19 @@ fn headers_footers_watermarks_and_backgrounds_show_update_and_remove() {
},
)
.unwrap();
- assert_eq!(s.get(id).unwrap().marks.len(), 3);
+ assert_eq!(s.get(id).unwrap().marks().len(), 3);
assert!(page_texts(&s, id)[0].contains("SECRET"));
s.apply(id, Edit::RemoveMarks { kind: MarkKind::HeaderFooter }).unwrap();
s.apply(id, Edit::RemoveMarks { kind: MarkKind::Watermark }).unwrap();
s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();
assert_eq!(page_texts(&s, id), ["Page 1", "Page 2"]);
- assert!(s.get(id).unwrap().marks.is_empty());
+ assert!(s.get(id).unwrap().marks().is_empty());
assert!(matches!(s.apply(id, Edit::RemoveMarks { kind: MarkKind::Watermark }), Err(EditError::Edit(_))));
assert_eq!(s.get(id).unwrap().can_undo(), Some("Remove background"));
}
#[test]
-fn open_populates_marks_and_added_from_the_combined_marker_scan() {
+fn marker_indexes_match_after_open_and_save_when_requested() {
let (mut source, source_id) = session_with(1);
let mut header = HeaderFooter::default();
header.text[0] = "Header".into();
@@ -2136,18 +2136,95 @@ fn open_populates_marks_and_added_from_the_combined_marker_scan() {
let expected_added = pdfcraft_edit::list_added(&reference);
source.mark_saved(source_id, bytes.clone(), None).unwrap();
let refreshed = source.get(source_id).unwrap();
- assert_eq!(refreshed.marks, expected_marks);
- assert_eq!(refreshed.added, expected_added);
+ assert_eq!(refreshed.marks(), expected_marks);
+ assert_eq!(refreshed.added(), expected_added);
let mut reopened = Session::new();
let reopened_id = reopened.open("marked.pdf", None, bytes, None).unwrap();
let opened = reopened.get(reopened_id).unwrap();
- assert_eq!(opened.marks, expected_marks);
- assert_eq!(opened.added, expected_added);
- assert_eq!(opened.marks.len(), 3);
- assert!(opened.marks.contains(&MarkKind::HeaderFooter));
- assert!(opened.marks.contains(&MarkKind::Watermark));
- assert!(opened.marks.contains(&MarkKind::Background));
- assert_eq!(opened.added.len(), 1);
+ assert_eq!(opened.marks(), expected_marks);
+ assert_eq!(opened.added(), expected_added);
+ assert_eq!(opened.marks().len(), 3);
+ assert!(opened.marks().contains(&MarkKind::HeaderFooter));
+ assert!(opened.marks().contains(&MarkKind::Watermark));
+ assert!(opened.marks().contains(&MarkKind::Background));
+ assert_eq!(opened.added().len(), 1);
+}
+
+#[test]
+fn secondary_indexes_load_once_and_follow_edit_scopes() {
+ reset_secondary_scan_counts();
+ let (mut session, id) = session_with(1);
+ assert_eq!(secondary_scan_counts(), (0, 0), "open does not scan markers or links");
+
+ {
+ let doc = session.get(id).unwrap();
+ assert!(doc.marks().is_empty());
+ assert!(doc.added().is_empty());
+ assert!(doc.added().is_empty());
+ assert_eq!(secondary_scan_counts(), (1, 0), "marks and added content share one scan");
+ assert!(doc.links().is_empty());
+ assert!(doc.links().is_empty());
+ assert_eq!(secondary_scan_counts(), (1, 1), "repeated reads reuse the link list");
+ }
+
+ session.apply(id, Edit::SetInfo { key: "Title".into(), value: "Changed".into() }).unwrap();
+ assert!(session.get(id).unwrap().links().is_empty());
+ assert!(session.get(id).unwrap().marks().is_empty());
+ assert_eq!(secondary_scan_counts(), (1, 1), "metadata does not invalidate either index");
+
+ session.apply(id, rect_comment(0, [20.0, 20.0, 60.0, 60.0])).unwrap();
+ assert!(session.get(id).unwrap().links().is_empty());
+ assert_eq!(secondary_scan_counts(), (1, 2), "comment edits invalidate the annotation-position link index");
+
+ session
+ .apply(
+ id,
+ Edit::AddLink {
+ page: 0,
+ rect: [10.0, 10.0, 80.0, 30.0],
+ action: LinkAction::Uri("https://example.org".into()),
+ style: LinkStyle::default(),
+ },
+ )
+ .unwrap();
+ assert_eq!(secondary_scan_counts(), (1, 2), "a link edit invalidates only the link list");
+ assert_eq!(session.get(id).unwrap().links()[0].index, 1, "link indexes include earlier annotations");
+ assert_eq!(secondary_scan_counts(), (1, 3));
+ session.undo(id).unwrap();
+ assert_eq!(session.get(id).unwrap().links().len(), 0);
+ assert_eq!(secondary_scan_counts(), (1, 4), "undo rebuilds the link list once");
+ session.redo(id).unwrap();
+ assert_eq!(session.get(id).unwrap().links()[0].index, 1);
+ assert_eq!(secondary_scan_counts(), (1, 5), "redo rebuilds the link list once");
+ session.apply(id, Edit::DeleteAnnotation { page: 0, index: 0 }).unwrap();
+ assert_eq!(session.get(id).unwrap().links()[0].index, 0, "deleting an earlier annotation shifts link indexes");
+ assert_eq!(secondary_scan_counts(), (1, 6), "comment deletion rebuilds annotation-position indexes");
+
+ session
+ .apply(id, Edit::AddText { page: 0, text: AddedText { rect: [20.0, 250.0, 100.0, 280.0], text: "Added".into(), ..Default::default() } })
+ .unwrap();
+ assert_eq!(secondary_scan_counts(), (1, 6), "content edits defer rebuilding until a marker getter is used");
+ assert_eq!(session.get(id).unwrap().added().len(), 1);
+ assert_eq!(session.get(id).unwrap().links().len(), 1);
+ assert_eq!(secondary_scan_counts(), (2, 6), "content edits preserve the link cache");
+
+ let mut header = HeaderFooter::default();
+ header.text[0] = "Header".into();
+ session.apply(id, Edit::AddHeaderFooter { pages: vec![0], settings: header, replace: false }).unwrap();
+ assert_eq!(session.get(id).unwrap().marks(), [MarkKind::HeaderFooter]);
+ assert_eq!(secondary_scan_counts(), (3, 6));
+ session.undo(id).unwrap();
+ assert!(session.get(id).unwrap().marks().is_empty());
+ assert_eq!(secondary_scan_counts(), (4, 6), "undo invalidates marker state");
+ session.undo(id).unwrap();
+ assert!(session.get(id).unwrap().added().is_empty());
+ assert_eq!(secondary_scan_counts(), (5, 6), "undo of added content invalidates marker state");
+ session.redo(id).unwrap();
+ assert_eq!(session.get(id).unwrap().added().len(), 1);
+ assert_eq!(secondary_scan_counts(), (6, 6), "redo of added content rebuilds once");
+ session.redo(id).unwrap();
+ assert_eq!(session.get(id).unwrap().marks(), [MarkKind::HeaderFooter]);
+ assert_eq!(secondary_scan_counts(), (7, 6), "redo of marks rebuilds once");
}
#[test]
@@ -2390,15 +2467,15 @@ fn added_text_and_images_render_and_stay_editable() {
}
s.apply(id, Edit::AddImage { page: 0, rect: None, name: "dot.png".into(), bytes: Arc::new(png) }).unwrap();
let d = s.get(id).unwrap();
- assert_eq!(d.added.len(), 2);
- assert_eq!(d.added[1].content.rect(), [90.0, 145.0, 110.0, 155.0], "20×10 px at 72 dpi, centred on 200×300");
- let moved = d.added[0].content.with_rect([30.0, 100.0, 190.0, 130.0]);
+ assert_eq!(d.added().len(), 2);
+ assert_eq!(d.added()[1].content.rect(), [90.0, 145.0, 110.0, 155.0], "20×10 px at 72 dpi, centred on 200×300");
+ let moved = d.added()[0].content.with_rect([30.0, 100.0, 190.0, 130.0]);
s.apply(id, Edit::UpdateContent { page: 0, index: 0, content: moved }).unwrap();
- assert_eq!(s.get(id).unwrap().added[0].content.rect()[3], 130.0);
+ assert_eq!(s.get(id).unwrap().added()[0].content.rect()[3], 130.0);
s.apply(id, Edit::DeleteContent { page: 0, index: 1 }).unwrap();
- assert_eq!(s.get(id).unwrap().added.len(), 1);
+ assert_eq!(s.get(id).unwrap().added().len(), 1);
s.undo(id).unwrap();
- assert_eq!(s.get(id).unwrap().added.len(), 2);
+ assert_eq!(s.get(id).unwrap().added().len(), 2);
}
#[test]
@@ -2430,7 +2507,7 @@ fn added_images_rotate_flip_and_crop_as_drawn() {
let blue = |c: [u8; 3]| c[2] > 200 && c[0] < 60;
// Display y 100–200 is rows 100–200 from the top on a 300 pt page.
assert!(red(colour_at(&s, 70, 150)) && blue(colour_at(&s, 130, 150)), "as placed: red left, blue right");
- let item = |s: &Session| s.get(id).unwrap().added[0].content.clone();
+ let item = |s: &Session| s.get(id).unwrap().added()[0].content.clone();
let AddedContent::Image(mut img) = item(&s) else { panic!() };
img.rotation = 1;
s.apply(id, Edit::UpdateContent { page: 0, index: 0, content: AddedContent::Image(img.clone()) }).unwrap();
@@ -2531,21 +2608,21 @@ fn links_from_urls_and_link_edits() {
assert_eq!(found[0].2, "http://www.example.org");
s.apply(id, Edit::AddLinks { links: found, style: LinkStyle::default() }).unwrap();
let d = s.get(id).unwrap();
- assert_eq!(d.links.len(), 1);
+ assert_eq!(d.links().len(), 1);
assert_eq!(d.info.links.len(), 1, "the viewer follows it");
assert!(s.find_urls(id).is_empty(), "already linked");
// Remove all links and undo.
s.apply(id, Edit::RemoveLinks { pages: None }).unwrap();
- assert!(s.get(id).unwrap().links.is_empty());
+ assert!(s.get(id).unwrap().links().is_empty());
assert_eq!(s.get(id).unwrap().can_undo(), Some("Remove all links"));
s.undo(id).unwrap();
- assert_eq!(s.get(id).unwrap().links.len(), 1);
+ assert_eq!(s.get(id).unwrap().links().len(), 1);
// Link Properties and delete.
- let l = s.get(id).unwrap().links[0].clone();
+ let l = s.get(id).unwrap().links()[0].clone();
s.apply(id, Edit::SetLink { page: 0, index: l.index, rect: None, action: Some(LinkAction::Page(0)), style: None }).unwrap();
- assert_eq!(s.get(id).unwrap().links[0].action, LinkAction::Page(0));
+ assert_eq!(s.get(id).unwrap().links()[0].action, LinkAction::Page(0));
s.apply(id, Edit::DeleteLink { page: 0, index: l.index }).unwrap();
- assert!(s.get(id).unwrap().links.is_empty());
+ assert!(s.get(id).unwrap().links().is_empty());
assert!(s.apply(id, Edit::RemoveLinks { pages: None }).is_err(), "nothing left to remove");
}
@@ -2575,14 +2652,14 @@ fn appearance_only_edit_preserves_gotor_action_semantics() {
let mut session = Session::new();
let id = session.open("source.pdf", Some("/docs/source.pdf".into()), Arc::new(bytes), None).unwrap();
let before = session.get(id).unwrap().info.links[0].target.clone();
- let mut style = session.get(id).unwrap().links[0].style;
+ let mut style = session.get(id).unwrap().links()[0].style;
style.visible = true;
style.width = 2.0;
session.apply(id, Edit::SetLink { page: 0, index: 0, rect: None, action: None, style: Some(style) }).unwrap();
let after = &session.get(id).unwrap().info.links[0].target;
assert_eq!(*after, before, "the GoToR file, destination and /NewWindow hint must remain unchanged");
- assert_eq!(session.get(id).unwrap().links[0].style, style, "the appearance edit is applied");
+ assert_eq!(session.get(id).unwrap().links()[0].style, style, "the appearance edit is applied");
}
#[test]
@@ -4556,7 +4633,7 @@ fn group_moves_preserve_rotated_added_content_raster_geometry() {
image.write_to(&mut png, image::ImageFormat::Png).unwrap();
s.apply(id, Edit::AddImage { page: 0, rect: Some([40.0, 40.0, 80.0, 70.0]), name: "quadrants.png".into(), bytes: Arc::new(png.into_inner()) })
.unwrap();
- let AddedContent::Image(mut image) = s.get(id).unwrap().added[1].content.clone() else { panic!() };
+ let AddedContent::Image(mut image) = s.get(id).unwrap().added()[1].content.clone() else { panic!() };
image.flip_h = true;
image.crop = [0.1, 0.0, 0.2, 0.0];
s.apply(id, Edit::UpdateContent { page: 0, index: 1, content: AddedContent::Image(image) }).unwrap();
@@ -4819,7 +4896,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
let annotations = format!("{:?}", before.info.annotations);
let links = format!("{:?}", before.links);
let form = before.form.clone();
- let marks = before.marks.clone();
+ let marks = before.marks().to_vec();
let bytes = before.bytes.clone();
let text = AddedText {
rect: [20.0, 20.0, 200.0, 60.0],
@@ -4837,8 +4914,8 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
assert_eq!(format!("{:?}", after.info.annotations), annotations);
assert_eq!(format!("{:?}", after.links), links);
assert_eq!(after.form, form, "no field was touched");
- assert_eq!(after.marks, marks, "no mark was touched");
- assert!(after.added.iter().any(|a| a.page == 1), "the added text is listed");
+ assert_eq!(after.marks(), marks, "no mark was touched");
+ assert!(after.added().iter().any(|a| a.page == 1), "the added text is listed");
assert_ne!(after.bytes, bytes, "the working file carries the edit");
assert_ne!(after.display, bytes, "the display copy carries the edit too");
// The display bytes still open and render the edited page.
@@ -4848,7 +4925,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
// Undo goes through the same narrow refresh without the edit at hand.
session.undo(id).unwrap();
let undone = session.get(id).unwrap();
- assert!(undone.added.is_empty(), "undo drops the added text");
+ assert!(undone.added().is_empty(), "undo drops the added text");
assert_eq!(format!("{:?}", undone.info.pages), pages);
}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index ba2d97040..22a96274c 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -2558,8 +2558,8 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
}
view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());
view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), scale);
- let added = doc.added.clone();
- let doc_links = if tool == QuickTool::Link { doc.links.clone() } else { Vec::new() };
+ let added = if editing_content { doc.added().to_vec() } else { Vec::new() };
+ let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };
if editing_content {
crate::content_ui::after_refresh(view, &added);
} else {
@@ -2961,7 +2961,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
&& resp.secondary_clicked()
&& can_modify
&& let Some(p) = pointer.filter(|p| xf.rect.contains(*p))
- && let Some(l) = doc.links.iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))
+ && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))
{
view.links.context = Some((i, l.index));
}
diff --git a/crates/ui-egui/src/content_ui.rs b/crates/ui-egui/src/content_ui.rs
index 72d308a15..58b35de9f 100644
--- a/crates/ui-egui/src/content_ui.rs
+++ b/crates/ui-egui/src/content_ui.rs
@@ -134,7 +134,7 @@ impl MoveBackground {
*self = Self { key, ..Default::default() };
if let Some((_, page, index)) = key {
self.renderer = doc.added_content_preview(page, index).ok().map(|p| p.renderer());
- self.from = on_page(&doc.added, page).into_iter().find(|(i, _)| *i == index).map(|(_, a)| a.content.rect());
+ self.from = on_page(doc.added(), page).into_iter().find(|(i, _)| *i == index).map(|(_, a)| a.content.rect());
}
}
if self.settling.is_some() {
@@ -727,7 +727,7 @@ impl crate::PdfCraftApp {
pub fn add_image(&mut self, name: String, bytes: Vec<u8>) {
let Some((i, id)) = self.active_ids() else { return };
let page = self.views[i].current;
- let before = self.session.get(id).map_or(0, |d| d.added.iter().filter(|a| a.page == page).count());
+ let before = self.session.get(id).map_or(0, |d| d.added().iter().filter(|a| a.page == page).count());
if self.apply_edit(Edit::AddImage { page, rect: None, name, bytes: std::sync::Arc::new(bytes) }) {
self.views[i].content.select_added = Some((page, before));
self.left = crate::LeftPanel::Tool("edit");
diff --git a/crates/ui-egui/src/link_ui.rs b/crates/ui-egui/src/link_ui.rs
index a969a195d..c714870c5 100644
--- a/crates/ui-egui/src/link_ui.rs
+++ b/crates/ui-egui/src/link_ui.rs
@@ -149,7 +149,7 @@ impl PdfCraftApp {
/// Open Link Properties for a new link area or an existing link.
pub(crate) fn open_link_props(&mut self, page: usize, rect: Option<[f64; 4]>, index: Option<usize>) {
let Some((_, id)) = self.active_ids() else { return };
- let existing = index.and_then(|i| self.session.get(id).and_then(|d| d.links.iter().find(|l| l.page == page && l.index == i).cloned()));
+ let existing = index.and_then(|i| self.session.get(id).and_then(|d| d.links().iter().find(|l| l.page == page && l.index == i).cloned()));
let draft = match existing {
Some(l) => LinkDraft {
page,
@@ -203,7 +203,7 @@ impl PdfCraftApp {
/// Remove every link in the active document.
pub fn remove_all_links(&mut self) {
let Some((_, id)) = self.active_ids() else { return };
- let count = self.session.get(id).map_or(0, |d| d.links.len());
+ let count = self.session.get(id).map_or(0, |d| d.links().len());
if count == 0 {
self.notify_tr("No links to remove");
return;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 411403039..8c39874d9 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -437,7 +437,7 @@ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
let image = app.active_ids().and_then(|(i, id)| {
let (page, index) = app.views[i].content.selected?;
let doc = app.session.get(id)?;
- match &doc.added.iter().filter(|a| a.page == page).nth(index)?.content {
+ match &doc.added().iter().filter(|a| a.page == page).nth(index)?.content {
pdfcraft_engine::AddedContent::Image(img) => Some((page, index, img.clone())),
_ => None,
}
@@ -457,7 +457,7 @@ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
let selected = app.active_ids().and_then(|(i, id)| {
let (page, index) = app.views[i].content.selected?;
let doc = app.session.get(id)?;
- let a = doc.added.iter().filter(|a| a.page == page).nth(index)?;
+ let a = doc.added().iter().filter(|a| a.page == page).nth(index)?;
match &a.content {
pdfcraft_engine::AddedContent::Text(text) => Some((page, index, text.clone())),
_ => None,
diff --git a/crates/ui-egui/tests/content.rs b/crates/ui-egui/tests/content.rs
index 722144896..3ad4851ab 100644
--- a/crates/ui-egui/tests/content.rs
+++ b/crates/ui-egui/tests/content.rs
@@ -45,7 +45,7 @@ fn click(h: &mut Harness<'static, PdfCraftApp>, p: Pos2) {
fn added(h: &Harness<'static, PdfCraftApp>) -> Vec<pdfcraft_engine::Added> {
let s = h.state();
- s.session.get(s.views[0].id).unwrap().added.clone()
+ s.session.get(s.views[0].id).unwrap().added().to_vec()
}
/// A click whose press and release arrive in the same frame, as a quick real mouse click does.
diff --git a/crates/ui-egui/tests/editing.rs b/crates/ui-egui/tests/editing.rs
index 360cb4f61..883c36722 100644
--- a/crates/ui-egui/tests/editing.rs
+++ b/crates/ui-egui/tests/editing.rs
@@ -3273,7 +3273,7 @@ fn check_added_text_drag(panel_open: bool) {
h.run_steps(4);
let added = |h: &Harness<'static, PdfCraftApp>| {
let app = h.state();
- app.session.get(app.views[0].id).unwrap().added.clone()
+ app.session.get(app.views[0].id).unwrap().added().to_vec()
};
let before_added = added(&h);
assert_eq!(before_added.len(), 1);
diff --git a/crates/ui-egui/tests/ui_group/marks.rs b/crates/ui-egui/tests/ui_group/marks.rs
index 285442f97..0a0e45b15 100644
--- a/crates/ui-egui/tests/ui_group/marks.rs
+++ b/crates/ui-egui/tests/ui_group/marks.rs
@@ -27,7 +27,7 @@ fn harness() -> Harness<'static, PdfCraftApp> {
fn marks(h: &Harness<'static, PdfCraftApp>) -> Vec<MarkKind> {
let s = h.state();
- s.session.get(s.views[0].id).unwrap().marks.clone()
+ s.session.get(s.views[0].id).unwrap().marks().to_vec()
}
#[test]
diff --git a/crates/ui-egui/tests/ui_group/pdf_links.rs b/crates/ui-egui/tests/ui_group/pdf_links.rs
index 0916de8e3..7ed2903bc 100644
--- a/crates/ui-egui/tests/ui_group/pdf_links.rs
+++ b/crates/ui-egui/tests/ui_group/pdf_links.rs
@@ -40,7 +40,7 @@ fn drag(h: &mut Harness<'static, PdfCraftApp>, a: Pos2, b: Pos2) {
fn links(h: &Harness<'static, PdfCraftApp>) -> Vec<pdfcraft_engine::LinkItem> {
let s = h.state();
- s.session.get(s.views[0].id).unwrap().links.clone()
+ s.session.get(s.views[0].id).unwrap().links().to_vec()
}
#[test]