mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 01:26:39 +00:00
Merge pull request #7760 from dotCooCoo/feat/graph-designs-from-other-document
Graphs: graph designs come in from another document
This commit is contained in:
@@ -19,7 +19,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
|
||||
use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
|
||||
use vectorcraft_geom::{PathData, Rect};
|
||||
|
||||
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
@@ -94,6 +94,9 @@ pub struct Clipboard {
|
||||
pub para_styles: Vec<TextStyleDef>,
|
||||
/// Brushes the objects' strokes use.
|
||||
pub brushes: Vec<Brush>,
|
||||
/// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the
|
||||
/// ones the document lacks; a design the document has under the same name stays as it is.
|
||||
pub graph_designs: Vec<GraphDesign>,
|
||||
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
|
||||
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
|
||||
pub source_artboard: Option<Rect>,
|
||||
@@ -395,7 +398,7 @@ impl Clipboard {
|
||||
if self.source_doc == Some(st.uid) && !self.colors_converted {
|
||||
return vec![];
|
||||
}
|
||||
self.conflicts(&st.doc, &self.used())
|
||||
self.conflicts(&st.doc, &self.used(&st.doc))
|
||||
}
|
||||
|
||||
/// A standalone document holding the objects and their resources (SVG export).
|
||||
@@ -408,6 +411,7 @@ impl Clipboard {
|
||||
d.graphic_styles.extend(self.graphic_styles.iter().cloned());
|
||||
d.char_styles = self.char_styles.clone().into();
|
||||
d.para_styles = self.para_styles.clone().into();
|
||||
d.graph_designs = self.graph_designs.clone();
|
||||
if !self.brushes.is_empty() {
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
// Each brush's place in the library by name: finding it by scanning the growing list
|
||||
@@ -469,6 +473,7 @@ impl Clipboard {
|
||||
char_styles: d.char_styles.to_vec(),
|
||||
para_styles: d.para_styles.to_vec(),
|
||||
brushes: vectorcraft_brush::library(&d),
|
||||
graph_designs: d.graph_designs.clone(),
|
||||
images: self.images.clone(),
|
||||
symbol_options: self.symbol_options.clone(),
|
||||
source_artboard: self.source_artboard,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The document resources copied objects use, and adding them to the document they're pasted into.
|
||||
//!
|
||||
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
|
||||
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
|
||||
//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to.
|
||||
//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those
|
||||
//! references, also through the symbols, patterns, styles, brush art and graph design art it finds,
|
||||
//! and keeps what they lead to.
|
||||
//!
|
||||
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
|
||||
//! is added, and a different one of the same name is added under a free name, which the pasted
|
||||
@@ -22,8 +23,8 @@ use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType,
|
||||
SymbolNineSlice, SymbolRegistration, TextStyleDef,
|
||||
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol,
|
||||
SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef,
|
||||
};
|
||||
|
||||
use super::super::brushsym::{set_natural_size, stored_natural_size};
|
||||
@@ -44,6 +45,7 @@ enum Res {
|
||||
ParaStyle,
|
||||
Brush,
|
||||
GraphicStyle,
|
||||
GraphDesign,
|
||||
}
|
||||
|
||||
impl Res {
|
||||
@@ -57,6 +59,7 @@ impl Res {
|
||||
Res::ParaStyle => "paraStyle",
|
||||
Res::Brush => "brush",
|
||||
Res::GraphicStyle => "graphicStyle",
|
||||
Res::GraphDesign => "graphDesign",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,6 +142,10 @@ fn node_refs(n: &Node, f: Visit) {
|
||||
for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) {
|
||||
f(Ref::Name(Res::ParaStyle, s));
|
||||
}
|
||||
// The designs its series draw their markers, columns or bars with.
|
||||
for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) {
|
||||
f(Ref::Name(Res::GraphDesign, d));
|
||||
}
|
||||
}
|
||||
match &m.kind {
|
||||
NodeKind::Text(t) => {
|
||||
@@ -217,6 +224,7 @@ struct Defs<'a> {
|
||||
char_styles: &'a [TextStyleDef],
|
||||
para_styles: &'a [TextStyleDef],
|
||||
brushes: Brushes<'a>,
|
||||
graph_designs: &'a [GraphDesign],
|
||||
/// Where each name is defined, built the first time a kind is followed.
|
||||
index: DefIndex,
|
||||
}
|
||||
@@ -236,6 +244,7 @@ struct DefIndex {
|
||||
char_styles: OnceCell<NameIndex>,
|
||||
para_styles: OnceCell<NameIndex>,
|
||||
brushes: OnceCell<NameIndex>,
|
||||
graph_designs: OnceCell<NameIndex>,
|
||||
}
|
||||
|
||||
/// The items of `list` named `name`, in order, `index` holding their positions (built from
|
||||
@@ -279,6 +288,7 @@ impl<'a> Defs<'a> {
|
||||
char_styles: &d.char_styles,
|
||||
para_styles: &d.para_styles,
|
||||
brushes: Brushes::Lazy(d, brushes),
|
||||
graph_designs: &d.graph_designs,
|
||||
index: DefIndex::default(),
|
||||
}
|
||||
}
|
||||
@@ -376,6 +386,7 @@ impl Used {
|
||||
Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))),
|
||||
// A scatter or art brush's art, a pattern brush's tiles.
|
||||
Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))),
|
||||
Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -406,7 +417,7 @@ pub struct ArtResources {
|
||||
/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them
|
||||
/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked
|
||||
/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles,
|
||||
/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// by identity, the other definitions by their saved form: working the key out walks `art` and
|
||||
/// the definitions it leads to, and never reads an image's bytes.
|
||||
pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a Node>) -> ArtResources {
|
||||
@@ -451,6 +462,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a No
|
||||
Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)),
|
||||
Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)),
|
||||
// Swatches below (tints count too); graphic styles go by id.
|
||||
Res::Swatch | Res::GraphicStyle => {}
|
||||
}
|
||||
@@ -824,6 +836,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 {
|
||||
@@ -1106,6 +1134,17 @@ pub(crate) struct Imported {
|
||||
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
|
||||
/// renamed, or a copy added renamed by an earlier paste.
|
||||
pub renamed: Vec<Value>,
|
||||
/// The graph designs the pasted graphs draw with that the document has under the same name
|
||||
/// 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<String>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
impl Imported {
|
||||
@@ -1161,15 +1200,24 @@ impl Clipboard {
|
||||
char_styles: pick(Res::CharStyle, &src.char_styles),
|
||||
para_styles: pick(Res::ParaStyle, &src.para_styles),
|
||||
brushes,
|
||||
graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(),
|
||||
set_densities: src.set_densities_of(&nodes),
|
||||
nodes,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The resources the objects use now (Paste without Formatting leaves text styles behind).
|
||||
pub(super) fn used(&self) -> Used {
|
||||
let defs = Defs {
|
||||
/// The resources the objects use now (Paste without Formatting leaves text styles behind),
|
||||
/// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as
|
||||
/// `d` keeps its own design.
|
||||
pub(super) fn used(&self, d: &Document) -> Used {
|
||||
let designs: Vec<GraphDesign> = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect();
|
||||
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,
|
||||
@@ -1177,9 +1225,9 @@ impl Clipboard {
|
||||
char_styles: &self.char_styles,
|
||||
para_styles: &self.para_styles,
|
||||
brushes: Brushes::Ready(&self.brushes),
|
||||
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).
|
||||
@@ -1200,7 +1248,8 @@ impl Clipboard {
|
||||
/// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another
|
||||
/// document's are, while its image blobs are still the document's own under their keys.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc)
|
||||
let used = self.used(d);
|
||||
self.import_used_with_images(d, &used, choices, same_doc && !self.colors_converted, same_doc)
|
||||
}
|
||||
|
||||
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
|
||||
@@ -1211,7 +1260,7 @@ impl Clipboard {
|
||||
if same_doc {
|
||||
return;
|
||||
}
|
||||
let used = self.used();
|
||||
let used = self.used(d);
|
||||
let colors: BTreeMap<String, Color> = self
|
||||
.conflicts(d, &used)
|
||||
.into_iter()
|
||||
@@ -1248,6 +1297,11 @@ impl Clipboard {
|
||||
) -> Result<Imported> {
|
||||
let mut out = Imported::default();
|
||||
out.relink.filters = self.filter_links(d, same_doc)?;
|
||||
let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name);
|
||||
let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count();
|
||||
if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX {
|
||||
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
|
||||
}
|
||||
self.import_images(d, used, same_doc_images, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
self.import_kinsoku_sets(d, used, same_doc, &mut out);
|
||||
@@ -1331,11 +1385,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 {
|
||||
@@ -1371,6 +1432,7 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
self.import_graphic_styles(d, used, same_doc, &mut out);
|
||||
self.import_graph_designs(d, used, same_doc, &mut out)?;
|
||||
for (r, name, def) in added_styles {
|
||||
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
|
||||
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
|
||||
@@ -1381,6 +1443,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));
|
||||
@@ -1497,6 +1560,10 @@ impl Clipboard {
|
||||
for a in self.brushes.iter().flat_map(Brush::art) {
|
||||
node_filters(a, &mut found);
|
||||
}
|
||||
// A design the document has under the same name stays its own, so its art here is not pasted.
|
||||
for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) {
|
||||
node_filters(&g.art, &mut found);
|
||||
}
|
||||
for g in &self.graphic_styles {
|
||||
appearance_filters(&g.appearance, &mut found);
|
||||
}
|
||||
@@ -1575,6 +1642,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)
|
||||
@@ -1624,6 +1692,71 @@ impl Clipboard {
|
||||
out.relink.styles.insert(g.id, d.graphic_style_id(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> {
|
||||
// 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, 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| 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();
|
||||
let kept: Vec<String> = 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);
|
||||
continue;
|
||||
}
|
||||
if d.graph_designs.len() >= GraphDesign::MAX {
|
||||
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
|
||||
}
|
||||
let mut art = (*g.art).clone();
|
||||
out.relink.node(&mut art);
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a loaded text style is in the document ([`import_text_styles`]).
|
||||
@@ -1663,6 +1796,72 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
|
||||
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
|
||||
let mut used = Used::default();
|
||||
let mut todo = vec![];
|
||||
for n in names {
|
||||
used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo);
|
||||
}
|
||||
used.follow(defs, todo);
|
||||
used
|
||||
}
|
||||
|
||||
/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes
|
||||
/// and images their art uses, and nothing else: what a document opened as a library keeps for the
|
||||
/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs.
|
||||
pub(crate) fn graph_design_library(src: &Document) -> Option<Document> {
|
||||
if src.graph_designs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let names: Vec<String> = src.graph_designs.iter().map(|g| g.name.clone()).collect();
|
||||
let library = OnceCell::new();
|
||||
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);
|
||||
}
|
||||
d.title = src.title.clone();
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// 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, and the art of `src`'s design of that name is not followed. → the
|
||||
/// names of the designs added ([`Imported::added_designs`]): those of `names` `d` lacked, and those
|
||||
/// their art uses; with the symbols added and the designs `d` kept that their art draws with
|
||||
/// ([`Imported::added_symbols`], [`Imported::kept_designs`]). 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<Imported> {
|
||||
let library = OnceCell::new();
|
||||
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![]);
|
||||
clip.import_used(d, &used, &SwatchChoices::default(), false)
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
/// share one namespace).
|
||||
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
|
||||
|
||||
@@ -1653,6 +1653,17 @@ 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,
|
||||
// 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);
|
||||
}
|
||||
// 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
|
||||
|
||||
@@ -41,6 +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::{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;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::data::fmt_value;
|
||||
use super::designs::design_names;
|
||||
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};
|
||||
@@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
let names = design_names(&s.doc()?.doc);
|
||||
let mut names = design_names(&s.doc()?.doc);
|
||||
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked.clone() };
|
||||
// The column design the picked series (all of them with none picked) share; a design deleted since doesn't count,
|
||||
// as those series draw plain columns.
|
||||
@@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned();
|
||||
let Some(v) = p.get("design") else {
|
||||
let options = shared.clone().unwrap_or_default();
|
||||
return Ok(json!({
|
||||
let mut out = json!({
|
||||
"designs": names,
|
||||
"design": shared.map(|c| c.design),
|
||||
"columnType": options.column_type.id(),
|
||||
"each": options.each,
|
||||
"fractions": options.fractions.id(),
|
||||
}));
|
||||
});
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
return Ok(out);
|
||||
};
|
||||
// A design of a loaded library comes into the document in the same undo step.
|
||||
let library = from_library(s, p, C)?;
|
||||
names.extend(library.as_ref().map(|(_, n)| n.clone()));
|
||||
let design = match v {
|
||||
Value::Null => None,
|
||||
Value::String(n) if names.contains(n) => Some(n.clone()),
|
||||
@@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// 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_for(&mut probe, lib, name, id, &mut spec)?;
|
||||
}
|
||||
let looks = column_designs(&probe, &spec);
|
||||
if generate_with(&mut probe, &spec, &looks).is_none() {
|
||||
return Err(bad(C, "the design is too big to draw in every column of this graph"));
|
||||
}
|
||||
s.edit("Graph Column", |d, sel| {
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(d, lib, name, id, &mut spec)?;
|
||||
}
|
||||
regenerate(d, id, spec)?;
|
||||
if !reselect.is_empty() {
|
||||
reselect_series(d, sel, id, &reselect);
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Design…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}",
|
||||
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}",
|
||||
has_doc,
|
||||
design
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Column…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}",
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}",
|
||||
has_selection,
|
||||
set_column
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Marker…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}",
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}",
|
||||
has_selection,
|
||||
set_marker
|
||||
),
|
||||
|
||||
@@ -1,44 +1,291 @@
|
||||
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 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};
|
||||
|
||||
/// The document's graph design names, in order.
|
||||
pub(super) fn design_names(d: &Document) -> Vec<String> {
|
||||
d.graph_designs.iter().map(|x| x.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// Whether graph `g` draws a series with design `name`, as its marker or its columns.
|
||||
/// 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 (in any case, as
|
||||
/// swatch library names are matched). `None` without
|
||||
/// `library`.
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Arc<Document>>> {
|
||||
let key = match p.get("library") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::String(k)) => k.as_str(),
|
||||
Some(_) => {
|
||||
let list = "graph.design";
|
||||
return Err(bad(cmd, format!("`library` is a library id or name (see {list})")));
|
||||
}
|
||||
};
|
||||
let libs = &s.graph_design_libraries;
|
||||
let own = concealed_library_id(s, key);
|
||||
libs.get(key)
|
||||
.or_else(|| own.as_deref().and_then(|id| libs.get(id)))
|
||||
.or_else(|| libs.iter().find(|l| l.name.eq_ignore_ascii_case(key)))
|
||||
.map(|l| Some(l.doc.clone()))
|
||||
.ok_or_else(|| bad(cmd, format!("no library `{key}`")))
|
||||
}
|
||||
|
||||
/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no
|
||||
/// loaded library holds graph designs.
|
||||
pub(super) fn libraries_json(s: &Session) -> Option<Value> {
|
||||
let libs: Vec<Value> = s
|
||||
.graph_design_libraries
|
||||
.iter()
|
||||
.map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) }))
|
||||
.collect();
|
||||
(!libs.is_empty()).then(|| json!(libs))
|
||||
}
|
||||
|
||||
/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a
|
||||
/// `library` and the document has no design of that name: the document's own design of a name is
|
||||
/// the one a graph draws with.
|
||||
pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Arc<Document>, String)>> {
|
||||
let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) };
|
||||
let Some(Value::String(n)) = p.get("design") else { return Ok(None) };
|
||||
if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !lib.graph_designs.iter().any(|x| x.name == *n) {
|
||||
return Err(bad(cmd, format!("no design named `{n}`")));
|
||||
}
|
||||
Ok(Some((lib, n.clone())))
|
||||
}
|
||||
|
||||
/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the
|
||||
/// graphs that already name a design the document lacked: one of `names`, or one their art uses.
|
||||
/// The graphs in the art of the symbols that came in are drawn with the designs the document kept.
|
||||
pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> {
|
||||
let imported = import_graph_designs(lib, d, names)?;
|
||||
if !imported.kept_designs.is_empty() {
|
||||
redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
|
||||
}
|
||||
if !imported.added_designs.is_empty() {
|
||||
refresh_graphs(d, &imported.added_designs, &[], &BTreeSet::new())?;
|
||||
}
|
||||
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 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)
|
||||
};
|
||||
// Point markers use the same range of designs: a scatter graph plots a pair of series for each.
|
||||
let plotted = if scatter { nser.div_ceil(2) } else { nser };
|
||||
let shown = |s: usize| s < plotted && (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).
|
||||
/// 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![];
|
||||
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)) {
|
||||
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: 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(())
|
||||
}
|
||||
|
||||
/// The designs no graph's series draw with (Select Unused).
|
||||
/// [`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<()> {
|
||||
for id in ids {
|
||||
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<String>,
|
||||
names: &std::collections::BTreeSet<String>,
|
||||
) {
|
||||
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<String>) -> 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<String>) {
|
||||
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): 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) {
|
||||
@@ -105,22 +352,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 }));
|
||||
@@ -159,7 +413,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
// Designs from a document loaded as a library: those the document has under the same name stay
|
||||
// as they are.
|
||||
if let Some(mut wanted) = names_param(p, "add", C)? {
|
||||
let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?;
|
||||
if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) {
|
||||
return Err(bad(C, format!("no design named `{n}`")));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
wanted.retain(|n| seen.insert(n.clone()));
|
||||
let (existing, added): (Vec<String>, Vec<String>) = wanted.into_iter().partition(|n| taken(s, n));
|
||||
if !added.is_empty() {
|
||||
s.edit("New Design", |d, _| bring_in(d, &lib, &added))?;
|
||||
}
|
||||
return Ok(json!({ "added": added, "existing": existing }));
|
||||
}
|
||||
if let Some(lib) = library_param(s, p, C)? {
|
||||
return Ok(json!({ "designs": design_names(&lib) }));
|
||||
}
|
||||
// The list, with the designs no graph draws with (Select Unused picks those).
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) }))
|
||||
let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) });
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -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<Value> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::designs::design_names;
|
||||
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};
|
||||
@@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
let names = design_names(&s.doc()?.doc);
|
||||
let mut names = design_names(&s.doc()?.doc);
|
||||
let Some(v) = p.get("design") else {
|
||||
// The design the picked series (all of them with none picked) share, or null.
|
||||
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked };
|
||||
@@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let used: Vec<Option<&String>> =
|
||||
all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect();
|
||||
let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d)));
|
||||
return Ok(json!({ "designs": names, "design": shared }));
|
||||
let mut out = json!({ "designs": names, "design": shared });
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
return Ok(out);
|
||||
};
|
||||
// A design of a loaded library comes into the document in the same undo step.
|
||||
let library = from_library(s, p, C)?;
|
||||
names.extend(library.as_ref().map(|(_, n)| n.clone()));
|
||||
let design = match v {
|
||||
Value::Null => None,
|
||||
Value::String(n) if names.contains(n) => Some(n.clone()),
|
||||
@@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
while spec.series_markers.last().is_some_and(Option::is_none) {
|
||||
spec.series_markers.pop();
|
||||
}
|
||||
if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET {
|
||||
let cost = match &library {
|
||||
Some((lib, name)) => {
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
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)),
|
||||
};
|
||||
if cost > MARKER_BUDGET {
|
||||
return Err(bad(C, "the design is too big to draw at every data point of this graph"));
|
||||
}
|
||||
s.edit("Graph Marker", |d, sel| {
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(d, lib, name, id, &mut spec)?;
|
||||
}
|
||||
regenerate(d, id, spec)?;
|
||||
if !reselect.is_empty() {
|
||||
reselect_series(d, sel, id, &reselect);
|
||||
|
||||
@@ -5469,6 +5469,964 @@ fn graph_designs_are_saved_pasted_and_deleted() {
|
||||
assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
}
|
||||
|
||||
/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold".
|
||||
fn save_coin_design(s: &mut Session) {
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
|
||||
}
|
||||
|
||||
/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other
|
||||
/// Library…) → its id.
|
||||
fn load_coin_library(s: &mut Session) -> String {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut src);
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"});
|
||||
let r = s.execute("swatch.library.load", &p).unwrap();
|
||||
assert_eq!(r["graphDesigns"], 1);
|
||||
r["library"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Whether some object of `n` is filled with a colour linked to swatch `name`.
|
||||
fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name)));
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// The Column dialog's list: none of the document's, Coin from the library.
|
||||
let q = s.execute("graph.column", &json!({})).unwrap();
|
||||
assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib)));
|
||||
assert_eq!(q["libraries"][0]["designs"], json!(["Coin"]));
|
||||
assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's");
|
||||
let steps = undo_len(&s);
|
||||
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
assert_eq!(undo_len(&s), steps + 1, "one undo step");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
|
||||
assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along");
|
||||
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold"));
|
||||
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design");
|
||||
// Undo takes the design, its swatch and the columns' design out together.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty());
|
||||
// Marker takes them too.
|
||||
let line = graph(&mut s, "line");
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]);
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
// An unknown library or design, and a library that is not a string, are refused.
|
||||
for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] {
|
||||
assert!(s.execute("graph.column", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
let steps = undo_len(&s);
|
||||
let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap();
|
||||
assert_eq!(r, json!({"added": [], "existing": ["Coin"]}));
|
||||
assert_eq!(undo_len(&s), steps, "nothing changed: no undo step");
|
||||
// Applying it with the library draws with the document's own design.
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
|
||||
assert!(d.swatch("Gold").is_none());
|
||||
assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library");
|
||||
assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err());
|
||||
assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err());
|
||||
// The document without it takes it as one undo step.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Coin"], "existing": []}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.graph_designs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_brings_the_designs_its_series_draw_with() {
|
||||
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();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
|
||||
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some());
|
||||
// A data edit redraws the pasted graph with the design.
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap();
|
||||
assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold"));
|
||||
// A document with its own design of that name keeps it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
|
||||
// The pasted graph is drawn with that design straight away.
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
// The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each
|
||||
// column and the legend swatch hold two paths.
|
||||
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<usize> = series(d.node(pasted).unwrap(), 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_the_document_keeps_brings_none_of_the_pasted_designs_resources() {
|
||||
// A column graph whose spec names marker design "Coin", which only line series draw: the
|
||||
// graph's own art does not use the design's swatch.
|
||||
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.marker", &json!({"design": "Coin"})).unwrap();
|
||||
assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin")));
|
||||
assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold"));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document with its own "Coin" keeps it and takes nothing the pasted design's art uses.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.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("edit.paste", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_naming_a_deleted_design_draws_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("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it");
|
||||
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 pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 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_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();
|
||||
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();
|
||||
let names: Vec<Option<String>> = 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#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
|
||||
const SHIFT_MORE: &str = r#"<filter id="Shift"><feOffset dx="9" dy="9"/></filter>"#;
|
||||
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<Option<String>> = 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<usize> = 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_leaves_a_scatter_graph_that_names_it_for_a_slot_it_does_not_plot() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// Four data columns plot two series, so marker slot 2 is never drawn.
|
||||
let id = make(&mut s, "scatter", ",y1,x1,y2,x2\nP,1,10,2,20\nQ,3,11,4,22");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(spec(&s, id).mark_points, "Mark Data Points is on");
|
||||
s.execute("graph.marker", &json!({"design": "Coin", "library": lib, "seriesIndexes": [2]})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_markers.get(2).cloned().flatten().as_deref(), Some("Coin"));
|
||||
// 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();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let names: Vec<Option<String>> = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
|
||||
assert_eq!(names[0].as_deref(), Some("Mine"), "not drawn again: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_a_library_design_brings_draws_its_graph_with_the_documents_design_it_keeps() {
|
||||
// The library's design "A" holds an instance of symbol "Chart", whose graph draws columns with
|
||||
// the library's "B": a rectangle and an ellipse.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut src, "B");
|
||||
let id = graph(&mut src, "column");
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
src.execute("graph.column", &json!({"design": "B"})).unwrap();
|
||||
let instance = src.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "A"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Lib.vectorcraft"});
|
||||
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
|
||||
// The document's own "B" is a single rectangle, and stays.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "B"})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "A"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.len(), 2, "A came in and B stayed");
|
||||
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<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [1, 1, 1, 1], "drawn with the document's B");
|
||||
}
|
||||
|
||||
#[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<_>>(), [Vec::<u32>::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<usize> = 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();
|
||||
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();
|
||||
// Made again under the same name as a rectangle and an ellipse.
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
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");
|
||||
let mut s = Session::new();
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let loaded = load_coin_library(&mut s);
|
||||
// The User Defined copy is a swatch file: it holds the swatches alone.
|
||||
let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string();
|
||||
assert_ne!(copy, loaded);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone();
|
||||
assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}]));
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
assert!(s.execute("graph.design", &json!({"library": copy})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size");
|
||||
let path = dir.join("big.vectorcraft");
|
||||
let f = std::fs::File::create(&path).unwrap();
|
||||
f.set_len(((256 << 20) + 1) as u64).unwrap();
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string();
|
||||
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() {
|
||||
// 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();
|
||||
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]
|
||||
fn reading_the_head_of_a_swatch_library_file_stops_at_the_limit() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-head");
|
||||
let path = dir.join("long.gpl");
|
||||
std::fs::write(&path, vec![b'a'; 1 << 20]).unwrap();
|
||||
// The read the limit check relies on returns the bytes up to one past the limit, not the file.
|
||||
let head = crate::cmd::fileio::read_file_head(&path.to_string_lossy(), 9).unwrap();
|
||||
assert_eq!(head.len(), 9);
|
||||
}
|
||||
|
||||
#[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
|
||||
// registration point and the Graphic export type.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap();
|
||||
src.execute("select.all", &json!({})).unwrap();
|
||||
let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"});
|
||||
let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [inst]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"});
|
||||
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap();
|
||||
let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc);
|
||||
assert!(from.symbol_nine_slice("Corner").is_some());
|
||||
assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner"));
|
||||
assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner"));
|
||||
assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_and_markers_survive_save_and_open() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -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;
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own), unless it has graph designs, which then load with no swatches. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -92,6 +92,45 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the
|
||||
/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DesignLibraries {
|
||||
libs: Vec<DesignLibrary>,
|
||||
}
|
||||
|
||||
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DesignLibrary {
|
||||
/// The id `swatch.library.load` gave the swatch library. A User Defined copy of it
|
||||
/// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// The designs and the resources their art uses.
|
||||
pub doc: Arc<vectorcraft_doc::Document>,
|
||||
}
|
||||
|
||||
impl DesignLibraries {
|
||||
/// The libraries, in the order they were loaded.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &DesignLibrary> {
|
||||
self.libs.iter()
|
||||
}
|
||||
|
||||
/// The library loaded as swatch library `id`.
|
||||
pub fn get(&self, id: &str) -> Option<&DesignLibrary> {
|
||||
self.libs.iter().find(|l| l.id == id)
|
||||
}
|
||||
|
||||
/// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id`
|
||||
/// before; with no designs, `id` no longer has any.
|
||||
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
|
||||
self.libs.retain(|l| l.id != id);
|
||||
if let Some(doc) = doc {
|
||||
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The libraries beyond the built-in ones: User Defined (the library files in the user library
|
||||
/// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use
|
||||
/// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]).
|
||||
@@ -354,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`")),
|
||||
@@ -777,12 +836,40 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 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", 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", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
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| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
// 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) {
|
||||
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
|
||||
}
|
||||
@@ -792,10 +879,17 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
|
||||
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
|
||||
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
let mut lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
let doc_designs = super::clipboard::resources::graph_design_library(&loaded.doc);
|
||||
if defaults || lib.is_empty() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
// A document with graph designs loads for them, with no swatches.
|
||||
if doc_designs.is_none() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
}
|
||||
lib.swatches.clear();
|
||||
lib.groups.clear();
|
||||
}
|
||||
designs = doc_designs;
|
||||
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
|
||||
patterns = Some(Arc::new(loaded.doc));
|
||||
}
|
||||
@@ -804,7 +898,9 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if info.category == "loaded" {
|
||||
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
|
||||
}
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
let count = designs.as_ref().map_or(0, |d| d.graph_designs.len());
|
||||
s.graph_design_libraries.set(&info.id, &info.name, designs);
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count}))
|
||||
}
|
||||
|
||||
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
|
||||
|
||||
@@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy
|
||||
}
|
||||
}
|
||||
|
||||
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects after
|
||||
/// its art changed from `old` outside symbol editing (a graph in it drawn again): a change to an
|
||||
/// object that is no longer there is dropped ([`follow_objects`]).
|
||||
pub(crate) fn follow_art_change(d: &mut Document, name: &str, old: &Arc<Node>) {
|
||||
let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return };
|
||||
let parts = |art: &Arc<Node>| 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
|
||||
|
||||
@@ -153,6 +153,9 @@ pub struct Session {
|
||||
pub(crate) pending_paint: Option<Paint>,
|
||||
/// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved.
|
||||
pub swatch_libraries: cmd::swatchlib::Libraries,
|
||||
/// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries →
|
||||
/// Other Library…), for the Graph Column and Graph Marker dialogs; not saved.
|
||||
pub graph_design_libraries: cmd::swatchlib::DesignLibraries,
|
||||
/// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it
|
||||
/// was selected on: read it with [`Session::selected_freeform_point`].
|
||||
pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>,
|
||||
|
||||
@@ -85,6 +85,7 @@ impl Session {
|
||||
recent_colors: vec![],
|
||||
pending_paint: None,
|
||||
swatch_libraries: Default::default(),
|
||||
graph_design_libraries: Default::default(),
|
||||
freeform_point: None,
|
||||
style_libraries: Default::default(),
|
||||
symbol_libraries: Default::default(),
|
||||
|
||||
@@ -9,8 +9,12 @@
|
||||
//! For Fractions; OK runs `graph.column`.
|
||||
//! Marker: the design the selected graph series draw their data points with, or None (the default
|
||||
//! square marker); OK runs `graph.marker`.
|
||||
//! Column and Marker also list, under each library's name, the graph designs of the documents
|
||||
//! Window › Swatch Libraries › Other Library… loaded that the document lacks; OK on one copies it
|
||||
//! into the document with the resources its art uses.
|
||||
//!
|
||||
//! Fields: `selected` (the selected designs' names; Column and Marker: one name, null for None),
|
||||
//! in Column and Marker `library` (the library of the selected design, null for the document's),
|
||||
//! in Graph Design `name` (the name Rename gives), and in Column `columnType`, `each` and
|
||||
//! `fractions`.
|
||||
|
||||
@@ -46,6 +50,7 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec {
|
||||
confirm: |app, d| {
|
||||
let p = json!({
|
||||
"design": d.fields.get("selected").and_then(Value::as_str),
|
||||
"library": library_of(d),
|
||||
"columnType": d.str("columnType"),
|
||||
"each": d.f64("each", vectorcraft_doc::ColumnDesign::EACH),
|
||||
"fractions": d.str("fractions"),
|
||||
@@ -59,7 +64,9 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec {
|
||||
pub(super) const MARKER_SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Graph Marker").into(),
|
||||
body: marker_body,
|
||||
confirm: |app, d| run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str) })),
|
||||
confirm: |app, d| {
|
||||
run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str), "library": library_of(d) }))
|
||||
},
|
||||
min_width: 300.0,
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
@@ -95,6 +102,24 @@ fn names(app: &VectorcraftApp) -> Result<Vec<String>, String> {
|
||||
Ok(st.doc.graph_designs.iter().map(|d| d.name.clone()).collect())
|
||||
}
|
||||
|
||||
/// The designs of the loaded libraries that the document lacks (the document's own design of a name
|
||||
/// is the one used), by library: its id, its name and the design names, libraries with none left
|
||||
/// out.
|
||||
fn library_designs(app: &VectorcraftApp) -> Vec<(String, String, Vec<String>)> {
|
||||
let own = names(app).unwrap_or_default();
|
||||
app.session
|
||||
.graph_design_libraries
|
||||
.iter()
|
||||
.map(|l| (l.id.clone(), l.name.clone(), l.doc.graph_designs.iter().map(|g| g.name.clone()).filter(|n| !own.contains(n)).collect::<Vec<_>>()))
|
||||
.filter(|(.., names)| !names.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Column and Marker's `library`: the library of the selected design, `None` for the document's.
|
||||
fn library_of(d: &Dialog) -> Option<&str> {
|
||||
d.fields.get("library").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// Graph Design's selected designs.
|
||||
fn selected(d: &Dialog) -> Vec<String> {
|
||||
d.fields.get("selected").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
@@ -105,8 +130,9 @@ fn select(d: &mut Dialog, names: Vec<String>) {
|
||||
d.fields.insert("selected".into(), json!(names));
|
||||
}
|
||||
|
||||
/// A design's art drawn in `r` (cached by the art's identity).
|
||||
fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) {
|
||||
/// A design's art drawn in `r` (cached by the art's identity): the document's design `name`, or
|
||||
/// with `library` that loaded library's.
|
||||
fn preview(ui: &egui::Ui, app: &VectorcraftApp, library: Option<&str>, name: &str, r: egui::Rect) {
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
thread_local! {
|
||||
@@ -114,11 +140,18 @@ fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) {
|
||||
static CACHE: crate::graphics::TexCache<HashMap<usize, egui::TextureHandle>> = crate::graphics::TexCache::default();
|
||||
}
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let Some(art) = st.doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return };
|
||||
let doc = match library {
|
||||
Some(id) => match app.session.graph_design_libraries.get(id) {
|
||||
Some(l) => &l.doc,
|
||||
None => return,
|
||||
},
|
||||
None => &st.doc,
|
||||
};
|
||||
let Some(art) = doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return };
|
||||
let key = std::sync::Arc::as_ptr(&art) as usize;
|
||||
let px = (r.width() * ui.ctx().pixels_per_point()).round() as u32;
|
||||
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| {
|
||||
let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(&st.doc, &art, px.max(16), Some([255, 255, 255, 255])))?;
|
||||
let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(doc, &art, px.max(16), Some([255, 255, 255, 255])))?;
|
||||
let color = crate::canvas::color_image(&img);
|
||||
let tex = ui.ctx().load_texture(format!("graph-design-{key}"), color, egui::TextureOptions::LINEAR);
|
||||
CACHE.with(|c| {
|
||||
@@ -177,7 +210,7 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b
|
||||
let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover());
|
||||
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside);
|
||||
if let Some(n) = &one {
|
||||
preview(ui, app, n, r.shrink(4.0));
|
||||
preview(ui, app, None, n, r.shrink(4.0));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
let button =
|
||||
@@ -220,37 +253,66 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b
|
||||
false
|
||||
}
|
||||
|
||||
/// The list of Column and Marker: None, then the designs `names`; a click picks one into `selected` (null for None).
|
||||
fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], salt: &str) {
|
||||
/// The list of Column and Marker: None, the document's designs `names`, then each loaded library's
|
||||
/// name and the designs of it in `libraries` ([`library_designs`]); a click picks one into
|
||||
/// `selected` (null for None) and its library into `library` (null for the document's).
|
||||
fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], libraries: &[(String, String, Vec<String>)], salt: &str) {
|
||||
widgets::list_box(ui, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt(salt).min_scrolled_height(160.0).max_height(160.0).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.set_min_height(160.0);
|
||||
let current = d.fields.get("selected").and_then(Value::as_str).map(str::to_string);
|
||||
let from = library_of(d).map(str::to_string);
|
||||
let pick = |d: &mut Dialog, name: Option<&str>, library: Option<&str>| {
|
||||
d.fields.insert("selected".into(), json!(name));
|
||||
d.fields.insert("library".into(), json!(library));
|
||||
};
|
||||
if ui.selectable_label(current.is_none(), tl!("None")).clicked() {
|
||||
d.fields.insert("selected".into(), Value::Null);
|
||||
pick(d, None, None);
|
||||
}
|
||||
for n in names {
|
||||
if ui.selectable_label(current.as_deref() == Some(n.as_str()), n.as_str()).clicked() {
|
||||
d.fields.insert("selected".into(), json!(n));
|
||||
if ui.selectable_label(from.is_none() && current.as_deref() == Some(n.as_str()), n.as_str()).clicked() {
|
||||
pick(d, Some(n), None);
|
||||
}
|
||||
}
|
||||
for (id, library, designs) in libraries {
|
||||
ui.add_space(4.0);
|
||||
// The library's own name, not interface text.
|
||||
widgets::dim_name(ui, library);
|
||||
for n in designs {
|
||||
let on = from.as_deref() == Some(id.as_str()) && current.as_deref() == Some(n.as_str());
|
||||
if ui.selectable_label(on, n.as_str()).clicked() {
|
||||
pick(d, Some(n), Some(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The design Column or Marker has selected, with its library (`None`: the document's), when the
|
||||
/// document or that library still has it.
|
||||
fn shown_design(d: &Dialog, names: &[String], libraries: &[(String, String, Vec<String>)]) -> Option<(Option<String>, String)> {
|
||||
let n = d.fields.get("selected").and_then(Value::as_str)?;
|
||||
match library_of(d) {
|
||||
None => names.iter().any(|x| x == n).then(|| (None, n.to_string())),
|
||||
Some(id) => libraries.iter().any(|(l, _, designs)| l == id && designs.iter().any(|x| x == n)).then(|| (Some(id.to_string()), n.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn column_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let names = names(app).unwrap_or_default();
|
||||
let libraries = library_designs(app);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(220.0);
|
||||
one_design_list(ui, d, &names, "graph-columns");
|
||||
one_design_list(ui, d, &names, &libraries, "graph-columns");
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover());
|
||||
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside);
|
||||
if let Some(n) = d.fields.get("selected").and_then(Value::as_str).filter(|n| names.iter().any(|x| x == n)) {
|
||||
preview(ui, app, n, r.shrink(4.0));
|
||||
if let Some((library, n)) = shown_design(d, &names, &libraries) {
|
||||
preview(ui, app, library.as_deref(), &n, r.shrink(4.0));
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
@@ -277,9 +339,10 @@ const EACH_RANGE: std::ops::RangeInclusive<f64> = 0.0001..=1_000_000_000.0;
|
||||
|
||||
fn marker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let names = names(app).unwrap_or_default();
|
||||
let libraries = library_designs(app);
|
||||
// A list as wide as Graph Design's, not the whole window.
|
||||
ui.set_width(220.0);
|
||||
one_design_list(ui, d, &names, "graph-markers");
|
||||
one_design_list(ui, d, &names, &libraries, "graph-markers");
|
||||
false
|
||||
}
|
||||
|
||||
@@ -377,4 +440,33 @@ mod tests {
|
||||
(super::COLUMN_SPEC.confirm)(&mut app, &d).unwrap();
|
||||
assert_eq!(app.session.execute("graph.column", &json!({})).unwrap()["design"], json!(null));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_lists_a_loaded_documents_designs_and_ok_copies_the_one_picked_in() {
|
||||
// A document with design "New Design", loaded as a swatch library (Other Library…).
|
||||
let src = app_with_design();
|
||||
let bytes = vectorcraft_format::save_file(&src.session.active().unwrap().doc);
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Dots.vectorcraft"});
|
||||
app.run("swatch.library.load", p).unwrap();
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let g = app.run("graph.create", json!({"type": "line", "x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [g]})).unwrap();
|
||||
let libraries = super::library_designs(&app);
|
||||
assert_eq!(libraries.len(), 1);
|
||||
let (id, _, designs) = &libraries[0];
|
||||
assert_eq!(designs, &["New Design".to_string()]);
|
||||
crate::menus::invoke(&mut app, "graph.marker", json!({}));
|
||||
frame(&mut app);
|
||||
let mut d: Dialog = app.ui.dialog.take().unwrap();
|
||||
d.fields.insert("selected".into(), json!("New Design"));
|
||||
d.fields.insert("library".into(), json!(id));
|
||||
app.ui.dialog = Some(d.clone());
|
||||
frame(&mut app);
|
||||
(super::MARKER_SPEC.confirm)(&mut app, &d).unwrap();
|
||||
assert_eq!(app.session.execute("graph.marker", &json!({})).unwrap()["design"], "New Design");
|
||||
assert_eq!(super::names(&app).unwrap(), ["New Design"]);
|
||||
// The document has it now, so the library lists it no more.
|
||||
assert!(super::library_designs(&app).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
+16
-3
@@ -5778,15 +5778,28 @@ document's swatches, as a library to add from. From an `.ase` file it reads RGB,
|
||||
spot or process swatches and keeps their color groups. A color book (such as a Pantone book you own) gives its RGB,
|
||||
CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks
|
||||
them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the
|
||||
same extension and bytes as one there, loads as that User Defined library (category `user`).
|
||||
same extension and bytes as one there, loads as that User Defined library (category `user`). A file larger than 256 MB
|
||||
is refused before it is read.
|
||||
From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches
|
||||
in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and
|
||||
art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot
|
||||
color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes
|
||||
in under a numbered name ("Ink 2") and the pattern links to that. A document with
|
||||
no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with
|
||||
"`<file>` has no swatches of its own". The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps`
|
||||
(`.epsf`) files as well as the library files.
|
||||
"`<file>` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The
|
||||
Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files.
|
||||
A document's graph designs come with it: the reply's `graphDesigns` counts them, and
|
||||
`graph.column`, `graph.marker` and `graph.design` take the library's id as `library` until the app quits (a User
|
||||
Defined copy made with `swatch.library.copyToUser` holds the swatches alone, so the designs stay under the loaded id).
|
||||
`graph.column {design, library}` and `graph.marker {design, library}` copy a design the document lacks into it, with the
|
||||
swatches, patterns, symbols, styles, brushes and images its art uses, in the same undo step as the graph change.
|
||||
`graph.design {library, add: name | [names]}` copies designs without applying them and returns `{added, existing}`, and
|
||||
`graph.design {library}` lists the library's designs. A design the document already has under the same name stays as it
|
||||
is. `graph.column` and `graph.marker` with no `design`, and `graph.design {}`, list the loaded libraries that hold
|
||||
designs as `libraries: [{library, name, designs}]`. Copying a graph and pasting it into another document brings the designs its series
|
||||
draw with in the same way; a pasted graph is drawn again with the document's design of that name when that design
|
||||
would draw it otherwise. The graphs already in the document that draw with a design the copy or paste adds, one a copied
|
||||
design's art uses included, are drawn again with it.
|
||||
`swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop
|
||||
app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64`
|
||||
as `.vcswatches`; a library with pattern swatches is refused) under a name no file there has, and lists it as User
|
||||
|
||||
@@ -1494,6 +1494,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out.
|
||||
The transparency, paint, stroke, gradient and overprint commands and Expand Appearance also leave the art of a column or marker design inside a series unchanged. The graph draws that art again from the design (`docs/mcp.md`).
|
||||
When that art is given first with `aligned: true`, the paint, stroke and gradient commands read the `item` as a row of the art's stack, and each other object edits its equal row.
|
||||
- **Graph designs from another document** ([Import a column or marker design](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=486)): a document opened with Window › Swatch Libraries › Other Library… adds its graph designs to the Column and Marker dialogs, listed under the library's name after the document's own. OK on one of them copies the design into the document with the swatches, patterns, symbols and styles its art uses, in the same undo step as the graph change (`graph.column` and `graph.marker` with `library`; `graph.design {library, add}` copies designs without applying them). A graph that is copied and pasted into another document brings the designs its series draw with. A design the document already has under the same name stays as it is, and a pasted graph is drawn again with that design when it would draw the graph otherwise, a VectorCraft rule. Tests: `designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied`, `a_design_the_document_has_under_the_same_name_stays_as_it_is`, `a_pasted_graph_brings_the_designs_its_series_draw_with` in `crates/engine/src/cmd/graph/tests.rs`.
|
||||
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View.
|
||||
While a drag rotates the view, a dial at the center of the canvas shows the angle.
|
||||
- **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation).
|
||||
|
||||
Reference in New Issue
Block a user