DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge branch 'main' into fix/21-indd-message
aionggb757687a41cb
diff --cc apps/designcraft/src/main.rsindex 7ef81106b,101a5f5f5..7a6115046--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@@ -89,6 -89,70 +89,71 @@@ fn save_prefs(app: &DesignApp)}}+ /// One file-type row in an open dialog. `open_filters` is what `pick_open` applies.+ struct OpenFilter {+ name: &'static str,+ extensions: &'static [&'static str],+ }++ fn open_filters(purpose: &str) -> &'static [OpenFilter] {+ match purpose {+ "swatches" => &[OpenFilter { name: "Swatch Exchange (ASE)", extensions: &["ase"] }],+ "script" => &[OpenFilter { name: "Script", extensions: &["dcscript", "txt", "json"] }],+ "icc" => &[OpenFilter { name: "ICC profile", extensions: &["icc", "icm"] }],+ "book" => &[OpenFilter { name: "Book", extensions: &["dcbook"] }],+ "xml" => &[OpenFilter { name: "XML", extensions: &["xml"] }],+ "library" => &[OpenFilter { name: "Object Library", extensions: &["dclib"] }],+ "dataMerge" => &[OpenFilter { name: "Data source (CSV, TSV, text, Excel)", extensions: &["csv", "tsv", "tab", "txt", "xlsx"] }],+ "place" => &[+ OpenFilter {+ name: "Graphics and text",+ extensions: &[+ "png",+ "jpg",+ "jpeg",+ "gif",+ "webp",+ "tif",+ "tiff",+ "bmp",+ "psd",+ "svg",+ "pdf",+ "ai",+ "eps",+ "txt",+ "docx",+ "rtf",+ "md",+ "xlsx",+ "idml",+ "designcraft",+ "mp4",+ "m4v",+ "mov",+ "webm",+ "mp3",+ "m4a",+ "wav",+ "ogg",+ ],+ },+ OpenFilter {+ name: "Graphics",+ extensions: &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai", "eps"],+ },+ OpenFilter { name: "Text (Word, RTF, plain, Excel)", extensions: &["docx", "rtf", "txt", "md", "xlsx"] },+ OpenFilter { name: "Video and sound", extensions: &["mp4", "m4v", "mov", "webm", "mp3", "m4a", "wav", "ogg"] },+ ],+ _ => &[- OpenFilter { name: "DesignCraft or IDML", extensions: &["designcraft", "idml"] },++ OpenFilter { name: "DesignCraft, IDML or InDesign", extensions: &["designcraft", "idml", "indd", "indt"] },+ OpenFilter { name: "DesignCraft", extensions: &["designcraft"] },+ OpenFilter { name: "InDesign Markup (IDML)", extensions: &["idml"] },++ OpenFilter { name: "InDesign Document or Template (INDD, INDT)", extensions: &["indd", "indt"] },+ ],+ }+ }+fn services() -> Services {Services {pick_open: Some(Box::new(|purpose: &str| {diff --cc crates/engine/src/cmd/file.rsindex a6859b0c2,e40000095..bfbdd20a7--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -674,37 -698,206 +715,241 @@@ mod layout_place_tests}}+#[cfg(test)]+mod indd_tests {+ use serde_json::json;++ use crate::Session;++ /// The start of an InDesign document: its signature, then the `DOCUMENT` class name.+ fn indd() -> Vec<u8> {+ let mut b = super::INDD_SIGNATURE.to_vec();+ b.extend_from_slice(b"DOCUMENT");+ b.resize(4096, 0);+ b+ }++ #[test]+ fn indd_files_say_to_export_idml() {+ let b64 = super::base64_encode(&indd());+ let mut s = Session::new();+ let open = s.execute("file.openBytes", &json!({"base64": b64, "name": "Brochure"})).unwrap_err().to_string();+ assert!(open.contains("InDesign document") && open.contains("IDML"), "{open}");+ s.execute("file.new", &json!({})).unwrap();+ let place = s.execute("file.place", &json!({"base64": b64, "name": "Brochure.indd"})).unwrap_err().to_string();+ assert!(place.contains("InDesign document") && place.contains("IDML"), "{place}");+ #[cfg(not(target_arch = "wasm32"))]+ {+ let path = std::env::temp_dir().join(format!("designcraft-indd-{}.indd", std::process::id()));+ std::fs::write(&path, indd()).unwrap();+ let open = s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();+ let _ = std::fs::remove_file(&path);+ assert!(open.contains("InDesign document"), "{open}");+ }+ assert_eq!(s.documents().len(), 1, "nothing was opened");+ }+}+++ #[cfg(test)]+ mod document_fonts_tests {+ use std::path::{Path, PathBuf};++ use designcraft_fonts::testing::font_with;+ use designcraft_fonts::{DOCUMENT_FONTS_FOLDER, FaceRef, FontDb, FontSource};+ use serde_json::{Value, json};++ use crate::Session;++ fn temp_dir(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("dc-open-docfonts-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join(DOCUMENT_FONTS_FOLDER)).unwrap();+ dir+ }++ /// A new document in `s` with a text frame holding `text` set in `family`.+ fn new_document(s: &mut Session, family: &str, text: &str) {+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": text})).unwrap();+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": text.len()})).unwrap();+ s.execute("type.char", &json!({"fontFamily": family, "fontStyle": "Regular"})).unwrap();+ }++ /// A document whose text ("Hello") is set in `family`, written to `path` (`.idml`: as IDML).+ fn write_document(path: &Path, family: &str) {+ write_document_with(path, family, "Hello");+ }++ fn write_document_with(path: &Path, family: &str, text: &str) {+ let mut s = Session::new();+ new_document(&mut s, family, text);+ if path.extension().is_some_and(|e| e == "idml") {+ std::fs::write(path, designcraft_idml::export_idml(&s.doc().unwrap().doc)).unwrap();+ } else {+ s.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap();+ }+ }++ fn font_entry(s: &mut Session, family: &str) -> Value {+ let l = s.execute("font.list", &json!({})).unwrap();+ l.as_array().unwrap().iter().find(|f| f["family"] == family).cloned().unwrap_or_else(|| panic!("{family} in {l}"))+ }++ /// Each character of the active document's text with the face it is drawn in.+ fn glyph_faces(s: &Session) -> Vec<(char, FaceRef)> {+ let st = s.doc().unwrap();+ let mut out = Vec::new();+ for (sid, story) in &st.doc.stories {+ let cs = s.cache.get(&st.doc, *sid, None);+ for g in cs.frames.iter().flat_map(|ft| &ft.lines).flat_map(|l| &l.glyphs).filter(|g| g.visible && g.len > 0) {+ out.push((story.text[g.byte..].chars().next().unwrap(), g.face));+ }+ }+ out+ }++ fn open(s: &mut Session, path: &Path) -> Value {+ s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap()+ }++ #[test]+ fn opening_a_document_loads_its_document_fonts() {+ const FAMILY: &str = "DocFont Open Test";+ let dir = temp_dir("designcraft");+ let fonts = dir.join(DOCUMENT_FONTS_FOLDER);+ std::fs::write(fonts.join("open.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap();+ std::fs::write(fonts.join("broken.otf"), b"not a font").unwrap();+ let path = dir.join("Brochure.designcraft");+ write_document(&path, FAMILY);+ assert!(!FontDb::global().has_family(FAMILY));++ let mut s = Session::new();+ let r = s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap();+ assert_eq!(r["documentFonts"], 1, "{r}");+ assert!(r["warnings"].to_string().contains("broken.otf"), "a damaged font is reported, not fatal: {r}");+ let f = font_entry(&mut s, FAMILY);+ assert_eq!((f["missing"].clone(), f["source"].clone()), (json!(false), json!("document")), "{f}");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn opening_an_idml_file_loads_its_document_fonts() {+ const FAMILY: &str = "DocFont IDML Test";+ let dir = temp_dir("idml");+ std::fs::write(dir.join(DOCUMENT_FONTS_FOLDER).join("idml.ttf"), font_with(FAMILY, &['H']).unwrap()).unwrap();+ let path = dir.join("Brochure.idml");+ write_document(&path, FAMILY);++ let mut s = Session::new();+ let r = s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap();+ assert_eq!(r["documentFonts"], 1, "{r}");+ assert_eq!(font_entry(&mut s, FAMILY)["missing"], false);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_document_without_the_folder_opens_as_before() {+ let dir = std::env::temp_dir().join(format!("dc-open-docfonts-none-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("Plain.designcraft");+ write_document(&path, designcraft_fonts::DEFAULT_FAMILY);+ let r = Session::new().execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap();+ assert_eq!((r["documentFonts"].clone(), r["warnings"].clone()), (json!(0), json!([])), "{r}");+ let _ = std::fs::remove_dir_all(&dir);+ }+ #[test]+ fn document_fonts_belong_to_their_document() {+ const FAMILY: &str = "DocFont Scoped";+ let (a, b) = (temp_dir("scoped-a"), temp_dir("scoped-b"));+ std::fs::write(a.join(DOCUMENT_FONTS_FOLDER).join("scoped.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap();+ write_document(&a.join("A.designcraft"), FAMILY);+ write_document(&b.join("B.designcraft"), FAMILY);++ let mut s = Session::new();+ assert_eq!(open(&mut s, &a.join("A.designcraft"))["documentFonts"], 1);+ assert_eq!(open(&mut s, &b.join("B.designcraft"))["documentFonts"], 0);+ // B, open at the same time, doesn't have A's font.+ assert_eq!(font_entry(&mut s, FAMILY)["missing"], true);+ assert!(glyph_faces(&s).iter().all(|(_, f)| f.family != FAMILY), "{:?}", glyph_faces(&s));+ s.execute("file.activate", &json!({"index": 0})).unwrap();+ assert_eq!(font_entry(&mut s, FAMILY)["source"], "document");+ assert!(glyph_faces(&s).iter().all(|(_, f)| f.family == FAMILY), "{:?}", glyph_faces(&s));+ let _ = std::fs::remove_dir_all(&a);+ let _ = std::fs::remove_dir_all(&b);+ }++ #[test]+ fn each_document_sets_its_own_font_of_a_name() {+ const FAMILY: &str = "DocFont Same";+ let (a, b) = (temp_dir("same-a"), temp_dir("same-b"));+ let (a_font, b_font) = (a.join(DOCUMENT_FONTS_FOLDER).join("same.ttf"), b.join(DOCUMENT_FONTS_FOLDER).join("same.ttf"));+ // A's font has both letters, B's only `b`.+ std::fs::write(&a_font, font_with(FAMILY, &['a', 'b']).unwrap()).unwrap();+ std::fs::write(&b_font, font_with(FAMILY, &['b']).unwrap()).unwrap();+ // The same words in both: the word cache must not hand one document's shaping to the other.+ write_document_with(&a.join("A.designcraft"), FAMILY, "ab ab ab");+ write_document_with(&b.join("B.designcraft"), FAMILY, "ab ab ab");++ let mut s = Session::new();+ open(&mut s, &a.join("A.designcraft"));+ open(&mut s, &b.join("B.designcraft"));+ // Fallback fonts for the `a` B's font lacks: never A's font.+ s.execute("document.preferences", &json!({"glyphFallback": true})).unwrap();+ let in_b = glyph_faces(&s);+ s.execute("file.activate", &json!({"index": 0})).unwrap();+ let in_a = glyph_faces(&s);+ assert_eq!((in_a.len(), in_b.len()), (8, 8), "{in_a:?} {in_b:?}");+ for (c, f) in &in_a {+ assert_eq!(f.source, FontSource::Document(a_font.clone()), "`{c}` in A");+ }+ for (c, f) in &in_b {+ match c {+ 'a' => assert!(f.family != FAMILY, "B's font lacks `a`, and A's isn't B's: {f:?}"),+ _ => assert_eq!(f.source, FontSource::Document(b_font.clone()), "`{c}` in B"),+ }+ }+ let _ = std::fs::remove_dir_all(&a);+ let _ = std::fs::remove_dir_all(&b);+ }++ #[test]+ fn closing_a_document_forgets_its_fonts_and_reopening_reuses_them() {+ const FAMILY: &str = "DocFont Closed";+ let dir = temp_dir("closed");+ std::fs::write(dir.join(DOCUMENT_FONTS_FOLDER).join("closed.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap();+ let path = dir.join("Closed.designcraft");+ write_document(&path, FAMILY);++ let mut s = Session::new();+ open(&mut s, &path);+ let first = glyph_faces(&s)[0].1;+ assert_eq!(first.family, FAMILY);+ s.execute("file.close", &json!({})).unwrap();+ // A new document can't use the closed document's font.+ new_document(&mut s, FAMILY, "Hello");+ assert_eq!(font_entry(&mut s, FAMILY)["missing"], true);+ assert!(glyph_faces(&s).iter().all(|(_, f)| f.family != FAMILY));+ // Reopened, the document has its font again: the face loaded the first time.+ assert_eq!(open(&mut s, &path)["documentFonts"], 1);+ assert!(glyph_faces(&s).iter().all(|(_, f)| *f == first), "{:?}", glyph_faces(&s));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_reverted_document_keeps_its_fonts() {+ const FAMILY: &str = "DocFont Reverted";+ let dir = temp_dir("revert");+ std::fs::write(dir.join(DOCUMENT_FONTS_FOLDER).join("revert.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap();+ let path = dir.join("Revert.designcraft");+ write_document(&path, FAMILY);++ let mut s = Session::new();+ open(&mut s, &path);+ s.execute("frame.create", &json!({"rect": [72, 400, 200, 500], "content": "text", "text": "x"})).unwrap();+ s.execute("file.revert", &json!({})).unwrap();+ assert_eq!(font_entry(&mut s, FAMILY)["source"], "document");+ assert!(glyph_faces(&s).iter().all(|(_, f)| f.family == FAMILY));+ let _ = std::fs::remove_dir_all(&dir);+ }+ }