Skip to content

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 Thayne7b33c981dca5
diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs
index 22562340d..0fbb10ced 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.rs
index 3b3e1dd3b..015bca346 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.rs
index 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.rs
index 8cfa4327f..e4d61d3f6 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -264,9 +264,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")]
@@ -295,7 +298,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);
}
// Image Import Options: which page of a PDF (1-based).
let pdf_page = match p.get("pdfPage").and_then(Value::as_u64) {
diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs
index e1c482a07..1195d1f3f 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,8 @@ 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, 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)))
+ let d = s.doc()?.doc.clone();
+ Ok(Value::Array(list(&d, &mut s.text_link_checks)))
}),
cmd!(
"links.relink",
@@ -154,26 +155,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 +202,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
@@ -220,8 +240,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)?;
@@ -238,18 +259,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));
}
@@ -271,10 +292,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}))
});
}
@@ -330,7 +351,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
@@ -344,7 +366,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 {
@@ -352,8 +374,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 {
@@ -368,8 +390,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}))
})
@@ -684,7 +706,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");
@@ -705,6 +727,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()));
@@ -762,12 +830,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.rs
index 4d4577a5f..1acff61c4 100644
--- a/crates/engine/src/cmd/place_text.rs
+++ b/crates/engine/src/cmd/place_text.rs
@@ -142,9 +142,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,
@@ -154,6 +157,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,
@@ -163,7 +167,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());
@@ -181,7 +191,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)
}
@@ -234,7 +244,14 @@ pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize) -> Resu
}
}
-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 {
@@ -310,7 +327,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.rs
index 82b4a59af..3b6471abe 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -286,6 +286,9 @@ pub struct Session {
pub book: Option<cmd::book::Book>,
/// Content Collector conveyor: collected objects as snippets (name, bytes).
pub conveyor: Vec<(String, Vec<u8>)>,
+ /// 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 {
@@ -307,6 +310,7 @@ impl Session {
clipboard: None,
recovery_dir: None,
text_clipboard: None,
+ text_link_checks: Default::default(),
ui_requests: vec![],
loaded: None,
transforms: Default::default(),