mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 08:11:41 +00:00
Merge main into #8336
# Conflicts: # crates/ui-egui/src/i18n/bg.tsv # crates/ui-egui/src/i18n/bs.tsv # crates/ui-egui/src/i18n/ca.tsv # crates/ui-egui/src/i18n/cs.tsv # crates/ui-egui/src/i18n/da.tsv # crates/ui-egui/src/i18n/de.tsv # crates/ui-egui/src/i18n/el.tsv # crates/ui-egui/src/i18n/es.tsv # crates/ui-egui/src/i18n/fi.tsv # crates/ui-egui/src/i18n/fr.tsv # crates/ui-egui/src/i18n/gu.tsv # crates/ui-egui/src/i18n/hi.tsv # crates/ui-egui/src/i18n/hu.tsv # crates/ui-egui/src/i18n/id.tsv # crates/ui-egui/src/i18n/it.tsv # crates/ui-egui/src/i18n/ja.tsv # crates/ui-egui/src/i18n/ka.tsv # crates/ui-egui/src/i18n/ko.tsv # crates/ui-egui/src/i18n/nl.tsv # crates/ui-egui/src/i18n/pl.tsv # crates/ui-egui/src/i18n/pt-br.tsv # crates/ui-egui/src/i18n/ru.tsv # crates/ui-egui/src/i18n/sv.tsv # crates/ui-egui/src/i18n/tr.tsv # crates/ui-egui/src/i18n/uk.tsv # crates/ui-egui/src/i18n/vi.tsv # crates/ui-egui/src/i18n/zh-hans.tsv # crates/ui-egui/src/i18n/zh-hant.tsv
This commit is contained in:
@@ -911,6 +911,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
|
||||
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets.
|
||||
pub use buildcmds::{TracePreset, TracePresetChange};
|
||||
|
||||
/// The `format`, extensions and largest size of the tracing presets files
|
||||
/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads.
|
||||
pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES};
|
||||
|
||||
/// An Image Trace made off the UI thread, and what it traced (#3098).
|
||||
pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::appearance::SharedStack;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_tools::builder::{edges, faces, is_live_paint};
|
||||
|
||||
use super::edit::{outermost, roots_of, selected_roots};
|
||||
use super::opacitymask::percent;
|
||||
@@ -48,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). In the contents of a Live Paint group the fill goes on its faces only, and its hidden source paths, like every contents edit, are left as they are. With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -57,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. In the contents of a Live Paint group the stroke goes on its edges only, and its hidden source paths are left as they are. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -129,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; a whole Live Paint group (selected, in ids, or `source` with `reverse`) takes the fill attributes on its faces and the stroke attributes on its edges (a whole-appearance pick: every fill row on each face and every stroke row on each edge, which keep their rows of the other kind and their effects; `append` adds the source's rows but not its object effects to them), and its hidden source paths keep their paint; a whole Live Paint group picked up (`source`, or selected first with `reverse`) gives its first face's fills with its first edge's strokes above them and the group's own opacity, blend mode and effects; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -280,7 +281,8 @@ impl ItemTarget {
|
||||
|
||||
/// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
|
||||
/// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
|
||||
/// ([`super::paint::live_paint_parts_skipped`]).
|
||||
/// ([`super::paint::live_paint_parts_skipped`]); an item edit with `target: "contents"` leaves out
|
||||
/// the parts of the other kind the same way ([`contents_skipped`]).
|
||||
pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result<Vec<NodeId>> {
|
||||
Ok(self.targets_and_skipped(s, p, fill)?.0)
|
||||
}
|
||||
@@ -290,13 +292,16 @@ impl ItemTarget {
|
||||
/// to new art.
|
||||
pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec<NodeId>, bool)> {
|
||||
let mut ids = self.targets(s, p)?;
|
||||
let mut skipped_any = false;
|
||||
if self == ItemTarget::Top {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
skipped_any = ids.len() != before;
|
||||
}
|
||||
// An item edit of the contents of a Live Paint group goes to its parts of the edited kind too.
|
||||
let skipped = if self == ItemTarget::Top {
|
||||
super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill)
|
||||
} else {
|
||||
contents_skipped(s, p, fill)?
|
||||
};
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
// A contents edit already leaves hidden source paths out of `ids`, so `skipped` is checked on its own too.
|
||||
let skipped_any = ids.len() != before || !skipped.is_empty();
|
||||
Ok((ids, skipped_any))
|
||||
}
|
||||
|
||||
@@ -491,15 +496,37 @@ pub(crate) fn subject_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
|
||||
/// Objects whose own appearance stack a command edits: `ids`/`id` (layers too; an id inside
|
||||
/// another given one is dropped), else the [`subject_roots`]; with `target: "contents"` the painted
|
||||
/// objects inside the groups and layers among them ([`leaf_targets`]).
|
||||
/// objects inside the groups and layers among them ([`leaf_targets`]), without the hidden source paths
|
||||
/// of Live Paint groups.
|
||||
pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let roots = if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
subject_roots(s)?
|
||||
let roots = appearance_roots(s, p)?;
|
||||
if !targets_contents(p)? {
|
||||
return Ok(roots);
|
||||
}
|
||||
let (_, _, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
|
||||
let mut ids = leaf_targets(s, &roots)?;
|
||||
ids.retain(|id| !hidden.contains(id));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The objects [`appearance_targets`] starts from: `ids`/`id`, else the [`subject_roots`].
|
||||
fn appearance_roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
subject_roots(s)
|
||||
} else {
|
||||
let d = &s.doc()?.doc;
|
||||
outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect())
|
||||
};
|
||||
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
|
||||
Ok(outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of the Live Paint groups whose contents `p` targets (`target: "contents"`) that a fill
|
||||
/// (`fill`) or stroke edit of those contents leaves as they are: their edges or faces. Empty without
|
||||
/// `target: "contents"`.
|
||||
pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<HashSet<NodeId>> {
|
||||
if !targets_contents(p)? {
|
||||
return Ok(HashSet::new());
|
||||
}
|
||||
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
|
||||
}
|
||||
|
||||
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
|
||||
@@ -897,7 +924,26 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
|
||||
let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" };
|
||||
let mut ids = row_targets(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
// A selected Live Paint group left with only its hidden source paths has nothing to edit: it is
|
||||
// still a selection, so the edit changes nothing.
|
||||
let roots = appearance_roots(s, p)?;
|
||||
if targets_contents(p)? && !roots.is_empty() && !super::paint::live_paint_split(&s.doc()?.doc, &roots).2.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
// In the contents of a Live Paint group, a new fill goes on its faces and a new stroke on its edges;
|
||||
// with no part of that kind, nothing changes.
|
||||
let skipped = contents_skipped(s, p, fill)?;
|
||||
if !skipped.is_empty() {
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
if ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
let defaults = s.paint.clone();
|
||||
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
|
||||
// row's paint, right above it in each target that has it (others take their top fill's paint).
|
||||
@@ -1779,7 +1825,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Reversed, the first selected object's attributes go onto the clicked object; with nothing
|
||||
// selected, what the Eyedropper picked up last does (#4382).
|
||||
let (source, mut targets) = if reverse {
|
||||
let source = match leaf_targets(s, &selected)?.into_iter().next() {
|
||||
// The selected objects are tried in order: a Live Paint group with a look is picked up as a whole
|
||||
// ([`live_paint_look`]), any other object gives its first painted leaf, and a group with nothing to pick
|
||||
// up (its hidden source paths are not what it draws) passes to the next object.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut first = None;
|
||||
for root in &selected {
|
||||
if d.node(*root).and_then(live_paint_look).is_some() {
|
||||
first = Some(*root);
|
||||
break;
|
||||
}
|
||||
let (_, _, hidden) = super::paint::live_paint_split(d, &[*root]);
|
||||
if let Some(leaf) = leaf_targets(s, &[*root])?.into_iter().find(|id| !hidden.contains(id)) {
|
||||
first = Some(leaf);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let source = match first {
|
||||
Some(first) => Some(first),
|
||||
None if s.eyedropper_sample.is_some() => None,
|
||||
None => return Err(bad(C, "select the object to copy from")),
|
||||
@@ -1788,10 +1850,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
(Some(clicked), leaf_targets(s, &selected)?)
|
||||
};
|
||||
targets.retain(|id| Some(*id) != source);
|
||||
// A whole Live Paint group takes the fill attributes on its faces and the stroke attributes on its edges, and its
|
||||
// hidden source paths keep their paint.
|
||||
let roots = if reverse { vec![clicked] } else { selected };
|
||||
let (faces, edges, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
|
||||
// Some(true) for a face, Some(false) for an edge.
|
||||
let part_of = |id: &NodeId| {
|
||||
if faces.contains(id) {
|
||||
Some(true)
|
||||
} else if edges.contains(id) {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let attrs_for = |id: &NodeId| {
|
||||
let mut a = attrs;
|
||||
match part_of(id) {
|
||||
Some(true) => a.appearance.stroke = StrokeAttrs::NONE,
|
||||
Some(false) => a.appearance.fill = FillAttrs::NONE,
|
||||
None => {}
|
||||
}
|
||||
a
|
||||
};
|
||||
// A pick of the whole appearance gives a face every fill row and an edge every stroke row.
|
||||
let whole = attrs.appearance.fill == FillAttrs::ALL && attrs.appearance.stroke == StrokeAttrs::ALL;
|
||||
// A source that is a Live Paint group is not one of its own targets: neither are its faces and edges.
|
||||
let mut inside_source = HashSet::new();
|
||||
if let Some(n) = source.and_then(|id| s.doc().ok()?.doc.node(id)).filter(|n| is_live_paint(n)) {
|
||||
n.walk(&mut |c| {
|
||||
inside_source.insert(c.id);
|
||||
});
|
||||
}
|
||||
targets.retain(|id| Some(*id) != source && !hidden.contains(id) && !inside_source.contains(id));
|
||||
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
|
||||
let node = match source {
|
||||
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
|
||||
Some(id) => {
|
||||
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
Arc::new(live_paint_look(n).unwrap_or_else(|| n.clone()))
|
||||
}
|
||||
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
|
||||
};
|
||||
let picked = Picked::of(&node);
|
||||
@@ -1919,7 +2016,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::overprint::edit_counted(s, "Eyedropper", |d| {
|
||||
for id in &targets {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
picked.apply(n, &attrs, append, characters.get(id));
|
||||
match part_of(id) {
|
||||
Some(fill) if whole && !append => picked.apply_rows(n, &attrs, fill),
|
||||
// `append` does not add the picked object effects to a face or edge, as a whole pick keeps the part's
|
||||
// own; a row's effects go with the row.
|
||||
Some(_) => {
|
||||
let effects = n.appearance.effects.len();
|
||||
picked.apply(n, &attrs_for(id), append, characters.get(id));
|
||||
n.appearance.effects.truncate(effects);
|
||||
}
|
||||
None => picked.apply(n, &attrs_for(id), append, characters.get(id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
check_text_bounds(d)?;
|
||||
@@ -2170,6 +2277,52 @@ impl Picked {
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
|
||||
/// A whole pick ([`Self::apply`] with every fill and stroke attribute) onto a Live Paint face
|
||||
/// (`fill`) or edge: the face's fills (the edge's strokes) become the picked ones, and its rows of
|
||||
/// the other kind and its effects stay as they are.
|
||||
fn apply_rows(&self, n: &mut Node, a: &EyedropperAttrs, fill: bool) {
|
||||
if a.appearance.transparency {
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
}
|
||||
let taken: Vec<AppearanceItem> = self.placed(n.geometric_bounds()).items.into_iter().filter(|it| it.is_fill() == fill).collect();
|
||||
// The picked rows go where the part's first row of that kind was, the other rows keep their order; without
|
||||
// such a row, fills go to the bottom and strokes to the top.
|
||||
let items = &n.appearance.items;
|
||||
let at = items.iter().position(|it| it.is_fill() == fill);
|
||||
let at = at.map_or(if fill { 0 } else { items.iter().filter(|it| it.is_fill() != fill).count() }, |i| {
|
||||
items.iter().take(i).filter(|it| it.is_fill() != fill).count()
|
||||
});
|
||||
let mut kept: Vec<AppearanceItem> = items.iter().filter(|it| it.is_fill() != fill).cloned().collect();
|
||||
kept.splice(at..at, taken);
|
||||
n.appearance.items = kept;
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Eyedropper picks up from a whole Live Paint group `n`: its first face (else its first edge) with that
|
||||
/// face's fills and the first edge's strokes above them, their gradients placed as on those parts, and the group's
|
||||
/// own opacity, blend mode and effects. None for any other object, and for a group with no face and no edge.
|
||||
fn live_paint_look(n: &Node) -> Option<Node> {
|
||||
if !is_live_paint(n) {
|
||||
return None;
|
||||
}
|
||||
let (face, edge) = (faces(n).first().copied(), edges(n).first().copied());
|
||||
let mut look = (**face.or(edge)?).clone();
|
||||
let rows = |part: Option<&Arc<Node>>, fill: bool| -> Vec<AppearanceItem> {
|
||||
part.map(|p| p.appearance.items.iter().filter(|it| it.is_fill() == fill).cloned().collect()).unwrap_or_default()
|
||||
};
|
||||
// The edge's stroke gradients, placed relative to the look's bounds as they are to the edge's.
|
||||
let mut strokes = Appearance { items: rows(edge, false), ..Default::default() };
|
||||
if let (Some(from), Some(to)) = (edge.and_then(|e| e.geometric_bounds()), look.geometric_bounds()) {
|
||||
strokes.rebase_gradients(from, to);
|
||||
}
|
||||
look.appearance.items = rows(face, true).into_iter().chain(strokes.items).collect();
|
||||
look.appearance.effects = n.appearance.effects.clone();
|
||||
look.opacity = n.opacity;
|
||||
look.blend = n.blend;
|
||||
Some(look)
|
||||
}
|
||||
|
||||
/// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates
|
||||
|
||||
@@ -178,6 +178,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
|
||||
BuiltinBrushLibrary { id: "ornamental", name: "Ornamental", make: ornamental },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
@@ -733,6 +734,53 @@ fn decorative() -> BrushLibrary {
|
||||
)
|
||||
}
|
||||
|
||||
/// Ornamental: one-pass flourishes and arrow accents that stretch with the path rather than
|
||||
/// repeating a pattern tile. Every shape is original filled vector art.
|
||||
fn ornamental() -> BrushLibrary {
|
||||
let scrollwork = group(vec![
|
||||
black(band(100.0, 1.2, 64, |x| 2.6 * (x / 100.0 * std::f64::consts::TAU).sin())),
|
||||
ring(Point::new(7.0, 0.0), 4.0, 2.0),
|
||||
ring(Point::new(93.0, 0.0), 4.0, 2.0),
|
||||
black(polygon(&[(28.0, 1.0), (34.0, -5.0), (40.0, -3.0), (33.0, 2.0)])),
|
||||
black(polygon(&[(60.0, 3.0), (66.0, 5.0), (72.0, -1.0), (67.0, -2.0)])),
|
||||
]);
|
||||
let arrow = group(vec![
|
||||
// The shaft runs into the head's notch at x = 85 so the two overlap.
|
||||
black(shapes::rectangle(Rect::new(4.0, -0.7, 86.0, 0.7))),
|
||||
black(polygon(&[(80.0, -6.5), (100.0, 0.0), (80.0, 6.5), (85.0, 0.0)])),
|
||||
ring(Point::new(7.0, 0.0), 4.0, 1.7),
|
||||
black(polygon(&[(25.0, -0.4), (31.0, -4.4), (37.0, -2.0), (31.0, 0.8)])),
|
||||
black(polygon(&[(43.0, 0.4), (49.0, 4.4), (55.0, 2.0), (49.0, -0.8)])),
|
||||
]);
|
||||
let mut petals = vec![black(band(100.0, 1.0, 48, |x| 1.8 * (x / 100.0 * std::f64::consts::PI).sin()))];
|
||||
for x in [19.0, 43.0, 67.0, 87.0] {
|
||||
let y = 1.8 * (x / 100.0 * std::f64::consts::PI).sin();
|
||||
petals.push(black(shapes::ellipse(Rect::new(x - 4.5, y - 7.5, x + 4.5, y - 0.3))));
|
||||
petals.push(black(shapes::ellipse(Rect::new(x - 3.5, y + 0.3, x + 3.5, y + 5.5))));
|
||||
}
|
||||
let petal_sweep = group(petals);
|
||||
let twin_curl = group(vec![
|
||||
black(band(100.0, 0.9, 64, |x| -3.8 + 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
|
||||
black(band(100.0, 0.9, 64, |x| 3.8 - 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
|
||||
ring(Point::new(8.0, -3.8), 3.0, 1.5),
|
||||
ring(Point::new(92.0, 3.8), 3.0, 1.5),
|
||||
]);
|
||||
let ornament = |name: &str, art: Node| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush { art, width: 300.0, colorization: Colorization::Tints, ..Default::default() }),
|
||||
};
|
||||
built(
|
||||
"Ornamental",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
ornament("Scrollwork", scrollwork),
|
||||
ornament("Filigree Arrow", arrow),
|
||||
ornament("Petal Sweep", petal_sweep),
|
||||
ornament("Twin Curl", twin_curl),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
|
||||
}
|
||||
|
||||
@@ -42,8 +42,12 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
|
||||
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
|
||||
pub use trace::{
|
||||
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
|
||||
};
|
||||
use trace::{
|
||||
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
|
||||
};
|
||||
|
||||
/// Name of an Image Trace group.
|
||||
pub const TRACE_NAME: &str = "Image Trace";
|
||||
@@ -208,6 +212,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
trace_presets_delete
|
||||
),
|
||||
cmd!(
|
||||
query "imageTrace.presets.import",
|
||||
"Import Image Trace Presets",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing",
|
||||
always,
|
||||
trace_presets_import
|
||||
),
|
||||
cmd!(
|
||||
query "imageTrace.presets.export",
|
||||
"Export Image Trace Presets",
|
||||
[],
|
||||
None,
|
||||
"{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it",
|
||||
always,
|
||||
trace_presets_export
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -168,6 +168,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if old.is_none() && new_name.is_some() {
|
||||
return Err(bad(C, format!("no saved preset named `{name}` to rename")));
|
||||
}
|
||||
if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first")));
|
||||
}
|
||||
// A saved preset changes from its own settings unless `preset` says where to start.
|
||||
let mut q = p.clone();
|
||||
if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) {
|
||||
@@ -203,6 +206,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result<Value>
|
||||
Ok(json!({ "deleted": deleted }))
|
||||
}
|
||||
|
||||
/// The `format` of a tracing presets file, also its extension.
|
||||
pub const TRACE_PRESET_FORMAT: &str = "vctracepresets";
|
||||
|
||||
/// The extensions of tracing presets files (opening one imports it).
|
||||
pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT];
|
||||
|
||||
/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of
|
||||
/// this version and earlier ones.
|
||||
const TRACE_PRESET_VERSION: u64 = 1;
|
||||
|
||||
/// The largest tracing presets file `imageTrace.presets.import` reads.
|
||||
pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20;
|
||||
|
||||
/// The most presets one tracing presets file may hold, and the most tracing presets that can be
|
||||
/// saved (so every saved preset fits in one exported file).
|
||||
const TRACE_PRESET_MAX_COUNT: usize = 1000;
|
||||
|
||||
pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.presets.export";
|
||||
let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(names)) => {
|
||||
let mut out: Vec<&TracePreset> = vec![];
|
||||
for n in names {
|
||||
let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?;
|
||||
if tr::preset(n).is_some() {
|
||||
return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported")));
|
||||
}
|
||||
let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?;
|
||||
if !out.iter().any(|o| o.name == q.name) {
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`names` must be an array of preset names")),
|
||||
None => s.prefs.trace_presets.iter().collect(),
|
||||
};
|
||||
if presets.is_empty() {
|
||||
return Err(bad(C, "no saved tracing presets to export"));
|
||||
}
|
||||
// A file is written only when `imageTrace.presets.import` can read it back.
|
||||
let count = presets.len();
|
||||
if count > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`")));
|
||||
}
|
||||
let rows: Vec<Value> = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect();
|
||||
let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows});
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if text.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20)));
|
||||
}
|
||||
match opt_str(C, p, "path")? {
|
||||
Some(path) => {
|
||||
crate::cmd::fileio::write_file(path, text.as_bytes())?;
|
||||
Ok(json!({"path": path, "count": count}))
|
||||
}
|
||||
None => Ok(json!({"data": text, "count": count})),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most
|
||||
/// [`TRACE_PRESET_MAX_BYTES`] of them.
|
||||
fn trace_preset_file(c: &str, p: &Value) -> Result<Vec<u8>> {
|
||||
let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20));
|
||||
let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) {
|
||||
(Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?,
|
||||
(None, Some(text), _) => {
|
||||
if text.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
(None, None, Some(b64)) => {
|
||||
if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 {
|
||||
return Err(too_big());
|
||||
}
|
||||
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?
|
||||
}
|
||||
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.presets.import";
|
||||
let replace = switch_or(p, "replace", false, C)?;
|
||||
let bytes = trace_preset_file(C, p)?;
|
||||
let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}"));
|
||||
let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?;
|
||||
if file["format"] != TRACE_PRESET_FORMAT {
|
||||
return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default())));
|
||||
}
|
||||
match file["version"].as_u64() {
|
||||
Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {}
|
||||
Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))),
|
||||
None => return Err(not_file("no `version`".into())),
|
||||
}
|
||||
let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?;
|
||||
if rows.len() > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len())));
|
||||
}
|
||||
// Every preset is checked before any is saved, so a file with a fault changes nothing.
|
||||
let mut presets: Vec<TracePreset> = Vec::with_capacity(rows.len());
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let name = row["name"].as_str().map(str::trim).unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return Err(bad(C, format!("preset {} has no name", i + 1)));
|
||||
}
|
||||
if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
|
||||
return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file")));
|
||||
}
|
||||
if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) {
|
||||
return Err(bad(C, format!("the file holds two presets named `{name}`")));
|
||||
}
|
||||
let params = match row.get("params").filter(|v| v.is_object()) {
|
||||
Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e {
|
||||
EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")),
|
||||
e => e,
|
||||
})?,
|
||||
None => return Err(bad(C, format!("`{name}` has no `params`"))),
|
||||
};
|
||||
presets.push(TracePreset { name: name.to_string(), params });
|
||||
}
|
||||
let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count();
|
||||
if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"),
|
||||
));
|
||||
}
|
||||
let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]);
|
||||
for preset in presets {
|
||||
let name = preset.name.clone();
|
||||
match s.trace_preset_index(&name) {
|
||||
Some(i) if replace => {
|
||||
let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue };
|
||||
// The saved preset keeps its name as it was saved.
|
||||
let kept = slot.name.clone();
|
||||
*slot = TracePreset { name: kept.clone(), params: preset.params };
|
||||
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false });
|
||||
replaced.push(kept);
|
||||
}
|
||||
Some(_) => skipped.push(name),
|
||||
None => {
|
||||
s.prefs.trace_presets.push(preset);
|
||||
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false });
|
||||
imported.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped}))
|
||||
}
|
||||
|
||||
/// The string `key` of `p` (`None` when it is missing or null); any other type is an error of
|
||||
/// command `c`.
|
||||
fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
@@ -443,20 +443,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
|
||||
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
|
||||
/// undo step, named as an Ellipse tool drag is.
|
||||
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With
|
||||
/// `anchors: "points"` the circle is a plain path with an anchor at each point
|
||||
/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an
|
||||
/// Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
|
||||
};
|
||||
let key = "anchors";
|
||||
let at_points = match p.get(key).map(Value::as_str) {
|
||||
None | Some(Some("standard")) => false,
|
||||
Some(Some("points")) => true,
|
||||
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))),
|
||||
};
|
||||
let (center, radius) = shapes::circle_through_points(&points)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
let mut out = if at_points {
|
||||
add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))?
|
||||
} else {
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?
|
||||
};
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
|
||||
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The
|
||||
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side, Inflate's
|
||||
//! puffed front and back). The
|
||||
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
|
||||
//! also edits.
|
||||
|
||||
@@ -28,7 +29,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Map Graphic",
|
||||
[],
|
||||
None,
|
||||
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
|
||||
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face; on Inflate the back takes graphics only with Both sides and Cap on), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Inflate in the art's plane, the graphic carried straight out onto the puffed face; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and on Inflate following the puff, Twist and Taper carrying the back's, each drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type), Revolve or Inflate; one undo step → {ids, graphic}",
|
||||
has_doc,
|
||||
map_graphic
|
||||
),
|
||||
@@ -134,6 +135,13 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
|
||||
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
|
||||
}
|
||||
// Inflate's back takes graphics where it puffs out: with Both sides and Cap on.
|
||||
if base.face == effects::PlanarFace::Back && effect.id == effects::INFLATE {
|
||||
let o = effects::inflate_options(&merged);
|
||||
if !(o.both_sides && o.cap) {
|
||||
return Err(bad(C, format!("object {}: Inflate's back takes graphics with Both sides and Cap on", id.0)));
|
||||
}
|
||||
}
|
||||
let mut graphic = base.clone();
|
||||
if p.get("scale").is_none()
|
||||
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
|
||||
|
||||
@@ -95,10 +95,10 @@ fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() {
|
||||
|
||||
#[test]
|
||||
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
|
||||
let (mut s, id) = setup("threeD.inflate");
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("Plane, Extrude and Revolve"), "{e}");
|
||||
assert!(e.contains("Plane, Extrude, Revolve and Inflate"), "{e}");
|
||||
let (mut s, id) = setup("threeD.rotate");
|
||||
for (p, says) in [
|
||||
(json!({"symbol": "Gone"}), "no symbol named"),
|
||||
@@ -188,11 +188,36 @@ fn set_params_edits_graphics_and_checks_them() {
|
||||
let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}});
|
||||
assert!(s.execute("effect.setParams", &null).is_err());
|
||||
assert_eq!(graphics(&s, id), moved);
|
||||
// Extrude to Plane keeps the graphics; to Inflate drops them.
|
||||
// Extrude to Plane keeps the graphics, and so does Inflate.
|
||||
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap();
|
||||
assert_eq!(graphics(&s, id), moved);
|
||||
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap();
|
||||
assert_eq!(graphics(&s, id), Value::Null);
|
||||
assert_eq!(graphics(&s, id), moved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_graphic_puts_a_graphic_on_an_inflate_and_its_back_only_with_both_sides() {
|
||||
let (mut s, id) = setup("threeD.inflate");
|
||||
let plain = {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap())
|
||||
};
|
||||
let history = undo_len(&s);
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
|
||||
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}]));
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn");
|
||||
// The back is flat until Both sides puffs it.
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("Both sides and Cap"), "{e}");
|
||||
assert_eq!(undo_len(&s), history);
|
||||
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"bothSides": true, "cap": false}})).unwrap();
|
||||
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).is_err());
|
||||
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"cap": true}})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap();
|
||||
assert_eq!(graphics(&s, id)[1]["face"], "back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -804,7 +804,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
|
||||
leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
|
||||
}
|
||||
_ => item.targets(s, p)?,
|
||||
_ => item.targets_for(s, p, !stroke)?,
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Overprint",
|
||||
[],
|
||||
None,
|
||||
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind → {changed: objects}",
|
||||
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
|
||||
has_doc,
|
||||
set_overprint
|
||||
),
|
||||
@@ -135,7 +135,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>
|
||||
.into_iter()
|
||||
.map(|fill| {
|
||||
let it = item.of_kind(s, fill);
|
||||
let ids = it.targets(s, p)?;
|
||||
let ids = it.targets_for(s, p, fill)?;
|
||||
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
|
||||
Ok((fill, it, ids))
|
||||
})
|
||||
|
||||
@@ -216,12 +216,15 @@ impl Session {
|
||||
}
|
||||
let first = st.doc.node(*st.selection.subjects().first()?)?;
|
||||
let item = self.appearance_item();
|
||||
// Only an active Appearance row is shown here: it is a row of the first selected object.
|
||||
if first.appearance.item_of_kind(item, !stroke).is_some() {
|
||||
return Some((Cow::Borrowed(first), item));
|
||||
}
|
||||
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
|
||||
// object without a painted object shows the defaults for new art.
|
||||
for id in st.selection.subjects() {
|
||||
// object without a painted object shows the defaults for new art. A face or edge selected with
|
||||
// its Live Paint group counts with the group, wherever it is in the selection.
|
||||
let covered = live_paint_covered(&st.doc, st.selection.subjects());
|
||||
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, stroke, &mut nodes);
|
||||
@@ -273,14 +276,6 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
|
||||
pub(crate) fn live_paint_parts(n: &Node) -> Vec<NodeId> {
|
||||
if !is_live_paint(n) {
|
||||
return vec![];
|
||||
}
|
||||
faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
|
||||
}
|
||||
|
||||
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
|
||||
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
|
||||
/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
|
||||
@@ -331,8 +326,9 @@ impl DocState {
|
||||
// Looking the first object up builds the id cache when there is none.
|
||||
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let mut covered = std::collections::HashSet::new();
|
||||
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
|
||||
// they count with their group's.
|
||||
let covered = live_paint_covered(&self.doc, &self.selection.objects);
|
||||
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
|
||||
// place it appears.
|
||||
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
|
||||
@@ -342,7 +338,6 @@ impl DocState {
|
||||
if covered.contains(&n.id) {
|
||||
continue;
|
||||
}
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
@@ -839,6 +834,36 @@ pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: boo
|
||||
out
|
||||
}
|
||||
|
||||
/// Faces, edges and the other objects (the hidden source paths) of Live Paint groups.
|
||||
pub(crate) type LivePaintParts = (std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>);
|
||||
|
||||
/// The faces, the edges and the hidden source paths of the Live Paint groups in `roots` (or inside them),
|
||||
/// found as [`live_paint_parts_skipped`] finds them.
|
||||
pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts {
|
||||
let groups = live_paint_groups(d, roots);
|
||||
let mut hidden = inside_live_paint(d, &groups);
|
||||
let (mut faces, mut edges) = (std::collections::HashSet::new(), std::collections::HashSet::new());
|
||||
for (_, f, e) in &groups {
|
||||
faces.extend(f.iter().copied());
|
||||
edges.extend(e.iter().copied());
|
||||
}
|
||||
hidden.retain(|id| !faces.contains(id) && !edges.contains(id));
|
||||
(faces, edges, hidden)
|
||||
}
|
||||
|
||||
/// The faces and edges in `selected` whose Live Paint group is selected too, itself or inside another selected
|
||||
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
|
||||
/// object in `selected` is inside a Live Paint group.
|
||||
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
|
||||
if !selected.iter().any(inside) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
let (mut parts, edges, _) = live_paint_split(d, selected);
|
||||
parts.extend(edges);
|
||||
parts
|
||||
}
|
||||
|
||||
/// The instance whose object is selected with Direct Selection, and that object's path
|
||||
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
|
||||
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
|
||||
@@ -1356,7 +1381,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
|
||||
// no row for) is still an error.
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
|
||||
let of = match item {
|
||||
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
|
||||
ItemTarget::Top => None,
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use super::{live_paint_covered, painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use crate::{DocState, Session};
|
||||
|
||||
thread_local! {
|
||||
@@ -39,12 +39,11 @@ fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -
|
||||
}
|
||||
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
let mut covered = HashSet::new();
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
st.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
if !covered.contains(&n.id) {
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
|
||||
@@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"color.gamutCheck",
|
||||
"color.harmony",
|
||||
"color.plates",
|
||||
"color.used",
|
||||
"dataset.capture",
|
||||
"dataset.delete",
|
||||
"dataset.list",
|
||||
|
||||
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
colors
|
||||
),
|
||||
cmd!(
|
||||
query "color.used",
|
||||
"Document Colors",
|
||||
[],
|
||||
None,
|
||||
"{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is",
|
||||
has_doc,
|
||||
used
|
||||
),
|
||||
cmd!(
|
||||
"recolor.apply",
|
||||
"Recolor Artwork",
|
||||
@@ -952,16 +961,19 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
|
||||
}
|
||||
|
||||
/// A colour the art uses: how often, and the global swatch it is linked to.
|
||||
/// A color the art uses: how often, and the global swatch of its first linked use in paint order.
|
||||
struct Used {
|
||||
color: Color,
|
||||
count: usize,
|
||||
swatch: Option<String>,
|
||||
/// The global swatch of the first linked use that is not a gradient stop mixing the swatch's
|
||||
/// ink with process inks, with the tint (0..1) its paint stores when the paint gives one.
|
||||
plain: Option<(String, Option<f32>)>,
|
||||
}
|
||||
|
||||
/// The unique colours of the objects `ids` and the objects inside them, most used first (ties by
|
||||
/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as
|
||||
/// fills or strokes. With `only`, an object not in it is left out with everything it holds.
|
||||
/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as
|
||||
/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds.
|
||||
fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> Vec<Used> {
|
||||
fn read<'a>(n: &'a Node, only: Option<&BTreeSet<NodeId>>, out: &mut Vec<&'a Node>) {
|
||||
if only.is_some_and(|o| !o.contains(&n.id)) {
|
||||
@@ -974,44 +986,64 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
|
||||
}
|
||||
let mut index: HashMap<ColorKey, usize> = HashMap::new();
|
||||
let mut used: Vec<(ColorKey, Used)> = vec![];
|
||||
let mut count = |c: &Color, link: Option<&str>| {
|
||||
let mut count_tint = |c: &Color, link: Option<&str>, tint: Option<f32>, mixed: bool| {
|
||||
let k = ColorKey::of(c);
|
||||
let i = *index.entry(k).or_insert_with(|| {
|
||||
used.push((k, Used { color: *c, count: 0, swatch: None }));
|
||||
used.push((k, Used { color: *c, count: 0, swatch: None, plain: None }));
|
||||
used.len() - 1
|
||||
});
|
||||
let u = &mut used[i].1;
|
||||
u.count += 1;
|
||||
if u.swatch.is_none() {
|
||||
u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string);
|
||||
if u.swatch.is_some() && (u.plain.is_some() || mixed) {
|
||||
return;
|
||||
}
|
||||
if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) {
|
||||
if u.swatch.is_none() {
|
||||
u.swatch = Some(l.to_string());
|
||||
}
|
||||
if u.plain.is_none() && !mixed {
|
||||
u.plain = Some((l.to_string(), tint));
|
||||
}
|
||||
}
|
||||
};
|
||||
// The patterns used as fills or strokes: their tiles count once each.
|
||||
// The patterns used as fills or strokes, and the patterns their tiles use: each tile counts
|
||||
// once, and a pattern whose tile uses itself, directly or through other patterns, counts once.
|
||||
let mut patterns: Vec<&str> = vec![];
|
||||
let mut nodes = vec![];
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
read(n, only, &mut nodes);
|
||||
}
|
||||
for m in nodes {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())),
|
||||
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| count(&p.color, None));
|
||||
}
|
||||
paints(m, &mut count_tint, &mut patterns);
|
||||
}
|
||||
for def in patterns.iter().filter_map(|p| d.pattern(p)) {
|
||||
def.art.iter().for_each(|n| node_colors(n, &mut count));
|
||||
let mut next = 0;
|
||||
while let Some(&name) = patterns.get(next) {
|
||||
next += 1;
|
||||
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
|
||||
a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns));
|
||||
}
|
||||
}
|
||||
used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0)));
|
||||
used.into_iter().map(|(_, u)| u).collect()
|
||||
}
|
||||
|
||||
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
|
||||
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
|
||||
/// add the patterns it is painted with to `patterns`.
|
||||
fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option<f32>, bool), patterns: &mut Vec<&'a str>) {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())),
|
||||
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| count(&p.color, None, None, false));
|
||||
}
|
||||
}
|
||||
|
||||
/// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the
|
||||
/// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once).
|
||||
fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec<Color> {
|
||||
@@ -1054,30 +1086,61 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<NodeId>, Option<B
|
||||
let st = s.doc()?;
|
||||
let ids = match p.get("ids") {
|
||||
Some(_) => checked_ids_param(s, p, "ids", cmd)?,
|
||||
None if st.selection.is_empty() => {
|
||||
let only = super::select::selectable_ids(&st.doc, st.isolation);
|
||||
return Ok((super::select::selectable(&st.doc, st.isolation), Some(only)));
|
||||
}
|
||||
None if st.selection.is_empty() => return Ok(all_art(st)),
|
||||
None => st.selection.objects.clone(),
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None))
|
||||
}
|
||||
|
||||
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
|
||||
let st = s.doc()?;
|
||||
let v: Vec<Value> = used_colors(&st.doc, &ids, only.as_ref())
|
||||
.iter()
|
||||
/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing
|
||||
/// selected).
|
||||
fn all_art(st: &crate::DocState) -> (Vec<NodeId>, Option<BTreeSet<NodeId>>) {
|
||||
let only = super::select::selectable_ids(&st.doc, st.isolation);
|
||||
(super::select::selectable(&st.doc, st.isolation), Some(only))
|
||||
}
|
||||
|
||||
/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see
|
||||
/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its
|
||||
/// color in its own model, and the swatch and tint come from its first linked use that is not a
|
||||
/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one).
|
||||
fn colors_json(used: &[Used], with_color: bool) -> Vec<Value> {
|
||||
used.iter()
|
||||
.map(|u| {
|
||||
let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count});
|
||||
if let Some(w) = &u.swatch {
|
||||
if with_color {
|
||||
v["color"] = json!(u.color);
|
||||
if let Some((w, tint)) = &u.plain {
|
||||
v["swatch"] = json!(w);
|
||||
if let Some(t) = tint {
|
||||
v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0);
|
||||
}
|
||||
}
|
||||
} else if let Some(w) = &u.swatch {
|
||||
v["swatch"] = json!(w);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "colors": v }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
|
||||
let st = s.doc()?;
|
||||
Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) }))
|
||||
}
|
||||
|
||||
/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes.
|
||||
fn used(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.used";
|
||||
let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX);
|
||||
let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty();
|
||||
let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) };
|
||||
let st = s.doc()?;
|
||||
let used = used_colors(&st.doc, &ids, only.as_ref());
|
||||
let uses: usize = used.iter().map(|u| u.count).sum();
|
||||
let shown = used.get(..limit.min(used.len())).unwrap_or_default();
|
||||
Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses }))
|
||||
}
|
||||
|
||||
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::appearance::{ItemTarget, edit_items, item_target};
|
||||
use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
|
||||
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
|
||||
use crate::DocState;
|
||||
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
|
||||
@@ -250,10 +250,15 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if item == ItemTarget::Top {
|
||||
own_stroke_or_leaves(s, p)?
|
||||
} else {
|
||||
item.targets(s, p)?
|
||||
item.targets_for(s, p, false)?
|
||||
};
|
||||
// A Live Paint group without edges was still selected or given: the options do not go to new art.
|
||||
let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
|
||||
let live_paint = !bucket
|
||||
&& if item == ItemTarget::Top {
|
||||
!live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty()
|
||||
} else {
|
||||
!super::appearance::contents_skipped(s, p, false)?.is_empty()
|
||||
};
|
||||
let new_art = bucket || (no_targets(&ids, p) && !live_paint);
|
||||
let given = !ids.is_empty() || live_paint;
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
@@ -453,12 +458,15 @@ impl Session {
|
||||
}
|
||||
let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) };
|
||||
let first = st.doc.node(*first)?;
|
||||
// Only an active Appearance row is shown here: it is a row of the first selected object.
|
||||
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
|
||||
return first.appearance.stroke_at(Some(i)).cloned();
|
||||
}
|
||||
// A Live Paint group without edges shows the next selected object's stroke; any other object
|
||||
// without a painted object shows none.
|
||||
for id in &st.selection.objects {
|
||||
// without a painted object shows none. A face or edge selected with its Live Paint group counts
|
||||
// with the group, wherever it is in the selection.
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, true, &mut nodes);
|
||||
@@ -532,7 +540,7 @@ impl DocState {
|
||||
} else {
|
||||
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let covered: std::collections::HashSet<vectorcraft_doc::NodeId> = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
|
||||
let covered = live_paint_covered(&self.doc, &self.selection.objects);
|
||||
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
|
||||
painted(n, true, true, &mut nodes);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -356,6 +356,7 @@ pub struct FillAttrs {
|
||||
|
||||
impl FillAttrs {
|
||||
pub const ALL: Self = Self { color: true, transparency: true, overprint: true };
|
||||
pub const NONE: Self = Self { color: false, transparency: false, overprint: false };
|
||||
}
|
||||
|
||||
impl Default for FillAttrs {
|
||||
@@ -383,6 +384,8 @@ pub struct StrokeAttrs {
|
||||
|
||||
impl StrokeAttrs {
|
||||
pub const ALL: Self = Self { color: true, transparency: true, overprint: true, weight: true, cap: true, join: true, miter: true, dash: true };
|
||||
pub const NONE: Self =
|
||||
Self { color: false, transparency: false, overprint: false, weight: false, cap: false, join: false, miter: false, dash: false };
|
||||
}
|
||||
|
||||
impl Default for StrokeAttrs {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -115,6 +115,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"paint",
|
||||
"pattern-borders",
|
||||
"decorative",
|
||||
"ornamental",
|
||||
"scatter-shapes",
|
||||
"stipple",
|
||||
"game-trails",
|
||||
@@ -197,6 +198,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
|
||||
("paint", "art"),
|
||||
("pattern-borders", "pattern"),
|
||||
("decorative", "pattern"),
|
||||
("ornamental", "art"),
|
||||
("scatter-shapes", "scatter"),
|
||||
("stipple", "scatter"),
|
||||
("game-trails", "art"),
|
||||
@@ -661,6 +663,57 @@ fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() {
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ornamental_brushes_draw_flourishes_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap();
|
||||
let names = ["Scrollwork", "Filigree Arrow", "Petal Sweep", "Twin Curl"];
|
||||
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
|
||||
let mut curve = line_to(20.0);
|
||||
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
|
||||
for b in &lib.brushes {
|
||||
let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) };
|
||||
assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints);
|
||||
assert_eq!(art.width, 300.0);
|
||||
for line in [line_to(2.0), line_to(180.0), curve.clone()] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
|
||||
let points = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
|
||||
}
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "ornamental", "name": b.name, "apply": true, "ids": [path]}));
|
||||
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
|
||||
assert_eq!(added["applied"], json!([path]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
|
||||
}
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
/// Filigree Arrow's shaft runs into its head with no gap, so a straight stroke draws one arrow.
|
||||
#[test]
|
||||
fn the_filigree_arrow_shaft_meets_its_head() {
|
||||
let s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap();
|
||||
let BrushKind::Art(art) = &lib.brush("Filigree Arrow").unwrap().kind else { panic!("Filigree Arrow is not an art brush") };
|
||||
let mut parts = vec![];
|
||||
art.art.walk(&mut |c| {
|
||||
if c.path_data().is_some() {
|
||||
parts.push(c.contains_fn());
|
||||
}
|
||||
});
|
||||
for y in [-0.6, 0.0, 0.6] {
|
||||
for i in 0..=930 {
|
||||
let p = vectorcraft_geom::Point::new(4.05 + 0.1 * f64::from(i), y);
|
||||
assert!(parts.iter().any(|inside| inside(p)), "gap at {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -4283,6 +4283,353 @@ fn live_paint_group_stroke_panel_edits_change_its_edges() {
|
||||
assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0));
|
||||
}
|
||||
|
||||
/// A face or edge selected before its Live Paint group counts with the group: the Fill proxy shows
|
||||
/// the faces' fill and the Stroke panel the edges' stroke, whatever the order of the selection.
|
||||
#[test]
|
||||
fn live_paint_group_proxies_do_not_depend_on_the_selection_order() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
|
||||
let magenta = serde_json::to_value(Paint::solid(Color::from_hex("#ff00ff").unwrap())).unwrap();
|
||||
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
|
||||
s.execute("select.set", &json!({"ids": [edge.0, g.0]})).unwrap();
|
||||
assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], magenta, "an edge first shows the faces' fill");
|
||||
// A face with a stroke of its own (from a file, say), selected first, shows the edges' stroke.
|
||||
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(face).unwrap();
|
||||
n.appearance.set_stroke(Paint::solid(Color::BLACK));
|
||||
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [face.0, g.0]})).unwrap();
|
||||
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
|
||||
}
|
||||
|
||||
/// The Eyedropper onto a whole selected Live Paint group, or reversed onto a clicked one, gives the
|
||||
/// picked fill attributes to its faces and the picked stroke attributes to its edges; its hidden
|
||||
/// source paths keep their paint.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges() {
|
||||
for reverse in [false, true] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [src.0], "weight": 3})).unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
let sources0 = sources_looks(&s, g);
|
||||
if reverse {
|
||||
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": g.0, "reverse": true})).unwrap();
|
||||
} else {
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
|
||||
}
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
|
||||
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
for (f, f0) in faces1.iter().zip(&faces0) {
|
||||
assert_eq!(f.fill_paint(), magenta, "reverse {reverse}: a face takes the fill");
|
||||
assert_eq!((f.stroke_paint(), f.stroke_width()), (f0.stroke_paint(), f0.stroke_width()), "reverse {reverse}: a face takes no stroke");
|
||||
}
|
||||
for (e, e0) in edges1.iter().zip(&edges0) {
|
||||
assert_eq!((e.stroke_paint(), e.stroke_width()), (blue.clone(), 3.0), "reverse {reverse}: an edge takes the stroke");
|
||||
assert_eq!(e.fill_paint(), e0.fill_paint(), "reverse {reverse}: an edge takes no fill");
|
||||
}
|
||||
assert_eq!(sources_looks(&s, g), sources0, "reverse {reverse}: the hidden source paths keep their paint");
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole-appearance Eyedropper pick of a source with several fills and strokes gives each face
|
||||
/// of a selected Live Paint group every fill row and each edge every stroke row.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_gives_every_fill_and_stroke_row() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [src.0]})).unwrap();
|
||||
s.execute("appearance.addStroke", &json!({"ids": [src.0]})).unwrap();
|
||||
let kinds = |a: &vectorcraft_doc::Appearance, fill: bool| a.items.iter().filter(|it| it.is_fill() == fill).count();
|
||||
let source = (*node(&s, src).appearance).clone();
|
||||
assert_eq!((kinds(&source, true), kinds(&source, false)), (2, 2));
|
||||
// A face with a stroke row below its fill keeps that row below the picked fills.
|
||||
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(face).unwrap();
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 9.0)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
let order: Vec<bool> = faces1[0].items.iter().map(|it| it.is_fill()).collect();
|
||||
assert_eq!(order.first(), Some(&false), "the face's lower stroke row stays below its fills: {order:?}");
|
||||
for (f, f0) in faces1.iter().zip(&faces0) {
|
||||
assert_eq!(kinds(f, true), 2, "a face takes every fill row");
|
||||
assert_eq!(kinds(f, false), kinds(f0, false), "a face keeps its strokes");
|
||||
}
|
||||
for (e, e0) in edges1.iter().zip(&edges0) {
|
||||
assert_eq!(kinds(e, false), 2, "an edge takes every stroke row");
|
||||
assert_eq!(kinds(e, true), kinds(e0, true), "an edge keeps its fills");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Appearance panel's edits of a Live Paint group's contents (`target: "contents"`) follow the
|
||||
/// group's rule: a new fill goes on its faces, a new stroke on its edges, and its hidden source paths
|
||||
/// keep their appearance under every contents edit.
|
||||
#[test]
|
||||
fn live_paint_group_contents_edits_follow_the_group_rule() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
let sources0 = sources_looks(&s, g);
|
||||
s.execute("appearance.addFill", &json!({"target": "contents"})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() == f0.items.len() + 1), "every face takes a new fill");
|
||||
assert_eq!(edges1, edges0, "edges take no new fill");
|
||||
s.execute("appearance.addStroke", &json!({"target": "contents"})).unwrap();
|
||||
let (faces2, edges2) = part_looks(&s, g);
|
||||
assert_eq!(faces2, faces1, "faces take no new stroke");
|
||||
assert!(edges2.iter().zip(&edges1).all(|(e, e0)| e.items.len() == e0.items.len() + 1), "every edge takes a new stroke");
|
||||
// A stroke row edit of the contents reaches the edges, not the faces.
|
||||
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 7})).unwrap();
|
||||
let (faces3, edges3) = part_looks(&s, g);
|
||||
assert_eq!(faces3, faces2, "faces keep their rows");
|
||||
assert!(edges3.iter().all(|e| e.stroke_at(Some(0)).map(|st| st.width) == Some(7.0)), "every edge's stroke row takes the weight");
|
||||
s.execute("appearance.clear", &json!({"target": "contents"})).unwrap();
|
||||
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their appearance");
|
||||
}
|
||||
|
||||
/// Fill edits of a Live Paint group's contents with an `item` (a gradient vector, Invert, Overprint
|
||||
/// Fill) change its faces and leave an edge's fill row as it is, and Overprint on the whole group goes
|
||||
/// to the faces' fills and the edges' strokes, leaving the hidden source paths as they are.
|
||||
#[test]
|
||||
fn live_paint_group_item_edits_and_overprint_follow_the_group_rule() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
|
||||
// Each edge gets a copy of a face's gradient fill row, below its stroke.
|
||||
let n = node(&s, g);
|
||||
let face_row = vectorcraft_tools::builder::faces(&n)[0].appearance.items[0].clone();
|
||||
let edge_ids: Vec<NodeId> = vectorcraft_tools::builder::edges(&n).iter().map(|e| e.id).collect();
|
||||
let mut face_ids: Vec<u64> = vectorcraft_tools::builder::faces(&n).iter().map(|f| f.id.0).collect();
|
||||
face_ids.sort_unstable();
|
||||
s.edit("t", |d, _| {
|
||||
for e in &edge_ids {
|
||||
d.node_mut(*e).unwrap().appearance.items.insert(0, face_row.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
let sources0 = sources_looks(&s, g);
|
||||
let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "item": 0, "target": "contents", "start": [0, 0], "end": [100, 0]})).unwrap();
|
||||
let mut changed: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
changed.sort_unstable();
|
||||
assert_eq!(changed, face_ids, "only the faces take the vector");
|
||||
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row keeps its vector");
|
||||
let stops = |a: &vectorcraft_doc::Appearance| match a.fill_paint() {
|
||||
Paint::Gradient(gr) => gr.gradient.stops.iter().map(|st| st.color).collect::<Vec<_>>(),
|
||||
_ => vec![],
|
||||
};
|
||||
let before: Vec<_> = part_looks(&s, g).0.iter().map(stops).collect();
|
||||
s.execute("paint.invert", &json!({"stroke": false, "item": 0, "target": "contents"})).unwrap();
|
||||
for (f, b) in part_looks(&s, g).0.iter().zip(&before) {
|
||||
assert_eq!(stops(f), b.iter().rev().copied().collect::<Vec<_>>(), "the black-to-white stops of a face's fill are inverted");
|
||||
}
|
||||
assert_ne!(part_looks(&s, g).0, faces0);
|
||||
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row is not inverted");
|
||||
s.execute("object.setOverprint", &json!({"fill": true, "item": 0, "target": "contents"})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
assert!(faces1.iter().all(|f| f.items[0].overprint()), "the faces' fill overprints");
|
||||
assert_eq!(edges1, edges0, "an edge's fill row does not overprint");
|
||||
s.execute("object.setOverprint", &json!({"fill": true, "stroke": true})).unwrap();
|
||||
let (_, edges2) = part_looks(&s, g);
|
||||
assert!(edges2.iter().all(|e| e.items.iter().all(|it| it.overprint() != it.is_fill())), "only the edges' strokes overprint");
|
||||
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their flags");
|
||||
}
|
||||
|
||||
/// A face selected before an ordinary group that holds its Live Paint group counts with that group:
|
||||
/// the Stroke panel shows the edges' stroke.
|
||||
#[test]
|
||||
fn live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(face).unwrap();
|
||||
n.appearance.set_stroke(Paint::solid(Color::BLACK));
|
||||
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [face.0, outer.0]})).unwrap();
|
||||
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
|
||||
assert!(!s.active().unwrap().stroke_mixed().weight, "the face's own stroke does not make the weight mixed");
|
||||
// An unfilled edge selected with the outer group does not make the faces' fill mixed.
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
|
||||
s.execute("select.set", &json!({"ids": [edge.0, outer.0]})).unwrap();
|
||||
let r = s.execute("paint.proxies", &json!({})).unwrap();
|
||||
assert_eq!(r["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#ff0000").unwrap())).unwrap());
|
||||
assert_eq!(r["fillMixed"], false, "the edge counts with its group");
|
||||
}
|
||||
|
||||
/// The Eyedropper picks up a whole Live Paint group as its faces' fill under its edges' stroke, and
|
||||
/// `append` onto a whole group adds the picked fills and strokes without the picked effects.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(g).unwrap().opacity = 0.5;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
|
||||
let a = (*node(&s, target).appearance).clone();
|
||||
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
|
||||
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
|
||||
assert_eq!(node(&s, target).opacity, 0.5, "the group's own opacity");
|
||||
// A Live Paint group with no face and no edge is not picked up: the next selected object is.
|
||||
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let en = node(&s, e);
|
||||
let parts: Vec<NodeId> =
|
||||
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
|
||||
assert!(!parts.is_empty());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, e)));
|
||||
let other = rect(&mut s, 700.0, 0.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [e.0, other.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
|
||||
assert_eq!(node(&s, target).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "the next selected object's fill");
|
||||
// Append a source with a drop shadow onto the whole group.
|
||||
let src = rect(&mut s, 500.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
|
||||
assert!(!node(&s, src).appearance.effects.is_empty());
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": src.0, "append": true})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
for (p, p0) in faces1.iter().chain(&edges1).zip(faces0.iter().chain(&edges0)) {
|
||||
assert_eq!(p.effects, p0.effects, "a face or edge takes no effect");
|
||||
}
|
||||
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() > f0.items.len()), "every face takes the fill");
|
||||
}
|
||||
|
||||
/// Reversed onto a clicked object, an empty Live Paint group first in the selection passes to the next
|
||||
/// selected Live Paint group, whose faces' fill and edges' stroke are both picked up.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
|
||||
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let en = node(&s, e);
|
||||
let parts: Vec<NodeId> =
|
||||
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true, "ids": [e.0, g.0]})).unwrap();
|
||||
let a = (*node(&s, target).appearance).clone();
|
||||
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
|
||||
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
|
||||
}
|
||||
|
||||
/// An Eyedropper pick whose source is the selected Live Paint group leaves the group's own faces and
|
||||
/// edges as they are.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_does_not_target_its_own_source_group() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap();
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap();
|
||||
let before = part_looks(&s, g);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": g.0})).unwrap();
|
||||
assert_eq!(part_looks(&s, g), before);
|
||||
}
|
||||
|
||||
/// A Live Paint group left with only its hidden source paths is still a selection: a stroke edit of its
|
||||
/// contents changes nothing and leaves the settings for new art as they are.
|
||||
#[test]
|
||||
fn live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let n = node(&s, g);
|
||||
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
|
||||
s.edit("t", |d, _| {
|
||||
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke());
|
||||
s.execute("stroke.setAdvanced", &json!({"target": "contents", "item": 0, "arrowScale": [200, 150]})).unwrap();
|
||||
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
|
||||
}
|
||||
|
||||
/// Adding a fill or a stroke to the contents of a Live Paint group left with only its hidden source paths
|
||||
/// succeeds and changes nothing, while an empty selection is still refused.
|
||||
#[test]
|
||||
fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let n = node(&s, g);
|
||||
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
|
||||
s.edit("t", |d, _| {
|
||||
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let before = node(&s, g);
|
||||
for cmd in ["appearance.addFill", "appearance.addStroke"] {
|
||||
s.execute(cmd, &json!({"target": "contents"})).unwrap();
|
||||
assert_eq!(node(&s, g), before, "{cmd} changes nothing");
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused");
|
||||
}
|
||||
|
||||
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
|
||||
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
|
||||
/// leaves the settings for new art as they are.
|
||||
@@ -4304,6 +4651,8 @@ fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() {
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
s.execute("stroke.weightUp", &json!({})).unwrap();
|
||||
s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap();
|
||||
// A stroke row edit of the group's contents finds no edge either.
|
||||
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 9})).unwrap();
|
||||
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
|
||||
assert_eq!(part_looks(&s, g), looks);
|
||||
|
||||
@@ -9280,6 +9629,111 @@ fn image_trace_built_in_presets_cannot_be_saved_over_or_deleted() {
|
||||
assert_eq!(six["params"], serde_json::to_value(vectorcraft_trace::preset("6 Colors").unwrap()).unwrap());
|
||||
}
|
||||
|
||||
/// Saved tracing presets go out to a .vctracepresets file and come back with their names and
|
||||
/// settings; a hand-written file in the documented layout imports too.
|
||||
#[test]
|
||||
fn image_trace_presets_export_and_import_round_trip() {
|
||||
let mut s = session();
|
||||
assert!(s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string().contains("no saved tracing presets"));
|
||||
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "preset": "6 Colors", "params": {"noise": 40, "ignoreWhite": true}})).unwrap();
|
||||
s.execute("imageTrace.presets.save", &json!({"name": "Ink", "params": {"threshold": 90, "fills": false, "strokes": true}})).unwrap();
|
||||
let e = s.execute("imageTrace.presets.export", &json!({"names": ["Default"]})).unwrap_err().to_string();
|
||||
assert!(e.contains("only saved presets are exported"), "{e}");
|
||||
assert!(s.execute("imageTrace.presets.export", &json!({"names": ["Nope"]})).is_err());
|
||||
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
|
||||
assert_eq!(all["count"], 2);
|
||||
let one = s.execute("imageTrace.presets.export", &json!({"names": ["poster", "Poster"]})).unwrap();
|
||||
assert_eq!(one["count"], 1);
|
||||
let file: Value = serde_json::from_str(all["data"].as_str().unwrap()).unwrap();
|
||||
assert_eq!((file["format"].as_str(), file["version"].as_u64()), (Some("vctracepresets"), Some(1)));
|
||||
let saved = s.prefs.trace_presets.clone();
|
||||
// Into a session without them: the same names and settings, and a new revision the panel follows.
|
||||
let mut t = session();
|
||||
let before = t.trace_presets_revision();
|
||||
let r = t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap();
|
||||
assert_eq!(r, json!({"imported": ["Poster", "Ink"], "replaced": [], "skipped": []}));
|
||||
assert_eq!(t.prefs.trace_presets, saved);
|
||||
assert_eq!(t.trace_presets_revision(), before + 2);
|
||||
// A file written by hand in the documented layout: missing settings are Default's.
|
||||
let hand = r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Hand", "params": {"mode": "grayscale", "colors": 12}}]}"#;
|
||||
t.execute("imageTrace.presets.import", &json!({ "dataBase64": vectorcraft_format::base64_encode(hand.as_bytes()) })).unwrap();
|
||||
let hand = t.trace_preset("hand").unwrap().params.clone();
|
||||
assert_eq!((hand.mode, hand.colors, hand.threshold), (vectorcraft_trace::Mode::Grayscale, 12, 128));
|
||||
}
|
||||
|
||||
/// Export writes no file that import would refuse (more than 1,000 presets, or more than 4 MiB),
|
||||
/// and no more than 1,000 tracing presets can be saved.
|
||||
#[test]
|
||||
fn image_trace_presets_export_keeps_to_what_import_reads() {
|
||||
let mut s = session();
|
||||
let params = vectorcraft_trace::preset("Default").unwrap();
|
||||
let preset = |name: String| crate::cmd::TracePreset { name, params: params.clone() };
|
||||
s.prefs.trace_presets = (1..=1001).map(|i| preset(format!("P{i}"))).collect();
|
||||
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("more than one file holds (1000)"), "{e}");
|
||||
s.prefs.trace_presets.pop();
|
||||
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
|
||||
assert_eq!(all["count"], 1000);
|
||||
let mut t = session();
|
||||
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap()["imported"].as_array().map(Vec::len), Some(1000));
|
||||
// No more can be saved or imported then, so every saved preset still fits in one file; a
|
||||
// saved preset can still change, and a file of saved names still replaces them.
|
||||
let e = t.execute("imageTrace.presets.save", &json!({"name": "One More"})).unwrap_err().to_string();
|
||||
assert!(e.contains("delete one first"), "{e}");
|
||||
t.execute("imageTrace.presets.save", &json!({"name": "P1", "params": {"noise": 9}})).unwrap();
|
||||
let one = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "Fresh", "params": {}}]}).to_string();
|
||||
let e = t.execute("imageTrace.presets.import", &json!({ "data": one })).unwrap_err().to_string();
|
||||
assert!(e.contains("more than 1000 saved"), "{e}");
|
||||
let again = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "P2", "params": {}}]}).to_string();
|
||||
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": again, "replace": true})).unwrap()["replaced"], json!(["P2"]));
|
||||
assert_eq!(t.prefs.trace_presets.len(), 1000);
|
||||
s.prefs.trace_presets = vec![preset("x".repeat(4 << 20))];
|
||||
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than 4 MiB"), "{e}");
|
||||
}
|
||||
|
||||
/// A saved preset of the same name is skipped unless `replace` is on; a file with a fault, or one
|
||||
/// too large, changes nothing.
|
||||
#[test]
|
||||
fn image_trace_presets_import_checks_the_whole_file_first() {
|
||||
let mut s = session();
|
||||
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
|
||||
let file = |rows: Value| json!({"format": "vctracepresets", "version": 1, "presets": rows}).to_string();
|
||||
let data = file(json!([{"name": "poster", "params": {"noise": 7}}, {"name": "Fresh", "params": {}}]));
|
||||
let r = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap();
|
||||
assert_eq!(r, json!({"imported": ["Fresh"], "replaced": [], "skipped": ["poster"]}));
|
||||
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 40);
|
||||
let r = s.execute("imageTrace.presets.import", &json!({"data": data, "replace": true})).unwrap();
|
||||
assert_eq!(r, json!({"imported": [], "replaced": ["Poster", "Fresh"], "skipped": []}));
|
||||
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 7);
|
||||
assert!(s.execute("imageTrace.presets.import", &json!({"data": data, "replace": "yes"})).is_err());
|
||||
let saved = s.prefs.trace_presets.clone();
|
||||
let revision = s.trace_presets_revision();
|
||||
let bad_files = [
|
||||
(file(json!([{"name": "New One", "params": {}}, {"name": "[Default]", "params": {}}])), "built-in preset"),
|
||||
(file(json!([{"name": "custom", "params": {}}])), "built-in preset"),
|
||||
(file(json!([{"name": "Twice", "params": {}}, {"name": "twice", "params": {}}])), "two presets named"),
|
||||
(file(json!([{"name": " ", "params": {}}])), "has no name"),
|
||||
(file(json!([{"name": "No Params"}])), "has no `params`"),
|
||||
(file(json!([{"name": "Neither", "params": {"fills": false, "strokes": false}}])), "Create needs fills"),
|
||||
(file(json!([{"name": "Typo", "params": {"nosie": 3}}])), "nosie"),
|
||||
(json!({"format": "vctracepresets", "version": 2, "presets": []}).to_string(), "newer"),
|
||||
(json!({"format": "vcflattener", "version": 1, "presets": []}).to_string(), "not a tracing presets file"),
|
||||
("{".to_string(), "not a tracing presets file"),
|
||||
(file(Value::Array(vec![json!({"name": "x", "params": {}}); 1001])), "more than 1000"),
|
||||
(" ".repeat((4 << 20) + 1), "larger than 4 MiB"),
|
||||
];
|
||||
for (data, why) in bad_files {
|
||||
let e = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{why}: {e}");
|
||||
}
|
||||
let big = vectorcraft_format::base64_encode(&vec![b' '; (4 << 20) + 1]);
|
||||
assert!(s.execute("imageTrace.presets.import", &json!({ "dataBase64": big })).unwrap_err().to_string().contains("larger than 4 MiB"));
|
||||
assert!(s.execute("imageTrace.presets.import", &json!({})).is_err());
|
||||
assert_eq!(s.prefs.trace_presets, saved, "nothing changed");
|
||||
assert_eq!(s.trace_presets_revision(), revision);
|
||||
}
|
||||
|
||||
/// Saved tracing presets are kept with the preferences, are not a preference key, and survive
|
||||
/// resetting the preferences.
|
||||
#[test]
|
||||
|
||||
@@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() {
|
||||
assert!(!node(&s, id).extras().pixel_aligned);
|
||||
}
|
||||
|
||||
/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a
|
||||
/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other
|
||||
/// `anchors` value is an error and draws nothing.
|
||||
#[test]
|
||||
fn anchors_at_the_points_puts_an_anchor_at_each_point() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
|
||||
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap());
|
||||
let n = node(&s, id);
|
||||
let anchors: Vec<Point> = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}");
|
||||
assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind);
|
||||
assert!(!n.extras().pixel_aligned);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap());
|
||||
let anchors: Vec<Point> = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(anchors.len(), 4, "{anchors:?}");
|
||||
assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0)));
|
||||
let (count, undo) = (object_count(&s), undo_len(&s));
|
||||
for bad in [json!("corners"), json!(true), json!(4), Value::Null] {
|
||||
let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string();
|
||||
assert!(e.contains("`anchors` must be one of standard, points"), "{e}");
|
||||
}
|
||||
assert_eq!((object_count(&s), undo_len(&s)), (count, undo));
|
||||
}
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..ViewInfo::default() }
|
||||
}
|
||||
|
||||
@@ -127,6 +127,25 @@ fn c_flips_and_brackets_size_the_last_sharp_arc() {
|
||||
assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
|
||||
}
|
||||
|
||||
/// The drawing end (where the Quick Pen toolbar sits beside) is the path's last point with the
|
||||
/// direction it arrives in: none before the first click, no direction for one point, and none
|
||||
/// once Escape ends the path.
|
||||
#[test]
|
||||
fn the_drawing_end_is_the_last_point_and_its_direction() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
assert_eq!(s.tool_drawing_end(view()), None);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
assert_eq!(s.tool_drawing_end(view()), Some((pt(100.0, 100.0), None)));
|
||||
click(&mut s, 100.0, 200.0);
|
||||
let (p, dir) = s.tool_drawing_end(view()).unwrap();
|
||||
assert_eq!(p, pt(100.0, 200.0));
|
||||
let dir = dir.unwrap();
|
||||
assert!(dir.x.abs() < 1e-9 && dir.y > 0.99, "arrives heading down: {dir:?}");
|
||||
key(&mut s, ToolKey::Escape);
|
||||
assert_eq!(s.tool_drawing_end(view()), None);
|
||||
}
|
||||
|
||||
/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a
|
||||
/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it.
|
||||
#[test]
|
||||
@@ -183,6 +202,251 @@ fn escape_ends_the_path_and_a_drag_places_the_piece() {
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
}
|
||||
|
||||
/// The piece a press draws ends where the press is let go, past the last drag too, and a press let
|
||||
/// go a drag's distance away with no drag in between places it there as well.
|
||||
#[test]
|
||||
fn the_piece_ends_where_the_press_is_let_go() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 120.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 150.0), v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0));
|
||||
let undo = undo_steps(&s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 100.0), v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(340.0, 100.0));
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// C and `[` `]` during a drag change the sharp-corner arc being dragged, within the press's one
|
||||
/// undo step.
|
||||
#[test]
|
||||
fn c_and_brackets_during_a_drag_change_the_arc_being_dragged() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
let undo = undo_steps(&s);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap();
|
||||
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
|
||||
key(&mut s, ToolKey::Letter('c'));
|
||||
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "flipped while dragging");
|
||||
key(&mut s, ToolKey::BracketLeft);
|
||||
assert_eq!(s.tool_options()["turn"], 165.0);
|
||||
// A 165° arc is two segments, and its middle point lies the arc's sagitta below the chord
|
||||
// (a 180° arc's lies 100 below).
|
||||
let half = 82.5f64.to_radians();
|
||||
let mid_165 = pt(200.0, 300.0 + 100.0 / half.sin() * (1.0 - half.cos()));
|
||||
assert_eq!(only_path(&s).anchors.len(), 3);
|
||||
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the dragged arc is 165°");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
|
||||
let sp = only_path(&s);
|
||||
assert_eq!(sp.anchors.len(), 3);
|
||||
assert!(sp.anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the flip and the size stay after the release");
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// An edit made by another command during a drag ends the path: the next drag does not draw over
|
||||
/// the edit, the piece stays as last shown, and the next click starts a new path.
|
||||
#[test]
|
||||
fn an_edit_during_a_drag_ends_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the edit and the piece as last shown");
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 2, "a new path");
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, a sharp-corner arc let go past the last drag is placed where it was
|
||||
/// let go, and C then flips that arc.
|
||||
#[test]
|
||||
fn a_deferred_arc_let_go_past_the_last_drag_flips() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 270.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
|
||||
let sp = only_path(&s);
|
||||
assert_eq!(sp.anchors.len(), 3);
|
||||
assert_eq!(sp.anchors.last().unwrap().p, pt(300.0, 300.0));
|
||||
let mid = sp.anchors.get(1).unwrap().p;
|
||||
key(&mut s, ToolKey::Letter('c'));
|
||||
let flipped = only_path(&s);
|
||||
assert_eq!(flipped.anchors.len(), 3);
|
||||
assert!(flipped.anchors.get(1).unwrap().p.distance(pt(200.0, 600.0 - mid.y)) < 1e-9, "flipped across the chord");
|
||||
}
|
||||
|
||||
/// An edit made by another command to the path's look during a drag ends the path too.
|
||||
#[test]
|
||||
fn a_look_edit_during_a_drag_ends_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 2, "a new path");
|
||||
}
|
||||
|
||||
/// An edit made by another command to another object during a drag stays and ends the path: the
|
||||
/// press previews no more, its piece stays as last shown, and the next click starts a new path.
|
||||
#[test]
|
||||
fn an_edit_to_another_object_during_a_drag_stays() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
|
||||
let rect = s.doc().unwrap().selection.objects[0];
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
|
||||
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
|
||||
let pen = paths(&s).into_iter().find(|(id, _)| *id != rect).unwrap().1;
|
||||
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 3, "a new path");
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, a drag during which another command edits the path adds no piece,
|
||||
/// and the edit stays.
|
||||
#[test]
|
||||
fn an_edit_during_a_deferred_drag_stays() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0)], "the edit, and no piece");
|
||||
}
|
||||
|
||||
/// An edit made by another command to another object during a click stays, and the path goes on:
|
||||
/// a click previews its piece only when the press begins.
|
||||
#[test]
|
||||
fn an_edit_to_another_object_during_a_click_stays() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
|
||||
let rect = s.doc().unwrap().selection.objects[0];
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
|
||||
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
|
||||
click(&mut s, 300.0, 200.0);
|
||||
let all = paths(&s);
|
||||
assert_eq!(all.len(), 2, "no new path");
|
||||
let pen = all.into_iter().find(|(id, _)| *id != rect).unwrap().1;
|
||||
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0), pt(300.0, 200.0)]);
|
||||
}
|
||||
|
||||
/// An edit made by another command during a click (a press let go where it went down) ends the
|
||||
/// path too: the next click starts a new path instead of drawing over the edit.
|
||||
#[test]
|
||||
fn an_edit_during_a_click_ends_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 180.0), v).unwrap();
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 2, "a new path");
|
||||
let ends: Vec<Point> = paths(&s)[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 180.0)], "the edit stays");
|
||||
}
|
||||
|
||||
/// With Align New Objects to Pixel Grid on, the path the tool draws is pixel-aligned: its points
|
||||
/// move onto the grid, and the next click and drag still go on drawing the same path.
|
||||
#[test]
|
||||
fn a_pixel_aligned_path_goes_on_drawing() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let ends = |s: &Session| only_path(s).anchors.iter().map(|a| a.p).collect::<Vec<Point>>();
|
||||
let two = ends(&s);
|
||||
assert_eq!(two.len(), 2);
|
||||
assert_eq!(two[0].y, two[1].y, "a level line");
|
||||
press(&mut s, &[(300.0, 150.0), (310.0, 170.0), (320.0, 200.0)]);
|
||||
let three = ends(&s);
|
||||
assert_eq!(three.len(), 3, "one path of three points");
|
||||
assert_eq!(three[..2], two[..], "the points before the piece stay as they were");
|
||||
assert!(three[2].distance(pt(320.0, 200.0)) <= 1.0, "the drag's piece ends near where it was let go: {:?}", three[2]);
|
||||
click(&mut s, 400.0, 100.0);
|
||||
let four = ends(&s);
|
||||
assert_eq!(four.len(), 4);
|
||||
assert_eq!(four[..3], three[..]);
|
||||
}
|
||||
|
||||
/// A dropped press takes back only its own piece, and with Real-time Drawing off a drag places its
|
||||
/// piece on the release: in both cases the next click goes on drawing the same path.
|
||||
#[test]
|
||||
fn a_dropped_press_and_a_deferred_drag_keep_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 150.0), v).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.len(), 2, "the dropped piece is gone");
|
||||
click(&mut s, 300.0, 200.0);
|
||||
assert_eq!(only_path(&s).anchors.len(), 3, "the path goes on");
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
press(&mut s, &[(400.0, 200.0), (420.0, 250.0), (450.0, 300.0)]);
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(450.0, 300.0));
|
||||
click(&mut s, 500.0, 100.0);
|
||||
assert_eq!(only_path(&s).anchors.len(), 5, "the path goes on after the deferred piece");
|
||||
}
|
||||
|
||||
/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back
|
||||
/// over the edit, and the next click starts a new path instead of rebuilding the old one.
|
||||
#[test]
|
||||
|
||||
@@ -133,6 +133,174 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() {
|
||||
assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_list_the_most_used_first_with_their_colors() {
|
||||
let mut s = session();
|
||||
let reds: Vec<NodeId> = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect();
|
||||
let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0}));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
assert_eq!(r["selection"], false, "{r}");
|
||||
let colors = r["colors"].as_array().unwrap();
|
||||
assert_eq!(colors.len(), 2, "{r}");
|
||||
assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3)));
|
||||
assert_eq!(colors[1]["count"], 1);
|
||||
let first = run(&mut s, "color.used", json!({"limit": 1}));
|
||||
assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used");
|
||||
assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color");
|
||||
// `color` is the color in its own model, which the paint commands take back.
|
||||
assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}");
|
||||
assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue)));
|
||||
// The selection's colors while something is selected; `selection: false` reads all the art.
|
||||
run(&mut s, "select.set", json!({"ids": [blue.0]}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}");
|
||||
let all = run(&mut s, "color.used", json!({"selection": false}));
|
||||
assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was");
|
||||
// A hidden object's color is left out with nothing selected, as Select All leaves it out.
|
||||
run(&mut s, "object.hide", json!({"ids": [reds[0].0]}));
|
||||
assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2);
|
||||
let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`selection` must be true or false"), "{e}");
|
||||
assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let tinted = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40}));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let c = &r["colors"][0];
|
||||
assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}");
|
||||
assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}");
|
||||
// recolor.colors keeps its own fields.
|
||||
assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None);
|
||||
// A swatch of paper white looks the same at every tint; the tint comes from the paint.
|
||||
run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true}));
|
||||
let paper = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333}));
|
||||
run(&mut s, "select.set", json!({"ids": [paper.0]}));
|
||||
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
|
||||
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
|
||||
// The tint is the paint's own, unrounded.
|
||||
let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else {
|
||||
panic!("a solid fill")
|
||||
};
|
||||
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
|
||||
assert!((tint - 0.33333).abs() < 1e-5);
|
||||
// A pattern's tile keeps its tint as well.
|
||||
run(&mut s, "select.set", json!({"ids": [paper.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let filled = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"}));
|
||||
run(&mut s, "select.set", json!({"ids": [filled.0]}));
|
||||
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
|
||||
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
|
||||
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_read_the_tiles_of_patterns_used_inside_pattern_tiles() {
|
||||
let mut s = session();
|
||||
let red = rect(&mut s, json!("#ff0000"));
|
||||
run(&mut s, "select.set", json!({"ids": [red.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let middle = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [middle.0], "swatch": "Inner"}));
|
||||
run(&mut s, "select.set", json!({"ids": [middle.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let square = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [square.0], "swatch": "Outer"}));
|
||||
// The inner tile's square is stroked with the outer pattern, so the two patterns use each other.
|
||||
let outer = s.doc().unwrap().doc.node(square).unwrap().appearance.fill_paint().clone();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let doc = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let tile = doc.pattern_mut("Inner").unwrap().art.first_mut().unwrap();
|
||||
std::sync::Arc::make_mut(tile).appearance.set_stroke(outer);
|
||||
run(&mut s, "select.set", json!({"ids": [square.0]}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let colors = r["colors"].as_array().unwrap();
|
||||
assert_eq!(colors.iter().map(|c| (c["hex"].as_str(), c["count"].as_u64())).collect::<Vec<_>>(), [(Some("#ff0000"), Some(1))], "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let shape = rect(&mut s, json!("#000000"));
|
||||
let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 };
|
||||
let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) };
|
||||
let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None);
|
||||
end.offset = 1.0;
|
||||
let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]);
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap();
|
||||
let mix = entry("cmyk 30 50 30 0");
|
||||
assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}");
|
||||
assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}");
|
||||
// recolor.colors keeps the swatch it lists.
|
||||
let listed = run(&mut s, "recolor.colors", json!({}));
|
||||
assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let shape = rect(&mut s, json!("#000000"));
|
||||
let plain = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50}));
|
||||
let ink = fill(&s, plain);
|
||||
// The stop below the plain fill has the same color, and process plates that add nothing.
|
||||
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
|
||||
let mut end = stop.clone();
|
||||
end.offset = 1.0;
|
||||
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
|
||||
assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recolor_colors_keeps_the_swatch_of_the_first_linked_use_when_a_mixed_stop_comes_first() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let shape = rect(&mut s, json!("#000000"));
|
||||
let plain = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Other", "tint": 50}));
|
||||
let ink = fill(&s, plain);
|
||||
// The stop below the plain fill has the same color, linked to another swatch, with process
|
||||
// plates that add nothing.
|
||||
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
|
||||
let mut end = stop.clone();
|
||||
end.offset = 1.0;
|
||||
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let three = |r: &Value| r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
|
||||
let used = run(&mut s, "color.used", json!({}));
|
||||
assert_eq!(three(&used)["swatch"], "Other", "{used}");
|
||||
let listed = run(&mut s, "recolor.colors", json!({}));
|
||||
assert_eq!(three(&listed)["swatch"], "Ink", "recolor.colors names the first linked use: {listed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -856,6 +856,12 @@ impl Session {
|
||||
self.ruler_origin = None;
|
||||
}
|
||||
|
||||
/// A guide is being dragged out of a ruler ([`Session::ruler_guide`]): its first event came
|
||||
/// and its release has not.
|
||||
pub fn ruler_guide_dragging(&self) -> bool {
|
||||
self.ruler_guide.is_some()
|
||||
}
|
||||
|
||||
/// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the
|
||||
/// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event.
|
||||
pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result<Vec<UiRequest>> {
|
||||
@@ -1256,6 +1262,12 @@ impl Session {
|
||||
self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx))
|
||||
}
|
||||
|
||||
/// The point a path the active tool is drawing goes on from, and the direction the path
|
||||
/// arrives there in (see `Tool::drawing_end`).
|
||||
pub fn tool_drawing_end(&mut self, view: ViewInfo) -> Option<(Point, Option<vectorcraft_geom::Vec2>)> {
|
||||
self.with_tool_cx(view, |t, cx| t.drawing_end(cx))
|
||||
}
|
||||
|
||||
pub fn overlays(&mut self, view: ViewInfo) -> Vec<Overlay> {
|
||||
// The Blend tool's first pick is not marked after an edit that dropped it.
|
||||
self.tell_tool_history_moved();
|
||||
@@ -1478,6 +1490,9 @@ impl Session {
|
||||
}
|
||||
// Every value is checked before any is set, so an invalid one changes nothing.
|
||||
vectorcraft_tools::builder::check_builder_options(id, &values)?;
|
||||
if id == vectorcraft_tools::circle::ID {
|
||||
vectorcraft_tools::circle::check_options(&values)?;
|
||||
}
|
||||
vectorcraft_tools::symbolism::check_options(id, &values)?;
|
||||
if id == vectorcraft_tools::cropimage::ID {
|
||||
use vectorcraft_tools::cropimage as crop;
|
||||
|
||||
Reference in New Issue
Block a user