Skip to content

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

Engine: route book chapters and atomic saves through the checked writers, and take file access out of fonts, IDML and ICC loading

Isaac Levined66f2c47ae1f
diff --git a/crates/color/src/cms/mod.rs b/crates/color/src/cms/mod.rs
index 2294d764e..ac7c45874 100644
--- a/crates/color/src/cms/mod.rs
+++ b/crates/color/src/cms/mod.rs
@@ -230,13 +230,6 @@ pub fn register_icc(bytes: &[u8], name: Option<String>) -> Result<ProfileInfo, C
Ok(info)
}
-/// Load a `.icc`/`.icm` file from disk (native only).
-#[cfg(not(target_arch = "wasm32"))]
-pub fn load_icc_file(path: &std::path::Path) -> Result<ProfileInfo, CmsError> {
- let bytes = std::fs::read(path).map_err(|e| CmsError::Io(format!("{}: {e}", path.display())))?;
- register_icc(&bytes, None)
-}
-
/// A colour-management context: resolved working spaces plus conversion settings.
#[derive(Clone)]
pub struct Cms {
diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs
index 4e4f1d8b7..be6676d7b 100644
--- a/crates/color/src/cms/tests.rs
+++ b/crates/color/src/cms/tests.rs
@@ -188,10 +188,8 @@ fn bad_icc_rejected() {
#[test]
fn loads_system_cmyk_icc() {
let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc");
- if !path.exists() {
- return;
- }
- let info = load_icc_file(path).unwrap();
+ let Ok(bytes) = std::fs::read(path) else { return };
+ let info = register_icc(&bytes, None).unwrap();
assert_eq!(info.kind, ProfileKind::Cmyk);
assert!(profiles().iter().any(|p| p.name == info.name && !p.builtin));
let c = Cms::new(&ColorSettings { cmyk: info.name.clone(), ..Default::default() }).unwrap();
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index f5d0113c1..c275fef91 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1889,7 +1889,7 @@ fn each_document_shapes_words_in_its_own_fonts() {
let folder = root.join(name);
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(folder.join("word.ttf"), font_with_glyph(FAMILY, &['a', 'b', ' '], glyph).unwrap()).unwrap();
- scopes.push((designcraft_fonts::FontDb::global().load_document_fonts(&folder).scope, glyph));
+ scopes.push((designcraft_fonts::FontDb::global().load_document_fonts(&folder, &|_| Ok(())).scope, glyph));
}
let text = "ab ab ab ab";
let mut faces = Vec::new();
@@ -1919,7 +1919,7 @@ fn composite_fonts_draw_from_the_documents_fonts() {
let folder = std::env::temp_dir().join(format!("dc-compose-composite-docfont-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(folder.join("digits.ttf"), font_with_glyph(FAMILY, &['1'], 'X').unwrap()).unwrap();
- let scope = FontDb::global().load_document_fonts(&folder).scope;
+ let scope = FontDb::global().load_document_fonts(&folder, &|_| Ok(())).scope;
let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
d.font_scope = scope;
std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {
diff --git a/crates/engine/src/atomic.rs b/crates/engine/src/atomic.rs
index 7eed2f028..96eb2f1f5 100644
--- a/crates/engine/src/atomic.rs
+++ b/crates/engine/src/atomic.rs
@@ -36,11 +36,6 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
write_atomic_with(path, |f| f.write_all(bytes))
}
-/// [`write_atomic`] for a command's `path` parameter: the error names the path.
-pub(crate) fn write_file(path: &str, bytes: &[u8]) -> crate::Result<()> {
- write_atomic(Path::new(path), bytes).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))
-}
-
/// Atomically replace (or create) `path` with what `fill` writes into the temporary file. When
/// `fill`, the flush or the rename fails, the temporary file is removed, `path` is untouched and
/// the error is returned.
diff --git a/crates/engine/src/cmd/book.rs b/crates/engine/src/cmd/book.rs
index 58edc6aa4..e278440e3 100644
--- a/crates/engine/src/cmd/book.rs
+++ b/crates/engine/src/cmd/book.rs
@@ -90,7 +90,7 @@ impl ChapterBatch {
}
fn commit(self) -> Result<()> {
- self.commit_with(write_staged_chapter)
+ self.commit_with(|path, staged| crate::io::replace_with(path, staged))
}
fn commit_with(self, mut write: impl FnMut(&std::path::Path, &std::path::Path) -> std::io::Result<()>) -> Result<()> {
@@ -110,12 +110,6 @@ impl ChapterBatch {
}
}
-#[cfg(not(target_arch = "wasm32"))]
-fn write_staged_chapter(path: &std::path::Path, staged: &std::path::Path) -> std::io::Result<()> {
- let mut input = std::fs::File::open(staged)?;
- crate::atomic::write_atomic_with(path, |file| std::io::copy(&mut input, file).map(|_| ()))
-}
-
/// Batch commands only write closed native chapters. IDML is an imported source, and an open
/// chapter's model (including unsaved edits) cannot be reconciled by a disk-only book update.
#[cfg(not(target_arch = "wasm32"))]
@@ -125,16 +119,16 @@ fn writable_chapter(s: &Session, path: &str, command: &'static str) -> Result<()
if Path::new(path).extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("idml")) {
return Err(bad(command, format!("cannot change imported IDML chapter {path}; convert it to a native DesignCraft document first")));
}
- let target = std::fs::canonicalize(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
- if s.docs.iter().any(|doc| doc.path.as_ref().is_some_and(|open| std::fs::canonicalize(open).is_ok_and(|open| open == target))) {
+ let target = crate::io::canonicalize(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ if s.docs.iter().any(|doc| doc.path.as_ref().is_some_and(|open| crate::io::canonicalize(open).is_ok_and(|open| open == target))) {
return Err(bad(command, format!("chapter {path} is open; close it before updating the book")));
}
- if !std::fs::metadata(&target).is_ok_and(|metadata| metadata.is_file()) {
+ if !crate::io::is_file(&target) {
return Err(bad(command, format!("chapter {path} is not a regular file")));
}
// Check both the file and its resolved parent without truncating it. Replacement needs a
// writable directory even when an in-place write would be permitted.
- std::fs::OpenOptions::new().write(true).open(&target).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ crate::io::writable(&target).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let parent = target.parent().ok_or_else(|| bad(command, format!("chapter {path} has no parent folder")))?;
tempfile::Builder::new().prefix(".designcraft-book-check-").tempfile_in(parent).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
Ok(())
diff --git a/crates/engine/src/cmd/book/safety_tests.rs b/crates/engine/src/cmd/book/safety_tests.rs
index e4ec20efd..e8fe37cc2 100644
--- a/crates/engine/src/cmd/book/safety_tests.rs
+++ b/crates/engine/src/cmd/book/safety_tests.rs
@@ -1,4 +1,4 @@
-use super::{ChapterBatch, MAX_BATCH_CHAPTERS, write_staged_chapter};
+use super::{ChapterBatch, MAX_BATCH_CHAPTERS};
use crate::Session;
use serde_json::json;
@@ -26,7 +26,7 @@ fn a_commit_failure_reports_the_completed_prefix_and_cleans_staging() {
let error = batch
.commit_with(|path, staged| {
calls += 1;
- if path == second { Err(std::io::Error::other("synthetic disk full")) } else { write_staged_chapter(path, staged) }
+ if path == second { Err(std::io::Error::other("synthetic disk full")) } else { crate::io::replace_with(path, staged) }
})
.unwrap_err()
.to_string();
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 587855415..64a73ab30 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, "{dir?} — write every unsaved document to the recovery folder (the app does this on a timer)", always, |s, p| {
let dir = recovery_dir(s, p, FolderAccess::Write)?;
- Ok(json!({"saved": crate::recovery::save(s, &dir)?}))
+ Ok(json!({"saved": crate::recovery::save_tracked(s, &dir)?}))
}),
cmd!(noundo "file.recovery.open", "Recover Documents", [], None, "{dir?} — reopen documents left in the recovery folder (unsaved)", always, |s, p| {
// Reopening removes the entries it read.
@@ -191,11 +191,9 @@ pub(crate) fn load_document_fonts(d: &mut Document, path: &str) -> (Option<Arc<c
use designcraft_fonts::DOCUMENT_FONTS_FOLDER;
let Some(folder) = std::path::Path::new(path).parent().map(document_fonts_folder) else { return (None, 0, Vec::new()) };
// A document's folder is the agent's to name (a recovery entry or a book lists paths too):
- // fonts outside the automation read root stay unloaded.
- if let Err(e) = crate::file_access::check_read(&folder) {
- return (None, 0, vec![format!("{DOCUMENT_FONTS_FOLDER}: {e}")]);
- }
- let r = designcraft_fonts::FontDb::global().load_document_fonts(&folder);
+ // the fonts crate asks the automation roots about the folder and each font file, so fonts
+ // outside the read root stay unloaded.
+ let r = designcraft_fonts::FontDb::global().load_document_fonts(&folder, &|p| crate::file_access::check_read(p));
d.font_scope = r.scope;
let scope = (r.scope != 0).then(|| Arc::new(crate::FontScope(r.scope)));
(scope, r.faces, r.skipped.into_iter().map(|s| format!("{DOCUMENT_FONTS_FOLDER}: {s}")).collect())
diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs
index 4fa214750..7bc7d533c 100644
--- a/crates/engine/src/io.rs
+++ b/crates/engine/src/io.rs
@@ -37,7 +37,39 @@ pub fn read_to_string(path: impl AsRef<Path>) -> Result<String, String> {
pub fn write_file(path: impl AsRef<Path>, bytes: &[u8]) -> Result<(), String> {
let path = path.as_ref();
crate::file_access::check_write(path)?;
- std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display()))
+ // Replaced atomically where there is a real file system (see `atomic`).
+ #[cfg(not(target_arch = "wasm32"))]
+ let written = crate::atomic::write_atomic(path, bytes);
+ #[cfg(target_arch = "wasm32")]
+ let written = std::fs::write(path, bytes);
+ written.map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// Atomically replace the file at `path` with the contents of `staged`, a private temporary file
+/// the engine made itself (so it is not checked), inside the automation write root when there is
+/// one.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn replace_with(path: impl AsRef<Path>, staged: impl AsRef<Path>) -> std::io::Result<()> {
+ let path = path.as_ref();
+ crate::file_access::check_write(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ let mut input = std::fs::File::open(staged)?;
+ crate::atomic::write_atomic_with(path, |file| std::io::copy(&mut input, file).map(|_| ()))
+}
+
+/// Could the file at `path` be opened for writing (without truncating it)? Inside the automation
+/// write root when there is one.
+pub fn writable(path: impl AsRef<Path>) -> std::io::Result<()> {
+ let path = path.as_ref();
+ crate::file_access::check_write(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ std::fs::OpenOptions::new().write(true).open(path).map(drop)
+}
+
+/// The canonical form of `path` (links resolved), inside the automation read root when there is
+/// one.
+pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<std::path::PathBuf> {
+ let path = path.as_ref();
+ crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ std::fs::canonicalize(path)
}
/// What the file system says about `path` (links followed), inside the automation read root when
diff --git a/crates/engine/src/tests_roots.rs b/crates/engine/src/tests_roots.rs
index 443403b0a..04711bba9 100644
--- a/crates/engine/src/tests_roots.rs
+++ b/crates/engine/src/tests_roots.rs
@@ -129,11 +129,15 @@ fn a_data_source_path_stored_in_a_document_is_read_through_the_roots() {
fn a_book_writes_its_chapters_only_inside_the_write_root() {
let (base, roots) = folders("book");
let chapter = base.join("in/a.designcraft");
- let mut s = Session::new();
- s.execute("file.new", &json!({})).unwrap();
- s.execute("file.save", &json!({"path": p(&chapter)})).unwrap();
let second = base.join("in/b.designcraft");
- s.execute("file.saveAs", &json!({"path": p(&second)})).unwrap();
+ {
+ // Made by another session: a book only rewrites chapters that are not open.
+ let mut maker = Session::new();
+ maker.execute("file.new", &json!({})).unwrap();
+ maker.execute("file.save", &json!({"path": p(&chapter)})).unwrap();
+ maker.execute("file.saveAs", &json!({"path": p(&second)})).unwrap();
+ }
+ let mut s = Session::new();
let before = (std::fs::read(&chapter).unwrap(), std::fs::read(&second).unwrap());
confine(Some(&roots), || {
s.execute("book.new", &json!({"path": p(&base.join("out/b.dcbook"))})).unwrap();
@@ -210,3 +214,20 @@ fn fonts_beside_a_document_outside_the_read_root_are_not_loaded() {
assert!(warnings.iter().any(|w| w.contains("x.ttf")), "without roots the folder is read and the bad font reported: {warnings:?}");
let _ = std::fs::remove_dir_all(base);
}
+
+#[cfg(unix)]
+#[test]
+fn a_font_file_that_links_out_of_the_read_root_is_skipped() {
+ let (base, roots) = folders("fontlink");
+ std::fs::create_dir_all(base.join("in/Document Fonts")).unwrap();
+ std::fs::write(base.join("outside/secret.ttf"), b"not a font").unwrap();
+ std::os::unix::fs::symlink(base.join("outside/secret.ttf"), base.join("in/Document Fonts/link.ttf")).unwrap();
+ let mut d = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default());
+ let doc = p(&base.join("in/doc.designcraft"));
+ let (_, _, warnings) = confine(Some(&roots), || cmd::load_document_fonts(&mut d, &doc));
+ assert!(warnings.iter().any(|w| w.contains("outside the read root")), "{warnings:?}");
+ assert!(!warnings.iter().any(|w| w.contains("not a font")), "the file was opened: {warnings:?}");
+ let (_, _, warnings) = cmd::load_document_fonts(&mut d, &doc);
+ assert!(warnings.iter().any(|w| w.contains("link.ttf")), "without roots the link is followed: {warnings:?}");
+ let _ = std::fs::remove_dir_all(base);
+}
diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs
index 14441e144..44a64bddc 100644
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@ -963,18 +963,33 @@ impl FontDb {
/// [`MAX_DOCUMENT_FONT_FILES`] (in name order), files over [`MAX_DOCUMENT_FONT_BYTES`] or past
/// [`MAX_DOCUMENT_FONTS_TOTAL`] in all, and files that aren't fonts are skipped with a note. A
/// missing folder loads nothing (scope 0).
+ ///
+ /// The folder is named by a document, so this crate does not trust it: `allow` (`Ok`, or why a
+ /// path may not be read) is asked about
+ /// the folder and about every font file in it before either is opened, and a path it refuses
+ /// is skipped with its message (the engine passes its automation-root check; a host with no
+ /// roots passes `&|_| Ok(())`).
#[cfg(not(target_arch = "wasm32"))]
- pub fn load_document_fonts(&self, folder: &std::path::Path) -> DocumentFonts {
+ pub fn load_document_fonts(&self, folder: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> Result<(), String>) -> DocumentFonts {
let mut out = DocumentFonts::default();
+ if let Err(why) = allow(folder) {
+ out.skipped.push(why);
+ return out;
+ }
let Ok(entries) = std::fs::read_dir(folder) else { return out };
- let mut files: Vec<std::path::PathBuf> = entries
- .flatten()
- .map(|e| e.path())
- .filter(|p| {
- let ext = p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());
- matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) && p.is_file()
- })
- .collect();
+ let mut files: Vec<std::path::PathBuf> = Vec::new();
+ for path in entries.flatten().map(|e| e.path()) {
+ let ext = path.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());
+ if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {
+ continue;
+ }
+ // Each file is vetted before it is touched at all, a link out of the folder included.
+ match allow(&path) {
+ Ok(()) if path.is_file() => files.push(path),
+ Ok(()) => {}
+ Err(why) => out.skipped.push(why),
+ }
+ }
files.sort();
let mut total = 0u64;
let mut own: Vec<Arc<FontFace>> = Vec::new();
diff --git a/crates/fonts/src/tests_docfonts.rs b/crates/fonts/src/tests_docfonts.rs
index 525bc50b8..f2f73bca7 100644
--- a/crates/fonts/src/tests_docfonts.rs
+++ b/crates/fonts/src/tests_docfonts.rs
@@ -36,7 +36,7 @@ fn document_fonts_load_ahead_of_installed_ones() {
let installed = db.face("DocFont Precedence", "Regular");
assert!(installed.covers('a') && matches!(installed.source, FontSource::Installed(_)), "{:?}", installed.source);
- let r = db.load_document_fonts(&folder);
+ let r = db.load_document_fonts(&folder, &|_| Ok(()));
assert_eq!((r.faces, r.skipped.len()), (1, 0), "{:?}", r.skipped);
let face = db.scoped(r.scope).face("DocFont Precedence", "Regular");
assert!(face.covers('b'), "the document's face wins");
@@ -45,7 +45,7 @@ fn document_fonts_load_ahead_of_installed_ones() {
assert!(db.face("DocFont Precedence", "Regular").covers('a'), "outside the document the installed face stays");
// Loading the folder again (another document beside it) shares the face, in a scope of its own.
- let again = db.load_document_fonts(&folder);
+ let again = db.load_document_fonts(&folder, &|_| Ok(()));
assert_eq!((again.faces, again.skipped.len()), (1, 0));
assert_ne!(again.scope, r.scope);
assert!(Arc::ptr_eq(&db.scoped(again.scope).face("DocFont Precedence", "Regular"), &face));
@@ -64,7 +64,7 @@ fn damaged_oversized_and_other_files_are_skipped() {
write_font(&folder.join("nested.ttf"), "inner.ttf", "DocFont Nested", &['n']);
let db = FontDb::with_font_dirs(vec![]);
- let r = db.load_document_fonts(&folder);
+ let r = db.load_document_fonts(&folder, &|_| Ok(()));
assert_eq!(r.faces, 1);
assert!(db.scoped(r.scope).has_family("DocFont Good"));
assert!(!db.has_family("DocFont Good"), "the document's alone");
@@ -85,7 +85,7 @@ fn the_number_of_files_read_is_capped() {
write_font(&folder, "zz-real.ttf", "DocFont Past Cap", &['z']);
let db = FontDb::with_font_dirs(vec![]);
- let r = db.load_document_fonts(&folder);
+ let r = db.load_document_fonts(&folder, &|_| Ok(()));
assert_eq!((r.faces, r.scope), (0, 0));
assert!(!db.scoped(r.scope).has_family("DocFont Past Cap"));
assert_eq!(r.skipped.len(), MAX_DOCUMENT_FONT_FILES + 1, "one note for each file read, one for the rest");
@@ -98,7 +98,7 @@ fn large_cjk_collections_are_within_the_limit() {
// macOS's Songti collection is 67 MB; full Noto/Source Han CJK collections are larger.
let folder = temp_dir("cjk-size");
std::fs::File::create(folder.join("cjk.ttc")).unwrap().set_len(200 << 20).unwrap();
- let r = FontDb::with_font_dirs(vec![]).load_document_fonts(&folder);
+ let r = FontDb::with_font_dirs(vec![]).load_document_fonts(&folder, &|_| Ok(()));
assert_eq!(r.skipped.len(), 1, "{:?}", r.skipped);
assert!(!r.skipped[0].contains("larger than"), "skipped for not being a font, not for its size: {:?}", r.skipped);
let _ = std::fs::remove_dir_all(&folder);
@@ -107,7 +107,7 @@ fn large_cjk_collections_are_within_the_limit() {
#[test]
fn a_missing_folder_loads_nothing() {
let db = FontDb::with_font_dirs(vec![]);
- let r = db.load_document_fonts(&std::env::temp_dir().join("dc-docfonts-no-such-folder").join(DOCUMENT_FONTS_FOLDER));
+ let r = db.load_document_fonts(&std::env::temp_dir().join("dc-docfonts-no-such-folder").join(DOCUMENT_FONTS_FOLDER), &|_| Ok(()));
assert_eq!((r.faces, r.scope, r.skipped.len()), (0, 0, 0));
}
@@ -118,7 +118,7 @@ fn each_scope_sees_its_own_fonts_only() {
write_font(&a, "a.ttf", FAMILY, &['a']);
write_font(&b, "b.ttf", FAMILY, &['b', '\u{E123}']);
let db = FontDb::with_font_dirs(vec![]);
- let (ra, rb) = (db.load_document_fonts(&a), db.load_document_fonts(&b));
+ let (ra, rb) = (db.load_document_fonts(&a, &|_| Ok(())), db.load_document_fonts(&b, &|_| Ok(())));
let (in_a, in_b) = (db.scoped(ra.scope), db.scoped(rb.scope));
assert!(in_a.face(FAMILY, "Regular").covers('a') && in_b.face(FAMILY, "Regular").covers('b'));
@@ -139,16 +139,16 @@ fn a_closed_scope_finds_nothing_and_reopening_reuses_the_faces() {
let folder = temp_dir("reopen");
let file = write_font(&folder, "r.ttf", FAMILY, &['r']);
let db = FontDb::with_font_dirs(vec![]);
- let r = db.load_document_fonts(&folder);
+ let r = db.load_document_fonts(&folder, &|_| Ok(()));
let face = db.scoped(r.scope).face(FAMILY, "Regular");
db.close_scope(r.scope);
assert!(!db.scoped(r.scope).has_family(FAMILY), "closed");
- let again = db.load_document_fonts(&folder);
+ let again = db.load_document_fonts(&folder, &|_| Ok(()));
assert!(Arc::ptr_eq(&db.scoped(again.scope).face(FAMILY, "Regular"), &face), "an unchanged file isn't read again");
// A file changed since is read again.
std::fs::write(&file, font_with(FAMILY, &['r', 's']).unwrap()).unwrap();
- let changed = db.load_document_fonts(&folder);
+ let changed = db.load_document_fonts(&folder, &|_| Ok(()));
let new_face = db.scoped(changed.scope).face(FAMILY, "Regular");
assert!(new_face.covers('s') && new_face.id() != face.id());
assert!(!db.scoped(again.scope).face(FAMILY, "Regular").covers('s'), "the document open before keeps what it opened with");
@@ -166,3 +166,27 @@ fn restricted_licence_reads_the_embedding_bits() {
assert!(!db.face(FALLBACK_FAMILY, "Regular").restricted_licence(), "the bundled fonts are OFL");
assert_eq!(db.face(FALLBACK_FAMILY, "Regular").source, FontSource::Bundled);
}
+
+#[test]
+fn the_access_check_vets_the_folder_and_every_file_before_it_is_opened() {
+ let folder = temp_dir("access");
+ write_font(&folder, "kept.ttf", "DocFont Kept", &['k']);
+ write_font(&folder, "refused.ttf", "DocFont Refused", &['r']);
+ let db = FontDb::with_font_dirs(vec![]);
+ let asked = std::sync::Mutex::new(Vec::new());
+ let allow = |p: &Path| {
+ asked.lock().unwrap().push(p.to_path_buf());
+ if p.ends_with("refused.ttf") { Err("refused.ttf: outside the read root".to_string()) } else { Ok(()) }
+ };
+ let r = db.load_document_fonts(&folder, &allow);
+ assert_eq!(r.faces, 1, "{:?}", r.skipped);
+ assert_eq!(r.skipped, vec!["refused.ttf: outside the read root".to_string()]);
+ let asked = asked.into_inner().unwrap();
+ assert_eq!(asked.first().map(PathBuf::as_path), Some(folder.as_path()), "the folder is asked about first");
+ assert!(asked.iter().any(|p| p.ends_with("kept.ttf")) && asked.iter().any(|p| p.ends_with("refused.ttf")));
+
+ // A refused folder is not even listed.
+ let r = db.load_document_fonts(&folder, &|_| Err("no".to_string()));
+ assert_eq!((r.faces, r.scope, r.skipped), (0, 0, vec!["no".to_string()]));
+ let _ = std::fs::remove_dir_all(&folder);
+}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 46c3253b6..41c79f0f7 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -29,21 +29,11 @@ fn uniform_cell_stroke(edges: &[designcraft_doc::CellStrokeAttrs; 4]) -> Option<
Some(designcraft_doc::CellStroke { weight: first.weight?, color: first.color.clone()?, tint: first.tint?, kind: first.kind.clone()? })
}
-/// Import an IDML package. Linked images are read from disk when available (not on wasm).
+/// Import an IDML package without reading its linked images from disk: this crate never touches
+/// the file system, so a caller that wants the links brings its own reader
+/// ([`import_idml_with`]). The engine passes one that checks the automation roots.
pub fn import_idml(bytes: &[u8]) -> Result<Document> {
- import_idml_with(bytes, &default_reader)
-}
-
-fn default_reader(path: &str) -> Option<Vec<u8>> {
- #[cfg(not(target_arch = "wasm32"))]
- {
- std::fs::read(path).ok()
- }
- #[cfg(target_arch = "wasm32")]
- {
- let _ = path;
- None
- }
+ import_idml_with(bytes, &|_| None)
}
/// Import with a custom reader for linked files (`path` → bytes).
@@ -68,7 +58,9 @@ pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<u
let mut lenient: HashMap<String, String> = HashMap::new();
for i in 0..zip.len() {
let mut f = zip.by_index(i).map_err(|e| IdmlError::NotIdml(e.to_string()))?;
- if f.is_dir() {
+ // A folder entry of the archive (the zip crate's own `is_dir`; spelled out so no file-system
+ // probe appears in this crate).
+ if f.name().ends_with('/') {
continue;
}
let name = f.name().to_string();
diff --git a/crates/ui-egui/src/panels/library.rs b/crates/ui-egui/src/panels/library.rs
index ccaa595dd..c64a61b26 100644
--- a/crates/ui-egui/src/panels/library.rs
+++ b/crates/ui-egui/src/panels/library.rs
@@ -195,8 +195,10 @@ pub fn scripts(app: &mut DesignApp, ui: &mut egui::Ui) {
if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Load…"))).clicked()
&& let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("script"))
{
- #[cfg(not(target_arch = "wasm32"))]
- match std::fs::read_to_string(&path) {
+ // Through the host's reader, like every other file the UI opens: this crate has no
+ // file system of its own.
+ let read = app.services.read.as_mut().map_or_else(|| Err("no file access".to_string()), |r| r(&path));
+ match read.and_then(|bytes| String::from_utf8(bytes).map_err(|e| e.to_string())) {
Ok(text) => {
let name = std::path::Path::new(&path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Script".into());
app.ui.scripts.push((name, text));