DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge remote-tracking branch 'origin/main' into package-pdf-preset
moppeeer6efe6f580c3c
diff --cc crates/engine/src/cmd/export.rsindex 6153a8ecf,a6dd964eb..5a282b726--- a/crates/engine/src/cmd/export.rs+++ b/crates/engine/src/cmd/export.rs@@@ -742,63 -799,21 +810,69 @@@ fn flatten_ppi(p: &Value) -> Result<OptSome(v) => Some(v.as_f64().filter(|v| (36.0..=1200.0).contains(v)).ok_or_else(|| bad("file.exportPdf", "`flatten`: high|medium|low or 36–1200 ppi"))?,),+ })+}++/// The catalog entries of the interactive view options in `p` (page mode and layout) and the+/// destination the first page opens at (`view`); unknown values are refused.+fn view_options(p: &Value) -> Result<(String, Option<&'static str>)> {+ let mut cat = String::new();+ if p.get("fullScreen").and_then(Value::as_bool) == Some(true) {+ cat.push_str("/PageMode/FullScreen");+ } else if p.get("bookmarksPanel").and_then(Value::as_bool) == Some(true) {+ cat.push_str("/PageMode/UseOutlines");+ }+ match str_param(p, "pageLayout") {+ Some("single") => cat.push_str("/PageLayout/SinglePage"),+ Some("continuous") => cat.push_str("/PageLayout/OneColumn"),+ Some("twoUp") => cat.push_str("/PageLayout/TwoPageLeft"),+ Some("twoUpCover") => cat.push_str("/PageLayout/TwoPageRight"),+ Some("twoUpContinuous") => cat.push_str("/PageLayout/TwoColumnRight"),+ Some(o) => return Err(bad("file.exportPdf", format!("unknown pageLayout `{o}`"))),+ None => {}+ }+ let dest = match str_param(p, "view") {+ None => None,+ Some("fitPage") => Some("/Fit"),+ Some("fitWidth") => Some("/FitH null"),+ Some("actual") => Some("/XYZ null null 1"),+ Some(o) => return Err(bad("file.exportPdf", format!("unknown view `{o}` (fitPage, fitWidth, actual)"))),};- let flattened = ppi.map(|ppi| flatten(&st.doc, &s.cache, ppi));- let base: &designcraft_doc::Document = flattened.as_ref().map_or(&st.doc, |f| &f.0);+ Ok((cat, dest))+}++/// Refuses PDF options `p` that `pdf_report` would refuse for a document of `pages` pages,+/// without exporting: `file.package` checks them before it writes anything.+pub(super) fn check_pdf_options(p: &Value, pages: usize) -> Result<()> {+ options(p, pages)?;+ flatten_ppi(p)?;+ view_options(p)?;+ Ok(())+}++/// The PDF of `doc` as `file.exportPdf` makes it from options `p`: flattened when asked, placed+/// PDFs with hidden layers and soft effects as images, the blend space, the view options and the+/// page transitions. `file.package` writes its PDF with it too.+pub(super) fn pdf_report(doc: &designcraft_doc::Document, cache: &designcraft_compose::Cache, p: &Value) -> Result<designcraft_pdf::ExportReport> {+ let opts = options(p, doc.page_count())?;+ let (mut cat, dest) = view_options(p)?;+ let flattened = flatten_ppi(p)?.map(|ppi| flatten(doc, cache, ppi));- // Placed PDFs with hidden layers go out as images showing just their visible layers.++ // PDF/A-2b: placed PDFs with hidden layers go out as images showing just their visible++ // layers (other exports keep them as vectors, with those layers off).++ let src = doc;+ let base: &designcraft_doc::Document = flattened.as_ref().map_or(doc, |f| &f.0);- let (layered, layer_count) = rasterize_layered(base)?;+ let (layered, layer_count) = if opts.standard == Standard::PdfA2b { rasterize_layered(base)? } else { (None, 0) };let base2: &designcraft_doc::Document = layered.as_ref().unwrap_or(base);- let (fx_doc, fx_count) = rasterize_effects(base2, &s.cache);+ let (fx_doc, fx_count) = rasterize_effects(base2, cache);let doc: &designcraft_doc::Document = fx_doc.as_ref().unwrap_or(base2);let boxed = super::interchange::with_pdf_boxes(doc);let doc: &designcraft_doc::Document = &boxed;- let r = designcraft_pdf::export_pdf_with_report(doc, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;+ let r = designcraft_pdf::export_pdf_with_report(doc, cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;let mut r = r;+ // Flattening and effect rasterization replace placements, so inspect the source too.- if st.doc.has_graphic_layer_visibility_overrides() && !r.warnings.iter().any(|w| w == designcraft_doc::GRAPHIC_LAYER_RENDERING_WARNING) {++ if src.has_graphic_layer_visibility_overrides() && !r.warnings.iter().any(|w| w == designcraft_doc::GRAPHIC_LAYER_RENDERING_WARNING) {+ r.warnings.push(designcraft_doc::GRAPHIC_LAYER_RENDERING_WARNING.into());+ }// Transparency Blend Space: the page group of pages with transparency.let spreads = designcraft_pdf::sheet_spreads(doc, &opts);let blended: Vec<bool> = spreads.iter().map(|si| doc.spreads.get(*si).is_some_and(|sp| sp.items.iter().any(|it| transparent(it)))).collect();@@@ -850,9 -888,193 +924,187 @@@{r.warnings.push(format!("transparency flattened: {n} region(s) rasterised"));}- match str_param(p, "path") {- Some(path) => {- write_file(path, &r.bytes)?;- Ok(json!({"path": path, "bytes": r.bytes.len(), "pages": r.pages, "warnings": r.warnings}))- }- None => Ok(json!({"base64": super::base64_encode(&r.bytes), "bytes": r.bytes.len(), "pages": r.pages, "warnings": r.warnings})),- }+ Ok(r)}+ #[cfg(test)]+ mod placed_layer_tests {+ use std::sync::Arc;++ use designcraft_doc::{AnchoredObject, Document, Item, ItemId, SpreadRef, StoryId, Table};+ use designcraft_geom::Rect;+ use serde_json::json;++ use crate::Session;++ fn two_layer_pdf() -> Vec<u8> {+ let content = "/OC /a BDC 0 0 1 rg 0 0 50 100 re f EMC /OC /b BDC 1 0 0 rg 50 0 50 100 re f EMC";+ let objs = [+ "<</Type/Catalog/Lang(en-GB)/Pages 2 0 R/OCProperties<</OCGs[5 0 R 6 0 R]/D<</Order[5 0 R 6 0 R]/Name(Default)/Locked[5 0 R]>>>>>>"+ .to_string(),+ "<</Type/Pages/Kids[3 0 R]/Count 1>>".to_string(),+ "<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/Resources<</Properties<</a 5 0 R/b 6 0 R>>>>/Contents 4 0 R>>".to_string(),+ format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()),+ "<</Type/OCG/Name(Blue)>>".to_string(),+ "<</Type/OCG/Name(Red)>>".to_string(),+ ];+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offs = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offs.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", i + 1, o).as_bytes());+ }+ let x = out.len();+ let mut t = format!("xref\n0 {}\n0000000000 65535 f\r\n", objs.len() + 1);+ for o in offs {+ t.push_str(&format!("{o:010} 00000 n\r\n"));+ }+ t.push_str(&format!("trailer\n<</Size {}/Root 1 0 R>>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1));+ out.extend_from_slice(t.as_bytes());+ out+ }++ fn placement<'a>(d: &'a Document, location: &str, id: ItemId, sid: StoryId) -> &'a Item {+ match location {+ "cell" => &d.story(sid).unwrap().tables.values().next().unwrap().cells[0].text.objects[0].item,+ "footnote" => &d.story(sid).unwrap().notes[0].text.objects[0].item,+ "endnote" => &d.story(sid).unwrap().endnotes[0].text.objects[0].item,+ "anchor" => &d.story(sid).unwrap().objects[0].item,+ _ => d.item(id).unwrap(),+ }+ }++ #[test]+ fn stale_layer_fields_on_non_pdf_placements_do_not_block_pdf_a() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let result = s+ .execute(+ "file.place",+ &json!({+ "base64": super::super::file::base64_encode(&two_layer_pdf()), "name": "layers.pdf",+ }),+ )+ .unwrap();+ let id = ItemId(result["id"].as_u64().unwrap());+ s.execute("object.layerOptions", &json!({"ids": [id.0], "hidden": ["Blue"]})).unwrap();+ // Relinking to an ordinary image can leave legacy fields on the placement.+ // They are not an actionable placed-PDF override and must not fail closed.+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ let aid = d.item(id).unwrap().graphic().unwrap().asset;+ let asset = Arc::make_mut(d.assets.get_mut(&aid).unwrap());+ asset.mime = "image/png".into();+ asset.data = Arc::new(designcraft_render::Rendered { width: 1, height: 1, pixels: vec![0, 0, 0, 0] }.to_png());+ let (copy, count) = super::rasterize_layered(d).unwrap();+ assert_eq!(count, 0);+ assert!(copy.is_none());+ s.execute("file.exportPdf", &json!({"standard": "a2b"})).unwrap();+ }++ fn check_placement(location: &str) {+ for all_on in [false, true] {+ check_choice(location, all_on);+ }+ }++ fn check_choice(location: &str, all_on: bool) {+ let mut s = Session::new();+ s.execute("file.new", &json!({"width": 100, "height": 100, "pages": 1})).unwrap();+ let placed = s+ .execute(+ "file.place",+ &json!({+ "base64": super::super::file::base64_encode(&two_layer_pdf()), "name": "layers.pdf",+ "x": 0, "y": 0, "width": 100,+ "spread": {"kind": if location == "parent" { "parent" } else { "doc" }, "index": 0}+ }),+ )+ .unwrap();+ let id = ItemId(placed["id"].as_u64().unwrap());+ let hidden = if all_on { vec![] } else { vec!["Blue"] };+ s.execute("object.layerOptions", &json!({"ids": [id.0], "hidden": hidden, "useDefaults": false})).unwrap();+ let sid = {+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ let layer = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 80.0), layer, "Body", Default::default()).unwrap();+ if !matches!(location, "doc" | "parent") {+ let item = (**d.spreads[0].items.iter().find(|it| it.id == id).unwrap()).clone();+ Arc::make_mut(&mut d.spreads[0]).items.retain(|it| it.id != id);+ let object = AnchoredObject { item, position: Default::default() };+ let story = d.story_mut(sid).unwrap();+ match location {+ "cell" => {+ let mut table = Table::new(1, 1, 1, 0, 0, 20.0);+ table.cells[0].text.insert_object(0, object);+ story.insert_table(0, table);+ }+ "footnote" => {+ story.insert_note(0, "Note", Default::default()).unwrap();+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, object);+ }+ "endnote" => {+ story.insert_endnote(0, "Endnote", Default::default()).unwrap();+ Arc::make_mut(&mut story.endnotes[0]).text.insert_object(0, object);+ }+ "anchor" => story.insert_object(0, object),+ _ => assert!(matches!(location, "doc" | "parent")),+ }+ }+ sid+ };+ // Exercise the real export command for each location, not just the traversal helper.+ let result = s.execute("file.exportPdf", &json!({"standard": "a2b"})).unwrap();+ assert!(+ result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("1 placed PDF(s)")),+ "{location}: {}",+ result["warnings"]+ );+ // Check the rewritten placement, including its pixels. Counting a placement without+ // updating the nested object would still export the file's default layer visibility.+ let source = &s.doc().unwrap().doc;+ let (copy, count) = super::rasterize_layered(source).unwrap();+ assert_eq!(count, 1, "{location}");+ let copy = copy.unwrap();+ let item = placement(©, location, id, sid);+ let asset = ©.assets[&item.graphic().unwrap().asset];+ assert_eq!(asset.mime, "image/png", "{location}");+ let image = designcraft_render::images::decoded(&asset.data, 0);+ let image = image.unwrap();+ let pixel = image.data()[usize::from(image.height()) / 2 * usize::from(image.width()) + usize::from(image.width()) / 4];+ assert_eq!(pixel.a, if all_on { 255 } else { 0 }, "Blue visibility at {location}, all_on={all_on}");+ // Export preparation must not change the open document's placement or source asset.+ let original = placement(source, location, id, sid);+ assert_eq!(original.pdf_hidden_layers, hidden);+ assert!(original.pdf_layer_override);+ assert_eq!(source.assets[&original.graphic().unwrap().asset].mime, "application/pdf");+ }++ #[test]+ fn layered_pdf_a_document_placement() {+ check_placement("doc");+ }+ #[test]+ fn layered_pdf_a_parent_placement() {+ check_placement("parent");+ }+ #[test]+ fn layered_pdf_a_story_anchor() {+ check_placement("anchor");+ }+ #[test]+ fn layered_pdf_a_table_cell_anchor() {+ check_placement("cell");+ }+ #[test]+ fn layered_pdf_a_footnote_anchor() {+ check_placement("footnote");+ }+ #[test]+ fn layered_pdf_a_endnote_anchor() {+ check_placement("endnote");+ }+ }+#[cfg(not(target_arch = "wasm32"))]fn write_file(path: &str, bytes: &[u8]) -> Result<()> {crate::io::write_file(path, bytes).map_err(EngineError::Other)diff --cc crates/engine/src/cmd/package.rsindex d415108c9,3598c3c21..5f907c7f6--- a/crates/engine/src/cmd/package.rs+++ b/crates/engine/src/cmd/package.rs@@@ -444,15 -437,19 +448,18 @@@ fn package(s: &mut Session, p: &Value)let opts = designcraft_idml::ExportOptions { embed_images: false };root.write(&path, &designcraft_idml::export_idml_with(&packed, &opts))?;files.push(path);+ if super::interchange::has_applicable_pdf_layer_overrides(&packed) {+ idml_layer_note = "\nPlaced PDF layers\nThe IDML copy links the placed PDFs, so it shows their file defaults. The DesignCraft document keeps each placement's Object Layer Options choice.\n";+ }}- if p.get("pdf").and_then(Value::as_bool).unwrap_or(false) {+ if let Some(params) = pdf {let path = package_output_path(&dir, &title, "pdf")?;- let bytes = designcraft_pdf::export_pdf(&super::interchange::with_pdf_boxes(&packed), &s.cache, &Default::default())- .map_err(|e| EngineError::Other(e.to_string()))?;- root.write(&path, &bytes)?;+ root.write(&path, &super::export::pdf_report(&packed, &s.cache, ¶ms)?.bytes)?;files.push(path);}- // The report: fonts (missing first), links, preflight, the user's instructions.- let mut r = format!("Package report: {display_title}\n\n");+ // The printing instructions first, as the form gave them; then the report: fonts (missing+ // first), links, preflight.+ let mut r = String::new();if let Some(t) = str_param(p, "instructions").filter(|t| !t.trim().is_empty()) {r += &format!("Instructions\n{t}\n\n");}@@@ -521,58 -518,32 +529,84 @@@ mod testsstd::fs::remove_dir_all(dir).unwrap();}+ /// `pdf` takes file.exportPdf's options (a PDF preset's): a PDF/X-4 package PDF; `true` is the+ /// default PDF, and bad options are refused.+ #[test]+ fn package_pdf_takes_export_options() {+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let dir = std::env::temp_dir().join(format!("dc-package-pdf-options-{}-{nonce}", std::process::id()));+ let mut s = Session::new();+ s.execute("file.new", &json!({"title": "Options", "width": 72, "height": 72})).unwrap();+ let x4 = dir.join("x4");+ s.execute("file.package", &json!({"dir": x4.to_string_lossy(), "idml": false, "pdf": {"standard": "x4"}})).unwrap();+ let has = |path: &std::path::Path, what: &[u8]| std::fs::read(path).unwrap().windows(what.len()).any(|w| w == what);+ assert!(has(&x4.join("Options.pdf"), b"GTS_PDFX"));+ let plain = dir.join("plain");+ s.execute("file.package", &json!({"dir": plain.to_string_lossy(), "idml": false, "pdf": true})).unwrap();+ assert!(!has(&plain.join("Options.pdf"), b"GTS_PDFX"));+ // Refused before anything is written: bad options, a bad flattener or view option, and a+ // `pdf` that is neither a switch nor options.+ for bad in [+ json!({"standard": "nope"}),+ json!({"flatten": "extreme"}),+ json!({"pageLayout": "spiral"}),+ json!({"view": "zoomed"}),+ json!("print"),+ json!(3),+ ] {+ let out = dir.join("bad");+ assert!(s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": bad})).is_err(), "{bad}");+ assert!(!out.exists(), "{bad}: bad options write nothing");+ }+ std::fs::remove_dir_all(dir).unwrap();+ }++ /// A preset that flattens transparency (Screen and Email's `flatten: low`) gives the packaged+ /// PDF the flattening `file.exportPdf` does.+ #[test]+ fn the_packaged_pdf_is_flattened_as_export_flattens_it() {+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let dir = std::env::temp_dir().join(format!("dc-package-pdf-flatten-{}-{nonce}", std::process::id()));+ let mut s = Session::new();+ s.execute("file.new", &json!({"title": "Flat", "width": 144, "height": 144})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [10, 10, 100, 100], "content": "unassigned"})).unwrap()["id"].clone();+ s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap();+ s.execute("object.opacity", &json!({"ids": [id], "opacity": 0.5})).unwrap();+ let exported = super::super::base64_decode(s.execute("file.exportPdf", &json!({"flatten": "low"})).unwrap()["base64"].as_str().unwrap());+ s.execute("file.package", &json!({"dir": dir.to_string_lossy(), "idml": false, "pdf": {"flatten": "low"}})).unwrap();+ let packaged = std::fs::read(dir.join("Flat.pdf")).unwrap();+ let images = |pdf: &[u8]| pdf.windows(b"/Subtype/Image".len()).filter(|w| *w == b"/Subtype/Image").count();+ assert!(images(&exported) > 0, "the export rasterises the transparent object");+ assert_eq!(images(&packaged), images(&exported), "so does the package");+ std::fs::remove_dir_all(dir).unwrap();+ }++ /// A per-placement PDF layer choice cannot travel in an IDML copy that links its files, so the+ /// report says the copies differ instead of leaving it to be discovered.+ #[test]+ fn package_report_names_placed_pdf_layer_choices() {+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let dir = std::env::temp_dir().join(format!("dc-package-pdf-layers-{}-{nonce}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let pdf = super::super::pdflayers::tests::two_layer_pdf();+ let mut s = Session::new();+ s.execute("file.new", &json!({"title": "LayeredPackage", "width": 100, "height": 100})).unwrap();+ let id = s+ .execute("file.place", &json!({"base64": super::super::base64_encode(&pdf), "name": "art.pdf", "x": 0, "y": 0, "width": 100}))+ .unwrap()["id"]+ .clone();+ s.execute("object.layerOptions", &json!({"ids": [id], "hidden": ["Red"]})).unwrap();+ let r = s.execute("file.package", &json!({"dir": dir.to_string_lossy(), "idml": true, "pdf": false})).unwrap();+ let report = r["report"].as_str().unwrap();+ assert!(report.contains("Placed PDF layers"), "{report}");+ // The DesignCraft copy keeps the choice; only the linked IDML copy shows file defaults.+ let packed = super::super::from_bytes(&std::fs::read(dir.join("LayeredPackage.designcraft")).unwrap()).unwrap();+ let item = packed.item(designcraft_doc::ItemId(id.as_u64().unwrap())).unwrap();+ assert_eq!(item.pdf_hidden_layers, vec!["Red".to_string()]);+ assert!(item.has_pdf_layer_override());+ std::fs::remove_dir_all(dir).unwrap();+ }+/// The package's IDML links its images to the files in the package's Links folder and embeds/// no copies of them.#[test]diff --cc crates/ui-egui/src/lib.rsindex c019a1503,96c2c6eda..e17baaeb9--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -21,7 -21,7 +21,8 @@@ pub mod menusmod modal_drag;mod new_document;mod object_control;+pub mod package_dialog;+ mod page_history;mod panel_docking;pub mod panels;mod prefs;