PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M1: List document revisions and open an earlier one (Document Properties ▸ Advanced; doc_revisions, doc_open_revision); PDF version reads 1.7, not 17
Brandon Thomas19b5b1d6d27a
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex e05bff302..37115b769 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -273,6 +273,13 @@ impl Automation {}"doc_optimize" => self.doc_optimize(&a)?,"doc_initial_view" => self.doc_initial_view(&a)?,+ "doc_revisions" => self.doc_revisions(&a)?,+ "doc_open_revision" => {+ let id = self.doc(&a)?.id;+ let n = usize::try_from(a.opt_int("revision")?.ok_or_else(|| ToolError::InvalidArgs("revision is required".into()))?).unwrap_or(0);+ let new = self.session.open_revision(id, n).map_err(failed)?;+ summary(self.session.get(new).ok_or_else(|| failed("the document vanished"))?)+ }"doc_export_images" | "doc_export_text" => self.export(name, &a)?,"doc_header_footer" | "doc_watermark" | "doc_background" | "doc_remove_marks" => self.marks(name, &a)?,"doc_unprotect" => {@@ -373,6 +380,24 @@ impl Automation {Ok(json!({ "path": path, "bytes": bytes.len(), "incremental": !full, "document": summary(self.doc(a)?) }))}+ fn doc_revisions(&mut self, a: &Args) -> Result<Value> {+ let doc = self.doc(a)?;+ let ends = doc.revision_ends();+ let sigs = doc.signatures.clone();+ let list: Vec<Value> = ends+ .iter()+ .enumerate()+ .map(|(i, end)| {+ let start = if i == 0 { 0 } else { ends[i - 1] };+ // A signature signs the revision its byte range ends in.+ let signed: Vec<&str> =+ sigs.iter().filter(|s| s.signed && s.signed_len > start && s.signed_len <= *end).map(|s| s.field.as_str()).collect();+ json!({ "revision": i + 1, "end": end, "bytes": end - start, "signed_by": signed })+ })+ .collect();+ Ok(json!({ "revisions": list, "unsaved_changes": doc.dirty }))+ }+fn doc_initial_view(&mut self, a: &Args) -> Result<Value> {use printcraft_engine::{InitialLayout as L, Magnification as M, Navigation as N};let bad = |m: String| ToolError::InvalidArgs(m);diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex 90a261eed..3308106cd 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -733,6 +733,10 @@ pub fn tools() -> Vec<ToolDef> {}),&["doc"],)),+ t("doc_revisions", "List revisions", "List the document's saved revisions (oldest first): each incremental update is one. Returns revision number, where it ends in the file and its size, and which signatures sign exactly that revision.")+ .with(schema(json!({ "doc": doc() }), &["doc"])),+ t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")+ .with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.").cmd("optimize.advanced").with(schema(diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rsindex fb3bcdc6a..225df17ed 100644--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@ -1008,6 +1008,14 @@ fn digital_ids_signing_and_validation_through_tools() {// A full rewrite is refused for a signed document.assert!(matches!(a.call("doc_save", &json!({ "doc": doc, "path": "copy.pdf", "full": true })), Err(ToolError::Failed(_))));ok(&mut a, "doc_save", json!({ "doc": doc }));+ // Three revisions: the original, the signature, the comment; the middle one is signed.+ let revs = ok(&mut a, "doc_revisions", json!({ "doc": doc }))["revisions"].as_array().cloned().unwrap();+ assert_eq!(revs.len(), 3, "{revs:?}");+ assert!(revs[0]["signed_by"].as_array().unwrap().is_empty() && revs[1]["signed_by"].as_array().unwrap().len() == 1, "{revs:?}");+ let old = ok(&mut a, "doc_open_revision", json!({ "doc": doc, "revision": 2 }))["doc"].as_u64().unwrap();+ assert_eq!(ok(&mut a, "comment_list", json!({ "doc": old }))["comments"].as_array().map(Vec::len), Some(0), "before the comment");+ assert_eq!(ok(&mut a, "sign_list", json!({ "doc": old }))["count"], 1);+ assert!(matches!(a.call("doc_open_revision", &json!({ "doc": doc, "revision": 4 })), Err(ToolError::Failed(_))));assert_eq!(ok(&mut a, "sign_trust", json!({ "clear": true }))["trusted"].as_array().unwrap().len(), 0);assert_eq!(ok(&mut a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"], "unknown");}diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rsindex e221c5374..c66f2b493 100644--- a/crates/cos/src/document.rs+++ b/crates/cos/src/document.rs@@ -389,6 +389,28 @@ impl Document {&self.revisions}+ /// Where each revision of the file ends (oldest first): the byte after the `%%EOF` (and its+ /// end-of-line) that closes its cross-reference section. `data[..end]` is that revision as it+ /// was saved. A linearized file's first-page section belongs to the revision it precedes, so+ /// ends only ever increase. Empty for a reconstructed file.+ pub fn revision_ends(&self) -> Vec<usize> {+ let d = &self.data[..];+ let mut ends: Vec<usize> = Vec::with_capacity(self.revisions.len());+ for r in self.revisions.iter() {+ let from = (r.xref_offset as usize).saturating_add(self.header_offset).min(d.len());+ let Some(at) = d[from..].windows(5).position(|w| w == b"%%EOF") else { continue };+ let mut end = from + at + 5;+ while end < d.len() && matches!(d[end], b'\r' | b'\n') && end - (from + at + 5) < 2 {+ end += 1;+ }+ match ends.last_mut() {+ Some(last) if end <= *last => {}+ _ => ends.push(end),+ }+ }+ ends+ }+pub fn repair_log(&self) -> &[String] {&self.repair_log}@@ -934,6 +956,24 @@ mod tests {assert!(doc.get(ObjRef::new(1, 0)).as_dict().unwrap().get(b"Lang").is_none());}+ #[test]+ fn revision_ends_split_incremental_updates() {+ let mut bytes = build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], "/Root 1 0 R");+ let first = bytes.len();+ let doc = Document::open(Arc::new(bytes.clone())).unwrap();+ assert_eq!(doc.revision_ends(), vec![first]);+ let mut edited = doc.clone();+ edited.update_dict(ObjRef::new(1, 0), |d| d.set(b"Lang".to_vec(), Object::String(crate::PdfString::literal("en")))).unwrap();+ bytes = crate::write_incremental(&edited, &crate::SaveOptions::default()).unwrap();+ let doc = Document::open(Arc::new(bytes.clone())).unwrap();+ let ends = doc.revision_ends();+ assert_eq!(ends.len(), 2, "{ends:?}");+ assert!(ends[0] >= first && ends[0] < bytes.len() && ends[1] == bytes.len(), "{ends:?} of {}", bytes.len());+ // The first revision opens on its own, without the update.+ let old = Document::open(Arc::new(bytes[..ends[0]].to_vec())).unwrap();+ assert!(old.get(ObjRef::new(1, 0)).as_dict().unwrap().get(b"Lang").is_none());+ }+#[test]fn damaged_xref_is_reconstructed() {let mut bytes = build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], "/Root 1 0 R");diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex c8c1832ff..04fdf89fa 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -279,6 +279,12 @@ impl Document {.unwrap_or_else(|| self.name.clone())}+ /// Where each saved revision of the file ends (oldest first; `bytes[..end]` is that+ /// revision). Unsaved edits aren't a revision yet.+ pub fn revision_ends(&self) -> Vec<usize> {+ self.editor.as_ref().map(|e| e.cos.revision_ends()).unwrap_or_default()+ }+/// Notes about damage repaired while opening (Document Properties ▸ Advanced, notices).pub fn repair_log(&self) -> Vec<String> {self.editor.as_ref().map(|e| e.cos.repair_log().to_vec()).unwrap_or_default()@@ -1406,6 +1412,17 @@ impl Session {/// Open a document from bytes. Rendering starts lazily when pages are requested.////// `password` is tried as either the user or owner password when the file is encrypted.+ /// Open saved revision `n` (1 = the oldest) of a document as a new, unsaved document named+ /// "<name> (revision n)".+ pub fn open_revision(&mut self, id: DocId, n: usize) -> Result<DocId, String> {+ let doc = self.get(id).ok_or("no such document")?;+ let ends = doc.revision_ends();+ let end = *n.checked_sub(1).and_then(|i| ends.get(i)).ok_or_else(|| format!("the document has {} revision(s)", ends.len()))?;+ let name = format!("{} (revision {n}).pdf", doc.name.trim_end_matches(".pdf"));+ let (bytes, password) = (Arc::new(doc.bytes[..end.min(doc.bytes.len())].to_vec()), doc.password.clone());+ self.open(name, None, bytes, password.as_deref()).map_err(|e| e.to_string())+ }+pub fn open(&mut self, name: impl Into<String>, path: Option<String>, bytes: Arc<Vec<u8>>, password: Option<&str>) -> Result<DocId, OpenError> {let cos = std::panic::catch_unwind(|| printcraft_cos::Document::open_with_password(bytes.clone(), password));// The renderer authenticates on its own. It cannot use the owner password of R2–R4diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rsindex 19884e4cd..8248b7092 100644--- a/crates/render/src/inspect.rs+++ b/crates/render/src/inspect.rs@@ -226,7 +226,7 @@ pub fn inspect(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Result<DocInfo, OLoadPdfError::Decryption(other) => OpenError::Unsupported(format!("encryption not supported: {other:?}")),LoadPdfError::Invalid => OpenError::Invalid("no readable page tree or cross-reference data was found".into()),})?;- let mut info = DocInfo { file_size: bytes.len(), pdf_version: format!("{:?}", pdf.version()), ..Default::default() };+ let mut info = DocInfo { file_size: bytes.len(), pdf_version: version_label(&format!("{:?}", pdf.version())), ..Default::default() };let pages = catch_unwind(AssertUnwindSafe(|| {let mut out = Vec::new();for (i, page) in pdf.pages().iter().enumerate() {@@ -958,3 +958,22 @@ trailer << /Root 1 0 R >>assert_eq!(pretty_date("yesterday"), "yesterday");}}++/// "1.7" from the parser's version name ("Pdf17", "V1_7", …).+fn version_label(name: &str) -> String {+ let digits: Vec<char> = name.chars().filter(char::is_ascii_digit).collect();+ match digits[..] {+ [a, b] => format!("{a}.{b}"),+ _ => name.to_owned(),+ }+}++#[cfg(test)]+mod version_tests {+ #[test]+ fn version_labels_read_as_numbers() {+ assert_eq!(super::version_label("Pdf17"), "1.7");+ assert_eq!(super::version_label("V2_0"), "2.0");+ assert_eq!(super::version_label("Unknown"), "Unknown");+ }+}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 64543fa38..6e20f023b 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -48,6 +48,7 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {let mut optimize_now = false;let mut duplicate_now: Option<Edit> = None;let mut replace_now = false;+ let mut open_revision: Option<usize> = None;let t = Tokens::get(ctx);let mut close = false;let mut next = dialog;@@ -302,7 +303,7 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {}}PropsTab::Advanced => {- row(ui, "PDF version", i.pdf_version.replace("Pdf", "").replace('_', "."));+ row(ui, "PDF version", i.pdf_version.clone());row(ui, "Location", doc.path.clone().unwrap_or_default());row(ui, "File size", format!("{} ({} bytes)", human_size(i.file_size), i.file_size));let p = &i.pages[0];@@ -314,6 +315,21 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {row(ui, "Layers", i.layers.len().to_string());row(ui, "Attachments", i.attachments.len().to_string());row(ui, "JavaScript", yes(i.has_javascript));+ // Each incremental update is a revision; earlier ones open as their own document.+ let ends = doc.revision_ends();+ if ends.len() > 1 {+ ui.label(egui::RichText::new("Revisions").color(t.text_muted));+ ui.horizontal_wrapped(|ui| {+ ui.label(ends.len().to_string());+ for n in (1..ends.len()).rev().take(12) {+ if ui.small_button(format!("View revision {n}")).on_hover_text("Open the file as it was saved then").clicked()+ {+ open_revision = Some(n);+ }+ }+ });+ ui.end_row();+ }// Reading Options: binding and language.if let Some((_, v)) = app.view_draft.as_mut() {let editable = doc.allows_modification();@@ -1075,7 +1091,7 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {app.apply_edit(Edit::Batch { label: "Change document properties".into(), edits });}// Protect / Remove security replace the Properties dialog.- let replaces = link_command.is_some_and(|c| c.starts_with("protect."));+ let replaces = link_command.is_some_and(|c| c.starts_with("protect.")) || open_revision.is_some();if modal.should_close() || close || replaces {app.dialog = None;app.props_draft = None;@@ -1086,6 +1102,9 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {if let Some(cmd) = link_command {app.execute(cmd);}+ if let Some(n) = open_revision {+ app.open_revision(n);+ }}/// Info edits needed to make the document match the Description draft.diff --git a/crates/ui-egui/src/sign_ui.rs b/crates/ui-egui/src/sign_ui.rsindex a144c51d3..8ac60b4fa 100644--- a/crates/ui-egui/src/sign_ui.rs+++ b/crates/ui-egui/src/sign_ui.rs@@ -293,6 +293,19 @@ impl PrintCraftApp {self.session.set_trusted_certificates(certs);}+ /// Open saved revision `n` (1 = the oldest) of the active document as a new document.+ pub fn open_revision(&mut self, n: usize) {+ let Some((_, id)) = self.active_ids() else { return };+ match self.session.open_revision(id, n) {+ Ok(new) => {+ let info = &self.session.get(new).expect("just opened").info;+ self.views.push(DocView::new(new, info));+ self.active = Some(self.views.len() - 1);+ }+ Err(e) => self.notify(format!("Couldn't open revision {n}: {e}")),+ }+ }+/// Open the signed version of a signature as a new document (View signed version).pub fn view_signed_version(&mut self, len: usize) {let Some((_, id)) = self.active_ids() else { return };diff --git a/crates/ui-egui/tests/viewer.rs b/crates/ui-egui/tests/viewer.rsindex 4187fa429..78e30caf5 100644--- a/crates/ui-egui/tests/viewer.rs+++ b/crates/ui-egui/tests/viewer.rs@@ -298,3 +298,27 @@ fn tab_and_window_show_the_document_title_when_asked() {assert_eq!(h.state().window_title, "Quarterly report — PrintCraft");h.get_by_label_contains("Quarterly report");}++#[test]+fn an_earlier_revision_opens_from_document_properties() {+ use printcraft_engine::Edit;+ let mut h = harness();+ {+ let s = h.state_mut();+ let id = s.views[s.active.unwrap()].id;+ s.session.apply(id, Edit::SetInfo { key: "Title".into(), value: "Second".into() }).unwrap();+ let bytes = s.session.save_bytes(id).unwrap();+ s.open_bytes("updated.pdf", None, bytes.to_vec()).unwrap();+ }+ h.run_steps(2);+ h.state_mut().dialog = Some(Dialog::Properties(printcraft_ui_egui::PropsTab::Advanced));+ h.run_steps(2);+ h.run_steps(2);+ h.get_by_label("View revision 1").click();+ h.run_steps(3);+ let s = h.state();+ assert!(s.dialog.is_none(), "{:?} {:?}", s.dialog, s.session.get(s.views[s.active.unwrap()].id).unwrap().name);+ let doc = s.session.get(s.views[s.active.unwrap()].id).unwrap();+ assert_eq!(doc.name, "updated (revision 1).pdf");+ assert_eq!(doc.info_value("Title"), None, "as it was before the update");+}diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex f7b694484..a626fdc10 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -367,11 +367,11 @@ title = "List document revisions from the xref chain"area = "A"tier = "P1"milestone = "M1"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "shipped"+commands = ["file.properties"]+tools = ["doc_revisions"]+evidence = ["crates/cos/src/document.rs::revision_ends_split_incremental_updates", "crates/automation/tests/automation.rs::digital_ids_signing_and_validation_through_tools"]+notes = "revision ends from the xref chain (linearized first-page sections fold into their revision); listed in Document Properties ▸ Advanced and by doc_revisions with the signatures covering each"[[feature]]id = "core.view-revision"@@ -379,11 +379,11 @@ title = "View an earlier revision as a read-only snapshot"area = "A"tier = "P1"milestone = "M9"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "shipped"+commands = ["file.properties"]+tools = ["doc_open_revision"]+evidence = ["crates/ui-egui/tests/viewer.rs::an_earlier_revision_opens_from_document_properties", "crates/automation/tests/automation.rs::digital_ids_signing_and_validation_through_tools"]+notes = "opens the revision's bytes as a new unsaved document named '<name> (revision n)'"[[feature]]id = "core.lazy-loading"