DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Links: only read a linked text file when its size or time changed
Jeffrey Thayned1fddc0ae8fb
diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rsindex 1b57f63cd..b89e1db4e 100644--- a/crates/doc/src/story.rs+++ b/crates/doc/src/story.rs@@ -169,6 +169,10 @@ pub struct TextFileLink {/// The file's size and FNV-1a hash (hex) when it was placed or last updated.pub size: u64,pub hash: String,+ /// Its modification time then (seconds since 1970; 0: unknown), as Data Merge keeps for its+ /// source: while size and time are unchanged, the Links panel doesn't read the file.+ #[serde(default, skip_serializing_if = "is_zero_i64")]+ pub mtime: i64,/// Imported style name → document style (`styleMap`), including the names Auto Rename chose.#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]pub style_map: BTreeMap<String, String>,@@ -183,6 +187,10 @@ pub struct TextFileLink {pub story_hash: String,}+fn is_zero_i64(v: &i64) -> bool {+ *v == 0+}+impl Story {pub fn new(id: StoryId) -> Self {Story {diff --git a/crates/engine/src/cmd/datamerge/mod.rs b/crates/engine/src/cmd/datamerge/mod.rsindex 547a80329..51c76d1f0 100644--- a/crates/engine/src/cmd/datamerge/mod.rs+++ b/crates/engine/src/cmd/datamerge/mod.rs@@ -24,6 +24,12 @@ use parse::{tile,};+pub(crate) use parse::fingerprint_from;++pub(crate) fn fingerprint_from_path(path: &str) -> Option<designcraft_doc::Fingerprint> {+ fingerprint_of(Path::new(path))+}+const PARENT_WARNING: &str = "A parent-page placeholder was left unfilled.";pub fn specs() -> Vec<CommandSpec> {diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rsindex 6ab10f3d9..e9dcf4d9c 100644--- a/crates/engine/src/cmd/datamerge/parse.rs+++ b/crates/engine/src/cmd/datamerge/parse.rs@@ -330,14 +330,18 @@ pub fn relative_between(from_dir: &Path, target: &Path) -> String {}pub fn fingerprint_of(path: &Path) -> Option<Fingerprint> {- let meta = std::fs::metadata(path).ok()?;+ Some(fingerprint_from(&std::fs::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().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)).unwrap_or(0);- Some(Fingerprint { size: meta.len(), mtime })+ Fingerprint { size: meta.len(), mtime }}pub fn status_of(path: &Path, previous: Option<Fingerprint>) -> SourceStatus {diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rsindex d655b2065..5dc7c9429 100644--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@ -479,9 +479,12 @@ fn file_save(s: &mut Session, p: &Value) -> Result<Value> {}fn file_place(s: &mut Session, p: &Value) -> Result<Value> {+ // The file's size and time before it is read (a linked text file remembers them).+ let mut before = None;let (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}")))?;#[cfg(target_arch = "wasm32")]@@ -510,7 +513,7 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {}// Text files (plain, Word, RTF) flow into frames.if designcraft_textimport::is_text_file(&name) {- return super::place_text::place_text(s, p, &name, &bytes, link);+ return super::place_text::place_text(s, p, &name, &bytes, link, before);}let want_w = p.get("width")diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rsindex 09e004659..c92802397 100644--- a/crates/engine/src/cmd/links.rs+++ b/crates/engine/src/cmd/links.rs@@ -10,7 +10,7 @@use std::sync::Arc;-use designcraft_doc::{AssetId, Content, Document, ItemId, Selection, Story, StoryId, TextFileLink};+use designcraft_doc::{AssetId, Content, Document, Fingerprint, ItemId, Selection, Story, StoryId, TextFileLink};use serde_json::{Value, json};use super::{CommandSpec, bad, cmd, has_doc, str_param};@@ -19,7 +19,11 @@ use crate::{EngineError, Result, Session};pub fn specs() -> Vec<CommandSpec> {vec![cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| {- Ok(Value::Array(list(&s.doc()?.doc)))+ // Taken out for the call so the document needn't be cloned on every poll.+ let mut checks = std::mem::take(&mut s.text_link_checks);+ let links = s.doc().map(|d| list(&d.doc, &mut checks));+ s.text_link_checks = checks;+ Ok(Value::Array(links?))}),cmd!("links.relink",@@ -154,26 +158,45 @@ pub(crate) fn checkable_size(len: usize) -> bool {len as u64 <= MAX_TEXT_LINK_BYTES}+/// 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.-pub fn text_status(l: &TextFileLink) -> &'static str {+/// [`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"))]{- match std::fs::metadata(&l.path) {- Err(_) => "missing",- Ok(m) if !m.is_file() => "missing",- Ok(m) if m.len() != l.size => "modified",- Ok(m) if m.len() > MAX_TEXT_LINK_BYTES => "tooLarge",- Ok(_) => match read_text(&l.path) {- Ok(b) if fnv_hex(&b) == l.hash => "ok",- Ok(_) => "modified",- Err(_) => "missing",- },+ let now = match std::fs::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.+ 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;+ let _ = (l, checks);"ok"}}@@ -182,11 +205,11 @@ 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) -> Vec<Value> {+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), "edited": story_hash(st) != l.story_hash, "uses": uses}))+ 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@@ -221,8 +244,9 @@ fn list(d: &Document) -> Vec<Value> {.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>> {+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)?;@@ -239,18 +263,18 @@ fn read_text(path: &str) -> Result<Vec<u8>> {if b.len() as u64 > MAX_TEXT_LINK_BYTES {return Err(too_large());}- Ok(b)+ Ok((b, super::datamerge::fingerprint_from(&m)))}#[cfg(target_arch = "wasm32")]-fn read_text(path: &str) -> Result<Vec<u8>> {+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]) -> Result<Vec<String>> {+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)?;+ 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));}@@ -272,10 +296,10 @@ fn reload(path: &str) -> Result<(Vec<u8>, (u32, u32))> {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 = read_text(&path)?;+ let (bytes, before) = read_text(&path)?;let name = file_name(&path);return s.edit(|d, _| {- let warnings = reimport(d, sid, &path, &bytes)?;+ let warnings = reimport(d, sid, &path, &bytes, before)?;Ok(json!({"name": name, "warnings": warnings}))});}@@ -333,7 +357,8 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {}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@@ -347,7 +372,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {.stories.values().filter(|st| all || only_story == Some(st.id))- .filter_map(|st| st.file_link.as_ref().filter(|l| text_status(l) == "modified").map(|l| (st.id, l.path.clone())))+ .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 (aid, path) in which {@@ -355,8 +380,8 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {}let mut fresh_texts = Vec::new();for (sid, path) in texts {- let bytes = read_text(&path)?;- fresh_texts.push((sid, path, bytes));+ let (bytes, before) = read_text(&path)?;+ fresh_texts.push((sid, path, bytes, before));}let n = fresh.len() + fresh_texts.len();if n == 0 {@@ -372,8 +397,8 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {}}let mut warnings = Vec::new();- for (sid, path, bytes) in &fresh_texts {- warnings.extend(reimport(d, *sid, path, bytes)?);+ for (sid, path, bytes, before) in &fresh_texts {+ warnings.extend(reimport(d, *sid, path, bytes, *before)?);}Ok(json!({"updated": n, "warnings": warnings}))})@@ -768,7 +793,7 @@ mod text_link_tests {// 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");+ 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");@@ -789,6 +814,52 @@ mod text_link_tests {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();+ 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();+ };+ 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(10);+ 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");+ // 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");+ 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()));@@ -846,12 +917,12 @@ mod text_link_read_tests {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))+ 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()))+ promptly(move || read_text(&p).map(|(b, _)| b.len()).map_err(|e| e.to_string()))}#[test]diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rsindex ee1ad9156..546f58954 100644--- a/crates/engine/src/cmd/place_text.rs+++ b/crates/engine/src/cmd/place_text.rs@@ -144,9 +144,12 @@ fn fill(story: &mut Story, from: &Story) {}/// The link a story placed from `path` keeps (Create Links When Placing Text Files).+/// `before`: the file's size and time before `bytes` were read (its time is kept only when the+/// size matches what was read).fn text_link(path: &str,bytes: &[u8],+ before: Option<designcraft_doc::Fingerprint>,map: std::collections::HashMap<String, String>,conflict: Conflict,remove: bool,@@ -156,6 +159,7 @@ fn text_link(path: path.to_string(),size: bytes.len() as u64,hash: super::links::fnv_hex(bytes),+ mtime: before.filter(|f| f.size == bytes.len() as u64).map_or(0, |f| f.mtime),style_map: map.into_iter().collect(),style_conflicts: conflict.name().into(),remove_styles: remove,@@ -165,7 +169,13 @@ fn text_link(/// Update Link of a linked text file: `bytes` (read from `path`) imported again into the story/// with the import options it was placed with, keeping its frames. Returns the import's warnings.-pub(crate) fn reimport(d: &mut Document, sid: StoryId, path: &str, bytes: &[u8]) -> Result<Vec<String>> {+pub(crate) fn reimport(+ d: &mut Document,+ sid: StoryId,+ path: &str,+ bytes: &[u8],+ before: Option<designcraft_doc::Fingerprint>,+) -> Result<Vec<String>> {let link =d.story(sid).and_then(|s| s.file_link.clone()).ok_or_else(|| bad("links.update", format!("story {} isn't linked to a file", sid.0)))?;let name = std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string());@@ -183,7 +193,7 @@ pub(crate) fn reimport(d: &mut Document, sid: StoryId, path: &str, bytes: &[u8])add_styles(d, &imp, conflict);let story = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?;fill(story, &imp.story);- story.file_link = Some(text_link(path, bytes, map, conflict, link.remove_styles, story));+ story.file_link = Some(text_link(path, bytes, before, map, conflict, link.remove_styles, story));Ok(imp.warnings)}@@ -308,7 +318,14 @@ fn add_flow_frame(Ok(fid)}-pub(super) fn place_text(s: &mut Session, p: &Value, name: &str, bytes: &[u8], path: Option<String>) -> Result<Value> {+pub(super) fn place_text(+ s: &mut Session,+ p: &Value,+ name: &str,+ bytes: &[u8],+ path: Option<String>,+ before: Option<designcraft_doc::Fingerprint>,+) -> Result<Value> {let mut imp = designcraft_textimport::import(name, bytes).map_err(|e| bad("file.place", e.to_string()))?;let remove = p.get("removeStyles").and_then(Value::as_bool).unwrap_or(false);if remove {@@ -386,7 +403,7 @@ pub(super) fn place_text(s: &mut Session, p: &Value, name: &str, bytes: &[u8], p};let story = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?;fill(story, &imp.story);- story.file_link = link.as_deref().map(|path| text_link(path, bytes, map.clone(), conflict, remove, story));+ story.file_link = link.as_deref().map(|path| text_link(path, bytes, before, map.clone(), conflict, remove, story));*sel = designcraft_doc::Selection::items(vec![fid]);sid};diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 1dbbb4291..1a09daa81 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -330,6 +330,9 @@ pub struct Session {/// New Document's Preview: the preview document's uid and the uid of the document that was/// active before it (see [`Session::preview_new_document`]).pub(crate) new_document_preview: Option<(u64, Option<u64>)>,+ /// Linked text files checked by the Links panel: path → the size and modification time the+ /// file had and the hash of its contents then, so a file touched but not changed is read once.+ pub(crate) text_link_checks: std::collections::HashMap<String, (designcraft_doc::Fingerprint, String)>,}impl Default for Session {@@ -358,6 +361,7 @@ impl Session {clipboard_origin: 0.0,recovery_dir: None,text_clipboard: None,+ text_link_checks: Default::default(),ui_requests: vec![],loaded: None,transforms: Default::default(),