mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-22 18:34:42 +01:00
Graphs: graph designs come in from another document
A document opened with Window > Swatch Libraries > Other Library... now adds its graph designs to the Column and Marker dialogs, listed under the library's name after the document's own designs. OK on one of them copies the design into the document with the swatches, patterns, symbols, styles, brushes and images its art uses, in the same undo step as the graph change. graph.column and graph.marker take `library`, graph.design takes `library` with `add`, and swatch.library.load reports `graphDesigns` and refuses a file larger than 256 MB before reading it. The clipboard carries the graph designs that copied graphs draw with, so a graph pasted into another document brings its designs. A design the document already has under the same name stays as it is, and a pasted graph is drawn again with it when it would draw the graph otherwise.
This commit is contained in:
1 parent
ccb62b0912
commit
18ffda75dc
15 files changed
+718
-40
No files matched your search
@@ -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};
|
||||
@@ -85,6 +85,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>,
|
||||
@@ -372,7 +375,7 @@ impl Clipboard {
|
||||
if self.source_doc == Some(st.uid) {
|
||||
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).
|
||||
@@ -385,6 +388,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
|
||||
|
||||
@@ -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
|
||||
@@ -21,7 +22,7 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice,
|
||||
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice,
|
||||
SymbolRegistration, TextStyleDef,
|
||||
};
|
||||
|
||||
@@ -42,6 +43,7 @@ enum Res {
|
||||
ParaStyle,
|
||||
Brush,
|
||||
GraphicStyle,
|
||||
GraphDesign,
|
||||
}
|
||||
|
||||
impl Res {
|
||||
@@ -55,6 +57,7 @@ impl Res {
|
||||
Res::ParaStyle => "paraStyle",
|
||||
Res::Brush => "brush",
|
||||
Res::GraphicStyle => "graphicStyle",
|
||||
Res::GraphDesign => "graphDesign",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,6 +140,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) => {
|
||||
@@ -215,6 +222,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,
|
||||
}
|
||||
@@ -234,6 +242,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
|
||||
@@ -277,6 +286,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(),
|
||||
}
|
||||
}
|
||||
@@ -374,6 +384,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))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -404,7 +415,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 {
|
||||
@@ -449,6 +460,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 => {}
|
||||
}
|
||||
@@ -1019,6 +1031,10 @@ 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>,
|
||||
}
|
||||
|
||||
impl Imported {
|
||||
@@ -1071,13 +1087,17 @@ 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(),
|
||||
nodes,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The resources the objects use now (Paste without Formatting leaves text styles behind).
|
||||
pub(super) fn used(&self) -> Used {
|
||||
/// 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();
|
||||
let defs = Defs {
|
||||
swatches: self.swatches.iter().collect(),
|
||||
symbols: &self.symbols,
|
||||
@@ -1086,6 +1106,7 @@ 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)
|
||||
@@ -1106,7 +1127,8 @@ impl Clipboard {
|
||||
/// under a free name ("Dots 2") is compared and added with that name. An error, with `d`
|
||||
/// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]).
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used(d, &self.used(), choices, same_doc)
|
||||
let used = self.used(d);
|
||||
self.import_used(d, &used, choices, same_doc)
|
||||
}
|
||||
|
||||
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
|
||||
@@ -1117,6 +1139,11 @@ impl Clipboard {
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> 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, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
let mut defs: Vec<Def<'_>> = vec![];
|
||||
@@ -1239,6 +1266,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) {
|
||||
@@ -1289,6 +1317,9 @@ impl Clipboard {
|
||||
for a in self.brushes.iter().flat_map(Brush::art) {
|
||||
node_filters(a, &mut found);
|
||||
}
|
||||
for g in &self.graph_designs {
|
||||
node_filters(&g.art, &mut found);
|
||||
}
|
||||
for g in &self.graphic_styles {
|
||||
appearance_filters(&g.appearance, &mut found);
|
||||
}
|
||||
@@ -1416,6 +1447,39 @@ impl Clipboard {
|
||||
out.relink.styles.insert(g.id, d.graphic_style_id(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 (the art may draw it).
|
||||
let moved = !same_doc && (!out.relink.renames.is_empty() || out.merged > 0);
|
||||
let differs = |n: &str| {
|
||||
let ours = d.graph_designs.iter().find(|x| x.name == n);
|
||||
let theirs = self.graph_designs.iter().find(|g| g.name == n);
|
||||
ours.is_some_and(|x| moved || theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art))
|
||||
};
|
||||
let named = used.names.get(&Res::GraphDesign).into_iter().flatten();
|
||||
out.kept_designs.extend(named.filter(|n| differs(n)).cloned());
|
||||
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);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a loaded text style is in the document ([`import_text_styles`]).
|
||||
@@ -1455,6 +1519,51 @@ 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();
|
||||
// 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. → each name, and whether its design was added. An error, with `d`
|
||||
/// unchanged, when `d` would hold more than [`GraphDesign::MAX`] designs.
|
||||
pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result<Vec<(String, bool)>> {
|
||||
let library = OnceCell::new();
|
||||
let used = designs_used(&Defs::of(src, &library), names);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let before: HashSet<String> = d.graph_designs.iter().map(|g| g.name.clone()).collect();
|
||||
clip.import_used(d, &used, &SwatchChoices::default(), false)?;
|
||||
Ok(names.iter().map(|n| (n.clone(), !before.contains(n))).collect())
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
@@ -1536,6 +1536,10 @@ 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.
|
||||
if !imported.kept_designs.is_empty() {
|
||||
super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?;
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
|
||||
// paste of guides alone keeps them where they were, but onto another artboard or every
|
||||
|
||||
@@ -40,6 +40,7 @@ pub use commands::specs;
|
||||
pub(crate) use data::apply_csv;
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, parse_csv, to_csv};
|
||||
pub(crate) use designs::redraw_with_designs;
|
||||
pub(crate) use edit::{graphs_holding, keep_placed};
|
||||
#[cfg(test)]
|
||||
use generate::generate;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::data::fmt_value;
|
||||
use super::designs::design_names;
|
||||
use super::designs::{bring_in, 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(&mut probe, lib, std::slice::from_ref(name))?;
|
||||
}
|
||||
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(d, lib, std::slice::from_ref(name))?;
|
||||
}
|
||||
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,11 +1,71 @@
|
||||
use super::edit::regenerate;
|
||||
use super::{Arc, Document, GraphDesign, GraphSpec, 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()
|
||||
}
|
||||
|
||||
/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`)
|
||||
/// that holds graph designs, by its id, the id a reply showed for it, or its name. `None` without
|
||||
/// `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 == 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 one the document lacked.
|
||||
pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> {
|
||||
for (name, added) in import_graph_designs(lib, d, names)? {
|
||||
if added {
|
||||
refresh_graphs_using(d, &name)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether graph `g` draws a series with design `name`, as its marker or its columns.
|
||||
fn draws_with(g: &GraphSpec, name: &str) -> bool {
|
||||
g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name)
|
||||
@@ -27,6 +87,27 @@ fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs
|
||||
/// `names`: pasted graphs, after the paste kept the document's own designs of those names.
|
||||
pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet<String>) -> Result<()> {
|
||||
let mut graphs = vec![];
|
||||
for id in ids {
|
||||
if let Some(n) = d.node(*id) {
|
||||
n.walk(&mut |m| {
|
||||
if m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
|
||||
graphs.push(m.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
for id in graphs {
|
||||
if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) {
|
||||
regenerate(d, id, spec)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The designs no graph's series draw with (Select Unused).
|
||||
fn unused_designs(d: &Document) -> Vec<String> {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
@@ -159,7 +240,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)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::designs::design_names;
|
||||
use super::designs::{bring_in, 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(&mut probe, lib, std::slice::from_ref(name))?;
|
||||
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(d, lib, std::slice::from_ref(name))?;
|
||||
}
|
||||
regenerate(d, id, spec)?;
|
||||
if !reselect.is_empty() {
|
||||
reselect_series(d, sel, id, &reselect);
|
||||
|
||||
@@ -4320,6 +4320,273 @@ 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_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_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");
|
||||
}
|
||||
|
||||
#[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_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();
|
||||
|
||||
@@ -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), 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) → {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), 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 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 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`]).
|
||||
@@ -734,8 +773,17 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
// The size is checked before the file is read.
|
||||
let max = super::place::document::MAX_FILE;
|
||||
if let Some(path) = text_param(p, "path", C)?
|
||||
&& super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64)
|
||||
{
|
||||
return Err(bad(C, format!("the file is larger than {} MB", max >> 20)));
|
||||
}
|
||||
let mut designs = None;
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
// 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) {
|
||||
palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))
|
||||
} else {
|
||||
@@ -743,10 +791,13 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
designs = super::clipboard::resources::graph_design_library(&loaded.doc);
|
||||
document_library(&loaded.doc, &[], stem(file).to_string(), C)
|
||||
}
|
||||
})?;
|
||||
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}))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -144,6 +144,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)>,
|
||||
|
||||
@@ -78,6 +78,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());
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -4413,7 +4413,18 @@ 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. 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. With no `design`, `graph.column`, `graph.marker` 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.
|
||||
`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`) under a name no file there has, and lists it as User Defined from then on; until the app
|
||||
|
||||
@@ -1164,6 +1164,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks.
|
||||
- **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete.
|
||||
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.
|
||||
- **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