Graphs: redraw graphs a paste or library adds a design for, reuse redrawn symbols

- A paste that adds a design the document lacked draws the document's
  graphs that name it again, in the same undo step; the pasted graphs keep
  their art.
- A library design brings along the designs its art uses, and the graphs
  that name any of them are drawn again. A design the document keeps
  brings none of the library design's resources.
- Only a series that draws a design is redrawn for it: a marker counts
  while Mark Data Points is on or the legend has an entry for the series,
  and a column design counts for a column or bar series.
- A symbol pasted a second time is the one the first paste added and drew
  again with the document's designs.
- Renaming a design renames it in the graphs of symbols and opacity masks,
  and Select Unused counts those graphs.
- swatch.library.load reads a file no further than the 256 MB limit.
This commit is contained in:
dotCooCoo
2026-11-19 06:18:09 -08:00
parent 4137b8e50a
commit 9d2bbbc6b4
7 changed files with 526 additions and 61 deletions
+56 -8
View File
@@ -762,6 +762,22 @@ fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
}
/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again
/// compares equal to art drawn the same way, whatever ids each drawing gave it.
fn without_ids(n: &Node) -> Node {
let mut n = n.clone();
n.id = vectorcraft_doc::NodeId(0);
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
mask.art = Arc::new(without_ids(&mask.art));
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
*c = Arc::new(without_ids(c));
}
}
n
}
/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by
/// `r`? Graphic style links don't count, as in [`same_art`].
fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
@@ -1051,6 +1067,8 @@ pub(crate) struct Imported {
/// The names of the symbols added to the document, whose art may hold graphs that draw with
/// [`Self::kept_designs`].
pub added_symbols: BTreeSet<String>,
/// The names of the graph designs added to the document.
pub added_designs: BTreeSet<String>,
/// The global and spot colors that took the document's color (merged).
merged_swatches: BTreeSet<String>,
}
@@ -1275,11 +1293,18 @@ impl Clipboard {
.collect(),
None => HashMap::new(),
};
// A symbol whose graphs the paste draws again with the document's designs is
// also the document's one that holds its art drawn that way (an earlier paste
// added it).
let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name)))
.then(|| self.redrawn_art(d, &def.art, &out.relink))
.flatten();
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| {
!fresh
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
&& (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|| redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art))
});
if let Some(name) = p.new_name(&def.name) {
if let Some(o) = options {
@@ -1499,6 +1524,27 @@ impl Clipboard {
}
}
/// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds
/// under a name whose design the clipboard lacks or holds with other art, as a paste that adds
/// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws
/// with such a design.
fn redrawn_art(&self, d: &mut Document, art: &Arc<Node>, relink: &Relink) -> Option<Node> {
let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n);
let differs: BTreeSet<String> = d
.graph_designs
.iter()
.filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art))
.map(|x| x.name.clone())
.collect();
if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) {
return None;
}
let mut n = (**art).clone();
relink.node(&mut n);
crate::cmd::graph::redraw_detached(d, &mut n, &differs);
Some(without_ids(&n))
}
/// Graph designs: the document's design of a name stays as it is and the pasted graphs draw
/// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the
/// resources placed above, with fresh ids. Called once every other resource is placed.
@@ -1538,6 +1584,7 @@ impl Clipboard {
let art = d.reid(&art);
d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) });
out.placed(Res::GraphDesign, &g.name, &Placed::Added);
out.added_designs.insert(g.name.clone());
}
Ok(())
}
@@ -1632,15 +1679,16 @@ pub(crate) fn graph_design_library(src: &Document) -> Option<Document> {
/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles,
/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a
/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the
/// same name stays as it is. → each name, and whether its design was added. An error, with `d`
/// unchanged, when `d` would hold more than [`GraphDesign::MAX`] designs.
pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result<Vec<(String, bool)>> {
/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the
/// names of the designs added: those of `names` `d` lacked, and those their art uses. An error,
/// with `d` unchanged, when `d` would hold more than [`GraphDesign::MAX`] designs.
pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result<BTreeSet<String>> {
let library = OnceCell::new();
let used = designs_used(&Defs::of(src, &library), names);
let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n);
let followed: Vec<GraphDesign> = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect();
let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before: HashSet<String> = d.graph_designs.iter().map(|g| g.name.clone()).collect();
clip.import_used(d, &used, &SwatchChoices::default(), false)?;
Ok(names.iter().map(|n| (n.clone(), !before.contains(n))).collect())
Ok(clip.import_used(d, &used, &SwatchChoices::default(), false)?.added_designs)
}
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
+5
View File
@@ -1625,6 +1625,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?;
super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
}
// The graphs already in the document that draw with a design the paste added are drawn
// again with it; the pasted ones already draw with it.
if !imported.added_designs.is_empty() {
super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?;
}
sel.set(new_ids.iter().copied());
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
// paste of guides alone keeps them where they were, but onto another artboard or every
+1 -1
View File
@@ -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_symbols_with_designs, redraw_with_designs};
pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs};
pub use edit::{GraphTypeSubject, graph_type_subject};
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
pub use generate::calculated_axes;
+122 -24
View File
@@ -1,5 +1,7 @@
use super::edit::{regenerate, regenerate_detached};
use super::{Arc, Document, GraphDesign, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param};
use std::collections::BTreeSet;
use super::{Arc, Document, GraphDesign, GraphKind, 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};
@@ -57,12 +59,11 @@ pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result<Option<(
}
/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the
/// graphs that already name one the document lacked.
/// graphs that already name a design the document lacked: one of `names`, or one their art uses.
pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> {
for (name, added) in import_graph_designs(lib, d, names)? {
if added {
refresh_graphs_using(d, &name)?;
}
let added = import_graph_designs(lib, d, names)?;
if !added.is_empty() {
refresh_graphs(d, &added, &[], &BTreeSet::new())?;
}
Ok(())
}
@@ -78,21 +79,58 @@ pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: sup
Ok(())
}
/// Whether graph `g` draws a series with design `name`, as its marker or its columns.
/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with
/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is
/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or
/// bars.
fn draws_with(g: &GraphSpec, name: &str) -> bool {
let scatter = g.kind == GraphKind::Scatter;
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
// The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank
// (a scatter graph's entries are its pairs of series, labeled by the first of each pair).
let in_legend = |s: usize| {
let entries = if scatter { nser.div_ceil(2) } else { nser };
let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str);
g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label)
};
let shown = |s: usize| g.mark_points || in_legend(s);
let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line);
let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar);
g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s))
|| g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s))
}
/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or
/// not the series draws with it.
fn names_design(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), in the layers,
/// in opacity-mask art and in symbols' art.
fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> {
let names = std::collections::BTreeSet::from([name.to_string()]);
refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new())
}
/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in
/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of
/// symbols `skip_symbols`.
pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet<String>, skip: &[super::NodeId], skip_symbols: &BTreeSet<String>) -> Result<()> {
let mut skipped = std::collections::HashSet::new();
for n in skip.iter().filter_map(|id| d.node(*id)) {
n.walk(&mut |m| {
skipped.insert(m.id);
});
}
let (mut ids, mut masked) = (vec![], vec![]);
d.walk(|n| {
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) {
if skipped.contains(&n.id) {
return;
}
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
ids.push(n.id);
}
if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, &names)) {
if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) {
masked.push(n.id);
}
});
@@ -104,17 +142,31 @@ fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> {
// 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);
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<String> = d.symbols.iter().map(|s| s.name.clone()).collect();
redraw_symbols_with_designs(d, &symbols, &names);
let symbols: BTreeSet<String> = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect();
redraw_symbols_with_designs(d, &symbols, names);
Ok(())
}
/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s
/// designs `names`.
pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet<String>) {
if holds(n, names) {
redraw_in(d, n, names);
}
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
/// with one of the designs `names`.
pub(crate) fn holds_designs(n: &Node, names: &BTreeSet<String>) -> bool {
holds(n, names)
}
/// 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<String>) -> Result<()> {
@@ -177,18 +229,57 @@ fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet<
}
}
/// The designs no graph's series draw with (Select Unused).
/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask
/// art and in symbols' art count.
fn unused_designs(d: &Document) -> Vec<String> {
let mut used = std::collections::HashSet::new();
d.walk(|n| {
let mut note = |n: &Node| {
if let Some(g) = n.extras().graph.as_deref() {
used.extend(g.series_markers.iter().flatten().cloned());
used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone()));
}
});
};
for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) {
vectorcraft_doc::swatches::walk_with_masks(art, &mut note);
}
d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect()
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design
/// `name` for a series ([`names_design`]).
fn names_in(n: &Node, name: &str) -> 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_design(g, name));
});
found
}
/// Graph `g`'s series that name design `old` name `new` instead.
fn rename_series(g: &mut GraphSpec, old: &str, new: &str) {
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
*m = new.to_string();
}
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
c.design = new.to_string();
}
}
/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included.
fn rename_in(n: &mut Node, old: &str, new: &str) {
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) {
rename_in(Arc::make_mut(&mut mask.art), old, new);
}
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
rename_series(g, old, new);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| names_in(c, old)) {
rename_in(Arc::make_mut(c), old, new);
}
}
}
/// Design names from param `key`: one name or a list of names.
fn names_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<String>>> {
match p.get(key) {
@@ -255,22 +346,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) {
x.name = new.clone();
}
let mut graphs = vec![];
let (mut graphs, mut masked) = (vec![], vec![]);
d.walk(|n| {
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) {
if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) {
graphs.push(n.id);
}
if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) {
masked.push(n.id);
}
});
for id in graphs {
if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) {
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
*m = new.clone();
}
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
c.design = new.clone();
}
rename_series(g, &old, &new);
}
}
// The graphs in opacity-mask art and in symbols' art follow too, their art as it is.
for id in masked {
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
rename_in(Arc::make_mut(&mut mask.art), &old, &new);
}
}
for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) {
rename_in(Arc::make_mut(&mut s.art), &old, &new);
}
Ok(())
})?;
return Ok(json!({ "name": to }));
+294 -12
View File
@@ -5713,7 +5713,9 @@ fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_com
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 ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink"));
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
assert_eq!((r["merged"].clone(), ink_renamed), expected, "{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();
@@ -5937,6 +5939,276 @@ fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design
assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now");
}
/// The graphs in `n`'s subtree, those in opacity-mask art included.
fn graphs_in(n: &vectorcraft_doc::Node) -> Vec<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
}
/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of
/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker
/// its columns do not draw, as a swatch library → its id.
fn load_chart_library(s: &mut Session, columns: bool) -> String {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut src);
let id = graph(&mut src, "column");
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap();
let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
src.execute("graph.design", &json!({"new": "Chart"})).unwrap();
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"});
s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string()
}
#[test]
fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() {
let mut s = Session::new();
let lib = load_chart_library(&mut s, false);
// The document keeps its own "Coin": nothing the library's "Coin" uses comes in.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in");
assert!(d.swatch("Gold").is_none());
// A document without one takes the design and its swatch.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some());
}
#[test]
fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() {
let mut s = Session::new();
let lib = load_chart_library(&mut s, true);
// A graph that names "Coin", which the document no longer has.
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 r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
assert_eq!(r, json!({"added": ["Chart"], "existing": []}));
let d = &s.doc().unwrap().doc;
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin");
}
#[test]
fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() {
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();
// An edit of the copied graph's art that drawing it 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();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose graph names "Coin", which it no longer has.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let own = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin");
let pasted = st.selection.objects.to_vec()[0];
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again");
}
#[test]
fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() {
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();
s.execute("edit.copy", &json!({})).unwrap();
// A line graph whose series name "Coin", which the document no longer has, as a marker that
// Mark Data Points does not show, with no legend or with a legend that has no entry for them.
for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] {
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv});
let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let mark = series(s.doc().unwrap().doc.node(own).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();
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin");
let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again");
}
}
#[test]
fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() {
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();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose "Coin" is other art: the first paste draws the symbol's graph with it.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
// The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one.
let columns = |s: &Session| {
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone();
let graph = graphs_in(&art).remove(0);
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::<Vec<usize>>()
};
s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin");
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
assert_eq!(names, ["Chart"]);
assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin");
}
#[test]
fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
// A copy of the document holds the same "Coin"; its "Gold" is another color.
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
for conflict in ["merge", "add"] {
s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap();
s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap();
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold"));
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}");
s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
assert_eq!(names, ["Chart"], "{conflict}");
}
}
#[test]
fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
// A column graph whose series name "Coin" as a marker, which columns do not draw.
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.marker", &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();
s.execute("select.set", &json!({"ids": [id.0]})).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 pasted = st.selection.objects.to_vec()[0];
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "not drawn again");
}
#[test]
fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let in_symbol = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let masked = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap();
let d = &s.doc().unwrap().doc;
let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
let mask = graphs_in(d.node(NodeId(r)).unwrap());
for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] {
let designs: Vec<String> = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect();
assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}");
}
assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art");
}
#[test]
fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
save_design(&mut s, "Pill");
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("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let masked = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Pill"})).unwrap();
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([]));
}
#[test]
fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user");
@@ -6029,18 +6301,28 @@ fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() {
#[test]
fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() {
let max = crate::cmd::place::document::MAX_FILE;
// With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused.
let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap();
assert!(!too_big(json!({"data": "abc"})));
assert!(too_big(json!({"data": "abcd"})));
let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]);
assert!(!too_big(json!({"dataBase64": b64(3)})));
assert!(too_big(json!({"dataBase64": b64(4)})));
}
#[test]
fn a_swatch_library_file_is_read_no_further_than_the_size_limit() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound");
let path = dir.join("grown.gpl");
std::fs::write(&path, [b'a'; 9]).unwrap();
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}");
}
let p = json!({"path": path});
let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into()));
// A file that grew past the limit after the size check is refused when it is read.
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string();
assert!(e.contains("larger than"), "{e}");
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string();
assert!(e.contains("parsed"), "{e}");
}
#[test]
+44 -13
View File
@@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
use vectorcraft_doc::pattern::pattern_paint;
use super::fileio::{create_dir, extension, read_file, write_file, write_new_file};
use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file};
use super::menucmds::squash;
use super::package::free_name;
use super::patternlib;
@@ -393,12 +393,32 @@ impl<L: LibraryFile> Libraries<L> {
/// or a file with the same extension and bytes as one there, is that User Defined library;
/// others are listed as loaded until the app quits.
pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result<L>) -> Result<(LibraryInfo, Arc<L>)> {
self.load_within(p, cmd, None, parse)
}
/// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer.
pub(crate) fn load_within(
&mut self,
p: &Value,
cmd: &str,
max: Option<usize>,
parse: impl FnOnce(&[u8], &str) -> Result<L>,
) -> Result<(LibraryInfo, Arc<L>)> {
let path = text_param(p, "path", cmd)?;
let data = text_param(p, "data", cmd)?;
let data_base64 = text_param(p, "dataBase64", cmd)?;
let name = text_param(p, "name", cmd)?;
let bytes = match (path, data, data_base64) {
(Some(path), ..) => read_file(path)?,
(Some(path), ..) => match max {
Some(max) => {
let bytes = read_file_head(path, max.saturating_add(1))?;
if bytes.len() > max {
return Err(bad(cmd, too_big_message(max)));
}
bytes
}
None => read_file(path)?,
},
(None, Some(text), _) => text.as_bytes().to_vec(),
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?,
_ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")),
@@ -816,27 +836,38 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
fn load(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.load";
// The size is checked before the file is read, copied or decoded.
let max = super::place::document::MAX_FILE;
let too_big = match text_param(p, "path", C)? {
/// The error for a library file larger than `max` bytes.
fn too_big_message(max: usize) -> String {
format!("the file is larger than {} MB", max >> 20)
}
/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes,
/// checked before the file is read, copied or decoded.
pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result<bool> {
Ok(match text_param(p, "path", cmd)? {
Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64),
None => match text_param(p, "data", C)? {
None => match text_param(p, "data", cmd)? {
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)
text_param(p, "dataBase64", cmd)?.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)));
})
}
fn load(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.load";
let max = super::place::document::MAX_FILE;
if library_too_big(p, C, max)? {
return Err(bad(C, too_big_message(max)));
}
let mut designs = None;
// The document a library with pattern swatches was read from, which holds their patterns.
let mut patterns = None;
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
// The file is read no further than the limit, so a file that grew since it was checked is
// refused too.
let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| {
// A library file, or a document whose swatches become the library and whose graph
// designs the Graph Column and Graph Marker dialogs offer.
if palette_io::sniff_bytes(bytes) {