DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #610 (linked text files read through crate::io, so the automation roots apply)
Brandon Thomas47e9e576d457
diff --cc ROADMAP.mdindex 7781c8edb,ebd979700..7b7af325e--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -135,14 -132,7 +135,15 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.+- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.+- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.+- **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.+- **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.+- **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.+- **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.+- **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.+ - **2026-10-12** · Linked text files (#597): placed Word, RTF and text files can stay linked; the Links panel shows them OK / Modified / Missing, and Update imports the file again into the same frames with the saved style map (the Links panel asks before replacing edits made in the layout). No readiness percentage change.- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.- **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.diff --cc crates/engine/src/cmd/datamerge/parse.rsindex e29ff5332,e9dcf4d9c..08c0ddc4b--- a/crates/engine/src/cmd/datamerge/parse.rs+++ b/crates/engine/src/cmd/datamerge/parse.rs@@@ -330,7 -330,11 +330,11 @@@ pub fn relative_between(from_dir: &Path}pub fn fingerprint_of(path: &Path) -> Option<Fingerprint> {- let meta = crate::io::metadata(path).ok()?;- Some(fingerprint_from(&std::fs::metadata(path).ok()?))++ Some(fingerprint_from(&crate::io::metadata(path).ok()?))+ }++ /// Size and modification time (whole seconds) from a file's metadata.+ pub fn fingerprint_from(meta: &std::fs::Metadata) -> Fingerprint {let mtime = meta.modified().ok()diff --cc crates/engine/src/cmd/file.rsindex 0b6893705,39e14c552..f63f0d6e9--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -103,7 -102,7 +103,7 @@@ pub fn specs() -> Vec<CommandSpec>"Place…",["File"],Some("Cmd+D"),- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link?: keep the file linked (Links panel; default: the linkTextFiles preference)}",++ "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link?: keep the file linked (Links panel; default: the linkTextFiles preference)}",has_doc,file_place),@@@ -294,8 -269,9 +296,9 @@@ fn file_place(s: &mut Session, p: &Valulet (bytes, name, link) = if let Some(b) = str_param(p, "base64") {(base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None)} else if let Some(path) = str_param(p, "path") {+ before = super::datamerge::fingerprint_from_path(path);#[cfg(not(target_arch = "wasm32"))]- let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let b = crate::io::read_file(path).map_err(EngineError::Other)?;#[cfg(target_arch = "wasm32")]let b: Vec<u8> = vec![];let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.into());diff --cc crates/engine/src/cmd/links.rsindex db8d55c38,45ce33956..1a47cf619--- a/crates/engine/src/cmd/links.rs+++ b/crates/engine/src/cmd/links.rs@@@ -111,7 -146,87 +146,87 @@@ pub fn status(a: &designcraft_doc::Asse}}- fn list(d: &Document) -> Vec<Value> {+ /// The largest linked text file read (the Data Merge source limit). Only regular files are read,+ /// so a link to a FIFO or a device (e.g. `/dev/zero`) can't block or fill memory.+ const MAX_TEXT_LINK_BYTES: u64 = super::datamerge::MAX_DATA_FILE_BYTES;++ /// Can a linked text file this size be checked and updated?+ pub(crate) fn checkable_size(len: usize) -> bool {+ len as u64 <= MAX_TEXT_LINK_BYTES+ }++ /// Can a size and time be trusted to change when the file does? Times are whole seconds, so not+ /// while the file was changed in the last two: another change in that second keeps the time. A+ /// time in the future (clock skew, a file copied from another machine) counts as settled, or such+ /// a file would be read on every poll; a later save gives it a time unlike the remembered one.+ pub(crate) fn settled(f: &Fingerprint) -> bool {+ #[cfg(not(target_arch = "wasm32"))]+ {+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX));+ f.mtime > now || now.saturating_sub(f.mtime) >= 2+ }+ #[cfg(target_arch = "wasm32")]+ {+ let _ = f;+ false+ }+ }++ /// Checked linked text files: path → (size and time, hash of the contents then).+ pub(crate) type TextChecks = std::collections::HashMap<String, (Fingerprint, String)>;++ /// Link status of a linked text file: `tooLarge` when it is the recorded size but over+ /// [`MAX_TEXT_LINK_BYTES`], so its contents aren't checked. The file is read only when its size+ /// is the recorded one but its time isn't, and then once per new time (`checks`): a file saved+ /// or synced again without changes stays OK.+ pub(crate) fn text_status(l: &TextFileLink, checks: &mut TextChecks) -> &'static str {+ #[cfg(not(target_arch = "wasm32"))]+ {- let now = match std::fs::metadata(&l.path) {++ let now = match crate::io::metadata(&l.path) {+ Err(_) => return "missing",+ Ok(m) if !m.is_file() => return "missing",+ Ok(m) => super::datamerge::fingerprint_from(&m),+ };+ if now.size != l.size {+ return "modified";+ }+ if l.mtime != 0 && now.mtime == l.mtime {+ return "ok";+ }+ let hash = match checks.get(&l.path) {+ Some((at, hash)) if *at == now => hash.clone(),+ _ if now.size > MAX_TEXT_LINK_BYTES => return "tooLarge",+ _ => match read_text(&l.path) {+ Ok((b, at)) => {+ let hash = fnv_hex(&b);+ // The time from before the read: a change during it is seen next time.+ if settled(&at) {+ checks.insert(l.path.clone(), (at, hash.clone()));+ }+ hash+ }+ Err(_) => return "missing",+ },+ };+ if hash == l.hash { "ok" } else { "modified" }+ }+ #[cfg(target_arch = "wasm32")]+ {+ let _ = (l, checks);+ "ok"+ }+ }++ fn file_name(path: &str) -> String {+ std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())+ }++ fn list(d: &Document, checks: &mut TextChecks) -> Vec<Value> {+ let texts = d.stories.values().filter_map(|st| {+ let l = st.file_link.as_ref()?;+ let uses: Vec<Value> = st.frames.iter().map(|id| json!({"id": id.0, "page": d.page_of_item(*id).map(|p| d.page_name(p))})).collect();+ Some(json!({"story": st.id.0, "name": file_name(&l.path), "path": l.path, "status": text_status(l, checks), "edited": story_hash(st) != l.story_hash, "uses": uses}))+ });let used = d.used_assets();d.assets.values()@@@ -143,9 -259,46 +259,46 @@@.collect()}+ /// A linked text file's bytes, with its size and time from before they were read.+ #[cfg(not(target_arch = "wasm32"))]+ fn read_text(path: &str) -> Result<(Vec<u8>, Fingerprint)> {- use std::io::Read;+ let err = |e: std::io::Error| EngineError::Other(format!("{path}: {e}"));- let m = std::fs::metadata(path).map_err(err)?;++ // The roots' own message when they refuse the path.++ crate::file_access::check_read(path).map_err(EngineError::Other)?;++ let m = crate::io::metadata(path).map_err(err)?;+ if !m.is_file() {+ return Err(EngineError::Other(format!("{path}: not a file")));+ }+ let too_large = || EngineError::Other(format!("{path}: larger than {} MiB", MAX_TEXT_LINK_BYTES / (1024 * 1024)));+ if m.len() > MAX_TEXT_LINK_BYTES {+ return Err(too_large());+ }+ // At most one byte over the limit, in case the file grew since.- let mut b = Vec::new();- std::fs::File::open(path).map_err(err)?.take(MAX_TEXT_LINK_BYTES + 1).read_to_end(&mut b).map_err(err)?;++ let b = crate::io::read_capped(path, MAX_TEXT_LINK_BYTES).map_err(err)?;+ if b.len() as u64 > MAX_TEXT_LINK_BYTES {+ return Err(too_large());+ }+ Ok((b, super::datamerge::fingerprint_from(&m)))+ }++ #[cfg(target_arch = "wasm32")]+ fn read_text(path: &str) -> Result<(Vec<u8>, Fingerprint)> {+ Err(EngineError::Other(format!("{path}: files can't be read on the web")))+ }++ /// Import a linked text file again; a warning says when edits made in the layout were replaced.+ fn reimport(d: &mut Document, sid: StoryId, path: &str, bytes: &[u8], before: Fingerprint) -> Result<Vec<String>> {+ let edited = d.story(sid).is_some_and(|st| st.file_link.as_ref().is_some_and(|l| story_hash(st) != l.story_hash));+ let mut warnings = super::place_text::reimport(d, sid, path, bytes, Some(before))?;+ if edited {+ warnings.insert(0, format!("{}: edits made to story {} in the layout were replaced by the file's text", file_name(path), sid.0));+ }+ Ok(warnings)+ }+#[cfg(not(target_arch = "wasm32"))]fn reload(path: &str) -> Result<(Vec<u8>, (u32, u32))> {- let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let b = crate::io::read_file(path).map_err(EngineError::Other)?;let px = designcraft_render::image_size(&b).ok_or_else(|| bad("links", format!("{path}: unsupported or corrupt image")))?;Ok((b, px))}@@@ -431,46 -606,297 +610,339 @@@ mod shared_asset_testsassert_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,+ }),+ );+ 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,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [1.0; 4],+ });+ 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(), &mut Default::default()), "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);+ }++ #[cfg(unix)]+ #[test]+ fn unchanged_linked_text_files_are_not_read_again() {+ use std::os::unix::fs::PermissionsExt;+ let dir = std::env::temp_dir().join(format!("dc-text-link-poll-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("note.txt");+ std::fs::write(&path, "Hello").unwrap();+ // Unreadable: a status that reads the file would say missing.+ let readable = |on: bool| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(if on { 0o644 } else { 0o000 })).unwrap();+ // A time `secs` ago (a file changed in the last two seconds is always read).+ let touch = |secs: u64| {+ let f = std::fs::File::options().write(true).open(&path).unwrap();+ f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap();+ };+ touch(60);+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap();+ let status = |s: &mut Session| text_rows(s)[0]["status"].as_str().unwrap().to_string();++ // Size and time as placed: not read.+ readable(false);+ if std::fs::read(&path).is_ok() {+ // Running as root: permissions don't stop reads, so this can't be observed.+ return;+ }+ assert_eq!(status(&mut s), "ok");+ // Saved again unchanged (a new time): read once, then not again.+ readable(true);+ touch(30);+ assert_eq!(status(&mut s), "ok");+ readable(false);+ assert_eq!(status(&mut s), "ok", "the second poll doesn't read it");+ // Changed, same size, new time: modified.+ readable(true);+ std::fs::write(&path, "Jello").unwrap();+ touch(20);+ assert_eq!(status(&mut s), "modified");+ // Changed again in the same second, same size: still seen (just-changed files are read).+ std::fs::write(&path, "Hello").unwrap();+ assert_eq!(status(&mut s), "ok");+ std::fs::write(&path, "Jello").unwrap();+ assert_eq!(status(&mut s), "modified");+ touch(10);+ // Updated: the new size and time are kept, so the next poll doesn't read it.+ s.execute("links.update", &json!({})).unwrap();+ readable(false);+ assert_eq!(status(&mut s), "ok");+ // A time in the future (clock skew): read once, then not on every poll.+ readable(true);+ let f = std::fs::File::options().write(true).open(&path).unwrap();+ f.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(3600)).unwrap();+ assert_eq!(status(&mut s), "ok");+ readable(false);+ assert_eq!(status(&mut s), "ok", "a future time is remembered");+ readable(true);+ 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, &mut Default::default()))+ }++ 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/ui-egui/src/panels/properties.rsindex 599dd4956,97bcf5b99..d582986d5--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@@ -2024,27 -1957,10 +2024,28 @@@ pub fn links_panel(app: &mut DesignAppcrate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Page · PPI")).color(t.text_dim).size(11.0));ui.end_row();for r in &rows {- let aid = r["asset"].as_u64().unwrap_or(0);+ // Asset and story ids come from one counter: a row is chosen by either.+ let aid = r["asset"].as_u64().or_else(|| r["story"].as_u64()).unwrap_or(0);let name = r["name"].as_str().unwrap_or("");- if ui.selectable_label(chosen == Some(aid), name).clicked() {+ let response = ui+ .vertical(|ui| {+ ui.set_width(name_width);+ let name = ui.add(egui::Button::selectable(chosen == Some(aid), name).truncate());+ match r["path"].as_str().filter(|path| !path.is_empty()) {+ Some(path) => name.union(+ ui.add(+ egui::Label::new(egui::RichText::new(path).color(t.text_dim).size(11.0))+ .truncate()+ .sense(Sense::click())+ .show_tooltip_when_elided(false),+ )+ .on_hover_text(path),+ ),+ None => name,+ }+ })+ .inner;+ if response.clicked() {chosen = Some(aid);}let (txt, col) = match r["status"].as_str().unwrap_or("") {