From 729d8d5184a955fdd345279e0356ecb5db469106 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 05:29:09 -0800 Subject: [PATCH] Links: Update Links reads files again for links inside symbols, patterns and masks Update Links, and opening a document with Update Links: Automatically, now read a modified file again for the images and placed documents in symbols, graph designs, patterns and opacity masks that show the same content as the objects read in the layers. By default Update Links also reads the files that only that art shows. Each nested object takes the file's place as its own Placement Options say, including the clip, and its link takes the new path, size, modification time and hash. Saving a document also refreshes the placed copies of it inside symbols, graph designs, patterns and opacity masks of the other open documents, not only those in the layers. Relink, Embed and Unembed still change only the objects they are given. --- crates/engine/src/cmd/links.rs | 278 +++++++++++++++++---- crates/engine/src/tests/links.rs | 73 +++++- crates/engine/src/tests/placed_document.rs | 30 +++ docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 5 files changed, 332 insertions(+), 57 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index c09ac67730..f3cd7b6b6c 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -24,11 +24,12 @@ use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Component, Path}; +use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::links::{Align, Preserve, hash_bytes}; use vectorcraft_doc::{Appearance, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions}; -use vectorcraft_geom::{Affine, Rect, shapes}; +use vectorcraft_geom::{Affine, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, id_param, ids_param, str_param}; @@ -49,7 +50,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. One undo step → {updated: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids]}", has_doc, update ), @@ -483,23 +484,183 @@ fn read_for(f: &mut Found, g: &Group, cmd: &str) -> Result { Ok(Read::Document(f.link(&bytes, &g.link), src)) } -/// Objects `ids` show what was read (see [`install`], [`install_document`]). -fn install_read(d: &mut Document, ids: &[NodeId], read: Read, force: Option) -> Result<()> { +/// Objects `ids` show what was read (see [`install`], [`install_document`]), and with `also`, the +/// objects outside the layer tree that show group `also`'s content. +fn install_read(d: &mut Document, ids: &[NodeId], read: Read, force: Option, also: Option<&Group>) -> Result<()> { + let also = also.map(|g| (g.link.path.as_str(), g.key.as_str())); match read { - Read::Image(r) => install(d, ids, r, force), - Read::Document(link, src) => install_document(d, ids, &link, &src, force), + Read::Image(r) => install(d, ids, r, force, also), + Read::Document(link, src) => install_document(d, ids, &link, &src, force, also), + } +} + +/// Is `n` a linked image (or, with `document`, a placed document) of the file at `path` showing +/// content `key`? +fn shows(n: &Node, (path, key): (&str, &str), document: bool) -> bool { + match &n.kind { + NodeKind::Image(im) => !document && im.key == key && im.link.as_ref().is_some_and(|l| l.path == path), + NodeKind::PlacedDocument(p) => document && p.key == key && p.link.path == path, + _ => false, + } +} + +/// The clipping path of `clip`: its room as a rectangle in its frame. +fn clip_shape((frame, room): Clip) -> PathData { + shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame) +} + +/// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and +/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for. +struct Nested<'a> { + pick: &'a dyn Fn(&Node) -> bool, + /// The object an object becomes, and the clip it takes ([`placed_xf`]). + make: &'a mut dyn FnMut(&Node) -> (Node, Option), + /// The next node id for a clip group (taken from the document after the walk). + next: u64, +} + +impl Nested<'_> { + /// Every root of `d`: the layers (whose own objects are left alone), then the art of symbols, + /// graph designs and patterns. + fn run(mut self, d: &mut Document) { + let first = d.peek_next_id(); + self.next = first; + for l in d.layers.iter_mut() { + self.update(l, false); + } + for root in d.symbols.iter_mut().map(|s| &mut s.art).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) { + self.root(root); + } + for root in d.patterns.iter_mut().flat_map(|p| &mut p.art) { + self.root(root); + } + for _ in first..self.next { + d.alloc_id(); + } + } + + /// The art at a root outside the layer tree (a symbol's, graph design's or pattern's art, or + /// mask art). + fn root(&mut self, n: &mut Arc) { + if !(self.pick)(n) { + return self.update(n, true); + } + let (new, clip) = (self.make)(n); + let mut new = Arc::new(new); + self.update(&mut new, true); + *n = match clip { + Some(clip) => Arc::new(self.clip_group(new, clip)), + None => new, + }; + } + + /// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays + /// the same node when none is there, and only the nodes on the way to one are copied. + fn update(&mut self, n: &mut Arc, nested: bool) { + let mask = n.extras().mask.as_ref().and_then(|m| { + let mut art = Arc::clone(&m.art); + self.root(&mut art); + (!Arc::ptr_eq(&art, &m.art)).then_some(art) + }); + let mut slots: Vec<(usize, Arc)> = vec![]; + if let Some(children) = n.children() { + // A clip group holding just the object: its clipping path changes. + let clip_path = match (&n.kind, &children[..]) { + (NodeKind::Group { clip: true, .. }, [c, _]) if matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c), + _ => None, + }; + for (i, c) in children.iter().enumerate() { + if !(nested && (self.pick)(c)) { + let mut new = Arc::clone(c); + self.update(&mut new, nested); + if !Arc::ptr_eq(&new, c) { + slots.push((i, new)); + } + continue; + } + let (new, clip) = (self.make)(c); + let mut new = Arc::new(new); + self.update(&mut new, true); + match (clip, clip_path) { + (None, _) => slots.push((i, new)), + (Some(clip), Some(path)) if i == 1 => { + let mut path = Node::clone(path); + if let NodeKind::Path { path: p, .. } = &mut path.kind { + *p = clip_shape(clip); + } + slots.extend([(0, Arc::new(path)), (1, new)]); + } + (Some(clip), _) => { + let group = self.clip_group(new, clip); + slots.push((i, Arc::new(group))); + } + } + } + } + if mask.is_none() && slots.is_empty() { + return; + } + let n = Arc::make_mut(n); + if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) { + m.art = art; + } + if let Some(children) = n.children_mut() { + for (i, c) in slots { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + } + + /// A clip group of `object` clipped to `clip`, as [`clip_image`] makes one in the layers. + fn clip_group(&mut self, object: Arc, clip: Clip) -> Node { + let (path_id, group_id) = (NodeId(self.next), NodeId(self.next + 1)); + self.next += 2; + let none = vectorcraft_color::Paint::None; + let mut path = Node::path(path_id, clip_shape(clip), Appearance::basic(none.clone(), none, 0.0)); + if let NodeKind::Path { clipping, .. } = &mut path.kind { + *clipping = true; + } + Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true }) } } /// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its -/// Placement Options say (`force`: as that Preserve choice says, whatever they say). -fn install_document(d: &mut Document, ids: &[NodeId], link: &LinkInfo, src: &super::place::document::Source, force: Option) -> Result<()> { +/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also` +/// (a file's path and the content shown), so do the placed documents outside the layer tree that +/// show that content. +fn install_document( + d: &mut Document, + ids: &[NodeId], + link: &LinkInfo, + src: &super::place::document::Source, + force: Option, + also: Option<(&str, &str)>, +) -> Result<()> { let mut clips = vec![]; let (w, h) = (src.frame.width(), src.frame.height()); + let placed = |p: &PlacedDocument| { + let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement }; + placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o) + }; + if let Some(also) = also { + let pick = |n: &Node| shows(n, also, true); + let mut make = |n: &Node| { + let mut n = n.clone(); + let mut clip = None; + if let NodeKind::PlacedDocument(p) = &mut n.kind { + let (xf, c) = placed(p); + (p.key, p.width, p.height, p.xf, p.link) = (src.key.clone(), w, h, xf, link.clone()); + clip = c; + } + (n, clip) + }; + Nested { pick: &pick, make: &mut make, next: 0 }.run(d); + } for id in ids { let Some(NodeKind::PlacedDocument(p)) = d.node(*id).map(|n| &n.kind) else { continue }; - let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement }; - let (xf, clip) = placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o); + let (xf, clip) = placed(p); if let Some(n) = d.node_mut(*id) && let NodeKind::PlacedDocument(p) = &mut n.kind { @@ -565,8 +726,8 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n /// Clip image `id` of `d` to `room` in `frame`: the clipping path of the clip group holding just /// it changes, else the image goes into a new clip group. -fn clip_image(d: &mut Document, id: NodeId, (frame, room): Clip) -> Result<()> { - let path = shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame); +fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { + let path = clip_shape(clip); let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind { NodeKind::Group { children, clip: true } => match &children[..] { [c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id), @@ -602,14 +763,33 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ let path = fileio::document_path(path, doc_path).map_err(|r| EngineError::Other(format!("the image `{path}` isn't followed: {r}")))?; let bytes = read_file(&path)?; let read = (link_info(&path, &bytes), linked_image(&bytes)?); - install(d, &[id], read, Some(Preserve::Bounds)) + install(d, &[id], read, Some(Preserve::Bounds), None) } /// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement -/// Options say (`force`: as that Preserve choice says, whatever they say). -fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option) -> Result<()> { +/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's +/// path and the content shown), so do the images outside the layer tree that show that content. +fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { let new_pt = super::place::pt_per_px(img.ppi); let mut clips = vec![]; + if let Some(also) = also { + // Every image picked shows content `also.1`, so one resolution serves them all. + let old_pt = file_pt(d, also.1); + let pick = |n: &Node| shows(n, also, false); + let mut make = |n: &Node| { + let mut n = n.clone(); + let mut clip = None; + if let NodeKind::Image(im) = &mut n.kind { + let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; + let size = |w: u32, h: u32| (w as f64, h as f64); + let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + clip = c; + } + (n, clip) + }; + Nested { pick: &pick, make: &mut make, next: 0 }.run(d); + } for id in ids { let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue }; let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; @@ -687,16 +867,10 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p match probe(&g, doc_path) { (Status::Missing, _) => out.missing.extend(row), (Status::Modified, Some(mut f)) if update || unread => { - match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, unread.then_some(Preserve::Bounds))) { - Ok(()) => { - // Links with no ids here were not read: they only take the path the file was found at. - if f.path != g.link.path { - moved.push((g.link.clone(), LinkInfo { path: f.path.clone(), ..g.link.clone() })); - } - if !unread { - out.updated.extend(row); - } - } + let force = unread.then_some(Preserve::Bounds); + match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) { + Ok(()) if unread => {} + Ok(()) => out.updated.extend(row), Err(_) => out.missing.extend(row), } } @@ -706,7 +880,7 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open")) } else { None }; match read { Some(Ok(read)) => { - if install_read(d, &g.ids, read, Some(Preserve::Bounds)).is_err() { + if install_read(d, &g.ids, read, Some(Preserve::Bounds), Some(&g)).is_err() { out.missing.extend(row); } } @@ -800,35 +974,31 @@ fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) { } /// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open -/// documents: read again from the new file, each as one Update Links step of its document. +/// documents, in the layers, symbols, graph designs, patterns and opacity masks: read again from +/// the new file, each as one Update Links step of its document. pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) { let path = absolute_path(path); - let targets: Vec<(usize, Vec)> = s + let targets: Vec = s .documents() .iter() .enumerate() .filter(|(_, st)| st.uid != saved) - .filter_map(|(i, st)| { - let mut ids = vec![]; - st.doc.walk(|n| { - if let NodeKind::PlacedDocument(p) = &n.kind - && p.link.path == path - { - ids.push(n.id.0); - } - }); - (!ids.is_empty()).then_some((i, ids)) + .filter(|(_, st)| { + let mut placed = false; + st.doc.visit_placed(|_, p| placed |= p.link.path == path); + placed }) + .map(|(i, _)| i) .collect(); if targets.is_empty() { return; } // Each document is updated as the active one, without switching tools. let back = s.active; - for (i, ids) in targets { + for i in targets { s.active = Some(i); // A file that can't be read leaves what its objects show: links.check reports it. - let _ = update(s, &json!({ "ids": ids })); + let _ = update_where(s, None, Some(&path)); } s.active = back; } @@ -918,24 +1088,32 @@ fn check(s: &mut Session, p: &Value) -> Result { } fn update(s: &mut Session, p: &Value) -> Result { + update_where(s, ids_param(p, "ids"), None) +} + +/// Update Links in the active document of `s` for objects `ids` (default: the linked files that +/// changed or show their preview), or with `path`, for the placed documents of the file at `path` +/// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that +/// show the same content are read again too, and have no ids to report. +fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) -> Result { let st = s.doc()?; - let ids = ids_param(p, "ids"); let (mut reads, mut missing) = (vec![], vec![]); - for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| !g.ids.is_empty()) { + let asked = ids.is_some() || path.is_some(); + for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| path.is_none_or(|p| g.document.is_some() && g.link.path == p)) { match probe(&g, st.path.as_deref()) { (Status::Missing, _) | (_, None) => missing.extend(ids_json(&g.ids)), - // Unchanged and showing the file: nothing to read unless asked for by id. - (Status::Ok, Some(_)) if ids.is_none() && !stale(&st.doc, &g) => {} + // Unchanged and showing the file: nothing to read unless asked for. + (Status::Ok, Some(_)) if !asked && !stale(&st.doc, &g) => {} // Unreadable as an image (or a document) counts as missing. (_, Some(mut f)) => match read_for(&mut f, &g, "links.update") { - Ok(read) => reads.push((g.ids, read)), + Ok(read) => reads.push((g, read)), Err(_) => missing.extend(ids_json(&g.ids)), }, } } - let updated: Vec = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect(); + let updated: Vec = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect(); if !reads.is_empty() { - s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, None)))?; + s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?; } Ok(json!({ "updated": updated, "missing": missing })) } @@ -1053,7 +1231,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { } let relinked: Vec = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect(); if !reads.is_empty() { - s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve)))?; + s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?; } not_found.sort(); not_found.dedup(); @@ -1312,7 +1490,7 @@ fn embed(s: &mut Session, p: &Value) -> Result { if !done.is_empty() || !documents.is_empty() { s.edit("Embed", |d, _| { for (ids, read) in reads { - install(d, &ids, read, Some(Preserve::Bounds))?; + install(d, &ids, read, Some(Preserve::Bounds), None)?; } for id in &done { if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) { @@ -1369,7 +1547,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { let img = linked_image(&bytes)?; write_file(&path, &bytes)?; let read = (link_info(&path, &bytes), img); - s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds)))?; + s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?; Ok(json!({ "id": id.0, "path": path })) } diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 1eeb1ac14d..07db9e0095 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -311,8 +311,8 @@ fn links_outside_the_layers_find_their_files_after_the_folder_moves() { } /// With Update Links: Automatically, a file in a symbol and in the layers that changed and moved -/// with the document is read again for the layers' image, and the symbol's link takes its new path -/// too. +/// with the document is read again for the layers' image and for the symbol's, and both links take +/// its new path, size and hash. #[test] fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { let a = Folder::new("nested-modified-a"); @@ -331,9 +331,72 @@ fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { let r = open(&mut s, &b.file("poster.vectorcraft")); assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}"); let moved = PathBuf::from(b.file("art/photo.png")); - let mut paths = vec![]; - s.doc().unwrap().doc.visit_images(|_, im| paths.extend(im.link.as_ref().map(|l| PathBuf::from(&l.path)))); - assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's"); + let blue = png(30, 30, BLUE); + let mut images = vec![]; + s.doc().unwrap().doc.visit_images(|_, im| { + let l = im.link.as_ref().unwrap(); + images.push((PathBuf::from(&l.path), l.size, l.hash.clone(), im.width, im.height, im.key.clone())); + }); + let key = image(&s, id).key; + let new = (moved, Some(blue.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&blue)), 30, 30, key); + assert_eq!(images, [new.clone(), new], "the layers' image, then the symbol's"); +} + +/// Update Links reads a changed file again for the images inside symbols, patterns and opacity +/// masks too: those showing the same content as an image in the layers, and those no object in the +/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step. +#[test] +fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { + let dir = Folder::new("nested-update"); + let (photo, logo) = (dir.file("photo.png"), dir.file("logo.png")); + write(&photo, &png(20, 10, RED)); + write(&logo, &png(20, 10, [200, 200, 20])); + let mut s = session(); + // photo.png in the layers, and in a symbol filling its bounds, clipped to them. + let id = place(&mut s, &photo); + s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let id = place(&mut s, &photo); + // logo.png only in a pattern and in an opacity mask. + let p = place(&mut s, &logo); + s.execute("object.pattern.make", &json!({"ids": [p.0], "edit": false})).unwrap(); + s.execute("edit.clear", &json!({"ids": [p.0]})).unwrap(); + let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); + let mask = place(&mut s, &logo); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); + // photo.png wider than the symbol's image is: filling its bounds overflows them. + let (blue, green) = (png(60, 20, BLUE), png(40, 20, [20, 200, 20])); + write(&photo, &blue); + write(&logo, &green); + let u = s.execute("links.update", &json!({})).unwrap(); + assert_eq!(u, json!({"updated": [id.0], "missing": []})); + // (name, size, hash, pixel size) of each image, which shows its file's pixels. + let images = |s: &Session| { + let d = &s.doc().unwrap().doc; + let mut out = vec![]; + d.visit_images(|_, im| { + let l = im.link.as_ref().unwrap(); + assert!(!d.images[&im.key].is_proxy(), "{} shows its preview", l.name()); + out.push((l.name().to_string(), l.size, l.hash.clone(), (im.width, im.height))); + }); + out.sort(); + out + }; + let shown = |name: &str, bytes: &[u8], size| (name.to_string(), Some(bytes.len() as u64), Some(vectorcraft_doc::links::hash_bytes(bytes)), size); + let logo_now = shown("logo.png", &green, (40, 20)); + let photo_now = shown("photo.png", &blue, (60, 20)); + assert_eq!(images(&s), [logo_now.clone(), logo_now, photo_now.clone(), photo_now]); + // The symbol's image is clipped to its old bounds. + let mut clipped = false; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| { + if let NodeKind::Group { children, clip: true } = &n.kind { + clipped |= + matches!(&children[..], [c, im] if matches!(c.kind, NodeKind::Path { clipping: true, .. }) && matches!(im.kind, NodeKind::Image(_))); + } + }); + assert!(clipped, "{:?}", s.doc().unwrap().doc.symbols[0].art); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s)); } #[test] diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 743f814946..e3e85d229e 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -891,6 +891,36 @@ fn saving_a_document_refreshes_the_open_documents_that_place_it() { assert_eq!(s.active_index(), Some(child), "the saved document stays active"); } +/// Placed documents inside a symbol and a pattern of another open document are read again when +/// their file is saved, as one in the layers is. +#[test] +fn saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns() { + let dir = Folder::new("placed-refresh-nested"); + let src = dir.file("logo.vectorcraft"); + source(&src, 100.0, 50.0, RED, 0); + let mut s = session(); + let id = place(&mut s, &src); + s.execute("symbol.new", &json!({"name": "Logo", "ids": [id.0]})).unwrap(); + let id = place(&mut s, &src); + s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let parent = s.active_index().unwrap(); + let mut in_layers = 0; + s.doc().unwrap().doc.walk(|n| in_layers += usize::from(matches!(n.kind, NodeKind::PlacedDocument(_)))); + assert_eq!(in_layers, 0, "no placed document in the layers"); + s.execute("document.open", &json!({"path": src})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#1414e6"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + let hash = Some(vectorcraft_doc::links::hash_bytes(&std::fs::read(&src).unwrap())); + let doc = &s.documents()[parent]; + assert_eq!(doc.history.undo.last().unwrap().label, "Update Links"); + assert!(near(centre_colour(&doc.doc), BLUE), "the symbol's instance shows the saved version"); + let mut hashes = vec![]; + doc.doc.visit_placed(|_, p| hashes.push(p.link.hash.clone())); + assert_eq!(hashes, [hash.clone(), hash], "the symbol's, then the pattern's"); +} + #[test] fn link_info_gives_the_artboards_size_not_pixels() { let dir = Folder::new("placed-info"); diff --git a/docs/mcp.md b/docs/mcp.md index 9ec05bd8d7..65a537dddc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4337,7 +4337,11 @@ The result lists `missingLinks` path isn't followed) when it isn't. The desktop app also checks the active document's links when its window comes back to the front, following the same preference. `links.check` reports every link's `status` (`ok`, `modified`, `missing`), `links.update {ids?}` reads modified files again and `links.relink {ids?, path | folder}` points images at -another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. A PNG, JPEG, +another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. +`links.update`, and `document.open` when it reads a modified file, also read the file again for the images and placed +documents inside symbols, graph designs, patterns and opacity masks that show the same content (by default also for +those that only that art shows); they have no ids, so the results do not list them. Saving a document also reads it +again for the placed documents of it inside that art in the other open documents. A PNG, JPEG, GIF or WebP file whose pixels can't be read is not shown: `links.relink` fails with "the image's pixels can't be read", and `links.update`, or `document.open` when it reads the file, lists it as missing, its images keeping what they showed. Without a file system (the web), linked images show their previews. A link whose path has a colon and no `/` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fcc2e558b1..b91dcb3fd8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1334,7 +1334,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On the desktop with Enable Background Export on (Preferences › File Handling), File › Package… collects the linked files and fonts and writes the package from the document as it was at OK on the thread that writes background saves and exports, with "Packaging" in the status bar and the busy spinner until it is written; a save of unsaved changes that Package starts is written first. `file.package` over MCP and scripts replies as before. - On the desktop with Enable Background Export on, Export for Screens and the Asset Export panel's Export encode and write their files (into the folder, or one ZIP in it) from the document as it was at OK on the thread that writes background saves and exports, with "Exporting" in the status bar and the export progress dialog, which counts the files and whose Cancel stops before the next file. `document.exportForScreens` and `assets.export` over MCP and scripts reply as before. - Missing linked files can be looked for in a folder and its subfolders: Find in Folder… in the Linked File Not Found dialog and in the Links panel menu lists the files with each one's name, those with the size and contents saved with the link first, and relinks the files chosen, copying an image's file into the document's folder when asked, without replacing a file there (`links.findFiles`, `links.relink {copy}`). In the Links panel it looks for the selected linked files when any are selected. - - Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`. + - Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Update Links, and opening with Update Links: Automatically, read a modified file again for that art too, and saving a document refreshes its placed copies inside symbols and patterns of the other open documents. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`, `update_links_reads_files_again_inside_symbols_patterns_and_masks`, `saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns`. - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. - On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed. - In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one.