Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #819: Keep a missing graphic missing when it is pasted into another document (#720)

aiongg0016b8260e17
diff --cc crates/engine/src/cmd/links.rs
index b37dae68e,933fdfbd4..c48b3651f
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@@ -569,236 -427,46 +569,282 @@@ mod shared_asset_tests
assert_eq!((g.asset, g.crop), (same, [1.0; 4]));
assert_eq!(dst.assets.len(), 2);
}
+
+ #[test]
+ fn pasted_missing_graphic_does_not_show_an_unrelated_target_asset() {
+ use designcraft_doc::build::NewDocument;
+ use designcraft_doc::{Asset, Graphic, Item, ItemId, Shape, SpreadRef};
+ let mut src = Document::new(&NewDocument::default());
+ let mut dst = Document::new(&NewDocument::default());
+ // The source graphic points at an asset the source does not have; the target uses that id for another image.
+ let missing = AssetId(src.alloc());
+ dst.assets.insert(
+ missing,
+ Arc::new(Asset {
+ id: missing,
+ name: "p.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(png(8, 4)),
+ pixels: None,
+ page: 0,
++ pdf_crop: Default::default(),
++ pdf_box: None,
+ }),
+ );
+ let iid = ItemId(src.alloc());
+ let mut it = Item::new(
+ iid,
+ src.default_layer(),
+ Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(0.0, 0.0, 9.0, 9.0)),
+ );
+ it.content = Content::Graphic(Graphic {
+ asset: missing,
+ size: (4.0, 4.0),
+ xf: designcraft_geom::Affine::IDENTITY,
++ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [1.0; 4],
++ wrap: Default::default(),
+ });
+ src.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let ids = super::super::object::duplicate_from(&mut dst, &src, &[iid], SpreadRef::Doc(0), designcraft_geom::Vec2::ZERO).unwrap();
+ let g = dst.item(ids[0]).and_then(|i| i.graphic()).unwrap();
+ assert_ne!(g.asset, missing);
+ assert!(!dst.assets.contains_key(&g.asset));
+ }
}
+
+#[cfg(test)]
+mod text_link_tests {
+ use serde_json::{Value, json};
+
+ use crate::Session;
+ use designcraft_doc::{ItemId, StoryId};
+
+ /// A small Word file: a Title paragraph, then Body paragraphs (`body` is WordprocessingML).
+ fn docx(body: &str) -> Vec<u8> {
+ use std::io::Write;
+ const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
+ let styles = format!(
+ r#"<w:styles {W}><w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:rPr><w:sz w:val="56"/></w:rPr></w:style>
+ <w:style w:type="paragraph" w:styleId="Body"><w:name w:val="Body"/><w:rPr><w:sz w:val="20"/></w:rPr></w:style></w:styles>"#
+ );
+ let doc = format!(
+ r#"<w:document {W}><w:body><w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Head</w:t></w:r></w:p>
+ <w:p><w:pPr><w:pStyle w:val="Body"/></w:pPr>{body}</w:p></w:body></w:document>"#
+ );
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let o = zip::write::SimpleFileOptions::default();
+ for (n, c) in [("word/document.xml", doc), ("word/styles.xml", styles)] {
+ w.start_file(n, o).unwrap();
+ w.write_all(c.as_bytes()).unwrap();
+ }
+ w.finish().unwrap().into_inner()
+ }
+
+ fn text_rows(s: &mut Session) -> Vec<Value> {
+ let l = s.execute("links.list", &json!({})).unwrap();
+ l.as_array().unwrap().iter().filter(|r| r.get("story").is_some()).cloned().collect()
+ }
+
+ fn story(s: &Session, sid: StoryId) -> designcraft_doc::Story {
+ s.doc().unwrap().doc.story(sid).unwrap().clone()
+ }
+
+ fn styles(st: &designcraft_doc::Story) -> Vec<String> {
+ st.paras.iter().map(|p| p.style.clone()).collect()
+ }
+
+ #[test]
+ fn linked_word_file_status_update_relink_and_unlink() {
+ let dir = std::env::temp_dir().join(format!("dc-text-link-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join("moved")).unwrap();
+ let path = dir.join("chapter.docx");
+ std::fs::write(&path, docx("<w:r><w:t>First draft.</w:t></w:r>")).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 2})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Body", "chars": {"size": 9}})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Headline", "chars": {"size": 30}})).unwrap();
+ // Two threaded frames.
+ let a = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text"})).unwrap()["id"].as_u64().unwrap();
+ let b = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "spread": 1, "content": "text"})).unwrap()["id"].as_u64().unwrap();
+ s.edit(|d, _| Ok(d.thread(ItemId(a), ItemId(b))?)).unwrap();
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+
+ // Place and link, with a style map and Auto Rename.
+ let r = s
+ .execute(
+ "file.place",
+ &json!({"path": path.to_string_lossy(), "frame": a, "link": true, "styleMap": {"Title": "Headline"}, "styleConflicts": "autoRename"}),
+ )
+ .unwrap();
+ let sid = StoryId(r["story"].as_u64().unwrap());
+ let placed = story(&s, sid);
+ assert_eq!(placed.text, "Head\nFirst draft.");
+ assert_eq!(styles(&placed), ["Headline", "Body_wrd_1"]);
+ let link = placed.file_link.clone().unwrap();
+ assert_eq!(link.path, path.to_string_lossy());
+ assert_eq!(link.style_conflicts, "autoRename");
+ assert_eq!(link.style_map.get("Title").map(String::as_str), Some("Headline"));
+ assert_eq!(link.style_map.get("Body").map(String::as_str), Some("Body_wrd_1"), "Auto Rename's choice is kept");
+ let rows = text_rows(&mut s);
+ assert_eq!(rows.len(), 1);
+ assert_eq!((rows[0]["story"].as_u64(), rows[0]["name"].as_str()), (Some(sid.0), Some("chapter.docx")));
+ assert_eq!((rows[0]["status"].as_str(), rows[0]["edited"].as_bool()), (Some("ok"), Some(false)));
+ assert_eq!(rows[0]["uses"].as_array().unwrap().len(), 2, "both threaded frames");
+
+ // The file changes (with tracked changes): Modified; Update imports it as if accepted, with
+ // the saved style map, into the same frames, without new renamed styles.
+ std::fs::write(
+ &path,
+ docx(r#"<w:r><w:t xml:space="preserve">Second </w:t></w:r><w:ins w:id="1" w:author="A"><w:r><w:t>revised </w:t></w:r></w:ins><w:del w:id="2" w:author="A"><w:r><w:delText>old </w:delText></w:r></w:del><w:r><w:t>draft.</w:t></w:r>"#),
+ )
+ .unwrap();
+ assert_eq!(text_rows(&mut s)[0]["status"], "modified");
+ let r = s.execute("links.update", &json!({"story": sid.0})).unwrap();
+ assert_eq!(r["updated"], 1);
+ assert_eq!(r["warnings"], json!([]), "no edits in the layout to replace");
+ let updated = story(&s, sid);
+ assert_eq!(updated.text, "Head\nSecond revised draft.");
+ assert_eq!(styles(&updated), ["Headline", "Body_wrd_1"]);
+ assert_eq!(updated.frames, [ItemId(a), ItemId(b)], "frames and thread kept");
+ assert!(s.doc().unwrap().doc.styles.para("Body_wrd_2").is_none());
+ assert!(s.doc().unwrap().doc.styles.para("Title").is_none(), "mapped styles aren't imported");
+ assert_eq!(text_rows(&mut s)[0]["status"], "ok");
+
+ // An edit in the layout, then the file changes again: Update replaces the edit and warns.
+ s.execute("story.setText", &json!({"story": sid.0, "text": "Fixed in layout"})).unwrap();
+ assert_eq!(text_rows(&mut s)[0]["edited"], true);
+ std::fs::write(&path, docx("<w:r><w:t>Third draft.</w:t></w:r>")).unwrap();
+ let r = s.execute("links.update", &json!({})).unwrap();
+ assert_eq!(r["updated"], 1);
+ let w = r["warnings"][0].as_str().unwrap();
+ assert!(w.contains("chapter.docx") && w.contains("replaced"), "{w}");
+ assert_eq!(story(&s, sid).text, "Head\nThird draft.");
+ assert_eq!(text_rows(&mut s)[0]["edited"], false);
+ // Undo brings the edit back.
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(story(&s, sid).text, "Fixed in layout");
+ s.execute("edit.redo", &json!({})).unwrap();
+
+ // Saved and opened again: the link and its options are kept.
+ let back = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();
+ assert_eq!(back.story(sid).unwrap().file_link, story(&s, sid).file_link);
+ assert_eq!(super::text_status(back.story(sid).unwrap().file_link.as_ref().unwrap()), "ok");
+
+ // The file moves: Missing; Relink to it imports it into the story.
+ let moved = dir.join("moved").join("chapter.docx");
+ std::fs::write(&moved, docx("<w:r><w:t>Moved draft.</w:t></w:r>")).unwrap();
+ std::fs::remove_file(&path).unwrap();
+ assert_eq!(text_rows(&mut s)[0]["status"], "missing");
+ s.execute("links.relink", &json!({"story": sid.0, "path": moved.to_string_lossy()})).unwrap();
+ let rows = text_rows(&mut s);
+ assert_eq!((rows[0]["status"].as_str(), rows[0]["path"].as_str()), (Some("ok"), Some(moved.to_string_lossy().as_ref())));
+ assert_eq!(story(&s, sid).text, "Head\nMoved draft.");
+
+ // Go To selects the story's frames; Unlink keeps the text and drops the file.
+ let r = s.execute("links.goTo", &json!({"story": sid.0})).unwrap();
+ assert_eq!(r["ids"], json!([a, b]));
+ s.execute("links.embed", &json!({"story": sid.0})).unwrap();
+ assert!(text_rows(&mut s).is_empty());
+ assert_eq!(story(&s, sid).text, "Head\nMoved draft.");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn create_links_when_placing_text_files_preference() {
+ let dir = std::env::temp_dir().join(format!("dc-text-link-pref-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("notes.txt");
+ std::fs::write(&path, "Plain text").unwrap();
+ let place = |s: &mut Session, extra: Value| {
+ let mut p = json!({"path": path.to_string_lossy(), "rect": [72, 72, 300, 200]});
+ p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ let r = s.execute("file.place", &p).unwrap();
+ (s.doc().unwrap().doc.story(StoryId(r["story"].as_u64().unwrap())).unwrap().file_link.is_some(), r)
+ };
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ assert!(!place(&mut s, json!({})).0, "off by default");
+ assert!(place(&mut s, json!({"link": true})).0);
+ s.execute("prefs.set", &json!({"linkTextFiles": true})).unwrap();
+ assert!(place(&mut s, json!({})).0, "the preference links");
+ assert!(!place(&mut s, json!({"link": false})).0, "`link` overrides it");
+ // Placed from bytes: no file to link.
+ let b64 = crate::cmd::base64_encode(b"Plain text");
+ let r = s.execute("file.place", &json!({"base64": b64, "name": "notes.txt", "rect": [72, 300, 300, 400]})).unwrap();
+ assert!(s.doc().unwrap().doc.story(StoryId(r["story"].as_u64().unwrap())).unwrap().file_link.is_none());
+ // Into an insertion point: not linked, with a warning.
+ let fr = s.execute("frame.create", &json!({"rect": [72, 500, 300, 600], "content": "text", "text": "Start end"})).unwrap();
+ let sid = fr["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 6, "focus": 6})).unwrap();
+ let r = s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap();
+ assert!(r["warnings"][0].as_str().unwrap().contains("not linked"), "{r}");
+ assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().file_link.is_none());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
+
+#[cfg(test)]
+#[cfg(unix)]
+mod text_link_read_tests {
+ use std::time::Duration;
+
+ use designcraft_doc::TextFileLink;
+
+ use super::{MAX_TEXT_LINK_BYTES, read_text, text_status};
+
+ /// `f` on another thread: a call that blocks fails the test instead of hanging it.
+ fn promptly<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let _ = tx.send(f());
+ });
+ // A timeout means the call blocked.
+ rx.recv_timeout(Duration::from_secs(10)).unwrap()
+ }
+
+ fn status_of(path: &std::path::Path, size: u64) -> &'static str {
+ let l = TextFileLink { path: path.to_string_lossy().to_string(), size, hash: "0".into(), ..Default::default() };
+ promptly(move || text_status(&l))
+ }
+
+ fn read(path: &std::path::Path) -> Result<usize, String> {
+ let p = path.to_string_lossy().to_string();
+ promptly(move || read_text(&p).map(|b| b.len()).map_err(|e| e.to_string()))
+ }
+
+ #[test]
+ fn links_to_fifos_devices_folders_and_huge_files_are_not_read() {
+ let dir = std::env::temp_dir().join(format!("dc-text-link-read-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ // A FIFO with no writer: reading it would block for ever.
+ let fifo = dir.join("pipe.docx");
+ assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
+ assert_eq!(status_of(&fifo, 0), "missing");
+ assert!(read(&fifo).is_err());
+ // A device that never ends, recorded with size 0 (as its metadata reports).
+ let zero = std::path::Path::new("/dev/zero");
+ assert_eq!(status_of(zero, 0), "missing");
+ assert!(read(zero).is_err());
+ // A folder.
+ assert_eq!(status_of(&dir, 0), "missing");
+ assert!(read(&dir).is_err());
+ // Over the limit (sparse, so cheap): not read; the same size is reported as too large
+ // to check rather than OK, another size as modified.
+ let big = dir.join("big.txt");
+ std::fs::File::create(&big).unwrap().set_len(MAX_TEXT_LINK_BYTES + 1).unwrap();
+ assert_eq!(status_of(&big, MAX_TEXT_LINK_BYTES + 1), "tooLarge");
+ assert_eq!(status_of(&big, 10), "modified");
+ assert!(read(&big).unwrap_err().contains("larger than"));
+ assert!(!super::checkable_size(MAX_TEXT_LINK_BYTES as usize + 1), "placing it doesn't link it");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --cc crates/engine/src/cmd/object.rs
index 41b285300,1d796cb07..e5d259804
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@@ -6,8 -6,8 +6,8 @@@ use std::sync::Arc
use designcraft_color::BlendMode;
use designcraft_doc::{
- Content, Document, Effects, Fill, Item, ItemId, ItemLoc, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame,
- TextFrameOptions, TextSel,
- AssetId, Content, Document, Fill, Item, ItemId, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, TextFrameOptions,
- TextSel,
++ AssetId, Content, Document, Effects, Fill, Item, ItemId, ItemLoc, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke,
++ TextFrame, TextFrameOptions, TextSel,
};
use designcraft_geom::{Affine, Point, Rect, Vec2, shapes};
use serde_json::{Value, json};