diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index e0def02934..de626e514b 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1048,6 +1048,11 @@ pub(crate) struct Imported { /// and that would draw them otherwise than the art they were pasted with: the document keeps /// its own, and the pasted graphs are drawn again with it. pub kept_designs: BTreeSet, + /// The names of the symbols added to the document, whose art may hold graphs that draw with + /// [`Self::kept_designs`]. + pub added_symbols: BTreeSet, + /// The global and spot colors that took the document's color (merged). + merged_swatches: BTreeSet, } impl Imported { @@ -1114,7 +1119,12 @@ impl Clipboard { /// `d` keeps its own design. pub(super) fn used(&self, d: &Document) -> Used { let designs: Vec = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect(); - let defs = Defs { + Used::of(&self.defs(&designs), &self.nodes) + } + + /// The clipboard's definitions, with graph designs `designs`. + fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> { + Defs { swatches: self.swatches.iter().collect(), symbols: &self.symbols, patterns: &self.patterns, @@ -1122,10 +1132,9 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), - graph_designs: &designs, + graph_designs: designs, index: DefIndex::default(), - }; - Used::of(&defs, &self.nodes) + } } /// The used global and spot colours whose name `d` gives another one: (pasted, document). @@ -1317,6 +1326,7 @@ impl Clipboard { for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) { out.relink.node(Arc::make_mut(&mut s.art)); } + out.added_symbols = added_symbols.into_iter().collect(); for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) { for a in &mut p.art { out.relink.node(Arc::make_mut(a)); @@ -1438,6 +1448,7 @@ impl Clipboard { for w in &bases { let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge { out.merged += 1; + out.merged_swatches.insert(w.name.clone()); Placed::Existing } else { add_swatch(d, w, same_doc) @@ -1495,15 +1506,25 @@ impl Clipboard { // Every name the pasted graphs draw with whose design in the document would draw them // otherwise: another design of that name, one the clipboard holds no design for (deleted // and made again), or, from another document, the same art when a resource came in renamed - // or a swatch took the document's color (the art may draw it). - let moved = !same_doc && (!out.relink.renames.is_empty() || out.merged > 0); + // or a swatch took the document's color, that the design's art uses. (An SVG filter effect + // carries its definition, so a filter that draws otherwise makes the art differ.) + let defs = self.defs(&self.graph_designs); + let moved = |n: &str| { + if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) { + return false; + } + let uses = designs_used(&defs, &[n.to_string()]); + out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from))) + || out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w)) + }; let differs = |n: &str| { let ours = d.graph_designs.iter().find(|x| x.name == n); let theirs = self.graph_designs.iter().find(|g| g.name == n); - ours.is_some_and(|x| moved || theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art)) + ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n)) }; let named = used.names.get(&Res::GraphDesign).into_iter().flatten(); - out.kept_designs.extend(named.filter(|n| differs(n)).cloned()); + let kept: Vec = named.filter(|n| differs(n)).cloned().collect(); + out.kept_designs.extend(kept); for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) { if d.graph_designs.iter().any(|x| x.name == g.name) { out.placed(Res::GraphDesign, &g.name, &Placed::Existing); @@ -1582,6 +1603,24 @@ pub(crate) fn graph_design_library(src: &Document) -> Option { let used = designs_used(&Defs::of(src, &library), &names); let clip = Clipboard::with_used(src, &used, &library, vec![]); let mut d = clip.to_document(); + // A new document's default swatches and graphic styles give way to the source's of the same + // name or id, so a design draws with the source's. + let defaults = d.swatches.len().saturating_sub(clip.swatches.len()); + let mut i = 0; + d.swatches.retain(|s| { + i += 1; + i > defaults || !clip.swatches.iter().any(|c| c.name == s.name) + }); + // The swatch groups are all a new document's. + for g in d.swatch_groups.iter_mut() { + g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name)); + } + let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len()); + let mut i = 0; + d.graphic_styles.retain(|g| { + i += 1; + i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name) + }); // The symbols keep their Symbol Options, which the document keeps by name. for (name, options) in &clip.symbol_options { options.give(&mut d, name); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e025b64e2c..b707a8367a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1619,9 +1619,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for id in &new_ids { super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default()); } - // A pasted graph whose design the document has under the same name draws with the document's. + // A pasted graph whose design the document has under the same name draws with the document's, + // in the pasted objects and in the art of the symbols the paste added. if !imported.kept_designs.is_empty() { super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?; + super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs); } sel.set(new_ids.iter().copied()); // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 2d48b6339a..13c34deb28 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,7 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; -pub(crate) use designs::redraw_with_designs; +pub(crate) use designs::{redraw_symbols_with_designs, redraw_with_designs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; diff --git a/crates/engine/src/cmd/graph/columns.rs b/crates/engine/src/cmd/graph/columns.rs index 4e56338849..6c87143618 100644 --- a/crates/engine/src/cmd/graph/columns.rs +++ b/crates/engine/src/cmd/graph/columns.rs @@ -1,5 +1,5 @@ use super::data::fmt_value; -use super::designs::{bring_in, design_names, from_library, libraries_json}; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::generate::generate_with; use super::markers::{design_frame, fit_affine}; @@ -493,7 +493,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { // Drawn once on a copy of the document, to refuse designs past the budget before the edit. let mut probe = (*s.doc()?.doc).clone(); if let Some((lib, name)) = &library { - bring_in(&mut probe, lib, std::slice::from_ref(name))?; + bring_in_for(&mut probe, lib, name, id, &mut spec)?; } let looks = column_designs(&probe, &spec); if generate_with(&mut probe, &spec, &looks).is_none() { @@ -501,7 +501,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { } s.edit("Graph Column", |d, sel| { if let Some((lib, name)) = &library { - bring_in(d, lib, std::slice::from_ref(name))?; + bring_in_for(d, lib, name, id, &mut spec)?; } regenerate(d, id, spec)?; if !reselect.is_empty() { diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 4d272d7bc3..1b7d89a8c5 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -1,5 +1,5 @@ -use super::edit::regenerate; -use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param}; +use super::edit::{regenerate, regenerate_detached}; +use super::{Arc, Document, GraphDesign, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param}; use crate::cmd::clipboard::resources::import_graph_designs; use crate::cmd::swatchlib::{concealed_library_id, shown_library_id}; @@ -9,7 +9,8 @@ pub(super) fn design_names(d: &Document) -> Vec { } /// The library param `library` names: a document Other Library… loaded (`swatch.library.load`) -/// that holds graph designs, by its id, the id a reply showed for it, or its name. `None` without +/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as +/// swatch library names are matched). `None` without /// `library`. fn library_param(s: &Session, p: &Value, cmd: &str) -> Result>> { let key = match p.get("library") { @@ -24,7 +25,7 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result Re Ok(()) } +/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws +/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it +/// was last drawn stays where it is. +pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> { + bring_in(d, lib, &[name.to_string()])?; + if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) { + spec.rect = g.rect; + } + Ok(()) +} + /// Whether graph `g` draws a series with design `name`, as its marker or its columns. fn draws_with(g: &GraphSpec, name: &str) -> bool { g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name) } -/// Regenerate the graphs whose series use design `name` (it was added or removed). +/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers, +/// in opacity-mask art and in symbols' art. fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> { - let mut ids = vec![]; + let names = std::collections::BTreeSet::from([name.to_string()]); + let (mut ids, mut masked) = (vec![], vec![]); d.walk(|n| { if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) { ids.push(n.id); } + if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, &names)) { + masked.push(n.id); + } }); for id in ids { if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) { regenerate(d, id, spec)?; } } + // The graphs in objects' opacity-mask art. + for id in masked { + let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue }; + redraw_in(d, &mut art, &names); + if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + // And the graphs in symbols' art, which instances draw. + let symbols: std::collections::BTreeSet = d.symbols.iter().map(|s| s.name.clone()).collect(); + redraw_symbols_with_designs(d, &symbols, &names); Ok(()) } /// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs /// `names`: pasted graphs, after the paste kept the document's own designs of those names. pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet) -> Result<()> { - let mut graphs = vec![]; for id in ids { - if let Some(n) = d.node(*id) { - n.walk(&mut |m| { - if m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { - graphs.push(m.id); - } - }); - } - } - for id in graphs { - if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) { - regenerate(d, id, spec)?; - } + let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue }; + redraw_in(d, &mut n, names); + *d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n; } Ok(()) } +/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the +/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own +/// designs of those names. +pub(crate) fn redraw_symbols_with_designs( + d: &mut Document, + symbols: &std::collections::BTreeSet, + names: &std::collections::BTreeSet, +) { + for i in 0..d.symbols.len() { + let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue }; + let old = s.art.clone(); + let mut art = (*old).clone(); + redraw_in(d, &mut art, names); + let Some(s) = d.symbols.get_mut(i) else { continue }; + s.art = Arc::new(art); + // Instances' changes to parts the redraw replaced are dropped. + let name = s.name.clone(); + crate::cmd::symboledit::follow_art_change(d, &name, &old); + } +} + +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series +/// with one of the designs `names`. +fn holds(n: &Node, names: &std::collections::BTreeSet) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))); + }); + found +} + +/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with +/// one of the designs `names`. +fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet) { + if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) { + redraw_in(d, &mut art, names); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { + regenerate_detached(d, n); + return; + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| holds(c, names)) { + redraw_in(d, Arc::make_mut(c), names); + } + } +} + /// The designs no graph's series draw with (Select Unused). fn unused_designs(d: &Document) -> Vec { let mut used = std::collections::HashSet::new(); diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index 728eff6427..e5ce1e7ed0 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) { /// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them). pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> { let n = d.node(id).ok_or(EngineError::NoNode(id))?; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); + Ok(()) +} + +/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art). +pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) { + let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return }; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); +} + +/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation. +fn carry_moves(n: &Node, spec: &mut GraphSpec) { if let Some((placed, now)) = measured(n) && placed.width() > 1e-9 && placed.height() > 1e-9 @@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R * Affine::translate(-placed.origin().to_vec2()); spec.rect = a.transform_rect_bbox(spec.rect); } - let children = generate(d, &spec); - spec.placed = children_bounds(&children); - spec.placed_art = art_bounds(&children); - let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; - if let Some(ch) = n.children_mut() { - *ch = children; - } - n.extras_mut().graph = Some(Box::new(spec)); - Ok(()) } pub(super) fn create(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/graph/markers.rs b/crates/engine/src/cmd/graph/markers.rs index 7045fee638..7b8a14d496 100644 --- a/crates/engine/src/cmd/graph/markers.rs +++ b/crates/engine/src/cmd/graph/markers.rs @@ -1,4 +1,4 @@ -use super::designs::{bring_in, design_names, from_library, libraries_json}; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::series::{picked_series, reselect_series}; use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json}; @@ -93,7 +93,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let cost = match &library { Some((lib, name)) => { let mut probe = (*s.doc()?.doc).clone(); - bring_in(&mut probe, lib, std::slice::from_ref(name))?; + bring_in_for(&mut probe, lib, name, id, &mut spec)?; marker_cost(&spec, &marker_designs(&probe, &spec)) } None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)), @@ -103,7 +103,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { } s.edit("Graph Marker", |d, sel| { if let Some((lib, name)) = &library { - bring_in(d, lib, std::slice::from_ref(name))?; + bring_in_for(d, lib, name, id, &mut spec)?; } regenerate(d, id, spec)?; if !reselect.is_empty() { diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 45ce34a157..c1230301bb 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5538,6 +5538,31 @@ fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() { } } +#[test] +fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A library's name works in any case, as swatch library names do. + assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]})); + for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] { + // The graph names design "Coin", which the document no longer has, and is moved after. + save_design(&mut s, "Coin"); + let id = graph(&mut s, kind); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute(cmd, &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap(); + s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap(); + let now = spec(&s, id).rect; + assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}"); + assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}"); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + } +} + #[test] fn a_design_the_document_has_under_the_same_name_stays_as_it_is() { let mut s = Session::new(); @@ -5659,6 +5684,234 @@ fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_tha assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); } +#[test] +fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + // An edit of the graph's art that drawing the graph again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design; its "Ink" is another color, so the pasted + // rectangle's swatch takes the document's color, or with "add" comes in renamed. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap(); + for conflict in ["merge", "add"] { + let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + assert!(r["merged"] == 1 || r["renamed"].as_array().is_some_and(|a| !a.is_empty()), "{conflict}: {r}"); + let st = s.doc().unwrap(); + let d = &st.doc; + let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap(); + let names: Vec> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}"); + } +} + +#[test] +fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() { + const SHIFT: &str = r#""#; + const SHIFT_MORE: &str = r#""#; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Coin"})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the + // pasted graph's filter keeps its own definition under another name. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let pasted = st.selection.objects.to_vec()[0]; + let names: Vec> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}"); +} + +#[test] +fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A graph that names "Coin", which the document no longer has, kept as a symbol's art. + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() { + use vectorcraft_doc::symbol_overrides::SymbolOverride; + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + let instance = NodeId(instance); + // A change to the graph itself, and one to a part of it that drawing it again replaces. + let changes = vec![ + SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() }, + SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() }, + ]; + s.edit("Change", |d, _| { + if let Some(n) = d.node_mut(instance) { + n.extras_mut().symbol_overrides = changes; + } + Ok(()) + }) + .unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone(); + assert_eq!(kept.iter().map(|o| o.path.clone()).collect::>(), [Vec::::new()], "{kept:?}"); +} + +#[test] +fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() { + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let mask_graph = |n: &vectorcraft_doc::Node| { + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + graphs.into_iter().next().expect("the masked graph") + }; + // In a symbol's art and among the pasted objects. + for in_symbol in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r }; + s.execute("select.set", &json!({"ids": [copied]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let g = if in_symbol { + mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art) + } else { + mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap()) + }; + let columns: Vec = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}"); + } +} + #[test] fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() { let mut s = Session::new(); @@ -5711,6 +5964,85 @@ fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() { assert!(e.contains("larger than 256 MB"), "{e}"); } +#[test] +fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut src, "Pill"); + let mut d = (*src.doc().unwrap().doc).clone(); + d.swatches.clear(); + d.swatch_groups.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"}); + let mut s = Session::new(); + let r = s.execute("swatch.library.load", &p).unwrap(); + assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1))); + // Without graph designs it has nothing to offer. + d.graph_designs.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("has no swatches of its own"), "{e}"); +} + +#[test] +fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A default swatch the source made global and gave another color, used by a design. + let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone(); + let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3)); + let (n, p) = (name.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Green"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect(); + assert_eq!(named.len(), 1, "one swatch named {name}"); + assert_eq!(named[0].paint, mine); + // And one named like a swatch in a default group. + let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone(); + let (n, p) = (grouped.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Grouped"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect(); + assert_eq!(all.len(), 1, "one swatch named {grouped}"); +} + +#[test] +fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() { + let max = crate::cmd::place::document::MAX_FILE; + let mut s = Session::new(); + // Text one byte over the limit, and base64 that decodes to one byte over it. + let chars = (max + 1) * 4 / 3 + 1; + // Each input is made in turn, so only one is held at a time. + for key in ["data", "dataBase64"] { + let value = if key == "data" { "a".repeat(max + 1) } else { "A".repeat(chars) }; + let mut p = serde_json::Map::new(); + p.insert(key.into(), serde_json::Value::String(value)); + let e = s.execute("swatch.library.load", &serde_json::Value::Object(p)).unwrap_err().to_string(); + assert!(e.contains("larger than 256 MB"), "{key}: {e}"); + } +} + #[test] fn a_library_design_brings_its_symbols_with_their_symbol_options() { // The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 7884ca6905..b16f743367 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -818,11 +818,19 @@ fn save(s: &mut Session, p: &Value) -> Result { fn load(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.load"; - // The size is checked before the file is read. + // The size is checked before the file is read, copied or decoded. let max = super::place::document::MAX_FILE; - if let Some(path) = text_param(p, "path", C)? - && super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64) - { + let too_big = match text_param(p, "path", C)? { + Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64), + None => match text_param(p, "data", C)? { + Some(text) => text.len() > max, + // Base64 holds 3 bytes in every 4 characters (padding and white space hold none). + None => { + text_param(p, "dataBase64", C)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max) + } + }, + }; + if too_big { return Err(bad(C, format!("the file is larger than {} MB", max >> 20))); } let mut designs = None; diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index a413631bb3..3b5d7cdf48 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec) { + let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return }; + let parts = |art: &Arc| match (&art.kind, art.children()) { + (NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true), + _ => (vec![art.clone()], false), + }; + let (old, new) = (parts(old), parts(&new)); + follow_objects(d, name, (&old.0, old.1), (&new.0, new.1)); +} + /// Each instance's appearance changes to objects of symbol `name`'s art follow those objects /// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art /// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the