PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge upstream main ec0a9650 into pr/attachments
Osvaldo Durane76adf812ac1
diff --cc crates/automation/tests/automation.rsindex 2e0ee7422,cbf40f196..84f59000a--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@@ -6698,42 -6766,92 +6766,132 @@@ fn a_root_less_write_output_is_atomic_tlet _ = std::fs::remove_dir_all(&dir);}+#[test]+fn attaching_and_deleting_files_through_the_tools() {+ let dir = workdir("attach");+ std::fs::write(dir.join("notes.txt"), b"keep this with the PDF").unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ assert!(ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].as_array().unwrap().is_empty());+ // A text file and a PDF, the PDF under a name of its own; the second notes.txt is kept apart.+ let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "notes.txt", "description": "Meeting notes" }));+ assert_eq!(r["name"], "notes.txt");+ let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "b.pdf", "name": "annex.pdf" }));+ assert_eq!(r["name"], "annex.pdf");+ let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));+ assert_eq!(r["name"], "notes.txt (2)");+ let listed = ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].clone();+ let names: Vec<&str> = listed.as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();+ assert_eq!(names, ["annex.pdf", "notes.txt", "notes.txt (2)"]);+ assert_eq!(listed[1]["description"], "Meeting notes");+ assert_eq!(listed[1]["size"], 22);+ // Saved and reopened, the attachment is there with its bytes.+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "with-notes.pdf" }));+ let saved = std::fs::read(dir.join("with-notes.pdf")).unwrap();+ let info = pdfcraft_render::inspect(std::sync::Arc::new(saved.clone()), None).unwrap();+ let att = info.attachments.iter().find(|x| x.name == "notes.txt").expect("notes.txt is in the file");+ assert_eq!(pdfcraft_render::attachment_data(&saved, None, att).unwrap(), b"keep this with the PDF");+ // Deleting one leaves the others; a name that is not there is refused; undo brings it back.+ ok(&mut a, "attachment_delete", json!({ "doc": doc, "name": "notes.txt" }));+ let names: Vec<String> = ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"]+ .as_array()+ .unwrap()+ .iter()+ .map(|x| x["name"].as_str().unwrap().to_string())+ .collect();+ assert_eq!(names, ["annex.pdf", "notes.txt (2)"]);+ assert!(a.call("attachment_delete", &json!({ "doc": doc, "name": "notes.txt" })).is_err());+ ok(&mut a, "edit_undo", json!({ "doc": doc }));+ assert_eq!(ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].as_array().unwrap().len(), 3);+ assert!(a.call("attachment_add", &json!({ "doc": doc, "path": "missing.txt" })).is_err(), "a file that is not there is refused");+}+++ #[test]+ fn fdf_nested_comment_values_survive_export_import_and_save_through_tools() {+ use pdfcraft_cos::{Dict, Document, Object, PdfString, SaveOptions, write_full};+ use std::sync::Arc;+ let dir = workdir("fdf-nested-values");+ let mut source = Document::open(Arc::new(fixture(1))).unwrap();+ let page = pdfcraft_model::pages(&source)[0].obj;+ let mut note = Dict::new();+ note.set(b"Type".to_vec(), Object::name("Annot"));+ note.set(b"Subtype".to_vec(), Object::name("Square"));+ note.set(b"NM".to_vec(), PdfString::text("nested-values"));+ note.set(b"Rect".to_vec(), Object::Array([10, 20, 30, 40].map(|value| Object::Ref(source.add(Object::Int(value)))).into()));+ note.set(b"C".to_vec(), Object::Array([0.25, 0.5, 0.75].map(|value| Object::Ref(source.add(Object::Real(value)))).into()));+ let note = source.add(note);+ source.update_dict(page, |dict| dict.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(note)]))).unwrap();+ std::fs::write(dir.join("source.pdf"), write_full(&source, &SaveOptions::default()).unwrap()).unwrap();+ let mut a = auto(&dir);+ let source = ok(&mut a, "doc_open", json!({ "path": "source.pdf" }))["doc"].as_u64().unwrap();++ ok(&mut a, "doc_export_data", json!({ "doc": source, "path": "notes.fdf", "what": "comments" }));+ let target = ok(&mut a, "doc_open", json!({ "path": "b.pdf" }))["doc"].as_u64().unwrap();+ ok(&mut a, "doc_import_data", json!({ "doc": target, "path": "notes.fdf" }));+ ok(&mut a, "doc_save", json!({ "doc": target, "path": "restored.pdf" }));+ let reopened = ok(&mut a, "doc_open", json!({ "path": "restored.pdf" }))["doc"].as_u64().unwrap();+ let after = ok(&mut a, "comment_list", json!({ "doc": reopened }));+ // The saved input has legal indirect scalar numbers. The engine's source inspection+ // currently reads those as defaults, so compare the restored data to the fixture's+ // known values (converted from PDF bottom-left to the tool's top-left coordinates).+ assert_eq!(after["comments"][0]["rect"], json!([10.0, 260.0, 30.0, 280.0]));+ assert_eq!(after["comments"][0]["color"], "#4080BF");+ }++ #[test]+ fn refused_fdf_export_keeps_the_destination_and_source_through_tools() {+ use pdfcraft_cos::{Dict, Document, Object, SaveOptions, write_full};+ use std::sync::Arc;+ let dir = workdir("fdf-export-limit");+ let mut source = Document::open(Arc::new(fixture(1))).unwrap();+ let page = pdfcraft_model::pages(&source)[0].obj;+ let mut note = Dict::new();+ note.set(b"Type".to_vec(), Object::name("Annot"));+ note.set(b"Subtype".to_vec(), Object::name("Square"));+ note.set(b"Rect".to_vec(), Object::Array(vec![10.into(), 20.into(), 30.into(), 40.into()]));+ note.set(b"PCData".to_vec(), Object::Array(vec![Object::Null; 100_001]));+ let note = source.add(note);+ source.update_dict(page, |dict| dict.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(note)]))).unwrap();+ let bytes = write_full(&source, &SaveOptions::default()).unwrap();+ std::fs::write(dir.join("source.pdf"), &bytes).unwrap();+ std::fs::write(dir.join("notes.fdf"), b"existing destination").unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "source.pdf" }))["doc"].as_u64().unwrap();+ let before = ok(&mut a, "comment_list", json!({ "doc": doc }));+ let error = a.call("doc_export_data", &json!({ "doc": doc, "path": "notes.fdf", "what": "comments" })).unwrap_err();+ assert!(error.to_string().contains("100,000 values"), "{error}");+ assert_eq!(std::fs::read(dir.join("notes.fdf")).unwrap(), b"existing destination");+ assert_eq!(std::fs::read(dir.join("source.pdf")).unwrap(), bytes);+ assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc })), before);+ }++ #[test]+ fn text_box_and_callout_fill_and_border_through_tools() {+ let dir = workdir("textbox-fill");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ for kind in ["textbox", "callout"] {+ let mut args = json!({ "doc": doc, "page": 1, "type": kind, "rect": [80, 40, 180, 100], "contents": "Example" });+ if kind == "callout" {+ args["to"] = json!([20, 120]);+ }+ let added = ok(&mut a, "comment_add", args);+ let comment = &added["comment"];+ ok(&mut a, "comment_edit", json!({ "doc": doc, "page": 1, "index": comment["index"], "fill": "white", "width": 3 }));+ }+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "filled.pdf" }));+ let mut session = pdfcraft_engine::Session::new();+ let bytes = std::sync::Arc::new(std::fs::read(dir.join("filled.pdf")).unwrap());+ let saved = session.open("filled.pdf", None, bytes, None).unwrap();+ for index in 0..2 {+ let props = session.get(saved).unwrap().comment_props(0, index).unwrap();+ assert_eq!((props.fill, props.width), (Some([1.0; 3]), Some(3.0)));+ ok(&mut a, "comment_edit", json!({ "doc": doc, "page": 1, "index": index + 1, "fill": "none" }));+ }+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "transparent.pdf" }));+ let bytes = std::sync::Arc::new(std::fs::read(dir.join("transparent.pdf")).unwrap());+ let saved = session.open("transparent.pdf", None, bytes, None).unwrap();+ for index in 0..2 {+ assert_eq!(session.get(saved).unwrap().comment_props(0, index).unwrap().fill, None);+ }+ }