DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge upstream/main into codex/fix-relink-eps
skylar taylor-barrick0d541deab74c
diff --cc Cargo.lockindex 6d85efbdd,bc2369d12..a2a1febc3--- a/Cargo.lock+++ b/Cargo.lock@@@ -978,10 -1066,9 +1066,10 @@@ dependencies =[[package]]name = "designcraft-format"- version = "0.4.0"+ version = "0.8.0"dependencies = ["designcraft-doc",+ "designcraft-images","serde","serde_json","thiserror 2.0.21",@@@ -1003,13 -1090,14 +1091,15 @@@ dependencies =[[package]]name = "designcraft-idml"- version = "0.4.0"+ version = "0.8.0"dependencies = ["designcraft-color",+ "designcraft-compose","designcraft-doc","designcraft-geom",+ "designcraft-images",- "quick-xml 0.38.4",+ "log",+ "quick-xml","thiserror 2.0.21","zip",]diff --cc apps/designcraft/src/main.rsindex 60155addb,a1b4d8276..b56878176--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@@ -264,16 -552,16 +556,26 @@@ fn main() -> std::process::ExitCode#[cfg(test)]mod tests {+ #[test]+ fn relink_open_dialog_lists_graphics() {+ let filters = super::open_filters("relink");+ let exts: Vec<&str> = filters.iter().flat_map(|filter| filter.extensions.iter().copied()).collect();+ for ext in ["png", "jpg", "tif", "psd", "svg", "pdf", "ai", "eps"] {+ assert!(exts.contains(&ext), "{ext} is missing from the relink dialog: {exts:?}");+ }+ assert!(!exts.contains(&"designcraft") && !exts.contains(&"idml"));+ }++ #[test]+ fn control_port_values_that_are_not_ports_are_ignored() {+ assert_eq!(super::control_port_from("--control", Some("7979".into())), Some(7979));+ assert_eq!(super::control_port_from("--control", Some(" 7979 ".into())), Some(7979));+ assert_eq!(super::control_port_from("--control", None), None);+ for bad in ["", "abc", "-1", "65536", "99999999999999999999"] {+ assert_eq!(super::control_port_from("--control", Some(bad.into())), None, "{bad:?}");+ }+ }+#[test]fn data_merge_open_dialog_lists_table_extensions() {let filters = super::open_filters("dataMerge");diff --cc crates/engine/src/cmd/datamerge/fill.rsindex eb3c42c7b,55db5d2a5..963f4189f--- a/crates/engine/src/cmd/datamerge/fill.rs+++ b/crates/engine/src/cmd/datamerge/fill.rs@@@ -340,7 -354,7 +354,7 @@@ fn place_imagereport.warnings.push(format!("Record {record}, field {field}: missing image {cell}."));return;};- let Some(((pw, ph), (nw, nh))) = designcraft_render::image_size(&bytes).zip(designcraft_render::image_natural_size(&bytes)) else {- let Some((pw, ph)) = designcraft_render::image_size(&bytes) else {++ let Some(((pw, ph), (nw, nh))) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0)) else {if let Some(it) = doc.item_mut(item) {it.content = Content::Unassigned;}@@@ -353,9 -367,31 +367,18 @@@report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() });return;};- let (nw, nh) = (f64::from(pw), f64::from(ph));let mode = fitting_of(&options.fitting);- let mut g =- Graphic { asset: AssetId(0), size: (nw, nh), xf: Affine::translate((inner.x0, inner.y0)), auto_fit: mode, fit_align: 0, crop: [0.0; 4] };- let fresh = AssetId(doc.alloc());- let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string());- let link = options.link_images.then(|| path.to_string_lossy().into_owned());- let aid = doc.add_asset(Asset {- id: fresh,- name,- mime: designcraft_render::image_mime(&bytes).to_string(),- link,- data: Arc::new(bytes),- pixels: Some((pw, ph)),- ..Default::default()- });+ let mut g = Graphic {- asset: aid,++ asset: AssetId(0),+ size: (nw, nh),+ xf: Affine::translate((inner.x0, inner.y0)),+ auto_fit: mode,+ fit_align: 0,+ crop: [0.0; 4],+ wrap: Default::default(),+ clip: None,+ fill: Default::default(),+ };if let Some(xf) = g.fitted(inner, mode) {g.xf = xf;}@@@ -365,30 -401,6 +388,27 @@@let m = bb.center();g.xf = Affine::translate((c.x - m.x, c.y - m.y)) * g.xf;}++ // Reject geometry that cannot be represented before an asset is allocated for it.+ if super::super::file::validate_placement((nw, nh), inner, g.xf, "data.merge").is_err() {+ if let Some(it) = doc.item_mut(item) {+ it.content = Content::Unassigned;+ }+ report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() });+ report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits."));+ return;+ }- let aid = AssetId(doc.alloc());++ let fresh = AssetId(doc.alloc());+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string());+ let link = options.link_images.then(|| path.to_string_lossy().into_owned());- doc.assets.insert(- aid,- Arc::new(Asset {- id: aid,- name,- mime: designcraft_render::image_mime(&bytes).to_string(),- link,- data: Arc::new(bytes),- pixels: Some((pw, ph)),- page: 0,- }),- );- g.asset = aid;++ g.asset = doc.add_asset(Asset {++ id: fresh,++ name,++ mime: designcraft_render::image_mime(&bytes).to_string(),++ link,++ data: Arc::new(bytes),++ pixels: Some((pw, ph)),++ ..Default::default()++ });if let Some(it) = doc.item_mut(item) {it.content = Content::Graphic(g);}diff --cc crates/engine/src/cmd/export.rsindex 70d94a332,9816e693b..8bbe41a8a--- a/crates/engine/src/cmd/export.rs+++ b/crates/engine/src/cmd/export.rs@@@ -24,8 -23,11 +24,11 @@@ pub fn specs() -> Vec<CommandSpec>"{path?, type?: saddleStitch|twoUpConsecutive, spaceBetween? (pt)} — printer spreads as PDF (pages imposed in booklet order) → {path, bytes, sheets} (no path: {base64, …})",has_doc, print_booklet),cmd!(noundo "file.exportHtml", "Export HTML…", ["File"], None,- "{path?, title?, language?} — one self-contained page (styles inline, images embedded), stories and graphics in reading order → {path, bytes} (no path: {text, bytes})",+ "{path?, title?, language?} — one self-contained page (styles inline, images embedded), stories and graphics in reading order → {path, bytes, warnings} (no path: {text, bytes, warnings})",has_doc, export_html),+ cmd!(noundo "file.exportPptx", "Export PowerPoint…", ["File"], None,+ "{path?, pages?: \"1-3,5\" | [1,3] (1-based positions; default all), lineBreaks?: keep|reflow (keep: DesignCraft's lines, spacing and leading; reflow: one box per frame, PowerPoint sets the lines), rasterize?: bool (default true: objects PowerPoint can't show — placed PDF/EPS, type on a path, some effects — go in as 300 ppi images), embedFonts?: bool (default true: the TrueType fonts whose licences allow it), title?, author?} — every page as a slide of editable shapes, pictures, text boxes and tables → {path, bytes, slides, warnings} (no path: {base64, …})",+ has_doc, export_pptx),cmd!(noundo "file.exportText", "Export Text…", ["File"], None,"{path?, format?: \"txt\"|\"rtf\"|\"tagged\" (Tagged Text; default from the path, else txt), story?, frame?} — the story being edited or of the selected frame → {path, bytes} (no path: {text, bytes})",has_story_target, export_text),@@@ -52,52 -55,21 +56,55 @@@ fn print_booklet(s: &mut Session, p: &V}}+/// HTML and reflowable EPUB embed the EPS preview; keep the session's source bytes intact.+fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Document>, Vec<String>) {+ // Match the exporter's reading order (including Article exclusions), not every asset+ // in the document: unused or hidden graphics must not prevent an export.+ let mut used = std::collections::BTreeSet::new();+ for block in designcraft_epub::reading_order(d) {+ let designcraft_epub::Block::Image(id) = block else { continue };+ let Some(it) = d.item(id) else { continue };+ let designcraft_doc::Content::Graphic(g) = &it.content else { continue };+ used.insert(g.asset);+ if d.assets.get(&g.asset).is_some_and(|a| designcraft_doc::media_kind(&a.mime).is_some())+ && let Some(poster) = it.media.as_ref().and_then(|m| m.poster)+ {+ used.insert(poster);+ }+ }+ let mut out = Cow::Borrowed(d);+ let mut warnings = Vec::new();+ for id in used {+ let Some(a) = d.assets.get(&id).filter(|a| designcraft_images::is_eps(&a.data)) else { continue };+ let png = designcraft_images::eps_png(&a.data);+ if png.is_none() {+ warnings.push(format!("{}: unusable EPS preview; graphic omitted", a.name));+ }+ if let Some(a) = out.to_mut().assets.get_mut(&id) {+ let a = Arc::make_mut(a);+ a.mime = "image/png".into();+ a.data = Arc::new(png.unwrap_or_default());+ }+ }+ (out, warnings)+}+fn export_html(s: &mut Session, p: &Value) -> Result<Value> {let st = s.doc()?;- let opts =- designcraft_epub::HtmlOptions { title: str_param(p, "title").map(str::to_string), language: str_param(p, "language").map(str::to_string) };+ let opts = designcraft_epub::HtmlOptions {+ title: str_param(p, "title").map(str::to_string),+ language: str_param(p, "language").map(str::to_string),+ generic_families: generic_families(&st.doc),+ };- let text = designcraft_epub::export_html(&st.doc, &opts);+ let (doc, warnings) = eps_previews(&st.doc);+ let text = designcraft_epub::export_html(&doc, &opts);match str_param(p, "path") {Some(path) => {#[cfg(not(target_arch = "wasm32"))]- std::fs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ crate::io::write_file(path, text.as_bytes()).map_err(EngineError::Other)?;- Ok(json!({"path": path, "bytes": text.len()}))+ Ok(json!({"path": path, "bytes": text.len(), "warnings": warnings}))}- None => Ok(json!({"bytes": text.len(), "text": text})),+ None => Ok(json!({"bytes": text.len(), "text": text, "warnings": warnings})),}}@@@ -191,8 -265,12 +300,14 @@@ fn export_epub(s: &mut Session, p: &ValNone => Ok(serde_json::json!({"base64": super::base64_encode(&bytes), "bytes": bytes.len(), "pages": pages.len()})),};}- let (epub_doc, warnings) = eps_previews(epub_doc);- let bytes = designcraft_epub::export_epub(epub_doc, &opts).map_err(|e| crate::EngineError::Other(e.to_string()))?;++ let (epub_doc, eps_warnings) = eps_previews(epub_doc);++ warnings.extend(eps_warnings);+ let bytes = designcraft_epub::export_epub(&epub_doc, &opts).map_err(|e| crate::EngineError::Other(e.to_string()))?;+ warnings.extend(- designcraft_epub::images_without_alt(epub_doc)++ designcraft_epub::images_without_alt(&epub_doc)+ .into_iter()+ .map(|name| format!("{name}: no alt text (Object Export Options); exported as decorative (alt=\"\")")),+ );match p.get("path").and_then(Value::as_str) {Some(path) => {#[cfg(not(target_arch = "wasm32"))]diff --cc crates/engine/src/cmd/file.rsindex 71d685da3,ace745627..56d5c0cd8--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -308,40 -685,61 +680,65 @@@ fn file_place(s: &mut Session, p: &Valulet lid = s.doc()?.active_layer;let px = p.get("x").and_then(Value::as_f64);let py = p.get("y").and_then(Value::as_f64);- let want_w = p.get("width").and_then(Value::as_f64);- // Prepare and validate all geometry before allocating an asset or changing a frame.- let d = &s.doc()?.doc;- let (frame_rect, xf, auto_fit) = if let Some(fid) = target_frame {- let r = d.item(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?.inner_bounds();- let k = (r.width() / nw).max(r.height() / nh);- let xf = Affine::translate((r.x0 + (r.width() - nw * k) / 2.0, r.y0 + (r.height() - nh * k) / 2.0)) * Affine::scale(k);- (r, xf, designcraft_doc::Fitting::FillProportionally)- } else {- let sp = d.spread(spread).ok_or_else(|| bad("file.place", "no such spread"))?;- let pr = sp.pages.first().map(|pg| pg.margin_rect()).unwrap_or(Rect::new(36.0, 36.0, 300.0, 300.0));- let (x, y) = (px.unwrap_or(pr.x0), py.unwrap_or(pr.y0));- let w = want_w.unwrap_or_else(|| nw.min(d.settings.page_width * 0.6));- let k = w / nw;- let (bx, by, bw, bh) = crop_box.unwrap_or((0.0, 0.0, nw, nh));- let r = Rect::new(x, y, x + bw * k, y + bh * k);- let xf = Affine::translate((x - bx * k, y - by * k)) * Affine::scale(k);- (r, xf, Default::default())- };- validate_placement((nw, nh), frame_rect, xf, "file.place")?;+ if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) {+ return load_cursor(s, asset, (bw, bh));+ }s.edit(|d, sel| {- let aid = AssetId(d.alloc());- let mime = designcraft_render::image_mime(&bytes).to_string();- d.assets.insert(aid, Arc::new(Asset { page: pdf_page, id: aid, name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) }));- let graphic = Content::Graphic(Graphic { asset: aid, size: (nw, nh), xf, auto_fit, fit_align: 4, crop: [0.0; 4] });+ let fresh = AssetId(d.alloc());+ let aid = d.add_asset(Asset { id: fresh, ..asset });+ // The width the whole page (or image) gets; the height follows the proportions.+ let w = match want_w {+ Some(w) => w,+ None => {+ let page_w = d.settings.page_width * 0.6;+ nw.min(page_w)+ }+ };let id = if let Some(fid) = target_frame {let it = d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?;- it.content = graphic;+ let r = it.inner_bounds();+ // Fill the frame proportionally once. Auto-Fit stays off, so resizing the frame crops.+ let k = (r.width() / bw).max(r.height() / bh);+ let (gw, gh) = (bw * k, bh * k);++ let xf = Affine::translate((r.x0 + (r.width() - gw) / 2.0, r.y0 + (r.height() - gh) / 2.0)) * Affine::scale(k);++ validate_placement((bw, bh), r, xf, "file.place")?;+ it.content = Content::Graphic(Graphic {+ asset: aid,+ size: (bw, bh),- xf: Affine::translate((r.x0 + (r.width() - gw) / 2.0, r.y0 + (r.height() - gh) / 2.0)) * Affine::scale(k),++ xf,+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ wrap: Default::default(),+ fill: Default::default(),+ });fid} else {+ let sp = d.spread(spread).ok_or_else(|| bad("file.place", "no such spread"))?;+ let pr = sp.pages.first().map(|pg| pg.margin_rect()).unwrap_or(Rect::new(36.0, 36.0, 300.0, 300.0));+ let (x, y) = (px.unwrap_or(pr.x0), py.unwrap_or(pr.y0));let id = ItemId(d.alloc());- let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(frame_rect));+ let k = w / nw;+ let r = super::finite_rect("file.place", Rect::new(x, y, x + bw * k, y + bh * k))?;++ let xf = Affine::translate((x, y)) * Affine::scale(k);++ validate_placement((bw, bh), r, xf, "file.place")?;+ let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r));it.object_style = d.styles.default_graphic_frame.clone();- it.content = graphic;+ if let Some(e) = d.styles.object_effects(&it.object_style) {+ it.effects = e.clone();+ }+ it.content = Content::Graphic(Graphic {+ asset: aid,+ size: (bw, bh),- xf: Affine::translate((x, y)) * Affine::scale(k),++ xf,+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ wrap: Default::default(),+ fill: Default::default(),+ });d.insert_item(spread, it, None)?;id};@@@ -428,19 -814,23 +838,23 @@@ pub(crate) fn validate_placement(size:fn place_load(s: &mut Session, p: &Value) -> Result<Value> {let (bytes, name, link) = read_source(p)?;let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?;- let size = eps_size(&bytes, "place.load")?.unwrap_or((pw as f64, ph as f64));- let natural = designcraft_render::natural_size(&bytes, 0).unwrap_or((pw as f64, ph as f64));++ let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64));+ let mime = designcraft_render::image_mime(&bytes).to_string();+ let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() };+ load_cursor(s, asset, natural)+ }++ /// Adds `asset` to the document (with a fresh id) and loads it into the place cursor.+ fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64)) -> Result<Value> {+ let name = asset.name.clone();+ let (pw, ph) = asset.pixels.unwrap_or_default();let aid = s.edit(|d, _| {- let aid = AssetId(d.alloc());- let mime = designcraft_render::image_mime(&bytes).to_string();- d.assets.insert(- aid,- Arc::new(Asset { page: 0, id: aid, name: name.clone(), mime, link: link.clone(), data: Arc::new(bytes), pixels: Some((pw, ph)) }),- );- Ok(aid)+ asset.id = AssetId(d.alloc());+ Ok(d.add_asset(asset))})?;- s.loaded = Some((aid, size));+ s.loaded = Some(crate::LoadedGraphic { asset: aid, size });s.set_tool("placeGun");- Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph}))+ Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true}))}fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {@@@ -450,39 -845,55 +869,52 @@@let frame = super::id_param(p, "frame");let rect = super::rect_param(p, "rect");let (x, y) = (super::f64_or(p, "x", 0.0), super::f64_or(p, "y", 0.0));- let r = s.edit(|d, sel| {- let id = match frame {- Some(fid) => {- let it = d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?;- let r = it.inner_bounds();- let k = (r.width() / nw).max(r.height() / nh);- it.content = Content::Graphic(Graphic {- asset: aid,- size: (nw, nh),- xf: Affine::translate((r.x0 + (r.width() - nw * k) / 2.0, r.y0 + (r.height() - nh * k) / 2.0)) * Affine::scale(k),- clip: None,- auto_fit: Default::default(),- fit_align: 4,- crop: [0.0; 4],- wrap: Default::default(),- fill: Default::default(),- });- fid+ let d = &s.doc()?.doc;+ let (frame_rect, xf, auto_fit) = if let Some(fid) = frame {+ let r = d.item(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?.inner_bounds();+ let k = (r.width() / nw).max(r.height() / nh);+ let xf = Affine::translate((r.x0 + (r.width() - nw * k) / 2.0, r.y0 + (r.height() - nh * k) / 2.0)) * Affine::scale(k);+ (r, xf, designcraft_doc::Fitting::FillProportionally)+ } else {+ if d.spread(sr).is_none() {+ return Err(bad("place.drop", "no such spread"));+ }+ // Drag: fit proportionally; click: actual size at the point.+ let (r, k) = match rect {+ Some(r) if r.width() > 2.0 && r.height() > 2.0 => {+ let k = (r.width() / nw).min(r.height() / nh);+ (Rect::new(r.x0, r.y0, r.x0 + nw * k, r.y0 + nh * k), k)}- None => {- // Drag: fit proportionally into the dragged rect; click: actual size at the point.- let (frame_r, k) = match rect {- Some(r) if r.width() > 2.0 && r.height() > 2.0 => {- let k = (r.width() / nw).min(r.height() / nh);- (Rect::new(r.x0, r.y0, r.x0 + nw * k, r.y0 + nh * k), k)- }- _ => (Rect::new(x, y, x + nw, y + nh), 1.0),- };- let frame_r = super::finite_rect("place.drop", frame_r)?;- let id = ItemId(d.alloc());- let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(frame_r));- it.object_style = d.styles.default_graphic_frame.clone();- if let Some(e) = d.styles.object_effects(&it.object_style) {- it.effects = e.clone();- }- it.content = Content::Graphic(Graphic {- asset: aid,- size: (nw, nh),- xf: Affine::translate((frame_r.x0, frame_r.y0)) * Affine::scale(k),- clip: None,- auto_fit: Default::default(),- fit_align: 4,- crop: [0.0; 4],- wrap: Default::default(),- fill: Default::default(),- });- d.insert_item(sr, it, None)?;- id+ _ => (Rect::new(x, y, x + nw, y + nh), 1.0),+ };+ (r, Affine::translate((r.x0, r.y0)) * Affine::scale(k), Default::default())+ };+ validate_placement((nw, nh), frame_rect, xf, "place.drop")?;+ let r = s.edit(|d, sel| {- let graphic = Content::Graphic(Graphic { asset: aid, size: (nw, nh), xf, auto_fit, fit_align: 4, crop: [0.0; 4] });++ let graphic = Content::Graphic(Graphic {++ asset: aid,++ size: (nw, nh),++ xf,++ clip: None,++ auto_fit,++ fit_align: 4,++ crop: [0.0; 4],++ wrap: Default::default(),++ fill: Default::default(),++ });+ let id = if let Some(fid) = frame {+ d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?.content = graphic;+ fid+ } else {+ let id = ItemId(d.alloc());+ let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(frame_rect));+ it.object_style = d.styles.default_graphic_frame.clone();++ if let Some(e) = d.styles.object_effects(&it.object_style) {++ it.effects = e.clone();+ }+ it.content = graphic;+ d.insert_item(sr, it, None)?;+ id};*sel = Selection::items(vec![id]);Ok(json!({"id": id.0}))@@@ -646,224 -1075,369 +1096,587 @@@ fn file_revert(s: &mut Session, _: &Val}}+ #[cfg(all(test, not(target_arch = "wasm32")))]+ mod image_place_tests {+ use designcraft_doc::{Content, ItemId};+ use designcraft_geom::Rect;+ use serde_json::{Value, json};++ use crate::Session;++ pub(super) fn image_file() -> std::io::Result<tempfile::NamedTempFile> {+ image_file_with_color(30)+ }++ fn image_file_with_color(red: u8) -> std::io::Result<tempfile::NamedTempFile> {+ let file = tempfile::Builder::new().suffix(".png").tempfile()?;+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [red, 90, 180, 255].repeat(800) }.to_png();+ std::fs::write(file.path(), png)?;+ Ok(file)+ }++ #[test]+ fn consecutive_path_placements_create_distinct_graphics() {+ let images = [image_file_with_color(30).unwrap(), image_file_with_color(31).unwrap(), image_file_with_color(32).unwrap()];+ let mut session = Session::new();+ session.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();+ let mut placements = Vec::new();+ let mut originals = Vec::new();++ for ((spread, x, y), image) in [(0, 0.0, 0.0), (1, 70.0, 90.0), (2, 150.0, 210.0)].into_iter().zip(&images) {+ let placed = session.execute("file.place", &json!({"path": image.path(), "spread": spread, "x": x, "y": y})).unwrap();+ let id = ItemId(placed["id"].as_u64().unwrap());+ assert!(+ placements.iter().all(|previous: &Value| previous["id"] != placed["id"]),+ "each explicit placement needs a distinct frame: {placed}"+ );+ let document = &session.doc().unwrap().doc;+ let item = document.item(id).unwrap();+ assert_eq!(item.bounds(), Rect::new(x, y, x + 40.0, y + 20.0));+ assert!(document.spreads[spread].items.iter().any(|item| item.id == id));+ originals.push(serde_json::to_value(item).unwrap());+ placements.push(placed);+ }++ let document = &session.doc().unwrap().doc;+ assert_eq!(document.spreads.iter().flat_map(|spread| &spread.items).filter(|item| matches!(item.content, Content::Graphic(_))).count(), 3);+ assert_eq!(document.assets.len(), 3);+ for (placed, original) in placements.iter().zip(originals) {+ assert_eq!(serde_json::to_value(document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap()).unwrap(), original);+ }+ let links = session.execute("links.list", &json!({})).unwrap();+ assert_eq!(links.as_array().unwrap().len(), 3);+ for (placed, image) in placements.into_iter().zip(&images) {+ let row = links.as_array().unwrap().iter().find(|row| row["asset"] == placed["asset"]).unwrap();+ assert_eq!(row["path"], json!(image.path()));+ assert_eq!(row["uses"].as_array().unwrap().len(), 1);+ assert_eq!(row["uses"][0]["id"], placed["id"]);+ }+ }++ #[test]+ fn individual_placement_parameters_bypass_selected_frames() {+ let image = image_file().unwrap();+ for graphic in [false, true] {+ for (key, value, expected) in [+ ("x", 0, Rect::new(0.0, 36.0, 40.0, 56.0)),+ ("y", 0, Rect::new(36.0, 0.0, 76.0, 20.0)),+ ("spread", 0, Rect::new(36.0, 36.0, 76.0, 56.0)),+ ("width", 0, Rect::ZERO),+ ("width", 80, Rect::new(36.0, 36.0, 116.0, 76.0)),+ ] {+ let mut session = Session::new();+ session.execute("file.new", &json!({})).unwrap();+ let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap();+ if graphic {+ session.execute("file.place", &json!({"path": image.path()})).unwrap();+ }+ let id = ItemId(selected["id"].as_u64().unwrap());+ let original = serde_json::to_value(session.doc().unwrap().doc.item(id).unwrap()).unwrap();+ let mut params = json!({"path": image.path()});+ params[key] = json!(value);++ let result = session.execute("file.place", ¶ms);+ if key == "width" && value == 0 {+ assert!(result.is_err(), "zero width must be rejected, graphic={graphic}");+ continue;+ }+ let placed = result.unwrap();++ assert_ne!(placed["id"], selected["id"], "{key}={value}, graphic={graphic}");+ let document = &session.doc().unwrap().doc;+ assert_eq!(serde_json::to_value(document.item(id).unwrap()).unwrap(), original);+ let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap();+ assert_eq!(item.bounds(), expected);+ let Content::Graphic(content) = &item.content else { panic!("placed frame must be graphic") };+ let [scale_x, _, _, scale_y, _, _] = content.xf.as_coeffs();+ assert!(scale_x > 0.0 && scale_y > 0.0);+ }+ }+ }++ #[test]+ fn explicit_frame_wins_over_placement_and_selection() {+ let image = image_file().unwrap();+ let mut session = Session::new();+ session.execute("file.new", &json!({})).unwrap();+ let target = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap();+ let selected = session.execute("frame.create", &json!({"rect": [300, 320, 400, 420]})).unwrap();++ let placed =+ session.execute("file.place", &json!({"path": image.path(), "frame": target["id"], "x": 0, "y": 0, "spread": 99, "width": 80})).unwrap();++ assert_eq!(placed["id"], target["id"]);+ let document = &session.doc().unwrap().doc;+ let item = document.item(ItemId(target["id"].as_u64().unwrap())).unwrap();+ assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0));+ assert!(matches!(item.content, Content::Graphic(_)));+ assert!(matches!(document.item(ItemId(selected["id"].as_u64().unwrap())).unwrap().content, Content::Unassigned));+ assert_eq!(document.spreads[0].items.len(), 2);+ }++ fn assert_width_rejected(width: Value) -> std::result::Result<(), Box<dyn std::error::Error>> {+ let image = image_file()?;+ for graphic in [false, true] {+ for explicit_frame in [false, true] {+ let mut session = Session::new();+ session.execute("file.new", &json!({}))?;+ let target = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]}))?;+ if graphic {+ session.execute("file.place", &json!({"path": image.path()}))?;+ }+ let mut params = json!({"path": image.path(), "width": width});+ if explicit_frame {+ params["frame"] = target["id"].clone();+ session.execute("frame.create", &json!({"rect": [300, 320, 400, 420]}))?;+ }+ let before = session.doc()?;+ let document = before.doc.clone();+ let selection = before.selection.clone();+ let revision = before.revision;+ let assets = document.assets.len();++ let result = session.execute("file.place", ¶ms);++ assert!(+ matches!(&result, Err(crate::EngineError::BadParams { .. })),+ "width={width}, graphic={graphic}, explicit_frame={explicit_frame}: expected BadParams, got {result:?}"+ );+ let error = result.err().ok_or_else(|| crate::EngineError::Other("expected placement error".into()))?;+ let crate::EngineError::BadParams { cmd, msg } = error else { return Err(error.into()) };+ assert_eq!(cmd, "file.place");+ assert!(msg.contains("width") && msg.contains("finite") && msg.contains("greater than zero"), "{msg}");+ let after = session.doc()?;+ assert!(std::sync::Arc::ptr_eq(&document, &after.doc));+ assert_eq!(after.selection, selection);+ assert_eq!(after.revision, revision);+ assert_eq!(after.doc.assets.len(), assets);+ }+ }+ Ok(())+ }++ #[test]+ fn width_rejected_when_zero() {+ assert_width_rejected(json!(0)).unwrap();+ }++ #[test]+ fn width_rejected_when_negative() {+ assert_width_rejected(json!(-80)).unwrap();+ }++ #[test]+ fn width_rejected_when_non_numeric() {+ for width in [json!("80"), json!(true), json!([80]), json!({"value": 80})] {+ assert_width_rejected(width).unwrap();+ }+ }++ fn assert_null_placement_uses_selection(keys: &[&str]) -> std::result::Result<(), Box<dyn std::error::Error>> {+ let image = image_file()?;+ let previous_image = image_file_with_color(31)?;+ for graphic in [false, true] {+ let mut session = Session::new();+ session.execute("file.new", &json!({}))?;+ let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]}))?;+ let previous = graphic.then(|| session.execute("file.place", &json!({"path": previous_image.path()}))).transpose()?;+ let mut params = json!({"path": image.path()});+ for key in keys {+ params[*key] = Value::Null;+ }++ let placed = session.execute("file.place", ¶ms)?;++ assert_eq!(placed["id"], selected["id"], "keys={keys:?}, graphic={graphic}");+ if let Some(previous) = previous {+ assert_ne!(placed["asset"], previous["asset"]);+ }+ let document = &session.doc()?.doc;+ let id = ItemId(selected["id"].as_u64().ok_or_else(|| crate::EngineError::Other("frame.create returned no numeric id".into()))?);+ let item = document.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?;+ assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0));+ assert!(matches!(&item.content, Content::Graphic(_)), "placed frame must be graphic");+ let Content::Graphic(content) = &item.content else {+ return Err(crate::EngineError::Other("placed frame must be graphic".into()).into());+ };+ assert_eq!(json!(content.asset.0), placed["asset"]);+ assert_eq!(document.spreads[0].items.len(), 1);+ }+ Ok(())+ }++ #[test]+ fn selection_used_when_x_null() {+ assert_null_placement_uses_selection(&["x"]).unwrap();+ }++ #[test]+ fn selection_used_when_y_null() {+ assert_null_placement_uses_selection(&["y"]).unwrap();+ }++ #[test]+ fn selection_used_when_spread_null() {+ assert_null_placement_uses_selection(&["spread"]).unwrap();+ }++ #[test]+ fn selection_used_when_width_null() {+ assert_null_placement_uses_selection(&["width"]).unwrap();+ }++ #[test]+ fn selection_used_when_all_placement_parameters_null() {+ assert_null_placement_uses_selection(&["x", "y", "spread", "width"]).unwrap();+ }++ #[test]+ fn implicit_placement_fills_empty_and_replaces_graphic_selection() {+ let image = image_file().unwrap();+ let previous_image = image_file_with_color(31).unwrap();+ for graphic in [false, true] {+ let mut session = Session::new();+ session.execute("file.new", &json!({})).unwrap();+ let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap();+ let previous = graphic.then(|| session.execute("file.place", &json!({"path": previous_image.path()})).unwrap());++ let placed = session.execute("file.place", &json!({"path": image.path()})).unwrap();++ assert_eq!(placed["id"], selected["id"]);+ if let Some(previous) = previous {+ assert_ne!(placed["asset"], previous["asset"]);+ }+ let document = &session.doc().unwrap().doc;+ let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap();+ assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0));+ let Content::Graphic(content) = &item.content else { panic!("placed frame must be graphic") };+ assert_eq!(json!(content.asset.0), placed["asset"]);+ assert_eq!(document.spreads[0].items.len(), 1);+ }+ }+ }++ #[cfg(test)]+ mod new_document_tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn saved_presets_make_documents_by_name() {+ let mut s = Session::new();+ let newsletter = json!({"name": "Newsletter", "units": "millimeters", "width": 595.2755905511812, "height": 841.8897637795277,+ "pages": 8, "facingPages": false, "columns": 3, "margins": {"top": 20, "bottom": 30, "inside": 40, "outside": 50},+ "bleed": [9, 9, 0, 9], "primaryTextFrame": true});+ assert_eq!(s.execute("file.savePreset", &newsletter).unwrap()["name"], "Newsletter");+ let listed = s.execute("file.presets", &json!({})).unwrap();+ let saved: Vec<_> = listed.as_array().unwrap().iter().filter(|p| p["saved"] == true).collect();+ assert_eq!(saved.len(), 1);+ assert_eq!((&saved[0]["name"], &saved[0]["units"]), (&json!("Newsletter"), &json!("millimeters")));+ // By name, case ignored; parameters still override the preset.+ s.execute("file.new", &json!({"preset": "newsletter", "pages": 4})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.page_count(), 4);+ assert!(!d.settings.facing_pages && d.settings.primary_text_frame);+ assert_eq!(d.settings.horizontal_units, designcraft_geom::Unit::Millimeters);+ assert_eq!(d.settings.bleed, [9.0, 9.0, 0.0, 9.0]);+ assert_eq!(d.page(0).unwrap().margins.outside, 50.0);+ assert!(d.title.starts_with("Untitled-"), "the preset's name isn't the document's");+ // The same name replaces it.+ s.execute("file.savePreset", &json!({"name": "NEWSLETTER", "pages": 2})).unwrap();+ assert_eq!(s.prefs.document_presets.len(), 1);+ s.execute("file.new", &json!({"preset": "Newsletter"})).unwrap();+ assert_eq!(s.doc().unwrap().doc.page_count(), 2);+ // Built-in names, empty and overlong names and impossible sizes are refused.+ for bad in [json!({"name": "a4"}), json!({"name": " "}), json!({}), json!({"name": "x".repeat(101)}), json!({"name": "Huge", "width": 1e9})]+ {+ assert!(s.execute("file.savePreset", &bad).is_err(), "{bad}");+ }+ s.execute("file.deletePreset", &json!({"name": "newsletter"})).unwrap();+ assert!(s.execute("file.deletePreset", &json!({"name": "newsletter"})).is_err());+ assert!(s.execute("file.new", &json!({"preset": "Newsletter"})).is_err());+ }++ #[test]+ fn new_document_takes_intent_units_start_page_bleed_and_slug() {+ let mut s = Session::new();+ let p = json!({"preset": "A4", "intent": "web", "units": "pixels", "startPage": 4, "bleed": [9, 0, 3, 6], "slug": 18});+ s.execute("file.new", &p).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.settings.intent, designcraft_doc::Intent::Web);+ assert_eq!(d.settings.horizontal_units, designcraft_geom::Unit::Pixels);+ assert_eq!(d.settings.bleed, [9.0, 0.0, 3.0, 6.0]);+ assert_eq!(d.settings.slug, [18.0; 4]);+ assert_eq!(d.page_name(0), "4");+ // Malformed edges are ignored, hostile ones bounded.+ s.execute("file.new", &json!({"bleed": [1, 2], "slug": [-5, 1e12, 0, 0]})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.settings.bleed, [0.0; 4]);+ assert_eq!(d.settings.slug, [0.0, 1296.0, 0.0, 0.0]);+ }++ #[test]+ fn a_new_document_preview_replaces_itself_and_leaves_the_session_as_it_was() {+ let dir = std::env::temp_dir().join(format!("dc-new-doc-preview-{}", std::process::id()));+ let mut s = Session::new();+ s.recovery_dir = Some(dir.clone());+ s.execute("file.new", &json!({})).unwrap();+ let first = s.doc().unwrap().uid;+ let a = s.preview_new_document(&json!({"width": 300})).unwrap();+ assert_eq!((s.doc().unwrap().uid, s.doc().unwrap().doc.title.as_str()), (a, "Untitled-2"));+ let b = s.preview_new_document(&json!({"width": 400, "columns": 3})).unwrap();+ assert_eq!(s.documents().len(), 2, "the preview replaces itself");+ assert!(s.preview_new_document(&json!({"width": 0})).is_err());+ let d = s.doc().unwrap();+ assert_eq!((d.uid, d.doc.settings.page_width, d.doc.page(0).unwrap().columns.count), (b, 400.0, 3), "a refused size keeps it");+ let listed = s.execute("document.list", &json!({})).unwrap();+ assert_eq!((listed[0].get("preview"), &listed[1]["preview"]), (None, &json!(true)));+ assert_eq!(s.end_new_document_preview(), Some(b));+ let d = s.doc().unwrap();+ assert_eq!((s.documents().len(), d.uid, d.is_dirty(), d.history.undo.len()), (1, first, false, 0));+ assert_eq!(s.end_new_document_preview(), None, "without a preview it does nothing");+ // Edited by a script while shown, it writes no recovery data while it is a preview, and+ // stays as a document when the window closes, with its Untitled number.+ let c = s.preview_new_document(&json!({})).unwrap();+ s.execute("frame.create", &json!({"rect": [10, 10, 100, 100]})).unwrap();+ assert_eq!(crate::recovery::save(&s, &dir).unwrap(), 0);+ // The app's timer saves through the command.+ assert_eq!(s.execute("file.recovery.save", &json!({})).unwrap()["saved"], 0);+ assert!(crate::recovery::list(&dir).is_empty());+ assert_eq!(s.end_new_document_preview(), None);+ assert_eq!((s.documents().len(), s.doc().unwrap().uid, s.doc().unwrap().doc.title.as_str()), (2, c, "Untitled-2"));+ s.execute("file.new", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.title, "Untitled-3");+ // Create with the previewed settings keeps the preview as the document.+ let d = s.preview_new_document(&json!({"pages": 2})).unwrap();+ assert_eq!(s.keep_new_document_preview(), Some(3));+ let st = s.doc().unwrap();+ assert_eq!((st.uid, st.doc.title.as_str(), s.new_document_preview()), (d, "Untitled-4", None));+ s.execute("file.new", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.title, "Untitled-5");+ let _ = std::fs::remove_dir_all(&dir);+ }+ }++#[cfg(test)]+pub(crate) mod eps_place_tests {+ use super::*;++ pub(crate) fn tiff_eps() -> Vec<u8> {+ let mut tiff = b"II".to_vec();+ tiff.extend(42u16.to_le_bytes());+ tiff.extend(8u32.to_le_bytes());+ tiff.extend(10u16.to_le_bytes());+ for (tag, ty, count, value) in [+ (256u16, 4u16, 1u32, 2u32),+ (257, 4, 1, 2),+ (258, 3, 3, 134),+ (259, 3, 1, 1),+ (262, 3, 1, 2),+ (273, 4, 1, 140),+ (277, 3, 1, 3),+ (278, 4, 1, 2),+ (279, 4, 1, 12),+ (284, 3, 1, 1),+ ] {+ tiff.extend(tag.to_le_bytes());+ tiff.extend(ty.to_le_bytes());+ tiff.extend(count.to_le_bytes());+ tiff.extend(value.to_le_bytes());+ }+ tiff.extend(0u32.to_le_bytes());+ for _ in 0..3 {+ tiff.extend(8u16.to_le_bytes());+ }+ tiff.extend([255, 0, 0].repeat(4));+ let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EOF\n";+ let mut eps = vec![0xC5, 0xD0, 0xD3, 0xC6];+ for n in [30usize, ps.len(), 0, 0, 30 + ps.len(), tiff.len()] {+ eps.extend((n as u32).to_le_bytes());+ }+ eps.extend([255, 255]);+ eps.extend(ps);+ eps.extend(tiff);+ eps+ }++ #[test]+ fn eps_degenerate_bounds_are_rejected_without_edits() {+ for bounds in ["0 0 1e-320 1e-320", "0 0 1e308 1e308", "0 0 inf 10"] {+ let source = format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: {bounds}\n%%EOF\n");+ for command in ["file.place", "place.load"] {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let before = s.doc().unwrap().doc.clone();+ let revision = s.doc().unwrap().revision;+ assert!(+ s.execute(command, &json!({"base64": base64_encode(source.as_bytes()), "name": "bad.eps", "width": 100})).is_err(),+ "{command}: {bounds}"+ );+ assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ assert_eq!(s.doc().unwrap().revision, revision);+ assert!(s.loaded.is_none());+ designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();+ }+ }+ }++ #[test]+ fn eps_fitting_overflow_is_rejected_before_document_edits() {+ let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 0.01 0.01\n%%EOF\n";+ let params = json!({"base64": base64_encode(source), "name": "small.eps"});+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let before = s.doc().unwrap().doc.clone();+ assert!(s.execute("file.place", &json!({"base64": base64_encode(source), "name": "small.eps", "width": 1e308})).is_err());+ assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ s.execute("place.load", ¶ms).unwrap();+ let before = s.doc().unwrap().doc.clone();+ assert!(s.execute("place.drop", &json!({"rect": [0, 0, 1e308, 1e308]})).is_err());+ assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ s.execute("place.drop", &json!({"rect": [72, 72, 172, 122]})).unwrap();+ designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();+ }++ #[test]+ fn eps_table_and_data_merge_reject_fitting_overflow() {+ let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 0.01 0.01\n%%EOF\n";+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect":[72,72,372,272],"content":"text"})).unwrap();+ s.execute("text.select", &json!({"story":r["story"],"anchor":0,"focus":0})).unwrap();+ s.execute("table.insert", &json!({"rows":1,"cols":1,"width":1e308})).unwrap();+ let before = s.doc().unwrap().doc.clone();+ assert!(s.execute("table.placeGraphic", &json!({"base64":base64_encode(source),"name":"small.eps","fit":"fill"})).is_err());+ assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ designcraft_format::load(&designcraft_format::save(&before).unwrap()).unwrap();++ let path = std::env::temp_dir().join(format!("dc-eps-fit-{}.eps", std::process::id()));+ std::fs::write(&path, source).unwrap();+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("data.source.select", &json!({"bytes":base64_encode(format!("@Photo\n{}\n",path.display()).as_bytes()),"name":"source.csv"}))+ .unwrap();+ let r = s.execute("frame.create", &json!({"rect":[0,0,1e308,100],"content":"graphic"})).unwrap();+ s.execute("data.placeholder.add", &json!({"field":"Photo","item":r["id"]})).unwrap();+ let result = s.execute("data.merge", &json!({"fitting":"fillProportionally"})).unwrap();+ assert_eq!(result["missingImages"].as_array().unwrap().len(), 1);+ assert!(s.doc().unwrap().doc.assets.is_empty());+ designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();+ let _ = std::fs::remove_file(path);+ }++ #[test]+ fn eps_table_and_data_merge_use_bounding_box_points() {+ let dir = std::env::temp_dir().join(format!("dc-eps-routes-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ for (index, bytes) in [b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EOF\n".to_vec(), tiff_eps()].into_iter().enumerate() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72,72,372,272], "content":"text"})).unwrap();+ s.execute("text.select", &json!({"story": r["story"], "anchor":0, "focus":0})).unwrap();+ s.execute("table.insert", &json!({"rows":1,"cols":1})).unwrap();+ s.execute("table.placeGraphic", &json!({"base64": base64_encode(&bytes), "name":"logo.eps"})).unwrap();+ let table = s.doc().unwrap().doc.stories.values().flat_map(|st| st.tables.values()).next().unwrap();+ assert_eq!(table.cells[0].graphic.as_ref().unwrap().size, (100.0, 50.0), "table {index}");+ let path = dir.join(format!("logo-{index}.eps"));+ std::fs::write(&path, &bytes).unwrap();+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute(+ "data.source.select",+ &json!({"bytes": base64_encode(format!("@Photo\n{}\n", path.display()).as_bytes()), "name":"source.csv"}),+ )+ .unwrap();+ let r = s.execute("frame.create", &json!({"rect":[72,72,372,272],"content":"graphic"})).unwrap();+ s.execute("data.placeholder.add", &json!({"field":"Photo","item":r["id"]})).unwrap();+ let result = s.execute("data.merge", &json!({"fitting":"none"})).unwrap();+ assert!(result["missingImages"].as_array().unwrap().is_empty());+ let g = s+ .doc()+ .unwrap()+ .doc+ .spreads+ .iter()+ .flat_map(|sp| &sp.items)+ .find_map(|it| if let Content::Graphic(g) = &it.content { Some(g) } else { None })+ .unwrap();+ assert_eq!(g.size, (100.0, 50.0), "merge {index}");+ designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();+ }+ let _ = std::fs::remove_dir_all(dir);+ }++ #[test]+ fn eps_idml_roundtrip_preserves_source_and_resource_type() {+ use std::io::Read;+ for bytes in [b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EOF\n".to_vec(), tiff_eps()] {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("file.place", &json!({"base64":base64_encode(&bytes),"name":"logo.eps"})).unwrap();+ let source = s.doc().unwrap().doc.clone();+ let idml = designcraft_idml::export_idml(&source);+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(&idml)).unwrap();+ let names: Vec<_> = z.file_names().filter(|n| n.starts_with("Spreads/")).map(str::to_string).collect();+ let mut xml = String::new();+ for name in names {+ z.by_name(&name).unwrap().read_to_string(&mut xml).unwrap();+ }+ assert!(xml.contains("<EPS "), "EPS resource element missing");+ assert!(xml.contains("Encapsulated PostScript (EPS)"));+ assert!(!xml.contains("Portable Network Graphics (PNG)"));+ let restored = designcraft_idml::import_idml(&idml).unwrap();+ let a = restored.assets.values().next().unwrap();+ assert_eq!(a.mime, "application/postscript");+ assert_eq!(a.data.as_slice(), bytes);+ assert!(designcraft_render::decode_pixmap(&a.data).is_some());+ // A linked-only EPS keeps its type even when the external file is unavailable;+ // when the resolver supplies it, sniff the raw source rather than PNG metadata.+ let mut linked = (*source).clone();+ let a = Arc::make_mut(linked.assets.values_mut().next().unwrap());+ a.link = Some("/synthetic/logo.eps".into());+ let idml = designcraft_idml::export_idml_with(&linked, &designcraft_idml::ExportOptions { embed_images: false });+ let missing = designcraft_idml::import_idml_with(&idml, &|_| None).unwrap();+ let a = missing.assets.values().next().unwrap();+ assert_eq!(a.mime, "application/postscript");+ assert!(a.data.is_empty());+ let resolved = designcraft_idml::import_idml_with(&idml, &|path| {+ assert_eq!(path, "/synthetic/logo.eps");+ Some(bytes.clone())+ })+ .unwrap();+ let a = resolved.assets.values().next().unwrap();+ assert_eq!(a.mime, "application/postscript");+ assert_eq!(a.data.as_slice(), bytes);+ }+ }++ #[test]+ fn eps_place_cursor_retains_source_and_uses_bounding_box_size() {+ let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%HiResBoundingBox: 0 0 100.5 50.25\n%%EOF\n";+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let result = s.execute("place.load", &json!({"base64": base64_encode(source), "name": "logo.eps"})).unwrap();+ let aid = AssetId(result["asset"].as_u64().unwrap());+ assert_eq!(s.doc().unwrap().doc.assets[&aid].data.as_slice(), source);+ assert_eq!(s.doc().unwrap().doc.assets[&aid].mime, "application/postscript");+ assert_eq!(s.doc().unwrap().doc.assets[&aid].pixels, Some((201, 101)));+ let result = s.execute("place.drop", &json!({"x": 72, "y": 72})).unwrap();+ let it = s.doc().unwrap().doc.item(ItemId(result["id"].as_u64().unwrap())).unwrap();+ let Content::Graphic(g) = &it.content else { panic!("expected a graphic") };+ assert_eq!(g.size, (100.5, 50.25));+ assert_eq!((it.bounds().width(), it.bounds().height()), g.size);+ let before = s.doc().unwrap().doc.clone();+ for invalid in ["%!PS-Adobe-3.0 EPSF-3.0\nno bounding box\n", "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 inf 10\n"] {+ let corrupt = json!({"base64": base64_encode(invalid.as_bytes()), "name": "bad.eps"});+ assert!(s.execute("place.load", &corrupt).is_err());+ assert!(s.execute("file.place", &corrupt).is_err());+ }+ assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ }+}+#[cfg(test)]mod pdf_crop_tests {use serde_json::json;diff --cc crates/engine/src/cmd/links.rsindex 5790e5d3a,9e06a566d..491687785--- a/crates/engine/src/cmd/links.rs+++ b/crates/engine/src/cmd/links.rs@@@ -23,7 -30,7 +30,7 @@@ pub fn specs() -> Vec<CommandSpec>"Relink…",["Window", "Links"],None,- "{asset, path} — use another file for every placement of the graphic; keeps the selected PDF page (error if missing)",- "{asset | story, path} — use another file for every placement of the graphic, or import another text file into the linked story",++ "{asset | story, path} — use another file for every placement of the graphic (keeps the selected PDF page; error if missing), or import another text file into the linked story",has_doc,relink),@@@ -153,44 -329,40 +329,59 @@@ fn reload(path: &str) -> Result<(Vec<u8Err(EngineError::Other(format!("{path}: files can't be read on the web")))}+fn relinked_asset(a: &designcraft_doc::Asset, path: &str) -> Result<Arc<designcraft_doc::Asset>> {+ let (bytes, px) = reload(path)?;+ let page = if designcraft_render::is_pdf(&bytes) { a.page } else { 0 };+ let px = if page > 0 {+ designcraft_render::pdf_page_size(&bytes, page as usize)+ .map(|(w, h)| (w.round().max(1.0) as u32, h.round().max(1.0) as u32))+ .ok_or_else(|| bad("links", format!("{path}: can't read PDF page {}", u64::from(page) + 1)))?+ } else {+ px+ };+ let mut a = a.clone();+ a.mime = designcraft_render::image_mime(&bytes).to_string();+ a.data = Arc::new(bytes);+ a.pixels = Some(px);+ a.page = page;+ a.name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());+ a.link = Some(path.to_string());++ // A placed PDF keeps its crop choice; its box is found on the new file.++ super::file::crop_pdf(&mut a);+ Ok(Arc::new(a))+}+fn relink(s: &mut Session, p: &Value) -> Result<Value> {+ let path = str_param(p, "path").ok_or_else(|| bad("links.relink", "missing path"))?.to_string();+ if let Some(sid) = story_param(p) {+ let (bytes, before) = read_text(&path)?;+ let name = file_name(&path);+ return s.edit(|d, _| {+ let warnings = reimport(d, sid, &path, &bytes, before)?;+ Ok(json!({"name": name, "warnings": warnings}))+ });+ }let aid = asset_param(p, "links.relink")?;- let path = str_param(p, "path").ok_or_else(|| bad("links.relink", "missing path"))?;- let (bytes, px) = reload(&path)?;- let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone());+ let a = s.doc()?.doc.assets.get(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?;- let fresh = relinked_asset(a, path)?;++ // Build the replacement before the edit: a file that cannot be read leaves the document as it was.++ let fresh = relinked_asset(a, &path)?;s.edit(|d, _| {- let a = d.assets.get_mut(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?;- let a = Arc::make_mut(a);- a.mime = designcraft_render::image_mime(&bytes).to_string();- a.data = Arc::new(bytes.clone());- a.pixels = Some(px);- a.name = name.clone();- a.link = Some(path.clone());- // A placed PDF keeps its crop choice; its box is found on the new file.- super::file::crop_pdf(a);+ let name = fresh.name.clone();+ d.assets.insert(aid, fresh);Ok(json!({"name": name}))})}fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {let dir = str_param(p, "dir").map(std::path::PathBuf::from);+ if let Some(dir) = &dir {+ // Refused outright: candidates outside the automation read root would only look missing.+ crate::file_access::check_read(dir).map_err(EngineError::Other)?;+ }let ext = str_param(p, "extension").map(|e| e.trim_start_matches('.').to_string());+ if ext.as_ref().is_some_and(|e| e.contains(['/', '\\', '\0'])) {+ return Err(bad("links.relinkFolder", "extension must not contain path separators or NUL"));+ }if dir.is_none() && ext.is_none() {return Err(bad("links.relinkFolder", "give `dir` and/or `extension`"));}@@@ -236,22 -397,50 +427,40 @@@}fn update(s: &mut Session, p: &Value) -> Result<Value> {- let d = &s.doc()?.doc;+ let d = s.doc()?.doc.clone();+ let checks = &mut s.text_link_checks;+ let (only_asset, only_story) = (p.get("asset").and_then(Value::as_u64), story_param(p));+ let all = only_asset.is_none() && only_story.is_none();- let which: Vec<(AssetId, String)> = d- .assets- .values()- .filter(|a| all || only_asset == Some(a.id.0))- .filter(|a| status(a) == "modified")- .filter_map(|a| a.link.clone().map(|l| (a.id, l)))- .collect();+ let texts: Vec<(StoryId, String)> = d+ .stories+ .values()+ .filter(|st| all || only_story == Some(st.id))+ .filter_map(|st| st.file_link.as_ref().filter(|l| text_status(l, checks) == "modified").map(|l| (st.id, l.path.clone())))+ .collect();let mut fresh = Vec::new();- for a in d.assets.values().filter(|a| p.get("asset").and_then(Value::as_u64).is_none_or(|x| x == a.id.0)).filter(|a| status(a) == "modified") {- for (aid, path) in which {- fresh.push((aid, reload(&path)?));++ for a in d.assets.values().filter(|a| all || only_asset == Some(a.id.0)).filter(|a| status(a) == "modified") {+ if let Some(path) = &a.link {+ fresh.push((a.id, relinked_asset(a, path)?));+ }}- let n = fresh.len();+ let mut fresh_texts = Vec::new();+ for (sid, path) in texts {+ let (bytes, before) = read_text(&path)?;+ fresh_texts.push((sid, path, bytes, before));+ }+ let n = fresh.len() + fresh_texts.len();if n == 0 {return Ok(json!({"updated": 0}));}s.edit(|d, _| {- for (aid, (bytes, px)) in &fresh {- if let Some(a) = d.assets.get_mut(aid) {- let a = Arc::make_mut(a);- a.data = Arc::new(bytes.clone());- a.pixels = Some(*px);- super::file::crop_pdf(a);- }+ for (aid, a) in fresh {+ d.assets.insert(aid, a);}- Ok(json!({"updated": n}))+ let mut warnings = Vec::new();+ for (sid, path, bytes, before) in &fresh_texts {+ warnings.extend(reimport(d, *sid, path, bytes, *before)?);+ }+ Ok(json!({"updated": n, "warnings": warnings}))})}diff --cc crates/engine/src/cmd/table.rsindex 01bf6e86f,c43c502bc..af3221054--- a/crates/engine/src/cmd/table.rs+++ b/crates/engine/src/cmd/table.rs@@@ -1219,37 -1897,31 +1897,34 @@@ fn place_graphic(s: &mut Session, p: &Vlet g = target(s, p, ID)?;let (bytes, name, link) = super::file::read_source(p)?;let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad(ID, "unsupported or corrupt image"))?;- let (nw, nh) = designcraft_render::image_natural_size(&bytes).ok_or_else(|| bad(ID, "invalid image dimensions"))?;++ let (nw, nh) = designcraft_render::natural_size(&bytes, 0).ok_or_else(|| bad(ID, "invalid image dimensions"))?;let fill = p.get("fit").and_then(Value::as_str) == Some("fill");+ // Compute fitting before the edit: a small EPS can overflow in a huge cell.+ let t = s.doc()?.doc.story(g.story).and_then(|st| st.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;+ let (r, c) = t.owner(g.range.r0, g.range.c0);+ let cell = t.cell(r, c).ok_or_else(|| bad(ID, "no cell"))?;+ let (rs, cs) = (cell.row_span.max(1) as usize, cell.col_span.max(1) as usize);+ let w: f64 = t.columns.get(c..c.saturating_add(cs).min(t.ncols())).ok_or_else(|| bad(ID, "invalid cell span"))?.iter().map(|x| x.width).sum();+ let h: f64 = t.rows.get(r..r.saturating_add(rs).min(t.nrows())).ok_or_else(|| bad(ID, "invalid cell span"))?.iter().map(|x| x.height).sum();+ let ins = cell.insets;+ let (bw, bh) = ((w - ins[1] - ins[3]).max(1.0), (h - ins[0] - ins[2]).max(1.0));+ let k = if fill { (bw / nw).max(bh / nh) } else { (bw / nw).min(bh / nh) };+ let xf = designcraft_geom::Affine::translate(((bw - nw * k) / 2.0, (bh - nh * k) / 2.0)) * designcraft_geom::Affine::scale(k);+ super::file::validate_placement((nw, nh), designcraft_geom::Rect::new(0.0, 0.0, bw, bh), xf, ID)?;s.edit(|d, sel| {- let aid = designcraft_doc::AssetId(d.alloc());+ let fresh = designcraft_doc::AssetId(d.alloc());let mime = designcraft_render::image_mime(&bytes).to_string();- d.assets.insert(- aid,- std::sync::Arc::new(designcraft_doc::Asset {- page: 0,- id: aid,- name,- mime,- link,- data: std::sync::Arc::new(bytes),- pixels: Some((pw, ph)),- }),- );+ let aid = d.add_asset(designcraft_doc::Asset {+ id: fresh,+ name,+ mime,+ link,+ data: std::sync::Arc::new(bytes),+ pixels: Some((pw, ph)),+ ..Default::default()+ });let st = d.story_mut(g.story).ok_or_else(|| bad(ID, "no story"))?;let t = st.table_mut(g.table).ok_or_else(|| bad(ID, "no table"))?;- let (r, c) = t.owner(g.range.r0, g.range.c0);- let cell = t.cell(r, c).ok_or_else(|| bad(ID, "no cell"))?;- let (rs, cs) = (cell.row_span.max(1) as usize, cell.col_span.max(1) as usize);- let w: f64 = t.columns[c..(c + cs).min(t.ncols())].iter().map(|x| x.width).sum();- let h: f64 = t.rows[r..(r + rs).min(t.nrows())].iter().map(|x| x.height).sum();- let ins = cell.insets;- let (bw, bh) = ((w - ins[1] - ins[3]).max(1.0), (h - ins[0] - ins[2]).max(1.0));- let (nw, nh) = (pw as f64, ph as f64);- let k = if fill { (bw / nw).max(bh / nh) } else { (bw / nw).min(bh / nh) };- let xf = designcraft_geom::Affine::translate(((bw - nw * k) / 2.0, (bh - nh * k) / 2.0)) * designcraft_geom::Affine::scale(k);let cell = t.cell_mut(r, c).ok_or_else(|| bad(ID, format!("no cell {r},{c}")))?;cell.graphic = Some(designcraft_doc::Graphic {asset: aid,diff --cc crates/format/src/lib.rsindex e58277e0b,d5653eb9d..8490fcddf--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@@ -25,9 -28,12 +29,12 @@@ pub enum FormatError#[error("not a DesignCraft document: {0}")]NotOurs(String),#[error("document is from a newer DesignCraft (format {0}); please update")]- TooNew(u32),+ TooNew(u64),#[error("{0}")]Io(String),+ /// The document holds something the file can't represent; nothing is written.+ #[error("{0}")]+ Unsaveable(String),}fn ext_for(mime: &str) -> &'static str {@@@ -55,11 -81,12 +83,15 @@@ fn save_with_large_entries_from(doc: &Dz.start_file("mimetype", stored).map_err(io)?;z.write_all(MIME.as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?;z.start_file("meta.json", deflate).map_err(io)?;- let meta = json!({"format": "designcraft", "version": VERSION, "generator": concat!("DesignCraft ", env!("CARGO_PKG_VERSION"))});+ // Older readers would silently omit EPS artwork. Preview-only legacy assets and+ // documents without EPS still use version 1 so their existing readers keep working.+ let version = if doc.assets.values().any(|a| designcraft_images::is_eps(&a.data)) { VERSION } else { 1 };+ let meta = json!({"format": "designcraft", "version": version, "generator": concat!("DesignCraft ", env!("CARGO_PKG_VERSION"))});z.write_all(meta.to_string().as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?;+ if let Some(png) = preview {+ z.start_file(PREVIEW, stored).map_err(io)?;+ z.write_all(png).map_err(|e| FormatError::Io(e.to_string()))?;+ }z.start_file("document.json", deflate).map_err(io)?;let json = serde_json::to_vec_pretty(doc).map_err(|e| FormatError::Io(e.to_string()))?;z.write_all(&json).map_err(|e| FormatError::Io(e.to_string()))?;@@@ -85,33 -153,82 +158,82 @@@ pub fn load(bytes: &[u8]) -> Result<Docload_legacy_json(bytes)}+ /// Most entries a `.designcraft` archive may hold.+ const MAX_ENTRIES: usize = 100_000;+ /// Most bytes `meta.json` or `document.json` may expand to.+ const MAX_JSON_BYTES: u64 = 256 << 20;+ /// Most bytes one embedded asset may expand to.+ const MAX_ASSET_BYTES: u64 = 1 << 30;+ /// Most bytes all the entries read from one archive may expand to together.+ const MAX_TOTAL_BYTES: u64 = 4 << 30;++ /// Read entry `name` of `z`, or `None` when it is missing or unreadable. Refuses an entry that+ /// expands past `limit` bytes or past what is `left` of the archive's budget, without+ /// decompressing more than that: the sizes the archive claims are not trusted.+ fn read_entry(z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str, limit: u64, left: &mut u64) -> Result<Option<Vec<u8>>, FormatError> {+ let too_big = || FormatError::Io(format!("{name} is larger than the {limit}-byte limit (or the archive is larger than {MAX_TOTAL_BYTES} bytes)"));+ let Ok(f) = z.by_name(name) else { return Ok(None) };+ let limit = limit.min(*left);+ if f.size() > limit {+ return Err(too_big());+ }+ let mut v = Vec::new();+ if f.take(limit.saturating_add(1)).read_to_end(&mut v).is_err() {+ return Ok(None);+ }+ let n = v.len() as u64;+ if n > limit {+ return Err(too_big());+ }+ *left = left.saturating_sub(n);+ Ok(Some(v))+ }+fn load_zip(bytes: &[u8]) -> Result<Document, FormatError> {let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::NotOurs(e.to_string()))?;- let read = |z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str| -> Option<Vec<u8>> {- let mut f = z.by_name(name).ok()?;- let mut v = Vec::new();- f.read_to_end(&mut v).ok()?;- Some(v)- };- if let Some(meta) = read(&mut z, "meta.json")- && let Ok(m) = serde_json::from_slice::<Value>(&meta)- && let Some(v) = m.get("version").and_then(Value::as_u64)- && v > u64::from(VERSION)- {- return Err(FormatError::TooNew(v));+ if z.len() > MAX_ENTRIES {+ return Err(FormatError::NotOurs(format!("{} entries (at most {MAX_ENTRIES})", z.len())));+ }+ let mut left = MAX_TOTAL_BYTES;+ let version = read_entry(&mut z, "meta.json", MAX_JSON_BYTES, &mut left)?+ .and_then(|meta| serde_json::from_slice::<Value>(&meta).ok())+ .and_then(|m| m.get("version").and_then(Value::as_u64))- .map_or(1, |v| u32::try_from(v).unwrap_or(u32::MAX));- if version > VERSION {++ .unwrap_or(1);++ if version > u64::from(VERSION) {+ return Err(FormatError::TooNew(version));}- let json = read(&mut z, "document.json").ok_or_else(|| FormatError::NotOurs("missing document.json".into()))?;+ let json = read_entry(&mut z, "document.json", MAX_JSON_BYTES, &mut left)?.ok_or_else(|| FormatError::NotOurs("missing document.json".into()))?;let mut v: Value = serde_json::from_slice(&json).map_err(|e| FormatError::NotOurs(e.to_string()))?;- upgrade(&mut v);+ upgrade_json(&mut v);let mut doc: Document = serde_json::from_value(v).map_err(|e| FormatError::NotOurs(e.to_string()))?;let names: Vec<String> = z.file_names().map(str::to_string).collect();+ // Files saved with one copy per placement: identical copies share one buffer as they are+ // read, so memory holds each distinct file once.+ let fingerprint = std::collections::hash_map::RandomState::new();+ let mut loaded: HashMap<u64, Vec<Arc<Vec<u8>>>> = HashMap::new();for name in names {let Some(stem) = name.strip_prefix("assets/") else { continue };let Some(id) = stem.split('.').next().and_then(|s| s.parse::<u64>().ok()) else { continue };- if let (Some(data), Some(a)) = (read(&mut z, &name), doc.assets.get_mut(&AssetId(id))) {- Arc::make_mut(a).data = Arc::new(data);+ // Entries for assets the document doesn't have are never decompressed.+ if !doc.assets.contains_key(&AssetId(id)) {+ continue;+ }+ if let (Some(data), Some(a)) = (read_entry(&mut z, &name, MAX_ASSET_BYTES, &mut left)?, doc.assets.get_mut(&AssetId(id))) {+ let same = loaded.entry(fingerprint.hash_one(data.as_slice())).or_default();+ let data = match same.iter().find(|d| ***d == data) {+ Some(d) => d.clone(),+ None => {+ let d = Arc::new(data);+ same.push(d.clone());+ d+ }+ };+ Arc::make_mut(a).data = data;}}- upgrade(&mut doc, version);++ upgrade(&mut doc, u32::try_from(version).unwrap_or(u32::MAX));+ doc.merge_duplicate_assets();+ doc.mark_differing_margins_local();doc.check().map_err(|e| FormatError::NotOurs(e.to_string()))?;Ok(doc)}@@@ -210,37 -377,62 +382,94 @@@ mod testsuse designcraft_doc::geom::Rect;use designcraft_doc::{Asset, ParaFormat, SpreadRef};+ fn png_asset(d: &mut Document, data: &[u8]) -> AssetId {+ let aid = AssetId(d.alloc());+ let a = Asset {+ id: aid,+ name: "x.png".into(),+ mime: "image/png".into(),+ data: Arc::new(data.to_vec()),+ pixels: Some((1, 1)),+ ..Default::default()+ };+ d.assets.insert(aid, Arc::new(a));+ aid+ }++ fn place(d: &mut Document, asset: AssetId, crop: f64) -> designcraft_doc::ItemId {+ use designcraft_doc::geom::{Affine, shapes};+ use designcraft_doc::{Content, Graphic, Item, ItemId, Shape};+ let id = ItemId(d.alloc());+ let mut it = Item::new(id, d.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)));+ it.content = Content::Graphic(Graphic {+ asset,+ size: (1.0, 1.0),+ xf: Affine::translate((crop, crop)),+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [crop; 4],+ wrap: Default::default(),+ fill: Default::default(),+ });+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ id+ }++ fn asset_entries(bytes: &[u8]) -> usize {+ let z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();+ z.file_names().filter(|n| n.starts_with("assets/")).count()+ }++ /// Zip `d` the way files were saved with one asset per placement (nothing merged or pruned).+ fn save_uncompacted(d: &Document) -> Vec<u8> {+ let mut buf = Cursor::new(Vec::new());+ let mut z = zip::ZipWriter::new(&mut buf);+ let opts = zip::write::SimpleFileOptions::default();+ z.start_file("mimetype", opts).unwrap();+ z.write_all(MIME.as_bytes()).unwrap();+ z.start_file("document.json", opts).unwrap();+ z.write_all(&serde_json::to_vec(d).unwrap()).unwrap();+ for (id, a) in &d.assets {+ z.start_file(format!("assets/{}.png", id.0), opts).unwrap();+ z.write_all(&a.data).unwrap();+ }+ z.finish().unwrap();+ buf.into_inner()+ }++ #[test]+ fn eps_source_requires_new_reader_but_preview_documents_keep_version_one() {+ let mut d = Document::new(&NewDocument::default());+ let version = |d: &Document| {+ let bytes = save(d).unwrap();+ let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();+ let mut meta = String::new();+ z.by_name("meta.json").unwrap().read_to_string(&mut meta).unwrap();+ serde_json::from_str::<Value>(&meta).unwrap()["version"].as_u64().unwrap()+ };+ assert_eq!(version(&d), 1);+ let aid = AssetId(d.alloc());+ let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EOF\n".to_vec();+ d.assets.insert(+ aid,+ Arc::new(Asset {+ id: aid,+ name: "logo.eps".into(),+ mime: "image/png".into(),+ link: None,+ data: Arc::new(source.clone()),+ pixels: Some((40, 20)),+ page: 0,++ ..Default::default()+ }),+ );+ assert_eq!(version(&d), 2, "sniff source even when legacy metadata says PNG");+ assert_eq!(load(&save(&d).unwrap()).unwrap().assets[&aid].data.as_slice(), source);+ Arc::make_mut(d.assets.get_mut(&aid).unwrap()).data = Arc::new(b"\x89PNG\r\n\x1a\npreview".to_vec());+ assert_eq!(version(&d), 1, "legacy EPS previews stay compatible");+ }+#[test]fn roundtrip_with_assets() {let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });@@@ -326,15 -773,204 +810,206 @@@#[test]fn rejects_garbage_and_newer_versions() {assert!(load(b"nope").is_err());- let mut buf = Cursor::new(Vec::new());- {- let mut z = zip::ZipWriter::new(&mut buf);- z.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();- z.write_all(br#"{"version": 99}"#).unwrap();- z.finish().unwrap();+ for version in [99u64, u64::from(u32::MAX) + 2] {+ let mut buf = Cursor::new(Vec::new());+ {+ let mut z = zip::ZipWriter::new(&mut buf);+ z.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(json!({"version": version}).to_string().as_bytes()).unwrap();+ z.finish().unwrap();+ }+ assert!(matches!(load(&buf.into_inner()), Err(FormatError::TooNew(v)) if v == version));}- assert!(matches!(load(&buf.into_inner()), Err(FormatError::TooNew(99))));}++ fn r7a_nullable_document(local_clear: bool, style_clear: bool) -> Document {+ use designcraft_doc::{CharAttrs, ParaAttrs};+ let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() });+ let base = d.styles.default_paragraph.clone();+ let chars = CharAttrs {+ leading_aki: Some(Some(4.0)),+ trailing_aki: Some(Some(3.0)),+ underline_weight: Some(Some(2.0)),+ underline_offset: Some(Some(1.0)),+ strikethrough_weight: Some(Some(2.0)),+ strikethrough_offset: Some(Some(1.0)),+ ..Default::default()+ };+ // Legacy JSON loads as format 1, whose upgrade pins Keep Lines Together and Align Left+ // Edge where a style chain leaves them unset; the base style sets them so both+ // formats resolve the same.+ let para = ParaAttrs {+ start_at: Some(Some(7)),+ paragraph_kashida_width: Some(Some(0.5)),+ kinsoku: Some(Some(Default::default())),+ keep_all_lines: Some(true),+ drop_cap_align_left: Some(true),+ ..Default::default()+ };+ let style = std::sync::Arc::make_mut(&mut d.styles).paragraph.iter_mut().find(|s| s.name == base).unwrap();+ style.chars = chars;+ style.para = para;+ let clear_chars = CharAttrs {+ leading_aki: Some(None),+ trailing_aki: Some(None),+ underline_weight: Some(None),+ underline_offset: Some(None),+ strikethrough_weight: Some(None),+ strikethrough_offset: Some(None),+ ..Default::default()+ };+ let clear_para = ParaAttrs { start_at: Some(None), paragraph_kashida_width: Some(None), kinsoku: Some(None), ..Default::default() };+ let selected = if style_clear {+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(designcraft_doc::styles::ParagraphStyle {+ name: "Defaults".into(),+ based_on: Some(base.clone()),+ next_style: None,+ para: clear_para.clone(),+ chars: clear_chars.clone(),+ shortcut: String::new(),+ });+ "Defaults".to_string()+ } else {+ base+ };+ let format = ParaFormat {+ style: selected,+ para: if local_clear { clear_para } else { ParaAttrs::default() },+ chars: if local_clear { clear_chars } else { CharAttrs::default() },+ table: None,+ };+ // Pin legacy paragraph defaults so both formats isolate nullable overrides.+ for style in &mut d.styles_mut().paragraph {+ style.para.keep_all_lines = Some(true);+ style.para.drop_cap_align_left = Some(false);+ }+ let layer = d.default_layer();+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 400.0), layer, "clear", format).unwrap();+ d+ }++ fn r7a_nullable_resolution(d: &Document) -> (designcraft_doc::ParaProps, designcraft_doc::CharProps) {+ let s = d.stories.values().find(|s| s.text == "clear").unwrap();+ d.styles.resolve_para(s.paras.first().unwrap())+ }++ fn r7a_assert_nullable_defaults_survive(d: &Document) {+ let expected = r7a_nullable_resolution(d);+ assert_eq!(expected.0.start_at, None);+ assert_eq!(expected.0.paragraph_kashida_width, None);+ assert_eq!(expected.0.kinsoku, None);+ assert_eq!(expected.1.leading_aki, None);+ // Legacy JSON is format 1: its upgrade pins older defaults on the other styles, so only+ // the native ZIP compares as the whole document.+ for (bytes, native) in [(save(d).unwrap(), true), (serde_json::to_vec(d).unwrap(), false)] {+ let back = load(&bytes).unwrap();+ assert_eq!(r7a_nullable_resolution(&back), expected, "saved explicit defaults must not become inherited values");+ if native {+ assert_eq!(back, *d, "the native ZIP preserves the complete document");+ }+ }+ }++ #[test]+ fn r7a_native_local_default_text_overrides_survive_zip_and_legacy_json() {+ r7a_assert_nullable_defaults_survive(&r7a_nullable_document(true, false));+ }++ #[test]+ fn r7a_native_named_style_default_overrides_survive_zip_and_legacy_json() {+ r7a_assert_nullable_defaults_survive(&r7a_nullable_document(false, true));+ }++ #[test]+ fn r7a_native_nullable_missing_and_explicit_value_controls() {+ let d = r7a_nullable_document(false, false);+ assert_eq!(r7a_nullable_resolution(&d).0.start_at, Some(7));+ assert_eq!(r7a_nullable_resolution(&d).1.leading_aki, Some(4.0));+ for (bytes, native) in [(save(&d).unwrap(), true), (serde_json::to_vec(&d).unwrap(), false)] {+ let back = load(&bytes).unwrap();+ assert_eq!(r7a_nullable_resolution(&back), r7a_nullable_resolution(&d));+ if native {+ assert_eq!(back, d);+ }+ }+ let attrs: designcraft_doc::CharAttrs = serde_json::from_value(json!({"size":null})).unwrap();+ assert!(attrs.size.is_none(), "nonnullable fields retain their existing null contract");+ let props: designcraft_doc::CharProps = serde_json::from_value(json!({"leadingAki":null})).unwrap();+ assert_eq!(props.leading_aki, None);+ }++ /// Write `len` bytes of `fill` to the current entry of `z`.+ fn write_fill(z: &mut zip::ZipWriter<Cursor<Vec<u8>>>, len: usize, fill: u8) {+ let chunk = vec![fill; 1 << 20];+ let mut left = len;+ while left > 0 {+ let n = left.min(chunk.len());+ z.write_all(&chunk[..n]).unwrap();+ left -= n;+ }+ }++ /// Make the archive claim that entry `name` expands to `size` bytes, in both its local header+ /// and its central directory record (the archive has no ZIP64 fields or data descriptors).+ fn claim_size(bytes: &mut [u8], name: &str, size: u32) {+ let mut patched = 0;+ for i in 0..bytes.len().saturating_sub(46) {+ let (size_at, len_at, name_at) = match &bytes[i..i + 4] {+ b"PK\x03\x04" => (22, 26, 30),+ b"PK\x01\x02" => (24, 28, 46),+ _ => continue,+ };+ let len = u16::from_le_bytes([bytes[i + len_at], bytes[i + len_at + 1]]) as usize;+ if bytes.get(i + name_at..i + name_at + len) == Some(name.as_bytes()) {+ bytes[i + size_at..i + size_at + 4].copy_from_slice(&size.to_le_bytes());+ patched += 1;+ }+ }+ assert_eq!(patched, 2, "{name} not found in both headers");+ }++ /// A small archive whose `document.json` expands past the 256 MiB limit while claiming to+ /// hold one byte is refused once the limit is reached, with an error that says so, instead of+ /// being read whole into memory.+ #[test]+ fn oversized_document_json_is_refused() {+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ write_fill(&mut z, (256 << 20) + 1, b' ');+ let mut bytes = z.finish().unwrap().into_inner();+ assert!(bytes.len() < 4 << 20, "{}", bytes.len());+ claim_size(&mut bytes, "document.json", 1);+ let Err(err) = load(&bytes) else { panic!("an oversized document.json loaded") };+ assert!(err.to_string().contains("limit"), "{err}");+ }++ /// An embedded file that expands past the 1 GiB limit (and says so) is refused too.+ #[test]+ fn oversized_asset_is_refused() {+ let mut d = Document::new(&NewDocument::default());+ let aid = png_asset(&mut d, &[1]);+ place(&mut d, aid, 0.0);+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();+ z.start_file(format!("assets/{}.png", aid.0), zip::write::SimpleFileOptions::default()).unwrap();+ write_fill(&mut z, (1 << 30) + 1, 0);+ let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an oversized asset loaded") };+ assert!(err.to_string().contains("limit"), "{err}");+ }++ /// An archive with more entries than any document needs is refused before any is read.+ #[test]+ fn too_many_entries_are_refused() {+ let d = Document::new(&NewDocument::default());+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);+ z.start_file("document.json", stored).unwrap();+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();+ for i in 0..100_000 {+ z.start_file(format!("junk/{i}"), stored).unwrap();+ }+ let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an archive with 100 001 entries loaded") };+ assert!(err.to_string().contains("entries"), "{err}");+ }}diff --cc crates/idml/Cargo.tomlindex f516a6150,023ac183a..e9fcca616--- a/crates/idml/Cargo.toml+++ b/crates/idml/Cargo.toml@@@ -12,7 -12,10 +12,11 @@@ workspace = trudesigncraft-geom = { workspace = true }designcraft-color = { workspace = true }designcraft-doc = { workspace = true }+designcraft-images = { workspace = true }thiserror = { workspace = true }+ log = { workspace = true }quick-xml = { workspace = true }zip = { workspace = true }++ [dev-dependencies]+ designcraft-compose = { workspace = true }diff --cc crates/idml/src/export.rsindex a31abd710,bb2b0d863..a773ec9e5--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@@ -1681,18 -2046,47 +2046,55 @@@ impl<'a> Ex<'a>el}+ /// The `TransparencySetting` children for `e`'s drop shadow and feather; `all` also writes the+ /// effects that are off (`Mode="None"`), as an object style that sets effects does.+ fn effect_els(&self, e: &designcraft_doc::Effects, all: bool) -> Vec<El> {+ let mut out = Vec::new();+ let ds = &e.drop_shadow;+ if ds.on || all {+ let a = self.d.light_angle(ds.angle, ds.global_light).to_radians();+ out.push(+ El::new("DropShadowSetting")+ .attr("Mode", if ds.on { "Drop" } else { "None" })+ .attr("XOffset", num(-ds.distance * a.cos()))+ .attr("YOffset", num(ds.distance * a.sin()))+ .attr("Size", num(ds.size))+ .attr("Spread", num(ds.spread))+ .attr("Opacity", pct(ds.opacity as f64))+ .attr("EffectColor", self.sw(&ds.color)),+ );+ }+ if e.feather > 0.0 || all {+ let corners = match e.feather_options.corners {+ designcraft_doc::FeatherCorners::Sharp => "Sharp",+ designcraft_doc::FeatherCorners::Rounded => "Rounded",+ designcraft_doc::FeatherCorners::Diffused => "Diffusion",+ };+ out.push(+ El::new("FeatherSetting")+ .attr("Mode", if e.feather > 0.0 { "Standard" } else { "None" })+ .attr("Width", num(e.feather))+ .attr("ChokeAmount", num(e.feather_options.choke))+ .attr("CornerType", corners),+ );+ }+ out+ }+fn image_el(&mut self, asset: &designcraft_doc::Asset, g: &designcraft_doc::Graphic) -> El {let is_pdf = asset.mime == "application/pdf";- let mut el = El::new(if is_pdf { "PDF" } else { "Image" }).attr("Self", self.fresh());+ let is_eps = asset.mime == "application/postscript" || designcraft_images::is_eps(&asset.data);+ let mut el = El::new(if is_eps {+ "EPS"+ } else if is_pdf {+ "PDF"+ } else {+ "Image"+ })+ .attr("Self", self.fresh());- if let Some((pw, ph)) = asset.pixels+ // A PDF is vector: its page size in `pixels` isn't a resolution, and a cropped graphic- // spans less than the page.++ // spans less than the page. An EPS's `pixels` is its preview raster, so it still counts.+ if let Some((pw, ph)) = asset.pixels.filter(|_| !is_pdf)&& g.size.0 > 0.0&& g.size.1 > 0.0{diff --cc crates/idml/src/import.rsindex f12add2a9,1e727bcb0..5cd3746a9--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -2107,18 -3017,55 +3017,56 @@@ impl<'r> Importer<'r>None => (0.0, 0.0, 0.0, 0.0),};let size = ((r - l).abs(), (b - t).abs());+ let wrap =+ if g.get("AppliedObjectStyle").is_some() { self.with_style(g, "TextWrapPreference") } else { g.find("TextWrapPreference").cloned() };+ let wrap = wrap.map(|w| text_wrap(&w)).unwrap_or_default();+ let clip = clipping_path(g, Affine::translate((-l, -t)));let link = g.find("Link");let uri = link.and_then(|k| k.get("LinkResourceURI")).map(uri_to_path);+ let graphic = |asset, size| {+ Content::Graphic(designcraft_doc::Graphic {+ asset,+ size,+ xf: gxf * Affine::translate((l, t)),+ clip: clip.clone(),+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ // A wrap set on the placed graphic (Direct Selection) is stored on the graphic element,+ // over the graphic's own object style when it names one.+ wrap,+ fill: Default::default(),+ })+ };let mut data = g.prop_el("Contents").map(|c| base64_decode(&c.text_content())).unwrap_or_default();+ let page = pdf_page_in(g);+ // Where the box sits on the page needs the PDF parsed: the engine finds it after import.+ let pdf_crop = pdf_attribute(g).and_then(|a| a.get("PDFCrop")).map_or(designcraft_doc::PdfCrop::Crop, names::pdf_crop_in);+ let mut read_from = None;if data.is_empty()&& let Some(p) = &uri- && let Some(d) = (self.read_link)(p){- data = d;- }- let (mime, px) = sniff_image(&data);+ // Every placement of a linked file with one page and crop shares one asset; read the+ // file once.+ let key = (p.clone(), page, pdf_crop);+ if let Some(id) = self.linked_assets.get(&key) {+ let size = self.assets.get(id).and_then(|a| svg_viewbox_size(&a.data)).unwrap_or(size);+ return graphic(*id, size);+ }+ if let Some(d) = (self.read_link)(p) {+ data = d;+ read_from = Some(key);+ }+ }+ // A linked file that can't be read shows the document's preview of it, if it has one. The+ // preview only stands in for the file: format and pixel size still describe the link.+ let preview = data.is_empty().then(|| g.get("Self").and_then(|s| self.previews.get(s))).flatten();+ // InDesign draws a viewBox-only SVG at one unit to the point: its GraphicBounds are the+ // art's bounds, which can overhang the viewBox, so they must not size the viewBox.+ let size = svg_viewbox_size(&data).unwrap_or(size);+ let (mime, px) = if preview.is_some() { (None, None) } else { sniff_image(&data) };let mime = mime.map(str::to_string).unwrap_or_else(|| match link.and_then(|k| k.get("LinkResourceFormat")).unwrap_or("") {+ f if f.contains("EPS") || g.local() == "EPS" => "application/postscript".into(),f if f.contains("JPEG") => "image/jpeg".into(),f if f.contains("TIFF") => "image/tiff".into(),f if f.contains("PDF") || g.local() == "PDF" => "application/pdf".into(),diff --cc crates/images/src/eps.rsindex 025ce9db6,5acbffcd1..33c8e1e38--- a/crates/images/src/eps.rs+++ b/crates/images/src/eps.rs@@@ -26,113 -27,34 +27,122 @@@ fn sections(bytes: &[u8]) -> (&[u8], Oppub fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> {let (ps, _) = sections(bytes);let head = String::from_utf8_lossy(&ps[..ps.len().min(64 * 1024)]);- let read = |key: &str| {+ // DSC allows (atend): scan a bounded trailer as well, without reading the whole program.+ let tail = String::from_utf8_lossy(&ps[ps.len().saturating_sub(64 * 1024)..]);+ let header_value = |key: &str| {- head.lines()+ // Lines may end in `\r` alone (classic Mac files).- head.split(['\n', '\r']).find_map(|l| {- let v: Vec<f64> = l.strip_prefix(key)?.split_whitespace().filter_map(|t| t.parse().ok()).collect();- // Finite corners and a finite size (subtracting extreme corners can overflow to infinity).- let [x0, y0, x1, y1] = <[f64; 4]>::try_from(v).ok()?;- let finite = [x0, y0, x1, y1, x1 - x0, y1 - y0].iter().all(|c| c.is_finite());- (finite && x1 > x0 && y1 > y0).then_some([x0, y0, x1, y1])- })++ head.split(['\n', '\r'])+ .take_while(|l| {+ (l.starts_with('%') || l.trim().is_empty())+ && ![+ "%%EndComments",+ "%%BeginDocument",+ "%%BeginProlog",+ "%%BeginSetup",+ "%%BeginData",+ "%%BeginBinary",+ "%%BeginResource",+ "%%Page:",+ ]+ .iter()+ .any(|k| l.starts_with(k))+ })+ .find_map(|l| l.strip_prefix(key))};- read("%%HiResBoundingBox:").or_else(|| read("%%BoundingBox:"))+ let hires = header_value("%%HiResBoundingBox:");+ let bbox = header_value("%%BoundingBox:");+ let at_end = |v: Option<&str>| v.is_some_and(|v| v.trim() == "(atend)");+ // An outer header box must not be replaced by a nested document's trailer comments.+ // Inspect the trailer only when the outer header delegates its bounds there.+ hires+ .and_then(parse_box)+ .or_else(|| (at_end(hires) || at_end(bbox)).then(|| trailer_box(&tail, "%%HiResBoundingBox:")).flatten())+ .or_else(|| bbox.and_then(parse_box))+ .or_else(|| at_end(bbox).then(|| trailer_box(&tail, "%%BoundingBox:")).flatten())+}++fn parse_box(value: &str) -> Option<[f64; 4]> {+ let mut words = value.split_whitespace();+ let mut bb = [0.0f64; 4];+ for n in &mut bb {+ *n = words.next()?.parse().ok()?;+ }- (words.next().is_none() && bb.iter().all(|n| n.is_finite()) && bb[2] > bb[0] && bb[3] > bb[1]).then_some(bb)++ // Finite corners and a finite size (subtracting extreme corners can overflow to infinity).++ let finite = [bb[0], bb[1], bb[2], bb[3], bb[2] - bb[0], bb[3] - bb[1]].iter().all(|n| n.is_finite());++ (words.next().is_none() && finite && bb[2] > bb[0] && bb[3] > bb[1]).then_some(bb)+}++fn trailer_box(tail: &str, key: &str) -> Option<[f64; 4]> {+ // Work backwards from the outer EOF so nesting remains known even when the bounded+ // window begins inside a child document. Opaque DSC data/resource blocks are skipped too.+ let mut nested = 0usize;- for line in tail.lines().rev() {++ for line in tail.split(['\n', '\r']).rev() {+ if ["%%EndDocument", "%%EndData", "%%EndBinary", "%%EndResource"].iter().any(|k| line.starts_with(k)) {+ nested = nested.checked_add(1)?;+ } else if ["%%BeginDocument", "%%BeginData", "%%BeginBinary", "%%BeginResource"].iter().any(|k| line.starts_with(k)) {+ nested = nested.checked_sub(1)?;+ } else if nested == 0+ && let Some(bb) = line.strip_prefix(key).and_then(parse_box)+ {+ return Some(bb);+ }+ }+ None+}++/// Natural EPS dimensions in points. Bound sizes before fitting or allocating a proxy:+/// sub-thousandth-point artwork and dimensions over 20,000 points aren't usable layouts.+pub fn eps_size(bytes: &[u8]) -> Option<(f64, f64)> {+ let bb = bounding_box(bytes)?;+ let (w, h) = (bb[2] - bb[0], bb[3] - bb[1]);+ ((0.001..=20_000.0).contains(&w) && (0.001..=20_000.0).contains(&h)).then_some((w, h))+}++fn preview(bytes: &[u8]) -> Option<(&[u8], (u32, u32))> {+ let (_, tiff) = sections(bytes);+ let tiff = tiff?;+ let (w, h) = crate::pixel_size(tiff)?;+ // Match the decoder's allocation budget, including conversion to RGBA.+ (w > 0 && h > 0 && u64::from(w) * u64::from(h) <= 256 * 1024 * 1024 / 4).then_some((tiff, (w, h)))+}++/// Proxy pixel dimensions, without encoding the placeholder just to read its size.+pub fn eps_pixel_size(bytes: &[u8]) -> Option<(u32, u32)> {+ let (w, h) = eps_size(bytes)?;+ Some(+ preview(bytes)+ .map(|(_, px)| px)+ .unwrap_or_else(|| ((w * 2.0).round().clamp(2.0, 4000.0) as u32, (h * 2.0).round().clamp(2.0, 4000.0) as u32)),+ )+}++/// A browser-readable EPS preview. Keep the original TIFF for print exports (CMYK inks),+/// but HTML and EPUB need PNG rather than a TIFF data URI or a mislabeled .png file.+pub fn eps_png(bytes: &[u8]) -> Option<Vec<u8>> {+ let (proxy, _) = eps_proxy(bytes)?;+ if proxy.starts_with(b"\x89PNG\r\n\x1a\n") {+ return Some(proxy);+ }+ let rgba = crate::decode_rgba(&proxy)?;+ let mut png = Vec::new();+ image::DynamicImage::ImageRgba8(rgba).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;+ Some(png)}/// The proxy for a placed EPS: (image bytes, its size in points). The TIFF preview when present,/// else a light grey placeholder with a cross, at 2 pixels per point.pub fn eps_proxy(bytes: &[u8]) -> Option<(Vec<u8>, (f64, f64))> {- let bb = bounding_box(bytes)?;- let (w, h) = (bb[2] - bb[0], bb[3] - bb[1]);- if let (_, Some(tiff)) = sections(bytes)- && crate::pixel_size(tiff).is_some()- {+ let (w, h) = eps_size(bytes)?;+ if let Some((tiff, _)) = preview(bytes) {return Some((tiff.to_vec(), (w, h)));}+ // Simple PostScript drawn here: InDesign's QR codes are coloured rectangles only.- if let Some(png) = render_rectangles(sections(bytes).0, bb) {++ if let Some(bb) = bounding_box(bytes)++ && let Some(png) = render_rectangles(sections(bytes).0, bb)++ {+ return Some((png, (w, h)));+ }- let (pw, ph) = ((w * 2.0).round().clamp(2.0, 4000.0) as u32, (h * 2.0).round().clamp(2.0, 4000.0) as u32);+ let (pw, ph) = eps_pixel_size(bytes)?;let mut img = image::RgbaImage::from_pixel(pw, ph, image::Rgba([228, 228, 228, 255]));// Diagonals and a border mark it as a stand-in.let n = pw.max(ph);@@@ -159,37 -228,53 +316,84 @@@ fn render_rectangles(ps: &[u8], bb: [f6mod tests {use super::*;+ #[test]+ fn eps_rejects_unsafe_bounds_and_accepts_trailer_bounds() {+ for bounds in ["0 0 1e-320 1e-320", "0 0 1e308 1e308", "0 0 inf 10"] {+ let eps = format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: {bounds}\n%%EOF\n");+ assert!(eps_proxy(eps.as_bytes()).is_none(), "{bounds}");+ }+ let mut eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: (atend)\n".to_vec();+ eps.extend(vec![b' '; 70_000]);+ eps.extend(b"\n%%Trailer\n%%BoundingBox: 0 0 20 10\n%%EOF\n");+ assert_eq!(eps_proxy(&eps).unwrap().1, (20.0, 10.0));+ }++ #[test]+ fn eps_nested_document_bounds_do_not_override_outer_artwork() {+ for (deferred, padding, child_padding) in [(false, 0, 0), (false, 8_000, 0), (true, 8_000, 0), (true, 0, 8_000)] {+ let mut eps =+ format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: {}\n%%EndComments\n", if deferred { "(atend)" } else { "0 0 100 50" }).into_bytes();+ eps.extend(b"% padding\n".repeat(padding));+ eps.extend(b"%%BeginDocument: child.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: (atend)\n%%EndComments\n");+ eps.extend(b"% child padding\n".repeat(child_padding));+ eps.extend(b"%%Trailer\n%%BoundingBox: 0 0 10 20\n%%HiResBoundingBox: 0 0 10 20\n%%EOF\n%%EndDocument\n");+ if deferred {+ eps.extend(b"%%Trailer\n%%BoundingBox: 0 0 100 50\n");+ }+ eps.extend(b"%%EOF\n");+ assert_eq!(eps_size(&eps), Some((100.0, 50.0)), "deferred={deferred}, padding={padding}, child_padding={child_padding}");+ }+ let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: (atend)\n%%HiResBoundingBox: (atend)\n%%EndComments\nnewpath\n%%Trailer\n%%BoundingBox: 0 0 101 51\n%%HiResBoundingBox: 0 0 100.5 50.25\n%%EOF\n";+ assert_eq!(eps_size(eps), Some((100.5, 50.25)));+ }++ #[test]+ fn simple_rectangle_eps_is_drawn_like_a_qr_code() {+ // As InDesign writes QR codes: a procedure for rectfill, a colour, then modules.+ let eps = b"%!PS-Adobe-3.1 EPSF-3.0\n%%BoundingBox: 0 0 4 4\n%%EndComments\n/rf { rectfill } bind def\n0 0 0 1 setcmykcolor\n0 2 2 2 rf\n2 0 2 2 rf\n%%EOF\n";+ let (png, size) = eps_proxy(eps).unwrap();+ assert_eq!(size, (4.0, 4.0));+ let img = image::load_from_memory(&png).unwrap().to_rgba8();+ assert_eq!(img.dimensions(), (32, 32), "8 pixels per point");+ // PostScript y runs up: (0, 2)–(2, 4) is the image's top left.+ assert_eq!(img.get_pixel(4, 4).0, [0, 0, 0, 255]);+ assert_eq!(img.get_pixel(28, 28).0, [0, 0, 0, 255]);+ assert_eq!(img.get_pixel(28, 4).0[3], 0, "undrawn stays transparent");+ assert_eq!(img.get_pixel(4, 28).0[3], 0);+ // Anything else (here a path) keeps the placeholder.+ let curve = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 4 4\n0 0 moveto 4 4 lineto stroke\n%%EOF\n";+ let (png, _) = eps_proxy(curve).unwrap();+ let img = image::load_from_memory(&png).unwrap().to_rgba8();+ assert_eq!(img.get_pixel(2, 4).0, [228, 228, 228, 255]);+ }++ /// The colour at pixel (x, y) of a drawn simple EPS (8 pixels per point).+ fn drawn(eps: &[u8], x: u32, y: u32) -> [u8; 4] {+ let (png, _) = eps_proxy(eps).unwrap();+ image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(x, y).0+ }++ #[test]+ fn gsave_grestore_pop_and_cr_line_ends_in_simple_eps() {+ // `\r`-only lines; red inside gsave/grestore, black again after; `pop` drops the 7.+ let eps = b"%!PS-Adobe-3.1 EPSF-3.0\r%%BoundingBox: 0 0 4 4\r/rf { rectfill } bind def\r0 0 0 1 setcmykcolor\rgsave 1 0 0 setrgbcolor 0 2 2 2 7 pop rf grestore\r2 0 2 2 rf\r%%EOF\r";+ assert_eq!(drawn(eps, 4, 4), [255, 0, 0, 255], "top left: red");+ assert_eq!(drawn(eps, 28, 28), [0, 0, 0, 255], "bottom right: the colour from before gsave");+ assert_eq!(drawn(eps, 28, 4)[3], 0, "top right: nothing (pop removed the extra operand)");+ // Unbounded nesting isn't drawn.+ let deep = format!("{} 0 0 2 2 rectfill", "gsave ".repeat(MAX_SAVE_DEPTH + 1));+ assert_eq!(render_rectangles(deep.as_bytes(), [0.0, 0.0, 4.0, 4.0]), None);+ }++ #[test]+ fn a_huge_token_stream_on_one_line_is_refused() {+ // One line of more operands than the token limit, then a rectangle.+ let ps = format!("{}\n0 0 2 2 rectfill\n", "0 ".repeat(MAX_TOKENS));+ assert_eq!(render_rectangles(ps.as_bytes(), [0.0, 0.0, 4.0, 4.0]), None);+ let ps = format!("{}\n0 0 2 2 rectfill\n", "0 ".repeat(1000));+ assert!(render_rectangles(ps.as_bytes(), [0.0, 0.0, 4.0, 4.0]).is_some(), "under the limit it is drawn");+ }+#[test]fn eps_bounding_box_and_proxies() {let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%HiResBoundingBox: 0 0 100.5 50.25\nnewpath\n%%EOF\n";diff --cc crates/images/src/lib.rsindex 0e0d204c7,24eeedb5f..a64ebace1--- a/crates/images/src/lib.rs+++ b/crates/images/src/lib.rs@@@ -8,9 -8,13 +8,13 @@@ use std::sync::{Arc, OnceLock}pub use resvg::usvg;+ pub mod colour;mod eps;+ mod jpeg;mod psd;+ mod tone;-pub use eps::{bounding_box as eps_bounding_box, eps_proxy, is_eps};+pub use eps::{bounding_box as eps_bounding_box, eps_pixel_size, eps_png, eps_proxy, eps_size, is_eps};+ pub use tone::{Tone, tone};/// CSS pixels (SVG user units) → points.pub const PT_PER_PX: f64 = 0.75;diff --cc crates/pdf/src/export.rsindex 4713f0df5,5eae34a77..3afe22015--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@@ -1165,37 -1318,49 +1318,60 @@@ impl Exporter<'_>return i.clone();}let asset = self.doc.assets.get(&id)?.clone();- // Use the same EPS preview as the renderer, preserving CMYK TIFF inks below.- let data = asset.data.clone();++ // Use the same EPS preview as the renderer, preserving CMYK TIFF inks below. The++ // content cache is keyed on the bytes actually converted, so equal previews share one.+ let data = if designcraft_images::is_eps(&asset.data) {+ let Some((proxy, _)) = designcraft_images::eps_proxy(&asset.data) else {+ self.warn(format!("image `{}` could not be decoded and was skipped", asset.name));+ self.images.insert(id, None);+ return None;+ };+ Arc::new(proxy)+ } else {+ asset.data.clone()+ };+ if let Some(converted) = self.images_by_content.get(&data).cloned() {+ if let Some(warning) = converted.warning {+ self.warn(format!("{}: {warning}", asset.name));+ }+ self.images.insert(id, Some(converted.image.clone()));+ return Some(converted.image);+ }let fmt = image::guess_format(&data).ok();+ #[cfg(test)]+ {+ self.image_conversions += 1;+ }+ let mut warning = None;+ let mode = RasterMode::for_standard(self.opts.standard);let img = match fmt {- Some(image::ImageFormat::Jpeg) => Image::from_jpeg(data.clone().into(), true).ok(),+ Some(image::ImageFormat::Jpeg) => jpeg(data.clone().into(), || embedded_icc(&data), mode),// A CMYK TIFF keeps its ink values (`image` decodes it to RGB, and 100% K would print// as four-colour black). PDF/A exports are RGB only.- Some(image::ImageFormat::Tiff) if !self.rgb_only && designcraft_images::is_cmyk_tiff(&data) => match cmyk_tiff(&data) {+ Some(image::ImageFormat::Tiff) if !self.rgb_only && designcraft_images::is_cmyk_tiff(&data) => match cmyk_tiff(&data, mode) {Some(img) => Some(img),None => {- self.warn(format!(- "{}: converted to RGB (a CMYK TIFF that is planar, has premultiplied alpha, uses other inks or is over 256 MiB)",- asset.name- ));- lossless(&data, fmt)+ warning = Some(CMYK_FALLBACK_WARNING);+ self.warn(format!("{}: {CMYK_FALLBACK_WARNING}", asset.name));+ lossless(&data, fmt, mode)}},- _ if self.opts.compress_images => recompress(&data).or_else(|| lossless(&data, fmt)),- _ => lossless(&data, fmt),+ _ if self.opts.compress_images => recompress(&data, mode).or_else(|| lossless(&data, fmt, mode)),+ _ => lossless(&data, fmt, mode),};if img.is_none() {- self.warn(format!("image `{}` could not be decoded and was skipped", asset.name));+ if data.is_empty() {+ // A linked file that wasn't found when the document was opened: nothing to decode.+ let at = asset.link.as_deref().map(|l| format!(" ({l})")).unwrap_or_default();+ self.warn(format!("image `{}` is missing{at} and was skipped", asset.name));+ } else {+ self.warn(format!("image `{}` could not be decoded and was skipped", asset.name));+ }+ }+ if let Some(image) = &img {+ // Share the original encoded payload. HashMap checks exact bytes after hashing,+ // so collisions cannot merge distinct images or their diagnostics.+ self.images_by_content.insert(data, ConvertedImage { image: image.clone(), warning });}self.images.insert(id, img.clone());img@@@ -1350,72 -1767,272 +1778,343 @@@ fn recompress(data: &[u8], mode: Rasterlet mut buf = Vec::new();let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, 90);image::ImageEncoder::write_image(enc, rgb.as_raw(), rgb.width(), rgb.height(), image::ExtendedColorType::Rgb8).ok()?;- Image::from_jpeg(buf.into(), true).ok()+ jpeg(buf.into(), || embedded_icc(data).filter(|p| is_rgb_icc(p)), mode)+ }++ #[cfg(test)]+ mod image_content_cache_tests {+ use super::*;+ use designcraft_doc::Asset;++ fn png(w: u32, h: u32, color: [u8; 4]) -> Vec<u8> {+ let image = image::RgbaImage::from_pixel(w, h, image::Rgba(color));+ let mut bytes = Vec::new();+ image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();+ bytes+ }+ fn asset(doc: &mut Document, bytes: Vec<u8>, name: &str) -> AssetId {+ let id = AssetId(doc.alloc());+ doc.assets.insert(id, Arc::new(Asset { id, name: name.into(), mime: "image/png".into(), data: Arc::new(bytes), ..Default::default() }));+ id+ }+ fn exporter<'a>(doc: &'a Document, cache: &'a Cache, opts: &'a PdfOptions) -> Exporter<'a> {+ Exporter {+ drawing_items: Vec::new(),+ doc,+ cache,+ opts,+ clip: Rect::ZERO,+ warnings: Vec::new(),+ images: HashMap::new(),+ images_by_content: ImageContentCache::default(),+ image_conversions: 0,+ pdfs: HashMap::new(),+ version: PdfVersion::Pdf17,+ too_new: Vec::new(),+ svgs: HashMap::new(),+ fonts: HashMap::new(),+ reverse_cmaps: HashMap::new(),+ rgb_only: false,+ tags: Vec::new(),+ story_tags: HashMap::new(),+ tag_story: None,+ text_area: None,+ para_tags: HashMap::new(),+ }+ }+ #[test]+ fn exact_bytes_reuse_conversion_under_real_hash_collisions() {+ use std::hash::{BuildHasher, Hasher};+ let mut d = Document::new(&Default::default());+ let red = png(2, 1, [255, 0, 0, 255]);+ let blue = png(1, 2, [0, 0, 255, 128]);+ let a1 = asset(&mut d, red.clone(), "a1");+ let b1 = asset(&mut d, blue.clone(), "b1");+ let a2 = asset(&mut d, red, "a2");+ let b2 = asset(&mut d, blue, "b2");+ assert!(!Arc::ptr_eq(&d.assets[&a1].data, &d.assets[&a2].data));+ let cache = Cache::new();+ let opts = PdfOptions::default();+ let mut ex = exporter(&d, &cache, &opts);+ let mut h1 = ex.images_by_content.hasher().build_hasher();+ h1.write(&d.assets[&a1].data);+ let mut h2 = ex.images_by_content.hasher().build_hasher();+ h2.write(&d.assets[&b1].data);+ assert_eq!(h1.finish(), h2.finish());+ assert_ne!(d.assets[&a1].data, d.assets[&b1].data);+ for (id, count, size) in [(a1, 1, (2, 1)), (b1, 2, (1, 2)), (a2, 2, (2, 1)), (a1, 2, (2, 1)), (b2, 2, (1, 2))] {+ assert_eq!(ex.load_image(id).unwrap().size(), size);+ assert_eq!(ex.image_conversions, count, "count actual converter executions, not krilla resource equality");+ }+ assert_eq!(ex.images.len(), 4);+ assert_eq!(ex.images_by_content.len(), 2);+ let first_key = ex.images_by_content.keys().find(|key| key.as_slice() == d.assets[&a1].data.as_slice()).unwrap();+ assert!(Arc::ptr_eq(first_key, &d.assets[&a1].data), "cache keys share the original encoded payload");+ ex.images_by_content.clear();+ assert_eq!(ex.load_image(a1).unwrap().size(), (2, 1));+ assert_eq!(ex.image_conversions, 2, "the AssetId cache remains the first lookup");+ assert!(ex.images_by_content.is_empty());+ }+ #[test]+ fn successful_content_cache_does_not_suppress_failure_names() {+ let mut d = Document::new(&Default::default());+ let a = asset(&mut d, vec![0, 1, 2, 3], "broken-a.png");+ let b = asset(&mut d, vec![0, 1, 2, 3], "broken-b.png");+ let cache = Cache::new();+ let opts = PdfOptions::default();+ let mut ex = exporter(&d, &cache, &opts);+ assert!(ex.load_image(a).is_none());+ assert!(ex.load_image(b).is_none());+ assert!(ex.load_image(a).is_none());+ assert_eq!(ex.image_conversions, 2);+ assert!(ex.images_by_content.is_empty());+ assert_eq!(ex.warnings.len(), 2);+ assert!(ex.warnings[0].contains("broken-a.png"));+ assert!(ex.warnings[1].contains("broken-b.png"));+ }+ #[test]+ fn content_cache_is_scoped_to_each_immutable_options_context() {+ let mut d = Document::new(&Default::default());+ let data = png(2, 2, [240, 20, 30, 255]);+ let a = asset(&mut d, data.clone(), "a");+ let b = asset(&mut d, data, "b");+ let cache = Cache::new();+ for compress_images in [false, true, false] {+ let opts = PdfOptions { compress_images, ..Default::default() };+ let mut ex = exporter(&d, &cache, &opts);+ assert!(ex.load_image(a).is_some());+ assert!(ex.load_image(b).is_some());+ assert_eq!(ex.image_conversions, 1);+ assert_eq!(ex.images_by_content.len(), 1);+ }+ }++ #[test]+ fn successful_cmyk_fallback_replays_each_asset_name_once_and_converts_once() {+ let bytes = crate::image_fixtures::cmyk_tiff(None, true);+ assert!(designcraft_images::is_cmyk_tiff(&bytes));+ assert!(designcraft_images::decode_cmyk_tiff(&bytes).is_none());+ assert!(designcraft_images::decode_rgba(&bytes).is_some());+ let mut d = Document::new(&Default::default());+ let a = asset(&mut d, bytes.clone(), "ink-a.tif");+ let b = asset(&mut d, bytes, "ink-b.tif");+ let cache = Cache::new();+ for compress_images in [false, true] {+ let opts = PdfOptions { compress_images, ..Default::default() };+ let mut ex = exporter(&d, &cache, &opts);+ for id in [a, b, a, b] {+ assert_eq!(ex.load_image(id).unwrap().size(), (2, 1));+ }+ assert_eq!(ex.image_conversions, 1);+ assert_eq!(ex.images_by_content.len(), 1);+ assert_eq!(ex.warnings, [format!("ink-a.tif: {CMYK_FALLBACK_WARNING}"), format!("ink-b.tif: {CMYK_FALLBACK_WARNING}")]);+ }+ }++ #[test]+ fn cmyk_alpha_and_rgb_only_context_keep_conversion_counts_and_failures() {+ let cache = Cache::new();+ for alpha in [None, Some(2), Some(1)] {+ let mut d = Document::new(&Default::default());+ let bytes = crate::image_fixtures::cmyk_tiff(alpha, false);+ // RGB-only exports get the RGB the screen shows.+ let screen_rgb: Vec<u8> =+ designcraft_images::decode_rgba(&bytes).map_or_else(Vec::new, |img| img.pixels().flat_map(|p| [p[0], p[1], p[2]]).collect());+ let a = asset(&mut d, bytes.clone(), "a.tif");+ let b = asset(&mut d, bytes, "b.tif");+ for standard in [Standard::None, Standard::PdfA2b, Standard::PdfX4, Standard::PdfA2b, Standard::None] {+ let opts = PdfOptions { standard, ..Default::default() };+ let mut ex = exporter(&d, &cache, &opts);+ ex.rgb_only = standard == Standard::PdfA2b;+ // Unassociated alpha (2) decodes as inks, and as RGB for RGB-only exports.+ // Associated alpha is rejected by both paths: retain both failure names.+ let succeeds = alpha.is_none() || alpha == Some(2);+ let first = ex.load_image(a);+ assert_eq!(first.is_some(), succeeds, "{alpha:?} {standard:?}");+ if alpha.is_none() {+ let (space, samples) = image_color_samples(first.unwrap());+ assert_eq!(space, if ex.rgb_only { "DeviceRGB" } else { "DeviceCMYK" });+ assert_eq!(samples, if ex.rgb_only { screen_rgb.clone() } else { crate::image_fixtures::INKS.to_vec() });+ }+ assert_eq!(ex.load_image(b).is_some(), succeeds, "{alpha:?} {standard:?}");+ assert_eq!(ex.load_image(a).is_some(), succeeds);+ assert_eq!(ex.image_conversions, if succeeds { 1 } else { 2 });+ assert_eq!(ex.images_by_content.len(), usize::from(succeeds));+ if succeeds {+ assert!(ex.warnings.is_empty());+ } else {+ for name in ["a.tif", "b.tif"] {+ assert!(ex.warnings.contains(&format!("image `{name}` could not be decoded and was skipped")));+ assert_eq!(ex.warnings.contains(&format!("{name}: {CMYK_FALLBACK_WARNING}")), !ex.rgb_only);+ }+ }+ }+ }+ }++ // Serialize the converted raster without an archival validator so the RGB-only pixel+ // contract stays independent of main's existing PDF/A interpolation validation failure.+ fn image_color_samples(image: Image) -> (String, Vec<u8>) {+ use hayro_syntax::object::Name;+ let mut pdf = krilla::Document::new();+ let size = Size::from_wh(20.0, 20.0).unwrap();+ let mut page = pdf.start_page_with(PageSettings::new(size));+ let mut surface = page.surface();+ surface.draw_image(image, size);+ surface.finish();+ page.finish();+ let bytes = pdf.finish().unwrap();+ let pdf = hayro_syntax::Pdf::new(bytes).unwrap();+ let stream = pdf+ .objects()+ .into_iter()+ .filter_map(|o| o.into_stream())+ .find(|s| s.dict().get::<Name>("Subtype").is_some_and(|n| n.as_str() == "Image"))+ .unwrap();+ (stream.dict().get::<Name>("ColorSpace").unwrap().as_str().to_owned(), stream.decoded().unwrap().into_owned())+ }++ #[test]+ fn content_cache_owns_only_existing_payloads_and_drops_with_exporter() {+ let mut d = Document::new(&Default::default());+ let bytes = png(2, 1, [20, 30, 40, 255]);+ let a = asset(&mut d, bytes.clone(), "a.png");+ let b = asset(&mut d, bytes, "b.png");+ let payload = Arc::downgrade(&d.assets[&a].data);+ let duplicate = Arc::downgrade(&d.assets[&b].data);+ let cache = Cache::new();+ let opts = PdfOptions::default();+ let mut ex = exporter(&d, &cache, &opts);+ assert!(ex.load_image(a).is_some());+ assert!(ex.load_image(b).is_some());+ assert_eq!(duplicate.strong_count(), 1, "a content hit must not retain the second encoded allocation");+ let key = ex.images_by_content.keys().next().unwrap();+ assert!(Arc::ptr_eq(key, &d.assets[&a].data));+ drop(ex);+ drop(d);+ assert!(payload.upgrade().is_none(), "no converted image or encoded key outlives this exporter");+ assert!(duplicate.upgrade().is_none());+ }+ }++ #[cfg(all(test, not(target_arch = "wasm32")))]+ mod unwind_tests {+ use super::*;+ use std::cell::Cell;++ thread_local! {+ static FAIL_NEXT_SURFACE: Cell<bool> = const { Cell::new(false) };+ }++ // Fail with live backend drawing state, so a missing guard or an unpatched destructor+ // makes the child fail. Thread-local state keeps unrelated export tests independent.+ #[allow(clippy::panic)] // Test-only fault injection exercises recovery with a live surface.+ pub(super) fn inject(surface: &mut krilla::surface::Surface<'_>) {+ if FAIL_NEXT_SURFACE.replace(false) {+ surface.push_transform(&krilla::geom::Transform::from_translate(2.0, 3.0));+ panic!("synthetic export drawing failure");+ }+ }++ #[test]+ fn export_entry_points_recover_in_a_subprocess() {+ const CHILD: &str = "DESIGNCRAFT_PDF_EXPORT_PANIC_PROBE";+ if std::env::var_os(CHILD).is_none() {+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "export::unwind_tests::export_entry_points_recover_in_a_subprocess", "--nocapture"])+ .env(CHILD, "1")+ .output()+ .unwrap();+ assert!(output.status.success(), "export child failed: {:?}\n{}", output.status, String::from_utf8_lossy(&output.stderr));+ assert!(String::from_utf8_lossy(&output.stdout).contains("all three export entry points recovered"));+ return;+ }+ let doc = Document::new(&designcraft_doc::build::NewDocument { pages: 1, ..Default::default() });+ let cache = Cache::new();+ let source = export_pdf(&doc, &cache, &Default::default()).unwrap();+ let parts = [(source, vec![(612.0, 792.0)])];+ for entry in ["document", "booklet", "merge"] {+ let export = || match entry {+ "document" => export_pdf(&doc, &cache, &Default::default()),+ "booklet" => export_booklet(&doc, &cache, &Default::default()).map(|report| report.bytes),+ _ => merge_pdfs(&parts, None),+ };+ FAIL_NEXT_SURFACE.set(true);+ assert!(matches!(export(), Err(PdfError::Write(message)) if message.contains("synthetic export drawing failure")), "{entry}");+ let fresh = export().unwrap();+ assert!(!hayro_syntax::Pdf::new(Arc::new(fresh)).unwrap().pages().is_empty(), "fresh {entry} export must still work");+ }+ println!("all three export entry points recovered");+ }}++#[cfg(test)]+mod eps_tests {+ use super::*;+ use hayro_syntax::object::Name;++ #[test]+ fn eps_tiff_preview_keeps_cmyk_inks_in_pdf() {+ let pixels = vec![0u8, 0, 0, 255, 0, 255, 255, 0];+ let mut tiff = Vec::new();+ tiff::encoder::TiffEncoder::new(std::io::Cursor::new(&mut tiff))+ .unwrap()+ .write_image::<tiff::encoder::colortype::CMYK8>(2, 1, &pixels)+ .unwrap();+ let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 2 1\n%%EOF\n";+ let mut eps = vec![0xC5, 0xD0, 0xD3, 0xC6];+ for value in [30usize, ps.len(), 0, 0, 30 + ps.len(), tiff.len()] {+ eps.extend((value as u32).to_le_bytes());+ }+ eps.extend([0xFF, 0xFF]);+ eps.extend_from_slice(ps);+ eps.extend_from_slice(&tiff);+ assert_eq!(designcraft_images::eps_proxy(&eps).unwrap().0, tiff);+ let mut doc = Document::new(&designcraft_doc::build::NewDocument::default());+ let aid = AssetId(doc.alloc());+ doc.assets.insert(+ aid,+ Arc::new(designcraft_doc::Asset {+ id: aid,+ name: "cmyk.eps".into(),+ mime: "application/postscript".into(),+ link: None,+ data: Arc::new(eps),+ pixels: Some((2, 1)),+ page: 0,++ ..Default::default()+ }),+ );+ let mut item = Item::new(+ designcraft_doc::ItemId(doc.alloc()),+ doc.default_layer(),+ designcraft_doc::Shape::Rectangle,+ designcraft_geom::shapes::rectangle(Rect::new(72.0, 72.0, 272.0, 172.0)),+ );+ item.content = Content::Graphic(designcraft_doc::Graphic {+ asset: aid,+ size: (2.0, 1.0),+ xf: Affine::translate((72.0, 72.0)) * Affine::scale(100.0),+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],++ clip: None,++ wrap: Default::default(),++ fill: Default::default(),+ });+ doc.insert_item(designcraft_doc::SpreadRef::Doc(0), item, None).unwrap();+ for standard in [Standard::None, Standard::PdfX4] {+ let report = export_pdf_with_report(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() }).unwrap();+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);+ let pdf = hayro_syntax::Pdf::new(report.bytes).unwrap();+ let images: Vec<_> = pdf+ .objects()+ .into_iter()+ .filter_map(|o| o.into_stream())+ .filter(|s| s.dict().get::<Name>("Subtype").is_some_and(|n| n.as_str() == "Image"))+ .map(|s| (s.dict().get::<Name>("ColorSpace").unwrap().as_str().to_string(), s.decoded().unwrap().into_owned()))+ .collect();+ assert_eq!(images, vec![("DeviceCMYK".to_string(), pixels.clone())], "{standard:?}");+ }+ }+}diff --cc crates/render/src/lib.rsindex 4a85ec326,297e8dab4..c42d8c897--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@@ -1028,9 -1211,13 +1217,14 @@@ pub fn image_size(bytes: &[u8]) -> Optidesigncraft_images::pixel_size(bytes)}- /// Natural graphic size in points; EPS uses its bounding box, independently of preview pixels.- pub fn image_natural_size(bytes: &[u8]) -> Option<(f64, f64)> {- if designcraft_images::is_eps(bytes) { designcraft_images::eps_size(bytes) } else { image_size(bytes).map(|(w, h)| (w as f64, h as f64)) }+ /// Natural size of a placed graphic, unrounded: a PDF page (crop box) and an SVG in points, a raster-/// in pixels. Placed graphics are drawn at this size; `image_size` rounds it to whole pixels for display.++/// in pixels, an EPS its bounding box independently of preview pixels. Placed graphics are drawn at++/// this size; `image_size` rounds it to whole pixels for display.+ pub fn natural_size(bytes: &[u8], page: usize) -> Option<(f64, f64)> {+ if is_pdf(bytes) {+ return pdf_page_size(bytes, page).map(|(w, h)| (w.max(1e-3), h.max(1e-3)));+ }+ designcraft_images::natural_size(bytes)}/// MIME type guess for encoded image bytes.@@@ -1180,34 -1468,31 +1475,59 @@@ mod testsuse designcraft_doc::build::NewDocument;use designcraft_doc::{Fill, ParaFormat};+ #[test]+ fn eps_source_decodes_like_its_preview() {+ let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EOF\n";+ let mut tiff = Vec::new();+ image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(3, 2, image::Rgba([255, 0, 0, 128])))+ .write_to(&mut std::io::Cursor::new(&mut tiff), image::ImageFormat::Tiff)+ .unwrap();+ let mut dos = vec![0xC5, 0xD0, 0xD3, 0xC6];+ for value in [30usize, source.len(), 0, 0, 30 + source.len(), tiff.len()] {+ dos.extend((value as u32).to_le_bytes());+ }+ dos.extend([0xFF, 0xFF]);+ dos.extend_from_slice(source);+ dos.extend_from_slice(&tiff);+ for source in [source.as_slice(), dos.as_slice()] {+ let proxy = designcraft_images::eps_proxy(source).unwrap().0;+ let actual = decode_pixmap(source).unwrap();+ let expected = decode_pixmap(&proxy).unwrap();+ assert_eq!((actual.width(), actual.height()), (expected.width(), expected.height()));+ assert_eq!(actual.data(), expected.data());+ assert_eq!(image_size(source), image_size(&proxy));+ assert_eq!(image_mime(source), "application/postscript");+ }+ let corrupt = b"%!PS-Adobe-3.0 EPSF-3.0\nno bounding box\n";+ assert!(decode_pixmap(corrupt).is_none());+ assert!(image_size(corrupt).is_none());+ }++ #[test]+ fn footnote_vector_objects_are_painted() {+ use designcraft_doc::{AnchorPosition, AnchoredObject, ItemId, Shape, SpreadRef};+ let mut d = Document::new(&NewDocument::default());+ let (_, sid) =+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(20.0, 20.0, 300.0, 300.0), d.default_layer(), "Body", ParaFormat::default()).unwrap();+ let mut item =+ Item::new(ItemId(d.alloc()), d.default_layer(), Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 12.0, 12.0)));+ item.fill = Fill::swatch(designcraft_color::swatch::BLACK);+ // Open contours with a fill are implicitly closed for painting. A single+ // open contour must not hide the whole compound glyph.+ item.path.subpaths[0].closed = false;+ let story = d.story_mut(sid).unwrap();+ story.insert_note(4, "", ParaFormat::default());+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 0.0 }));+ let cache = Cache::new();+ let cs = cache.get(&d, sid, None);+ let note = &cs.frames[0].notes[0];+ let object = ¬e.text.frames[0].objects[0];+ let centre = note.origin + object.origin.to_vec2() + designcraft_geom::Vec2::new(6.0, 6.0);+ let image = Renderer::new().render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();+ let pixel = image.pixel(centre.x as u32, centre.y as u32);+ assert!(pixel[0] < 80 && pixel[1] < 80 && pixel[2] < 80, "{pixel:?}");+ }+/// `Rendered` has public fields: a buffer that doesn't match the stated size used to panic/// in `to_png`./// A canvas 65535 pixels wide (any render wider than that was clamped to it) panicked inside