mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 10:07:27 +00:00
Merge pull request #7040 from dotCooCoo/fix/nested-link-ids
Links: list and manage linked art in symbols, graph designs, patterns and masks by id
This commit is contained in:
@@ -13,7 +13,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::findfiles::{self, Limits, Visitor};
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd};
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param};
|
||||
|
||||
/// The most linked files one search looks for.
|
||||
const MAX_LINKS: usize = 1_000;
|
||||
@@ -143,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = match p.get("ids") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => {
|
||||
let ids = checked_ids_param(s, p, "ids", C)?;
|
||||
let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
|
||||
// Images and placed documents in opacity-mask art and in the art of symbols, graph
|
||||
// designs and patterns are named by their ids too (`links.list`).
|
||||
let ids = ids_param(p, "ids", C)?.unwrap_or_default();
|
||||
let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind);
|
||||
if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) {
|
||||
return Err(bad(C, format!("no such object id {value}")));
|
||||
}
|
||||
let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
|
||||
if let Some(id) = ids.iter().find(|id| !linkable(id)) {
|
||||
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
|
||||
}
|
||||
|
||||
+141
-72
@@ -30,6 +30,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
|
||||
StoredPlace, StoredRoot,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
|
||||
@@ -43,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Check Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
@@ -52,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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. 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], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
"{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. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -70,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Relink",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
@@ -79,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Links",
|
||||
[],
|
||||
None,
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -88,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Go To Link",
|
||||
[],
|
||||
None,
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}",
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
|
||||
has_doc,
|
||||
go_to
|
||||
),
|
||||
@@ -156,7 +157,8 @@ impl Status {
|
||||
struct Group {
|
||||
link: LinkInfo,
|
||||
key: String,
|
||||
/// The objects in the layers (images in symbols and patterns share the content, not an id).
|
||||
/// The stored objects showing it: in the layers, in opacity-mask art and in the art of symbols,
|
||||
/// graph designs and patterns ([`Document::visit_stored`]), each once.
|
||||
ids: Vec<NodeId>,
|
||||
/// Placed documents: what they show.
|
||||
document: Option<Shown>,
|
||||
@@ -177,8 +179,9 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option<Shown>)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]): an
|
||||
/// image placed from a DCS file has its plate files of their own too, beside its file.
|
||||
/// Every linked file of `d` with the ids of the objects showing it, wherever they are stored (for
|
||||
/// [`crate::link_watch`]): an image placed from a DCS file has its plate files of their own too,
|
||||
/// beside its file.
|
||||
pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
|
||||
let mut out = vec![];
|
||||
for g in groups(d, None).into_iter().filter(|g| !g.ids.is_empty()) {
|
||||
@@ -190,8 +193,10 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when
|
||||
/// given), then, without `ids`, the ones only symbols and patterns show.
|
||||
/// The linked images and placed documents of `d` by file and content, wherever they are stored
|
||||
/// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object
|
||||
/// visited before it has (art being edited on a layer and its definition) counts once, by its
|
||||
/// first place; without `ids` its content is still grouped.
|
||||
fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
|
||||
let mut out: Vec<Group> = vec![];
|
||||
let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new();
|
||||
@@ -210,24 +215,48 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
|
||||
g.ids.push(id);
|
||||
}
|
||||
};
|
||||
d.walk(|n| {
|
||||
if let Some((l, key, document)) = linked(n)
|
||||
&& wanted.as_ref().is_none_or(|ids| ids.contains(&n.id))
|
||||
{
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
d.visit_stored(|n, _| {
|
||||
let Some((l, key, document)) = linked(n) else { return };
|
||||
// Id 0 names no object.
|
||||
let first = n.id.0 != 0 && seen.insert(n.id);
|
||||
if first && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) {
|
||||
add(l, key, document, Some(n.id));
|
||||
} else if ids.is_none() {
|
||||
add(l, key, document, None);
|
||||
}
|
||||
});
|
||||
if ids.is_none() {
|
||||
d.visit_images(|_, im| {
|
||||
if let Some(l) = &im.link {
|
||||
add(l, &im.key, None, None);
|
||||
}
|
||||
});
|
||||
d.visit_placed(|_, p| add(&p.link, &p.key, Some((p.bounding, p.page_box)), None));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Stored object `id` of `d` ([`Document::stored_node`]).
|
||||
fn stored(d: &Document, id: NodeId) -> Option<&Node> {
|
||||
d.stored_node(id).map(|(n, _)| &**n)
|
||||
}
|
||||
|
||||
/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none).
|
||||
fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
ids.iter().copied().filter(|id| d.node(*id).is_none()).collect()
|
||||
}
|
||||
|
||||
/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree
|
||||
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`.
|
||||
fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
|
||||
if place.in_layers() {
|
||||
return None;
|
||||
}
|
||||
let mut owner = match place.root {
|
||||
StoredRoot::Layer(_) => json!({ "kind": "layers" }),
|
||||
StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }),
|
||||
StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }),
|
||||
StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }),
|
||||
};
|
||||
if let Some(m) = place.mask_of {
|
||||
owner["maskOf"] = json!(m.0);
|
||||
}
|
||||
Some(owner)
|
||||
}
|
||||
|
||||
/// A linked file where it was found.
|
||||
struct Found {
|
||||
path: String,
|
||||
@@ -493,8 +522,8 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
|
||||
}
|
||||
|
||||
/// The linked files of the open document `st` that `links.findFiles` looks for, each with the
|
||||
/// objects in the layers that show it: the files of objects `ids` whatever their status, else the
|
||||
/// files that can't be found.
|
||||
/// stored objects that show it: the files of objects `ids` whatever their status, else the files
|
||||
/// that can't be found.
|
||||
pub(crate) fn files_to_find(st: &crate::DocState, ids: Option<&[NodeId]>) -> Vec<(LinkInfo, Vec<NodeId>)> {
|
||||
groups(&st.doc, ids)
|
||||
.into_iter()
|
||||
@@ -708,7 +737,7 @@ fn clip_to(
|
||||
type Remake<'a> = dyn FnMut(&Node, Option<(&PathData, FillRule)>) -> (Node, ClipTo) + 'a;
|
||||
|
||||
/// 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.
|
||||
/// opacity masks, where [`Document::node`] does not find them) that `pick` holds for.
|
||||
struct Nested<'a> {
|
||||
pick: &'a dyn Fn(&Node) -> bool,
|
||||
make: &'a mut Remake<'a>,
|
||||
@@ -854,10 +883,10 @@ impl Nested<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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); with `also`
|
||||
/// (a file's path and the content shown), so do the placed documents outside the layer tree that
|
||||
/// show that content.
|
||||
/// Placed documents `ids` (in the layers or outside them) 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); 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],
|
||||
@@ -872,8 +901,10 @@ fn install_document(
|
||||
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 nested = nested_ids(d, ids);
|
||||
if also.is_some() || !nested.is_empty() {
|
||||
let pick =
|
||||
|n: &Node| matches!(n.kind, NodeKind::PlacedDocument(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, true)));
|
||||
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
@@ -1037,26 +1068,39 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
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); with `also` (a file's
|
||||
/// path and the content shown), so do the images outside the layer tree that show that content.
|
||||
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
|
||||
/// placed as its 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 images outside the layer tree that
|
||||
/// show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, 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);
|
||||
// The clipping path the old content's DCS file drew it through.
|
||||
let old_clip = d.images.get(also.1).and_then(ImageBlob::separated_clip);
|
||||
let nested = nested_ids(d, ids);
|
||||
if also.is_some() || !nested.is_empty() {
|
||||
let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false)));
|
||||
// The resolution of each content the images picked show, and the clipping path its DCS file
|
||||
// drew it through, looked up once each.
|
||||
let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new();
|
||||
d.visit_stored(|n, _| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& pick(n)
|
||||
&& !old.contains_key(&im.key)
|
||||
{
|
||||
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip)));
|
||||
}
|
||||
});
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
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 (old_pt, old_clip) = match old.get(&im.key) {
|
||||
Some((pt, clip)) => (*pt, clip.as_ref()),
|
||||
None => (super::place::pt_per_px(None), None),
|
||||
};
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
clip = clip_to(im.xf, old_clip.as_ref(), c, &img, xf, held);
|
||||
clip = clip_to(im.xf, old_clip, c, &img, xf, held);
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
}
|
||||
(n, clip)
|
||||
@@ -1267,7 +1311,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
|
||||
}
|
||||
}
|
||||
// The objects in symbols, graph designs, patterns and opacity masks that show the same file and
|
||||
// content, which have no ids here, whatever else their links hold.
|
||||
// content, whatever else their links hold, those whose id an earlier object has included.
|
||||
if !moved.is_empty() {
|
||||
let mut by_path: BTreeMap<String, Vec<(String, bool, LinkInfo)>> = BTreeMap::new();
|
||||
for (path, key, document, new) in moved {
|
||||
@@ -1302,13 +1346,25 @@ fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked image objects (or placed documents) `ids` link to `link`.
|
||||
/// Linked image objects (or placed documents) `ids`, in the layers or outside them, link to `link`.
|
||||
fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
|
||||
for id in ids {
|
||||
let nested = nested_ids(d, ids);
|
||||
for id in ids.iter().filter(|id| !nested.contains(id)) {
|
||||
if let Some(l) = d.node_mut(*id).and_then(link_mut) {
|
||||
*l = link.clone();
|
||||
}
|
||||
}
|
||||
if !nested.is_empty() {
|
||||
let pick = |n: &Node| nested.contains(&n.id) && linked(n).is_some();
|
||||
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
|
||||
let mut out = n.clone();
|
||||
if let Some(l) = link_mut(&mut out) {
|
||||
*l = link.clone();
|
||||
}
|
||||
(out, ClipTo::Keep)
|
||||
};
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
|
||||
@@ -1540,7 +1596,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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.
|
||||
/// show the same content are read again too.
|
||||
fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (mut reads, mut missing) = (vec![], vec![]);
|
||||
@@ -1606,7 +1662,7 @@ enum Scope {
|
||||
Each,
|
||||
/// The objects given or selected.
|
||||
Selected,
|
||||
/// Every object in the layers linked to the same file as one given or selected.
|
||||
/// Every stored object linked to the same file as one given or selected.
|
||||
All,
|
||||
/// The objects given or selected, then every other missing link whose file name is in the new
|
||||
/// file's folder.
|
||||
@@ -1690,7 +1746,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// An image or a placed document, with its link.
|
||||
let image = |id: &NodeId| {
|
||||
st.doc.node(*id).and_then(|n| match &n.kind {
|
||||
stored(&st.doc, *id).and_then(|n| match &n.kind {
|
||||
NodeKind::Image(im) => Some(im.link.as_ref()),
|
||||
NodeKind::PlacedDocument(p) => Some(Some(&p.link)),
|
||||
_ => None,
|
||||
@@ -1715,22 +1771,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// All Instances: the other objects in the layers linked to the same files.
|
||||
// All Instances: the other stored objects linked to the same files, each once.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut more = vec![];
|
||||
st.doc.walk(|n| {
|
||||
st.doc.visit_stored(|n, _| {
|
||||
if let Some((l, _, _)) = linked(n)
|
||||
&& paths.contains(l.path.as_str())
|
||||
&& !given.contains(&n.id)
|
||||
&& n.id.0 != 0
|
||||
&& given.insert(n.id)
|
||||
{
|
||||
more.push(n.id);
|
||||
}
|
||||
});
|
||||
ids.extend(more);
|
||||
}
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
|
||||
}
|
||||
// (ids, the file) per file to read.
|
||||
@@ -1766,7 +1823,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut images = vec![];
|
||||
let mut documents: Vec<((u32, bool, PageBox), Vec<NodeId>)> = vec![];
|
||||
for id in ids {
|
||||
match st.doc.node(id).map(|n| &n.kind) {
|
||||
match stored(&st.doc, id).map(|n| &n.kind) {
|
||||
Some(NodeKind::PlacedDocument(pl)) => {
|
||||
let k = (pl.page(), pl.bounding, pl.page_box);
|
||||
match documents.iter_mut().find(|(e, _)| *e == k) {
|
||||
@@ -1916,9 +1973,9 @@ fn copy_into_folder(_: &str, _: &[u8], _: &Path) -> Result<(String, bool)> {
|
||||
|
||||
// ---------- the Links panel ----------
|
||||
|
||||
/// Image object `id` of `d`.
|
||||
/// Image object `id` of `d`, wherever it is stored.
|
||||
fn image_of(d: &Document, id: NodeId) -> Option<&ImageObject> {
|
||||
match &d.node(id)?.kind {
|
||||
match &stored(d, id)?.kind {
|
||||
NodeKind::Image(im) => Some(im),
|
||||
_ => None,
|
||||
}
|
||||
@@ -1936,7 +1993,7 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match image_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image", id.0))),
|
||||
}
|
||||
}
|
||||
@@ -1950,9 +2007,9 @@ fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Placement Options of image or placed document `id` of `d`.
|
||||
/// The Placement Options of image or placed document `id` of `d`, wherever it is stored.
|
||||
fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
|
||||
match &d.node(id)?.kind {
|
||||
match &stored(d, id)?.kind {
|
||||
NodeKind::Image(im) => Some(im.placement),
|
||||
NodeKind::PlacedDocument(p) => Some(p.placement),
|
||||
_ => None,
|
||||
@@ -1965,12 +2022,12 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match placement_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
|
||||
/// Per linked image or placed document of `st`, wherever it is stored: its file's status, where it was found when away from
|
||||
/// its path, and whether the image shows its preview (each file probed once).
|
||||
pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
|
||||
let mut out = BTreeMap::new();
|
||||
@@ -2071,17 +2128,20 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
|
||||
let statuses = statuses(st);
|
||||
let mut objects = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
|
||||
objects.push(n);
|
||||
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
|
||||
// order they are stored (opacity-mask art, symbols, graph designs, patterns), each once.
|
||||
let (mut objects, mut nested) = (vec![], vec![]);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
st.doc.visit_stored(|n, place| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) {
|
||||
if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) }
|
||||
}
|
||||
});
|
||||
// Top first, as the Layers panel lists them.
|
||||
objects.reverse();
|
||||
objects.extend(nested);
|
||||
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
let mut rows = vec![];
|
||||
for n in objects {
|
||||
for (n, place) in objects {
|
||||
let (status, found, preview) = match statuses.get(&n.id) {
|
||||
Some((s, f, p)) => (s.as_str(), f.as_deref(), *p),
|
||||
None => ("embedded", None, false),
|
||||
@@ -2124,6 +2184,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if preview {
|
||||
row["preview"] = json!(true);
|
||||
}
|
||||
if let Some(owner) = owner_json(&st.doc, place) {
|
||||
row["owner"] = owner;
|
||||
}
|
||||
if interactions.contains(&n.id) {
|
||||
row["dcsTransparency"] = json!(true);
|
||||
}
|
||||
@@ -2144,15 +2207,21 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id = linked_param(st, p, "links.goTo")?;
|
||||
// An object in mask art or a definition has no place of its own on the canvas: the selection
|
||||
// is cleared, and the reply names what holds it.
|
||||
if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) {
|
||||
s.select(|_, sel| sel.set([]))?;
|
||||
return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner }));
|
||||
}
|
||||
let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default();
|
||||
s.select(|_, sel| sel.set([id]))?;
|
||||
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] }))
|
||||
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1], "onCanvas": true }))
|
||||
}
|
||||
|
||||
fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.embed";
|
||||
let st = s.doc()?;
|
||||
let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind);
|
||||
let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind);
|
||||
let linked = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => im.link.is_some(),
|
||||
Some(NodeKind::PlacedDocument(_)) => true,
|
||||
@@ -2210,7 +2279,7 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
install(d, &ids, read, Some(Preserve::Bounds), None)?;
|
||||
}
|
||||
for id in &done {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
|
||||
im.link = None;
|
||||
}
|
||||
}
|
||||
@@ -2238,7 +2307,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let st = s.doc()?;
|
||||
let id = image_param(st, p, C)?;
|
||||
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
@@ -2324,7 +2393,7 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) {
|
||||
|
||||
/// Link Info of placed document `id`.
|
||||
fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
|
||||
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
|
||||
@@ -2404,7 +2473,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
s.edit("Placement Options", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(o) = d.node_mut(*id).and_then(placement_mut) {
|
||||
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
|
||||
set(o);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -944,7 +944,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, [id]) => *id,
|
||||
_ => return Err(bad(C, "select one image or pass id")),
|
||||
};
|
||||
let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
// An image in opacity-mask art or a definition's art is found by its id too (`links.list`).
|
||||
let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
|
||||
let [a, b, c, d, ..] = im.xf.as_coeffs();
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::unique_name;
|
||||
|
||||
@@ -118,11 +118,12 @@ impl Used {
|
||||
type Renames = BTreeMap<String, (Option<String>, bool)>;
|
||||
|
||||
/// Names in `dst` for the `used` definitions of `src` (`def`): the same name when `dst` has none
|
||||
/// (copied) or an equal one (shared), else a free variant (`taken`, copied).
|
||||
fn names<T: PartialEq>(
|
||||
/// (copied) or one that is the `same` (shared), else a free variant (`taken`, copied).
|
||||
fn names<T>(
|
||||
used: &[String],
|
||||
def: impl Fn(&str) -> Option<T>,
|
||||
existing: impl Fn(&str) -> Option<T>,
|
||||
same: impl Fn(&T, &T) -> bool,
|
||||
taken: impl Fn(&str) -> bool,
|
||||
) -> Renames {
|
||||
let mut out = Renames::new();
|
||||
@@ -130,7 +131,7 @@ fn names<T: PartialEq>(
|
||||
let Some(d) = def(name) else { continue };
|
||||
let entry = match existing(name) {
|
||||
None => (Some(name.clone()), true),
|
||||
Some(e) if e == d => (Some(name.clone()), false),
|
||||
Some(e) if same(&e, &d) => (Some(name.clone()), false),
|
||||
Some(_) => {
|
||||
(Some(unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || out.values().any(|(n, _)| n.as_deref() == Some(c)))), true)
|
||||
}
|
||||
@@ -140,6 +141,65 @@ fn names<T: PartialEq>(
|
||||
out
|
||||
}
|
||||
|
||||
/// `n` as `dst` would copy it in ([`Document::reid`]), with the ids a document of its own gives it:
|
||||
/// art copied in once, which differs from the file's only in its ids, compares equal to the file's.
|
||||
fn canon(dst: &Document, n: &Node) -> Node {
|
||||
let mut own = Document::new(0.0, 0.0);
|
||||
// Pixels the art carries take a key `dst` doesn't use for other pixels, as they do in `dst`.
|
||||
let mut keys = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind
|
||||
&& im.pixels.is_some()
|
||||
{
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
for (k, blob) in &dst.images {
|
||||
if keys.iter().any(|key| k == key || k.strip_prefix(key.as_str()).is_some_and(|rest| rest.starts_with('-'))) {
|
||||
own.images.insert(k.clone(), blob.clone());
|
||||
}
|
||||
}
|
||||
own.reid(n)
|
||||
}
|
||||
|
||||
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
fn same_symbol(dst: &Document, a: &Symbol, b: &Symbol) -> bool {
|
||||
let own = |s: &Symbol| Symbol { art: Arc::new(canon(dst, &s.art)), ..s.clone() };
|
||||
own(a) == own(b)
|
||||
}
|
||||
|
||||
/// Do patterns `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
fn same_pattern(dst: &Document, a: &PatternDef, b: &PatternDef) -> bool {
|
||||
let bare = |p: &PatternDef| PatternDef { art: vec![], ..p.clone() };
|
||||
bare(a) == bare(b) && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| canon(dst, x) == canon(dst, y))
|
||||
}
|
||||
|
||||
/// Does art `a` use a resource that `m` (images, symbols, patterns, brushes, swatches) gives
|
||||
/// another name, or a swatch whose link `m` drops?
|
||||
fn uses_moved(a: &Node, m: [&Renames; 5]) -> bool {
|
||||
let moved = |map: &Renames, k: &str| map.get(k).is_some_and(|(new, _)| new.as_deref() != Some(k));
|
||||
let (mut a, mut any) = (a.clone(), false);
|
||||
refs(&mut a, &mut |r| {
|
||||
any |= match r {
|
||||
Ref::Image(k) => moved(m[0], k),
|
||||
Ref::Symbol(k) => moved(m[1], k),
|
||||
Ref::Pattern(k) => moved(m[2], k),
|
||||
Ref::Brush(k) => moved(m[3], k),
|
||||
Ref::Swatch(link) => link.as_deref().is_some_and(|k| moved(m[4], k)),
|
||||
}
|
||||
});
|
||||
any
|
||||
}
|
||||
|
||||
/// Copy each of `shared` in `map` under a free name, as [`names`] does for a definition `dst`
|
||||
/// holds differently.
|
||||
fn unshare(map: &mut Renames, shared: &[String], used: &[String], taken: impl Fn(&str) -> bool) {
|
||||
for name in shared {
|
||||
let free = unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || map.values().any(|(n, _)| n.as_deref() == Some(c)));
|
||||
map.insert(name.clone(), (Some(free), true));
|
||||
}
|
||||
}
|
||||
|
||||
/// The renamed resources whose definitions are copied: (name in `src`, name in `dst`).
|
||||
fn copies(m: &Renames) -> Vec<(&str, &str)> {
|
||||
m.iter().filter(|(_, (_, copy))| *copy).filter_map(|(old, (new, _))| Some((old.as_str(), new.as_deref()?))).collect()
|
||||
@@ -194,14 +254,17 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
}
|
||||
}
|
||||
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |c| dst.images.contains_key(c));
|
||||
let symbols = names(
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
|
||||
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
|
||||
// draws: placing the same file again shares what the first placement brought.
|
||||
let mut symbols = names(
|
||||
&used.symbols,
|
||||
|n| src.symbols.iter().find(|s| s.name == n),
|
||||
|n| dst.symbols.iter().find(|s| s.name == n),
|
||||
|a, b| same_symbol(dst, a, b),
|
||||
|c| dst.symbols.iter().any(|s| s.name == c),
|
||||
);
|
||||
let patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |c| dst.pattern(c).is_some());
|
||||
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
|
||||
// A swatch the document defines differently isn't renamed (that would add look-alike swatches):
|
||||
// the colours linked to it keep their look, unlinked.
|
||||
let swatches: Renames = used
|
||||
@@ -236,12 +299,33 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
any
|
||||
};
|
||||
let mut dst_brushes = vectorcraft_brush::library(dst);
|
||||
let brushes = names(
|
||||
let mut brushes = names(
|
||||
&used.brushes,
|
||||
|n| src_brushes.iter().find(|b| b.name == n).map(|b| (b, moves_art(b))),
|
||||
|n| dst_brushes.iter().find(|b| b.name == n).map(|b| (b, false)),
|
||||
|a, b| a == b,
|
||||
|c| dst_brushes.iter().any(|b| b.name == c),
|
||||
);
|
||||
// Likewise a symbol, pattern or brush whose art uses a resource that moves isn't the
|
||||
// document's of that name: it is copied under a free name, which can move what uses it in turn.
|
||||
loop {
|
||||
let maps = [&images, &symbols, &patterns, &brushes, &swatches];
|
||||
let shared = |map: &Renames| map.iter().filter(|(_, (_, copy))| !*copy).map(|(k, _)| k.clone()).collect::<Vec<_>>();
|
||||
let sym: Vec<String> =
|
||||
shared(&symbols).into_iter().filter(|n| src.symbols.iter().any(|s| s.name == *n && uses_moved(&s.art, maps))).collect();
|
||||
let pat: Vec<String> =
|
||||
shared(&patterns).into_iter().filter(|n| src.pattern(n).is_some_and(|p| p.art.iter().any(|a| uses_moved(a, maps)))).collect();
|
||||
let bru: Vec<String> = shared(&brushes)
|
||||
.into_iter()
|
||||
.filter(|n| src_brushes.iter().find(|b| b.name == *n).is_some_and(|b| brush_art(&mut b.clone()).into_iter().any(|a| uses_moved(a, maps))))
|
||||
.collect();
|
||||
if sym.is_empty() && pat.is_empty() && bru.is_empty() {
|
||||
break;
|
||||
}
|
||||
unshare(&mut symbols, &sym, &used.symbols, |c| dst.symbols.iter().any(|s| s.name == c));
|
||||
unshare(&mut patterns, &pat, &used.patterns, |c| dst.pattern(c).is_some());
|
||||
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
|
||||
}
|
||||
|
||||
let mut rename = |r: Ref| {
|
||||
let (map, k) = match r {
|
||||
@@ -272,6 +356,8 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
|
||||
def.name = new.to_string();
|
||||
refs(Arc::make_mut(&mut def.art), &mut rename);
|
||||
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
|
||||
def.art = Arc::new(dst.reid(&def.art));
|
||||
dst.symbols.push(def);
|
||||
}
|
||||
}
|
||||
@@ -280,6 +366,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
def.name = new.to_string();
|
||||
for a in &mut def.art {
|
||||
refs(Arc::make_mut(a), &mut rename);
|
||||
*a = Arc::new(dst.reid(a));
|
||||
}
|
||||
dst.patterns.push(def);
|
||||
}
|
||||
|
||||
@@ -378,8 +378,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
|
||||
/// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file
|
||||
/// without Link gives (its resources joining `d`, renamed where `d` uses a name for something
|
||||
/// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand.
|
||||
/// A placed document in opacity-mask art or in the art of a symbol, graph design or pattern is
|
||||
/// replaced where it is stored.
|
||||
pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let n = d.stored_node(id).map(|(n, _)| Node::clone(n)).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) };
|
||||
let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?;
|
||||
let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob)
|
||||
@@ -395,6 +397,10 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m);
|
||||
let mut out = n.clone();
|
||||
out.kind = art.kind;
|
||||
if d.node(id).is_none() {
|
||||
*d.stored_node_mut(id).ok_or(EngineError::NoNode(id))? = out;
|
||||
return Ok(());
|
||||
}
|
||||
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
d.remove(id)?;
|
||||
d.insert(par, index, out)?;
|
||||
|
||||
@@ -326,6 +326,31 @@ fn update_link_takes_the_files_clipping_path_into_symbols_too() {
|
||||
assert_eq!(symbol_clip_width(&s, "Pic"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_and_relink_by_id_keep_the_clipping_path_of_a_dcs_image_in_a_symbol() {
|
||||
let dir = temp_dir("symbol-clip-by-id");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
|
||||
s.execute("symbol.new", &json!({ "name": "Pic", "ids": [r["ids"][0]] })).unwrap();
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image is listed");
|
||||
let id = row["id"].as_u64().unwrap();
|
||||
assert_eq!(row["format"], "DCS", "{list}");
|
||||
let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path");
|
||||
// The composite now drawn through the left quarter of the page (same length).
|
||||
let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1);
|
||||
std::fs::write(&path, text.as_bytes()).unwrap();
|
||||
assert_eq!(s.execute("links.update", &json!({ "ids": [id] })).unwrap()["updated"], json!([id]));
|
||||
let after = symbol_clip_width(&s, "Pic").expect("still clipped");
|
||||
assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}");
|
||||
// Relinked by its id to a plain image: the DCS file's clipping path goes.
|
||||
let png = dir.join("plain.png");
|
||||
image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap();
|
||||
s.execute("links.relink", &json!({ "ids": [id], "path": png.to_string_lossy() })).unwrap();
|
||||
assert_eq!(symbol_clip_width(&s, "Pic"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_lost_its_clipping_path_unclips_the_image() {
|
||||
let dir = temp_dir("update-lost-clip");
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind};
|
||||
use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind, StoredRoot};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
@@ -446,8 +446,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 for the symbol's, and both links take
|
||||
/// its new path, size and hash.
|
||||
/// with the document is read again for the layers' image and for the symbol's, both are listed by
|
||||
/// their ids, 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");
|
||||
@@ -458,13 +458,14 @@ fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() {
|
||||
s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap();
|
||||
let id = place(&mut s, &pic);
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
|
||||
let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0));
|
||||
let id = place(&mut s, &pic);
|
||||
save(&mut s, &a.file("poster.vectorcraft"));
|
||||
write(&pic, &png(30, 30, BLUE));
|
||||
std::fs::remove_dir_all(&b.0).unwrap();
|
||||
std::fs::rename(&a.0, &b.0).unwrap();
|
||||
let r = open(&mut s, &b.file("poster.vectorcraft"));
|
||||
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}");
|
||||
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0, in_symbol.0])), "{r}");
|
||||
let moved = PathBuf::from(b.file("art/photo.png"));
|
||||
let blue = png(30, 30, BLUE);
|
||||
let mut images = vec![];
|
||||
@@ -521,7 +522,8 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
|
||||
|
||||
/// 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.
|
||||
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
|
||||
/// and the reply lists each by its id.
|
||||
#[test]
|
||||
fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
let dir = Folder::new("nested-update");
|
||||
@@ -533,11 +535,13 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
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 in_symbol = stored_image_in(&s, StoredRoot::Symbol(0));
|
||||
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 p = stored_image_in(&s, StoredRoot::Pattern { pattern: 0, art: 0 });
|
||||
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();
|
||||
@@ -546,7 +550,8 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
write(&photo, &blue);
|
||||
write(&logo, &green);
|
||||
let u = s.execute("links.update", &json!({})).unwrap();
|
||||
assert_eq!(u, json!({"updated": [id.0], "missing": []}));
|
||||
// By file: photo.png in the layers and the symbol, then logo.png in the mask and the pattern.
|
||||
assert_eq!(u, json!({"updated": [id.0, in_symbol.0, mask.0, p.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;
|
||||
@@ -576,6 +581,193 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s));
|
||||
}
|
||||
|
||||
/// The files only art outside the layers shows: one in a symbol, a graph design, a pattern and an
|
||||
/// opacity mask each, no object in the layers linked to any of them.
|
||||
const NESTED: [&str; 4] = ["symbol.png", "design.png", "pattern.png", "mask.png"];
|
||||
|
||||
/// A document whose only links are [`NESTED`]'s files in `dir`.
|
||||
fn nested_links(dir: &Folder) -> Session {
|
||||
for (i, name) in (0u8..).zip(NESTED) {
|
||||
write(&dir.file(name), &png(20, 10, [20 + 50 * i, 90, 160]));
|
||||
}
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &dir.file("symbol.png"));
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [s.doc().unwrap().selection.objects[0].0]})).unwrap();
|
||||
let id = place(&mut s, &dir.file("design.png"));
|
||||
s.execute("graph.design", &json!({"new": "Bar"})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
let id = place(&mut s, &dir.file("pattern.png"));
|
||||
s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
|
||||
let mask = place(&mut s, &dir.file("mask.png"));
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The id of the `links.list` row of file `name`.
|
||||
fn row_id(s: &mut Session, name: &str) -> u64 {
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name).unwrap_or_else(|| panic!("{name} in {list}"));
|
||||
row["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// The link of stored object `id`.
|
||||
fn stored_link(s: &Session, id: u64) -> Option<LinkInfo> {
|
||||
match &s.doc().unwrap().doc.stored_node(NodeId(id)).unwrap().0.kind {
|
||||
NodeKind::Image(im) => im.link.clone(),
|
||||
k => panic!("not an image: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of the first image stored in the art of `root`.
|
||||
fn stored_image_in(s: &Session, root: StoredRoot) -> NodeId {
|
||||
let mut found = None;
|
||||
s.doc().unwrap().doc.visit_stored(|n, place| {
|
||||
if found.is_none() && place.root == root && matches!(n.kind, NodeKind::Image(_)) {
|
||||
found = Some(n.id);
|
||||
}
|
||||
});
|
||||
found.unwrap_or_else(|| panic!("no image in {root:?}"))
|
||||
}
|
||||
|
||||
/// Images in symbols, graph designs, patterns and opacity masks are listed and checked with ids of
|
||||
/// their own, one row each with what holds it, and the missing filter counts them.
|
||||
#[test]
|
||||
fn links_outside_the_layers_are_listed_and_checked_with_ids() {
|
||||
let dir = Folder::new("nested-ids");
|
||||
let mut s = nested_links(&dir);
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let rows = list["links"].as_array().unwrap();
|
||||
let owners: Vec<(&str, &str)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), r["owner"]["kind"].as_str().unwrap_or("-"))).collect();
|
||||
assert_eq!(owners, [("mask.png", "layers"), ("symbol.png", "symbol"), ("design.png", "graphDesign"), ("pattern.png", "pattern")], "{list}");
|
||||
assert_eq!(rows[1]["owner"]["name"], "Mark");
|
||||
let masked = s.doc().unwrap().doc.layers[0].children().unwrap().iter().find(|n| n.extras().mask.is_some()).unwrap().id;
|
||||
assert_eq!(rows[0]["owner"]["maskOf"], json!(masked.0));
|
||||
let ids: std::collections::BTreeSet<u64> = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect();
|
||||
assert_eq!(ids.len(), 4, "{list}");
|
||||
assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}");
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
let checked: Vec<(&str, &Value)> = check["links"].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap(), &l["ids"])).collect();
|
||||
assert_eq!(checked.len(), 4, "{check}");
|
||||
for (name, ids) in checked {
|
||||
assert_eq!(*ids, json!([row_id(&mut s, name)]), "{check}");
|
||||
}
|
||||
std::fs::remove_file(dir.file("design.png")).unwrap();
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
assert_eq!((check["missing"].as_u64(), check["modified"].as_u64()), (Some(1), Some(0)), "{check}");
|
||||
let design = row_id(&mut s, "design.png");
|
||||
let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap();
|
||||
assert_eq!((missing["missing"].as_u64(), &missing["links"][0]["id"]), (Some(1), &json!(design)), "{missing}");
|
||||
let one = s.execute("links.check", &json!({"ids": [design]})).unwrap();
|
||||
assert_eq!(one["links"][0]["status"], "missing", "{one}");
|
||||
}
|
||||
|
||||
/// Every links command takes the id of an image outside the layers and acts on that object: Link
|
||||
/// Info, Go To (which clears the selection and names the symbol), Placement Options, Relink, Update and
|
||||
/// Embed.
|
||||
#[test]
|
||||
fn links_commands_act_on_images_outside_the_layers_by_id() {
|
||||
let dir = Folder::new("nested-act");
|
||||
let mut s = nested_links(&dir);
|
||||
let symbol = row_id(&mut s, "symbol.png");
|
||||
let info = s.execute("links.info", &json!({"id": symbol})).unwrap();
|
||||
assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("symbol.png"), Some("ok"), Some(symbol)), "{info}");
|
||||
let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0);
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
let go = s.execute("links.goTo", &json!({"id": symbol})).unwrap();
|
||||
assert_eq!(
|
||||
(go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()),
|
||||
(json!(false), json!("symbol"), json!("Mark")),
|
||||
"{go}"
|
||||
);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected");
|
||||
s.execute("links.placementOptions", &json!({"ids": [symbol], "preserve": "fit"})).unwrap();
|
||||
let placement = s.execute("links.placementOptions", &json!({"ids": [symbol]})).unwrap();
|
||||
assert_eq!(placement["placement"]["preserve"], "fit");
|
||||
// Relink: the symbol's image shows the new file.
|
||||
let other = dir.file("other.png");
|
||||
write(&other, &png(40, 20, BLUE));
|
||||
let r = s.execute("links.relink", &json!({"ids": [symbol], "path": other})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([symbol]), "{r}");
|
||||
assert_eq!(stored_link(&s, symbol).unwrap().path, other);
|
||||
// Update: a changed pattern file is read again for the pattern's image.
|
||||
let pattern = row_id(&mut s, "pattern.png");
|
||||
let changed = png(30, 30, RED);
|
||||
write(&dir.file("pattern.png"), &changed);
|
||||
let r = s.execute("links.update", &json!({"ids": [pattern]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([pattern]), "{r}");
|
||||
assert_eq!(stored_link(&s, pattern).unwrap().size, Some(changed.len() as u64));
|
||||
// Embed: the design's image keeps its pixels and no longer links.
|
||||
let design = row_id(&mut s, "design.png");
|
||||
let r = s.execute("links.embed", &json!({"ids": [design]})).unwrap();
|
||||
assert_eq!(r["embedded"], json!([design]), "{r}");
|
||||
assert!(stored_link(&s, design).is_none());
|
||||
let row = s.execute("links.list", &json!({"show": "embedded"})).unwrap();
|
||||
assert_eq!(row["links"][0]["id"], json!(design), "{row}");
|
||||
// Relink All Instances takes the other stored objects linked to the same file.
|
||||
let mask = row_id(&mut s, "mask.png");
|
||||
let r = s.execute("links.relink", &json!({"ids": [symbol], "path": dir.file("mask.png"), "scope": "all"})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([symbol]), "{r}");
|
||||
let r = s.execute("links.relink", &json!({"ids": [mask], "path": other, "scope": "all"})).unwrap();
|
||||
let mut relinked: Vec<u64> = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
relinked.sort();
|
||||
let mut both = vec![symbol, mask];
|
||||
both.sort();
|
||||
assert_eq!(relinked, both, "{r}");
|
||||
}
|
||||
|
||||
/// Opening a document reports missing and modified files that only art outside the layers shows,
|
||||
/// by their objects' ids, and those ids stay the same after the document is saved and opened again.
|
||||
#[test]
|
||||
fn open_reports_links_outside_the_layers_by_id() {
|
||||
let dir = Folder::new("nested-open");
|
||||
let mut s = nested_links(&dir);
|
||||
let path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &path);
|
||||
let ids: Vec<u64> = NESTED.iter().map(|name| row_id(&mut s, name)).collect();
|
||||
std::fs::remove_file(dir.file("symbol.png")).unwrap();
|
||||
write(&dir.file("pattern.png"), &png(30, 30, RED));
|
||||
let r = open(&mut s, &path);
|
||||
let names = |k: &str| r[k].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap().to_string(), l["ids"].clone())).collect::<Vec<_>>();
|
||||
assert_eq!(names("missingLinks"), [("symbol.png".to_string(), json!([ids[0]]))], "{r}");
|
||||
assert_eq!(names("modifiedLinks"), [("pattern.png".to_string(), json!([ids[2]]))], "{r}");
|
||||
let again: Vec<u64> = NESTED.iter().map(|name| row_id(&mut s, name)).collect();
|
||||
assert_eq!(again, ids, "the ids are saved");
|
||||
}
|
||||
|
||||
/// A document whose symbol and mask art repeat the ids of objects in the layers (or have none)
|
||||
/// opens with ids of their own there, the layer tree's kept; the links commands then tell them apart.
|
||||
#[test]
|
||||
fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() {
|
||||
let dir = Folder::new("nested-repeat");
|
||||
let mut s = nested_links(&dir);
|
||||
let layer_image = place(&mut s, &dir.file("symbol.png"));
|
||||
let path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &path);
|
||||
// The symbol's image takes the id of the image in the layers, the mask's image none.
|
||||
let mut saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
saved["document"]["symbols"][0]["art"]["id"] = json!(layer_image.0);
|
||||
let layer = &mut saved["document"]["layers"][0]["kind"]["children"];
|
||||
let masked = layer.as_array_mut().unwrap().iter_mut().find(|n| n.get("mask").is_some() || n["extras"].get("mask").is_some()).unwrap();
|
||||
let mask = if masked.get("mask").is_some() { &mut masked["mask"] } else { &mut masked["extras"]["mask"] };
|
||||
mask["art"]["id"] = json!(0);
|
||||
std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap();
|
||||
open(&mut s, &path);
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let ids: Vec<u64> = list["links"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect();
|
||||
let unique: std::collections::BTreeSet<u64> = ids.iter().copied().collect();
|
||||
assert_eq!((ids.len(), unique.len()), (5, 5), "{list}");
|
||||
assert!(!ids.contains(&0), "{list}");
|
||||
assert_eq!(list["links"][0]["id"], json!(layer_image.0), "the layer tree keeps its ids: {list}");
|
||||
let symbol = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("links.embed", &json!({"ids": [symbol]})).unwrap();
|
||||
assert!(stored_link(&s, symbol).is_none());
|
||||
assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked");
|
||||
}
|
||||
|
||||
/// An image that Placement Options clip, alone in a group the user made, goes into a new clip group
|
||||
/// inside that group when its file grows, in the layers and in a symbol's art; the user's group
|
||||
/// stays a plain group.
|
||||
|
||||
@@ -213,7 +213,7 @@ fn go_to_selects_the_image() {
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
assert_ne!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let r = run(&mut s, "links.goTo", json!({"id": id.0}));
|
||||
assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0]}));
|
||||
assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0], "onCanvas": true}));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[1].id;
|
||||
assert!(s.execute("links.goTo", &json!({"id": rect.0})).is_err(), "not an image");
|
||||
|
||||
@@ -47,6 +47,30 @@ fn update_changed_reads_changed_files_again_once() {
|
||||
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 1);
|
||||
}
|
||||
|
||||
/// A file only a symbol's art shows is watched too, and read again by the id of the symbol's image.
|
||||
#[test]
|
||||
fn update_changed_reads_a_file_only_a_symbol_shows() {
|
||||
let dir = Folder::new("watch-symbol");
|
||||
let path = dir.file("art.png");
|
||||
std::fs::write(&path, png(40, 40, RED)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
|
||||
let instance = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("edit.clear", &json!({"ids": [instance.0]})).unwrap();
|
||||
let mut in_symbol = None;
|
||||
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)) {
|
||||
in_symbol = Some(n.id.0);
|
||||
}
|
||||
});
|
||||
let in_symbol = in_symbol.expect("the symbol's image");
|
||||
assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([]));
|
||||
save(&path, &png(40, 40, BLUE));
|
||||
assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([in_symbol]));
|
||||
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_look_follows_update_links() {
|
||||
for (mode, key) in [("automatically", "updated"), ("askWhenModified", "ask"), ("manually", "modified")] {
|
||||
|
||||
@@ -662,6 +662,101 @@ fn placed_art_brings_its_symbols_and_swatches_renaming_on_conflict() {
|
||||
assert!(linked, "still linked to the swatch it brought");
|
||||
}
|
||||
|
||||
/// The symbol and pattern art placed art brings takes ids of the document's own: the file's ids
|
||||
/// already name other objects there, and the Links panel names linked art in symbols by its id.
|
||||
#[test]
|
||||
fn placed_art_brings_its_symbols_and_patterns_with_ids_of_the_documents_own() {
|
||||
let mut src = session();
|
||||
src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
src.execute("symbol.new", &json!({"name": "Star"})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
let tile = src.doc().unwrap().selection.objects[0];
|
||||
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
|
||||
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
|
||||
let bytes = serialize(&mut src, "vectorcraft");
|
||||
// The document's objects take the same ids the file's do.
|
||||
let mut s = session();
|
||||
for x in [0, 20, 40, 60] {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap();
|
||||
}
|
||||
s.execute("symbol.new", &json!({"name": "Box"})).unwrap();
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(doc.symbols.iter().any(|x| x.name == "Star") && doc.pattern("Dots").is_some());
|
||||
let mut ids = vec![];
|
||||
doc.visit_stored(|n, _| ids.push(n.id.0));
|
||||
let unique: std::collections::BTreeSet<u64> = ids.iter().copied().collect();
|
||||
assert_eq!(unique.len(), ids.len(), "{ids:?}");
|
||||
}
|
||||
|
||||
/// Placing the same file again shares the symbols and patterns the first placement brought: their
|
||||
/// art differs from the file's only in its ids, so no `Star 2` or `Dots 2` joins the document.
|
||||
#[test]
|
||||
fn placing_the_same_art_again_shares_its_symbols_and_patterns() {
|
||||
let mut src = session();
|
||||
src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
src.execute("symbol.new", &json!({"name": "Star"})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
let tile = src.doc().unwrap().selection.objects[0];
|
||||
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
|
||||
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
|
||||
let bytes = serialize(&mut src, "vectorcraft");
|
||||
let mut s = session();
|
||||
let counts = |s: &Session| {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
(doc.symbols.len(), doc.patterns.len())
|
||||
};
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
let once = counts(&s);
|
||||
for _ in 0..2 {
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
}
|
||||
assert_eq!(counts(&s), once);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(!doc.symbols.iter().any(|x| x.name == "Star 2") && doc.pattern("Dots 2").is_none());
|
||||
}
|
||||
|
||||
/// A symbol whose art matches the document's own but uses a pattern the document defines
|
||||
/// differently is not shared: it comes in under a free name, using the pattern it brings.
|
||||
#[test]
|
||||
fn placed_art_does_not_share_a_symbol_whose_pattern_moves() {
|
||||
let mut src = session();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
let tile = src.doc().unwrap().selection.objects[0];
|
||||
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
|
||||
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
|
||||
src.execute("symbol.new", &json!({"name": "Star", "ids": [tile.0]})).unwrap();
|
||||
let bytes = serialize(&mut src, "vectorcraft");
|
||||
let mut s = session();
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
// The document's "Dots" changes; its "Star" still matches the file's.
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = Arc::make_mut(&mut st.doc);
|
||||
let dots = d.pattern_mut("Dots").unwrap();
|
||||
dots.tile = Rect::new(0.0, 0.0, 50.0, 50.0);
|
||||
let r = place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
let mut symbol = None;
|
||||
node(&s, &r["ids"][0]).walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol: name, .. } = &n.kind {
|
||||
symbol = Some(name.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(symbol.as_deref(), Some("Star 2"));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let star2 = doc.symbols.iter().find(|x| x.name == "Star 2").unwrap();
|
||||
let mut fills = vec![];
|
||||
star2.art.walk(&mut |n| {
|
||||
fills.extend(n.appearance.items.iter().filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => match &f.paint {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}))
|
||||
});
|
||||
assert_eq!(fills, ["Dots 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_art_brings_its_brushes_renaming_on_conflict() {
|
||||
// The file: a path with its own brush, and one with a brush the defaults hold.
|
||||
|
||||
Reference in New Issue
Block a user