Skip to content

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

Assets: files with different paths stay separate assets

aiongg10546a6e663b
diff --git a/crates/doc/src/assets.rs b/crates/doc/src/assets.rs
index 73f7ac98d..24ba5c243 100644
--- a/crates/doc/src/assets.rs
+++ b/crates/doc/src/assets.rs
@@ -15,18 +15,27 @@ use crate::{Asset, AssetId, Content, Document, Item};
const MAX_DEPTH: usize = 64;
impl Asset {
- /// Whether `other` holds the same file: the same type, page and bytes. Assets without bytes
- /// (a link that couldn't be read) are the same only when they link to the same path.
+ /// Whether `other` holds the same file: the same type, page, link and bytes. Files at
+ /// different paths stay apart even with identical bytes, since each can be updated or
+ /// relinked on its own. Assets without bytes (a link that couldn't be read) are the same only
+ /// when they link to the same path.
pub fn same_file(&self, other: &Asset) -> bool {
if self.mime != other.mime || self.page != other.page {
return false;
}
+ if self.link != other.link {
+ return false;
+ }
match (self.data.is_empty(), other.data.is_empty()) {
- (false, false) => Arc::ptr_eq(&self.data, &other.data) || (self.data.len() == other.data.len() && *self.data == *other.data),
- (true, true) => self.link.is_some() && self.link == other.link,
+ (false, false) => self.same_bytes(other),
+ (true, true) => self.link.is_some(),
_ => false,
}
}
+
+ fn same_bytes(&self, other: &Asset) -> bool {
+ Arc::ptr_eq(&self.data, &other.data) || (self.data.len() == other.data.len() && *self.data == *other.data)
+ }
}
/// The asset in `assets` holding the same file as `asset`.
@@ -35,17 +44,16 @@ pub fn find_same_asset(assets: &BTreeMap<AssetId, Arc<Asset>>, asset: &Asset) ->
}
/// Add `asset` to `assets` unless they already hold the same file; returns the id placements
-/// should reference. A reused asset without a link takes the new asset's link.
-pub fn insert_asset(assets: &mut BTreeMap<AssetId, Arc<Asset>>, asset: Asset) -> AssetId {
+/// should reference. A new asset with the bytes of an existing one shares its buffer.
+pub fn insert_asset(assets: &mut BTreeMap<AssetId, Arc<Asset>>, mut asset: Asset) -> AssetId {
if let Some(id) = find_same_asset(assets, &asset) {
- if let Some(a) = assets.get_mut(&id)
- && a.link.is_none()
- && asset.link.is_some()
- {
- Arc::make_mut(a).link = asset.link;
- }
return id;
}
+ if !asset.data.is_empty()
+ && let Some(a) = assets.values().find(|a| a.same_bytes(&asset))
+ {
+ asset.data = Arc::clone(&a.data);
+ }
let id = asset.id;
assets.insert(id, Arc::new(asset));
id
@@ -240,28 +248,15 @@ impl Document {
}
let mut reps: HashMap<(usize, &str, u32), Vec<&Arc<Asset>>> = HashMap::new();
let mut map = HashMap::new();
- let mut links = Vec::new();
for a in self.assets.values() {
let bucket = reps.entry((a.data.len(), a.mime.as_str(), a.page)).or_default();
match bucket.iter().find(|r| r.same_file(a)) {
Some(r) => {
map.insert(a.id, r.id);
- if r.link.is_none()
- && let Some(l) = &a.link
- {
- links.push((r.id, l.clone()));
- }
}
None => bucket.push(a),
}
}
- for (id, link) in links {
- if let Some(a) = self.assets.get_mut(&id)
- && a.link.is_none()
- {
- Arc::make_mut(a).link = Some(link);
- }
- }
self.remap_assets(&map);
self.assets.retain(|id, _| !map.contains_key(id));
map.len()
@@ -302,14 +297,13 @@ mod tests {
fn identical_files_share_one_asset() {
let mut d = Document::new(&Default::default());
let a = d.add_asset(asset(1, b"same"));
- let b = d.add_asset(Asset { link: Some("/x/p.png".into()), ..asset(2, b"same") });
+ let b = d.add_asset(asset(2, b"same"));
let c = d.add_asset(asset(3, b"diff"));
let p = d.add_asset(Asset { page: 1, ..asset(4, b"same") });
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(a, p);
assert_eq!(d.assets.len(), 3);
- assert_eq!(d.assets[&a].link.as_deref(), Some("/x/p.png"));
// Unreadable links match by path only.
let m1 = d.add_asset(Asset { link: Some("/m/1.png".into()), ..asset(5, b"") });
let m2 = d.add_asset(Asset { link: Some("/m/2.png".into()), ..asset(6, b"") });
@@ -319,6 +313,21 @@ mod tests {
assert_ne!(m3, m4);
}
+ #[test]
+ fn files_at_different_paths_stay_separate_assets() {
+ let mut d = Document::new(&Default::default());
+ let linked = |id, path: &str| Asset { link: Some(path.into()), ..asset(id, b"same") };
+ let embedded = d.add_asset(asset(1, b"same"));
+ let a = d.add_asset(linked(2, "/p/a.png"));
+ let b = d.add_asset(linked(3, "/q/b.png"));
+ assert_eq!(d.add_asset(linked(4, "/p/a.png")), a, "the same path placed again");
+ assert_eq!(d.assets.len(), 3);
+ assert!(embedded != a && a != b && embedded != b);
+ assert_eq!(d.assets[&embedded].link, None);
+ assert_eq!(d.assets[&b].link.as_deref(), Some("/q/b.png"));
+ assert!(Arc::ptr_eq(&d.assets[&a].data, &d.assets[&b].data), "identical bytes share one buffer");
+ }
+
#[test]
fn compaction_merges_duplicates_and_drops_unused_assets() {
let mut d = Document::new(&Default::default());
diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs
index 687cd7b1a..73de3ea7e 100644
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@ -350,6 +350,38 @@ mod shared_asset_tests {
assert_eq!(names, ["a.png", "c.png"]);
}
+ #[test]
+ fn files_with_identical_bytes_at_different_paths_keep_their_own_links() {
+ let dir = std::env::temp_dir().join(format!("dc-same-bytes-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let (a, b) = (dir.join("a.png"), dir.join("b.png"));
+ std::fs::write(&a, png(10, 10)).unwrap();
+ std::fs::write(&b, png(10, 10)).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ for (path, x) in [(&a, 72), (&b, 200)] {
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap();
+ }
+ assert_eq!(s.doc().unwrap().doc.assets.len(), 2);
+ let rows = |s: &mut Session| -> Vec<(String, Value)> {
+ let l = s.execute("links.list", &json!({})).unwrap();
+ l.as_array().unwrap().iter().map(|r| (r["path"].as_str().unwrap().to_string(), r["pixels"].clone())).collect()
+ };
+ let paths = |r: &[(String, Value)]| r.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>();
+ let before = rows(&mut s);
+ assert_eq!(paths(&before), [a.to_string_lossy(), b.to_string_lossy()]);
+
+ // b.png changes on disk: updating it leaves a.png's placement alone.
+ std::fs::write(&b, png(20, 10)).unwrap();
+ assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1);
+ let after = rows(&mut s);
+ assert_eq!(paths(&after), paths(&before));
+ assert_eq!((after[0].1.clone(), after[1].1.clone()), (json!([10, 10]), json!([20, 10])));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn pasted_graphics_reuse_the_identical_asset_of_the_target() {
use designcraft_doc::build::NewDocument;
diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs
index 2de45402d..408bb3ccc 100644
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@ -317,6 +317,27 @@ mod tests {
}
}
+ #[test]
+ fn files_with_identical_bytes_at_different_paths_keep_their_paths() {
+ let mut d = Document::new(&NewDocument::default());
+ let ids: Vec<AssetId> = (0..3).map(|_| png_asset(&mut d, &[3; 32])).collect();
+ for (id, link) in ids.iter().zip(["/p/a.png", "/q/b.png"]) {
+ if let Some(a) = d.assets.get_mut(id) {
+ Arc::make_mut(a).link = Some(link.into());
+ }
+ }
+ let items: Vec<_> = ids.iter().enumerate().map(|(k, id)| place(&mut d, *id, k as f64)).collect();
+ for bytes in [save(&d).unwrap(), save_uncompacted(&d)] {
+ let back = load(&bytes).unwrap();
+ assert_eq!(back.assets.len(), 3);
+ let links: Vec<Option<&str>> = items
+ .iter()
+ .map(|i| back.item(*i).and_then(|i| i.graphic()).and_then(|g| back.assets.get(&g.asset)).unwrap().link.as_deref())
+ .collect();
+ assert_eq!(links, [Some("/p/a.png"), Some("/q/b.png"), None]);
+ }
+ }
+
#[test]
fn older_files_with_one_asset_per_placement_open_with_one() {
let mut d = Document::new(&NewDocument::default());
diff --git a/crates/idml/src/tests/assets.rs b/crates/idml/src/tests/assets.rs
index a5cd90fb0..dd2761442 100644
--- a/crates/idml/src/tests/assets.rs
+++ b/crates/idml/src/tests/assets.rs
@@ -75,7 +75,8 @@ fn one_file_placed_several_times_imports_as_one_asset() {
reads.set(reads.get() + 1);
p.ends_with("couple.jpg").then(|| bytes.clone())
};
- // Three placements linking the file, and one embedding the same bytes under another path.
+ // Three placements linking the file, and one embedding the same bytes under another path:
+ // that one keeps its own asset and path.
let frames = vec![
frame(1, 0.0, 1.0, &image(1, PHOTO, None)),
frame(2, 100.0, 2.0, &image(2, PHOTO, None)),
@@ -84,19 +85,21 @@ fn one_file_placed_several_times_imports_as_one_asset() {
];
let d = import_idml_with(&package(&frames), &reader).unwrap();
assert_eq!(reads.get(), 1, "the linked file is read once");
- assert_eq!(d.assets.len(), 1);
- let a = d.assets.values().next().unwrap();
- assert_eq!(a.link.as_deref(), Some("/photos/wedding day/couple.jpg"));
+ assert_eq!(d.assets.len(), 2);
let p = placements(&d);
assert_eq!(p.iter().map(|(_, c, _)| c[0]).collect::<Vec<_>>(), vec![1.0, 2.0, 3.0, 4.0]);
- assert!(p.iter().all(|(id, _, _)| *id == a.id));
+ let link = |id| d.assets.get(id).and_then(|a| a.link.as_deref());
+ let links: Vec<_> = p.iter().map(|(id, _, _)| link(id)).collect();
+ assert_eq!(links[..3], [Some("/photos/wedding day/couple.jpg"); 3]);
+ assert_eq!(links[3], Some("/elsewhere/copy.jpg"));
+ assert!(p[..3].iter().all(|(id, _, _)| *id == p[0].0));
- // Exported linked or embedded, the round trip keeps one asset and each placement's crop and
- // transform.
+ // Exported linked or embedded, the round trip keeps the two assets and each placement's crop
+ // and transform.
for embed_images in [false, true] {
let out = export_idml_with(&d, &ExportOptions { embed_images });
let back = import_idml_with(&out, &reader).unwrap();
- assert_eq!(back.assets.len(), 1, "embed_images: {embed_images}");
+ assert_eq!(back.assets.len(), 2, "embed_images: {embed_images}");
let q = placements(&back);
assert_eq!(q.len(), 4);
for ((_, c0, x0), (_, c1, x1)) in p.iter().zip(&q) {