Merge main into fix/graph-stacked-column-legend-stroke

This commit is contained in:
dotCooCoo
2026-11-15 13:43:18 -08:00
143 changed files with 5901 additions and 629 deletions
+19 -2
View File
@@ -446,7 +446,7 @@ pub(crate) fn rows_per_target(d: &Document, of: Option<NodeId>, ids: &[NodeId],
}
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
fn targets_contents(p: &Value) -> Result<bool> {
pub(crate) fn targets_contents(p: &Value) -> Result<bool> {
match p.get("target") {
None | Some(Value::Null) => Ok(false),
Some(v) => match v.as_str() {
@@ -508,6 +508,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId>
ids
}
/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's
/// art has no row of that kind for is still an error of `cmd`, as on any other object.
pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec<NodeId>, item: ItemTarget, fill: bool, cmd: &str) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
for (id, it) in ids.iter().zip(item.per_target(s, &ids)) {
if let (Some(it), Some(n)) = (it, d.node(*id))
&& super::graph::is_design_art(d, *id)
{
it.resolve(&n.appearance, fill, cmd)?;
}
}
Ok(drop_design_art(d, ids))
}
/// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that
/// [`super::graph::is_design_art`] accepts.
pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
@@ -720,7 +734,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
let holder = match reference_of(s, p, item, cmd)? {
Some(of) => Some(of),
None => {
let ids = drop_design_art(d, appearance_targets(s, p)?);
let all = appearance_targets(s, p)?;
// The art of a graph design is left out, unless it is all there is: the item is then a row of that art.
let kept = drop_design_art(d, all.clone());
let ids = if kept.is_empty() { all } else { kept };
ids.get(item.anchor(s, &ids)).copied()
}
};
+1 -1
View File
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
+4 -1
View File
@@ -1035,10 +1035,13 @@ impl Imported {
self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone());
}
}
/// Point a pasted copy at the document's resources.
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
}
}
+12 -1
View File
@@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> {
patterns: HashMap<String, Option<String>>,
new_images: Vec<(String, ImageBlob)>,
new_patterns: Vec<PatternDef>,
/// Objects inside the recolored ones that keep their colors, with everything inside them.
skip: HashSet<NodeId>,
changed: usize,
}
@@ -236,6 +238,7 @@ impl<'a> Recolor<'a> {
patterns: HashMap::new(),
new_images: vec![],
new_patterns: vec![],
skip: HashSet::new(),
changed: 0,
}
}
@@ -254,7 +257,7 @@ impl<'a> Recolor<'a> {
/// A pass that maps colors as this one does, with nothing recolored yet.
fn again(&self) -> Self {
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) }
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) }
}
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
@@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> {
fn image(&mut self, key: &str) -> Option<String> {
self.pass.image(self.d, key)
}
fn enters(&mut self, n: &Node) -> bool {
!self.pass.skip.contains(&n.id)
}
}
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f))
}
/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are.
pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet<NodeId>) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) })
}
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) })
+64 -13
View File
@@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
let mut spans = [reach, 2.0 * reach];
// The lengths along the path ahead and back, measured once when an anchor needs them.
let (mut ahead, mut back) = (None, None);
if closed {
let mut total = 0.0;
for i in 0..n {
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
}
let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum());
if !(total.is_finite() && total > 0.0) {
return corners;
}
@@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
continue;
}
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach));
let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue };
let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach));
let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) else { continue };
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
.into_iter()
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
@@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
corners
}
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
/// anchor on a path of very many very short segments.
const MAX_CORNER_WALK: usize = 256;
/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead
/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last
/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l`
/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short
/// stretch keeps its length next to very long ones. The segment past an open path's end has no
/// length.
fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec<Vec<f64>> {
let n = anchors.len();
let lens: Vec<f64> =
(0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect();
let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::<Vec<f64>>()];
while let Some(last) = blocks.last().filter(|b| b.len() > 1) {
let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect();
blocks.push(next);
}
blocks
}
/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back
/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None`
/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks`
/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of
/// very many short segments is not walked one segment at a time from each anchor.
fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec<f64>], reach: f64) -> Option<Point> {
let (n, (i, forward)) = (anchors.len(), from);
let start = if forward { i } else { n - 1 - i };
let end = start
+ if closed {
n
} else if forward {
n - 1 - i
} else {
i
};
let (mut pos, mut gone) = (start, 0.0);
// The largest block that starts at `pos`, stays within the walk and ends within `dist`, until
// none does; a block whose length is not a number is never skipped.
while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| {
let size = 1usize << l;
let len = lens.get(pos >> l).copied()?;
(pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len))
}) {
pos += size;
gone += len;
}
let at = if forward { pos % n } else { n - 1 - pos % n };
walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0]
}
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
/// past no more than `segments` segments, measured along the lines between each curved segment's
@@ -1099,11 +1145,12 @@ mod tests {
}
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
/// over that reach.
/// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its
/// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51°
/// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long
/// are corners too.
#[test]
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() {
let side = 400.0 * std::f64::consts::SQRT_2;
let steps = side.ceil() as usize;
let mut pts = vec![(-3000.0, 0.0)];
@@ -1120,6 +1167,10 @@ mod tests {
let top = steps + 1;
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
assert!(smooth_corners(&anchors, false, 10.0)[top]);
assert!(smooth_corners(&anchors, false, 300.0)[top]);
let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]);
let corners = smooth_corners(&long, false, 0.5);
assert!(corners[2] && corners[3] && corners[4], "{corners:?}");
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
}
+1 -1
View File
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste",
["Edit"],
Some("Cmd+V"),
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Offset)
),
+56 -27
View File
@@ -978,15 +978,18 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
/// id): those made from its own fills and strokes, or with `all` every member. The other members
/// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are
/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a
/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they
/// have before that. Returns what each of those other members' expansions lists, by the member's
/// new id.
/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
/// the member's new id.
fn expand_pieces(
d: &mut Document,
m: &mut Node,
all: bool,
brushes: &[vectorcraft_brush::Brush],
skip: &[NodeId],
kept: &mut Vec<NodeId>,
stroke_art: effects::StrokeArt,
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
let id = m.id;
@@ -1002,9 +1005,23 @@ fn expand_pieces(
if all || c.id == id {
effects::expand_art(d, c, stroke_art);
} else if has_seeded(c) && repeats_an_id(c, &seen) {
listed = Some(expand_in_place(d, c, brushes));
listed = Some(expand_in_place(d, c, brushes, skip));
}
let mut was = vec![];
if !skip.is_empty() {
c.walk(&mut |n| was.push(n.id));
}
fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default());
if !was.is_empty() {
// A copy of an object `skip` lists is left as it is too.
let mut at = 0;
c.walk(&mut |n| {
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
kept.push(n.id);
}
at += 1;
});
}
if let Some(listed) = listed {
expanded.insert(c.id, listed);
}
@@ -1058,9 +1075,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
type Listed = (NodeId, usize);
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec<Listed> {
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
let mut listed = vec![];
if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) {
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
*c = e;
}
listed
@@ -1084,9 +1101,16 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
/// transparency.
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
expand_node_except(d, id, brushes, &[], out);
}
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
/// copies of it that such an effect makes are left as they are too.
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
let Some(n) = d.node(id).cloned() else { return };
let mut listed = vec![];
let m = expanded_node(d, n, brushes, &mut listed);
let m = expanded_node(d, n, brushes, skip, &mut listed);
out.extend(listed.into_iter().map(|(id, _)| id));
if let Some(mut m) = m {
// Art made from type takes its emoji's pixels into the document.
@@ -1099,10 +1123,10 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<Listed>) -> Option<Node> {
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
let id = n.id;
if !expandable(&n) {
if skip.contains(&id) || !expandable(&n) {
return None;
}
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
@@ -1139,7 +1163,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
let c = Arc::make_mut(c);
if i == 0 {
expanded = expand_in_place(d, c, brushes);
expanded = expand_in_place(d, c, brushes, skip);
fresh_ids_listed(d, c, &mut seen, &mut expanded);
} else {
effects::fresh_ids(d, c, &mut seen);
@@ -1169,6 +1193,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
let mut members = std::collections::HashMap::new();
// New ids of the copies of objects `skip` lists among those members.
let mut kept = vec![];
let expanded = match image {
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
// keeps it as its only member).
@@ -1180,7 +1206,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
@@ -1201,7 +1227,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget);
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
m
})
};
@@ -1223,6 +1249,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
}
if container {
let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) };
// The place of each member in the walk of `n`: after `n` and the members before it.
let mut at = 1;
for c in n.children_mut().into_iter().flatten() {
@@ -1235,7 +1262,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
match members.remove(&c.id) {
Some(listed) => out.extend(listed),
None => {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
*c = Arc::new(e);
changed = true;
}
@@ -1280,9 +1307,20 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
// geometry it hasn't changed.
if vectorcraft_plugins::safe_mode::active() {
// A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a
// series.
// series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it
// with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group
// then becomes an image of all of it).
let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots);
let designs = super::appearance::design_art_in(&d, &roots);
let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty();
let designs: Vec<NodeId> = super::appearance::design_art_in(&d, &roots)
.into_iter()
.filter(|art| {
!d.ancestry(*art).is_some_and(|up| {
let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len());
up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members))
})
})
.collect();
if !designs.is_empty() {
let view = d.to_mut();
for id in designs {
@@ -1313,16 +1351,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let mut out = vec![];
let threaded = super::threads::frames(d);
for id in &roots {
expand_node(d, *id, &brushes, &mut out);
}
for id in &designs {
if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) {
*slot = was.clone();
}
}
if !designs.is_empty() {
// A mark that expands into a group stays listed: only what lies in the restored art is left out.
out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a))));
expand_node_except(d, *id, &brushes, &designs, &mut out);
}
super::dimension::put_back(d, lifted);
// A dimension whose source was replaced stays where it was, no longer linked.
+18 -10
View File
@@ -149,7 +149,9 @@ pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
/// and symbol editing layers never, opacity masks not with SVG Tiny 1.2, and objects with effects
/// SVG has no filters for as the images the file draws of them), of the art the file draws for each
/// placed document, and of the symbols, patterns and brushes that art uses; with
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
/// and each data set's image. The error names no file or folder.
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
@@ -162,21 +164,27 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
return Ok(());
}
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
// layers kept: the encoder refuses them anyway.
let (link, preserve, hidden) = match super::svg::options_map(p) {
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
// layers kept and SVG 1.1: the encoder refuses them anyway.
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
Ok(m) => {
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
let tiny = m.get("profile").and_then(Value::as_str) == Some("tiny12");
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"), tiny)
}
Err(_) => (true, true, true),
Err(_) => (true, true, true, false),
};
// The opacity-mask and symbol editing layers are never written.
let d = &*d.without_edit_modes();
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
if preserve && crate::cmd::links::names_hidden_file(d, base)
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
{
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden, tiny);
// The SVG draws the objects with effects it has no filters for as images of them, as the
// encoder and the clipboard prepare them.
let drawing_names = || {
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(d, !tiny);
let d = flat.as_ref().unwrap_or(d);
names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
};
if preserve && crate::cmd::links::names_hidden_file(d, base) || names(d) && drawing_names() {
return Err(bad(cmd, IMAGE_OUTSIDE));
}
Ok(())
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+44 -6
View File
@@ -87,8 +87,9 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
if count > MAX_SLICES {
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
}
let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget);
let mut out = vec![];
for _ in 0..count {
for i in 0..count {
// The ID and group ID.
r.take(8)?;
let origin = r.u32()?;
@@ -116,9 +117,10 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
format!("#{red:02x}{green:02x}{blue:02x}")
};
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
// error.
if r.rest().starts_with(&16u32.to_be_bytes()) {
// doesn't start one is the next slice. When the records follow one another, only the
// last one may be followed by a descriptor. A descriptor read that uses up the budget is
// an error.
if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) {
let mut ahead = Reader::new(r.rest());
ahead.u32()?;
match descriptor(&mut ahead, 0, budget) {
@@ -139,6 +141,37 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
Ok(out)
}
/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one
/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is
/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor.
fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool {
if !(0..count).all(|_| skip_record(&mut r).is_ok()) {
return false;
}
r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok())
}
/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings
/// are checked and read past without being decoded.
fn skip_record(r: &mut Reader<'_>) -> Result<(), String> {
// The ID and group ID.
r.take(8)?;
if r.u32()? == 1 {
r.take(4)?;
}
units(r)?;
// The type and the rectangle.
r.take(20)?;
for _ in 0..4 {
units(r)?;
}
r.take(1)?;
units(r)?;
// The alignments and the background color.
r.take(12)?;
Ok(())
}
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
@@ -221,12 +254,17 @@ fn text_len(n: usize) -> Result<usize, String> {
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
let bytes = units(r)?;
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
}
/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units.
fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> {
let n = text_len(r.u32()? as usize)?;
r.take(n.checked_mul(2).ok_or(TRUNCATED)?)
}
/// A descriptor's value, as far as the slices need it.
#[derive(Clone, Debug, PartialEq)]
enum Value {
@@ -262,6 +262,32 @@ fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
assert_eq!(names, ["a", "b"]);
}
#[test]
fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() {
// The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18
// bytes also read as a descriptor of version 16 with no items.
let records: Vec<S> = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect();
let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
for trailing in [vec![], descriptor_after] {
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 17, "{got:?}");
assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), ""));
assert_eq!(got[16].1.name, "a");
}
// A descriptor after each record whose class ID is four zero bytes, with no items, followed by
// records with no strings: the records don't also read one after another.
let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat();
let trailing = [16u32.to_be_bytes().to_vec(), empty].concat();
for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] {
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({}));
let w = warnings(&r);
assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}");
assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}");
}
}
#[test]
fn version_6_descriptors_share_one_budget_of_values() {
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
+246 -41
View File
@@ -185,9 +185,12 @@ impl Sets {
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that
/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps
/// only its part above the later box's top, so boxes staggered right and down each meet only the
/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]).
/// a later box of its group overlaps and ends no further right than keeps only the part the later
/// box doesn't cover: its part above the later box's top when the later box starts lower and ends
/// no higher than it, and its part below the later box's bottom when the later box starts no lower
/// and ends higher than it. The open box's top then moves down in the tree, so boxes staggered right
/// and down, or right and up, each meet only the one before. Fails only when cancelled
/// ([`vectorcraft_doc::cancel`]).
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
Ok(sweep(bounds, None)?.groups())
}
@@ -206,27 +209,25 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
};
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
let n = boxes.len();
// Each box's place in the tree: by top (then index).
let mut by_top: Vec<usize> = (0..n).collect();
by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b)));
let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect();
let mut leaf = vec![0usize; n];
for (pos, &k) in by_top.iter().enumerate() {
leaf[k] = pos;
}
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
let size = n.next_power_of_two().max(1);
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
let set = |low: &mut [f64], pos: usize, v: f64| {
let mut i = pos + size;
low[i] = v;
while i > 1 {
i /= 2;
low[i] = low[2 * i].max(low[2 * i + 1]);
}
// The places an open box's top can be at in the tree: a box's top, or just below a box's
// bottom, where a later box cuts it short (`-0.0` as `0.0`).
let mut places: Vec<f64> = boxes.iter().flat_map(|(_, b)| [b.y0 + 0.0, b.y1.next_up() + 0.0]).collect();
places.sort_by(f64::total_cmp);
places.dedup_by(|a, b| a.total_cmp(b).is_eq());
let place = |y: f64| {
let y = y + 0.0;
let p = places.partition_point(|t| t.total_cmp(&y).is_lt());
places.get(p).is_some_and(|t| t.total_cmp(&y).is_eq()).then_some(p)
};
// Each box's part still open, from its top to its bottom, and the place of its top while it
// is open.
let mut top: Vec<f64> = boxes.iter().map(|(_, b)| b.y0).collect();
let mut bottom: Vec<f64> = boxes.iter().map(|(_, b)| b.y1).collect();
let mut open: Vec<Option<usize>> = vec![None; n];
// The tree of the open boxes without transparency (every box without `see_through`) and the
// see-through boxes'.
let mut trees = [Open::new(places.len()), Open::new(if see_through.is_some() { places.len() } else { 0 })];
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
let mut by_left: Vec<usize> = (0..n).collect();
by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0));
let mut by_right: Vec<usize> = (0..n).collect();
@@ -241,7 +242,9 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
while let Some(&c) = by_right.get(closing)
&& boxes[c].1.x1 < b.x0
{
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
if let Some(p) = open[c].take() {
trees[tree(c)].take(p, c, &bottom);
}
closing += 1;
}
// The open boxes it joins with their top at most this bottom and their bottom at least
@@ -253,21 +256,32 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
Some(_) if shadows => &[0, 1],
Some(_) => &[1],
};
let below = tops.partition_point(|t| *t <= b.y1);
let below = places.partition_point(|t| *t <= b.y1);
met.clear();
for &t in looks {
let tr = &trees[t];
stack.clear();
stack.push((1, 0, size));
stack.push((1, 0, tr.size));
while let Some((node, lo, hi)) = stack.pop() {
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
if lo >= below || low[t][node] < b.y0 {
if lo >= below || tr.low[node] < b.y0 {
continue;
}
if hi - lo == 1 {
met.push(by_top[lo]);
// The boxes with their top here, lowest bottom first.
for &(_, o) in tr.at[lo].iter().rev() {
if bottom[o] < b.y0 {
break;
}
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
met.push(o);
}
continue;
}
let mid = (lo + hi) / 2;
@@ -286,30 +300,91 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
let ob = boxes[o].1;
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
});
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
// see-through. Likewise, whatever later overlaps the part of an open box at or below this
// one's top, when that box ends no further right or lower than this one, overlaps this
// one: the open box then keeps only the part above this one's top.
let cut = b.y0.next_down();
// Whatever overlaps the open part of a box inside this one overlaps this one, and joins it
// when this one is see-through. Likewise, whatever later overlaps the part of an open box
// this one covers, when that box ends no further right than this one, overlaps this one:
// the open box then keeps only the part above this one's top, when this one reaches its
// bottom, or only the part below this one's bottom, when this one reaches its top.
for &o in &met {
sets.join(boxes[k].0, boxes[o].0);
let ob = boxes[o].1;
if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 {
let Some(p) = open[o] else { continue };
if !shadows || Some(o) == holder || b.x1 < boxes[o].1.x1 {
continue;
}
if b.y0 <= ob.y0 {
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
} else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] {
set(&mut low[tree(o)], leaf[o], cut);
let (t, u) = (top[o], bottom[o]);
let tr = &mut trees[tree(o)];
if b.y0 <= t && u <= b.y1 {
tr.take(p, o, &bottom);
open[o] = None;
continue;
}
if holder.is_some() || (b.y1 < u && t < b.y0) {
continue;
}
let (t, u) = if u <= b.y1 { (t, b.y0.next_down()) } else { (b.y1.next_up(), u) };
// Every top it can get has a place; one without stays as it is.
let Some(q) = place(t) else { continue };
tr.take(p, o, &bottom);
(top[o], bottom[o]) = (t, u);
open[o] = (t <= u).then_some(q);
if t <= u {
tr.put(q, o, &bottom);
}
}
if holder.is_none() {
set(&mut low[tree(k)], leaf[k], b.y1);
if holder.is_none()
&& let Some(p) = place(b.y0)
{
open[k] = Some(p);
trees[tree(k)].put(p, k, &bottom);
}
}
Ok(sets)
}
/// The open boxes of [`sweep`] by the place of their tops, in a tree that knows the lowest bottom
/// below each of its branches.
struct Open {
size: usize,
/// The lowest bottom of the open boxes below each node (−∞: none open).
low: Vec<f64>,
/// The open boxes at each place, by bottom ([`order`]) and then index.
at: Vec<BTreeSet<(i64, usize)>>,
}
impl Open {
fn new(places: usize) -> Self {
let size = places.next_power_of_two().max(1);
Self { size, low: vec![f64::NEG_INFINITY; 2 * size], at: vec![BTreeSet::new(); places] }
}
/// Opens box `k` at place `p`, with its bottom `bottom[k]`.
fn put(&mut self, p: usize, k: usize, bottom: &[f64]) {
self.at[p].insert((order(bottom[k]), k));
self.fix(p, bottom);
}
/// Closes box `k` at place `p`, while its bottom is still `bottom[k]`.
fn take(&mut self, p: usize, k: usize, bottom: &[f64]) {
self.at[p].remove(&(order(bottom[k]), k));
self.fix(p, bottom);
}
fn fix(&mut self, p: usize, bottom: &[f64]) {
let mut i = p + self.size;
self.low[i] = self.at[p].last().map_or(f64::NEG_INFINITY, |&(_, k)| bottom[k]);
while i > 1 {
i /= 2;
self.low[i] = self.low[2 * i].max(self.low[2 * i + 1]);
}
}
}
/// `v` as an integer in the same order as [`f64::total_cmp`].
fn order(v: f64) -> i64 {
let b = v.to_bits() as i64;
b ^ (((b >> 63) as u64) >> 1) as i64
}
/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box
/// touches.
struct Blocks {
@@ -775,6 +850,136 @@ mod tests {
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
}
/// `n` boxes of one size, each a little right of and above the one before, all overlapping and
/// none inside another.
fn staggered_up(n: usize) -> Vec<Option<Rect>> {
let w = 2.0 * n as f64;
(0..n).map(|i| Some(Rect::new(i as f64, -(i as f64), w + i as f64, w - i as f64))).collect()
}
/// Each box of a stagger right and up meets only the box before it, which keeps only its part
/// below the new box's bottom, not every box still open; so does each box of a stagger left and
/// down, which the sweep meets right and up.
#[test]
fn boxes_staggered_up_meet_only_the_box_before() {
let n = 512;
let bounds = staggered_up(n);
let all = vec![(0..n).collect::<Vec<_>>()];
let mut sets = sweep(&bounds, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), every_pair(&bounds));
assert_eq!(sets.groups(), all);
let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
let mut reversed = bounds.clone();
reversed.reverse();
let mut sets = sweep(&reversed, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
let mut sets = sweep(&reversed, Some(&vec![true; n])).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
}
/// An open box cut short from above keeps the part a later box would meet without meeting the
/// box that cut it: a part below that box, a part further right, or any part when that box is
/// opaque or held; a box cut from above and from below keeps its middle.
#[test]
fn a_box_is_cut_short_from_above_only_where_the_later_box_covers_it() {
let k = Rect::new(5.0, -5.0, 15.0, 10.0);
let cases = [
// Below `k`: the last box overlaps only the bottom of the first.
("below", vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 15.0, 9.0, 25.0))], vec![true, true, false]),
// Further right than `k`: `k` cuts nothing and the last box overlaps the first.
("right", vec![Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(k), Some(Rect::new(17.0, 2.0, 25.0, 4.0))], vec![true, true, false]),
// Just below `k`'s bottom, and touching it.
(
"edge",
vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 10.0, 9.0, 12.0)), Some(Rect::new(8.0, 10.5, 9.0, 12.0))],
vec![false, true, false, false],
),
// An opaque `k` doesn't join the opaque last box, which joins the see-through first one.
("opaque", vec![Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, -10.0, 7.0, 2.0))], vec![true, false, false]),
// A see-through `k` held by a see-through box around it isn't opened and cuts nothing short.
(
"held",
vec![
Some(Rect::new(0.0, -6.0, 30.0, 28.0)),
Some(Rect::new(1.0, 0.0, 10.0, 20.0)),
Some(k),
Some(Rect::new(6.0, 11.0, 7.0, 13.0)),
Some(Rect::new(6.0, 4.0, 7.0, 6.0)),
],
vec![true, false, true, false, false],
),
// Cut from above, then from below: a later box inside what is left joins the first.
(
"middle",
vec![
Some(Rect::new(0.0, 0.0, 10.0, 30.0)),
Some(Rect::new(2.0, -5.0, 12.0, 10.0)),
Some(Rect::new(3.0, 20.0, 13.0, 40.0)),
Some(Rect::new(5.0, 15.0, 6.0, 16.0)),
Some(Rect::new(5.0, 9.0, 6.0, 10.0)),
Some(Rect::new(5.0, 20.0, 6.0, 20.0)),
],
vec![false, true, true, false, false, false],
),
// Signed zeros, a point and a box that isn't finite.
(
"zeros",
vec![
Some(Rect::new(-0.0, -0.0, 4.0, 8.0)),
Some(Rect::new(0.0, -2.0, 6.0, -0.0)),
Some(Rect::new(1.0, 0.0, 1.0, 0.0)),
Some(Rect::new(2.0, f64::NEG_INFINITY, 3.0, 1.0)),
Some(Rect::new(3.0, f64::MAX, 3.0, f64::MAX)),
Some(Rect::new(3.5, 0.0, 3.5, 0.0)),
],
vec![false, true, false, true, true, false],
),
];
for (what, bounds, see) in cases {
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "{what}");
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "{what}, with transparency");
let mut sets = sweep(&bounds, Some(&vec![true; bounds.len()])).unwrap();
assert_eq!(sets.groups(), every_pair(&bounds), "{what}, all see-through");
}
}
/// Boxes stepping right and alternately up and down, so that open boxes are cut short from
/// above and from below, of mixed sizes, some see-through, group as comparing every pair groups
/// them.
#[test]
fn boxes_stepping_up_and_down_group_as_comparing_every_pair() {
let mut seed = 0x6a09_e667_f3bc_c908u64;
let mut next = |m: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1000) as f64 / 1000.0 * m
};
for round in 0..40 {
let n = 10 + round * 3;
let mut y = 0.0;
let bounds: Vec<Option<Rect>> = (0..n)
.map(|i| {
let up = if (i / (1 + round % 3)) % 2 == 0 { -1.0 } else { 1.0 };
y += up * (next(4.0).floor() + 1.0);
let x = i as f64 + next(2.0).floor();
let (w, h) = (next(12.0).floor() + 4.0, next(16.0).floor() + 2.0);
Some(Rect::new(x, y, x + w, y + h))
})
.collect();
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
let see: Vec<bool> = (0..n).map(|_| next(1.0) < if round % 2 == 0 { 0.5 } else { 0.9 }).collect();
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
}
}
/// An open box keeps the part a later box would meet without meeting the box that cut it short:
/// a part lower than that box, a part further right, or any part when that box is opaque.
#[test]
+11 -5
View File
@@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
// Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
// not one for new art.
let selected = !ids.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?;
// How the gradient lies on a stroke (the panel's Stroke buttons).
let mode = match str_param(p, "strokeMode") {
None => None,
@@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
_ => None,
});
let for_default = match p.get("aspect").and_then(Value::as_f64) {
Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => {
Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => {
let mut q = p.clone();
q["aspect"] = json!(-a);
std::borrow::Cow::Owned(q)
@@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
// A spread for selected gradients leaves a freeform default (which has no ends) as it is.
let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad());
let for_default = match for_default {
q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => {
q if spreads && selected && default_kind == Some(GradientKind::Freeform) => {
let mut q = q.into_owned();
if let Some(o) = q.as_object_mut() {
o.remove("spread");
@@ -579,8 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
};
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
.map_err(|e| bad(C, e))?;
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
let of = super::appearance::reference_of(s, p, item, C)?;
// Only design art was given or selected: nothing changes, the defaults and the remembered paint included.
if selected && ids.is_empty() {
// An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error.
edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?;
return Ok(json!({"ids": []}));
}
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
let shown_at = super::appearance::first_edited(s, item, of, &ids);
// The objects returned: with a design's art, those with a row equal to the art's.
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
@@ -770,7 +776,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
if targets.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?;
let model = super::paint::new_color_model(s, &Value::Null);
let of = super::appearance::reference_of(s, p, item, C)?;
// The objects returned: with a design's art, those with a row equal to the art's.
+3 -3
View File
@@ -49,9 +49,9 @@ use generate::generate;
use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among,
series_marks_in, series_object_opacity_differs, shown_paint,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades,
is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
};
#[cfg(test)]
+63
View File
@@ -1,4 +1,5 @@
use vectorcraft_color::BlendMode;
use vectorcraft_doc::swatches::walk_with_masks;
use vectorcraft_geom::Shape;
use super::axis::radar_axis;
@@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) {
}
}
/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included)
/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a
/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`].
pub(crate) fn wedge_shades(n: &Node) -> HashMap<NodeId, Vec<bool>> {
let mut out = HashMap::new();
walk_with_masks(n, &mut |m| {
if let Some(g) = m.extras().graph.as_deref()
&& g.kind == GraphKind::Pie
&& g.legend
&& g.pie_legend_in_wedges
&& !g.label_styles.legend_fill_is_own()
{
out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect());
}
});
out
}
/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a
/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept
/// their darkness keep their labels as they are.
pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap<NodeId, Vec<bool>>) {
let mut changed = vec![];
walk_with_masks(n, &mut |m| {
if let Some(before) = was.get(&m.id)
&& pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied())
{
changed.push(m.id);
}
});
if !changed.is_empty() {
restore_contrast(n, &changed);
}
}
/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw
/// sets them on their wedges.
fn restore_contrast(n: &mut Node, ids: &[NodeId]) {
if ids.contains(&n.id) {
let on_dark = match n.extras().graph.as_deref() {
Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)),
None => HashMap::new(),
};
set_legend_fills(n, &on_dark);
}
let holds = |c: &Node| {
let mut found = false;
walk_with_masks(c, &mut |m| found |= ids.contains(&m.id));
found
};
if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art))
&& let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
{
restore_contrast(Arc::make_mut(&mut m.art), ids);
}
for c in n.children_mut().into_iter().flatten() {
if holds(c) {
restore_contrast(Arc::make_mut(c), ids);
}
}
}
/// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them.
fn legend_labels(n: &Node) -> Vec<&Node> {
legend_in(n.children().map_or(&[], |c| c.as_slice()))
+258 -1
View File
@@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() {
/// it, and edit the other objects they are given.
#[test]
fn paint_commands_leave_a_graph_designs_art_out() {
let (mut s, _, copy, art, mark) = design_art();
let (mut s, graph, copy, art, mark) = design_art();
let fill = top_row(&s, art, true);
let commands = [
("stroke.set", json!({"weight": 5})),
@@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() {
("paint.swap", json!({})),
("paint.default", json!({})),
("paint.invert", json!({"item": fill, "stroke": false})),
("paint.invert", json!({})),
];
let (copy_was, art_was) = (look(&s, copy), look(&s, art));
for (cmd, p) in &commands {
@@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() {
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
assert_eq!(look(&s, art), art_was);
// Given the whole graph, Invert recolors the marks and leaves the art.
let mark_was = look(&s, mark);
s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap();
assert_eq!(look(&s, art), art_was);
assert_ne!(look(&s, mark), mark_was);
// A freeform gradient point is refused on the art alone.
refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]}));
}
@@ -517,6 +523,182 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() {
assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient");
}
/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the
/// paint for new art and the remembered colors as they are.
#[test]
fn paint_edits_of_design_art_alone_leave_the_defaults() {
let (mut s, _, _, art, _) = design_art();
let fill = top_row(&s, art, true);
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors));
let commands = [
("paint.editGradient", json!({"kind": "linear"})),
("paint.editGradient", json!({"kind": "radial", "stroke": true})),
("paint.swap", json!({})),
("paint.default", json!({})),
("paint.invert", json!({"item": fill, "stroke": false})),
("paint.complement", json!({"item": fill, "stroke": false})),
("paint.invert", json!({})),
("paint.complement", json!({"stroke": true})),
("stroke.set", json!({"weight": 7})),
("stroke.weightUp", json!({})),
];
for (cmd, p) in &commands {
let was = defaults(&s);
let mut q = p.clone();
q["ids"] = json!([art.0]);
s.execute(cmd, &q).unwrap();
assert_eq!(defaults(&s), was, "{cmd}, given");
// Selecting the art makes the defaults take its paint.
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
let was = defaults(&s);
s.execute(cmd, p).unwrap();
assert_eq!(defaults(&s), was, "{cmd}, selected");
s.execute("select.set", &json!({"ids": []})).unwrap();
}
// A bad `item`, `aligned` or `target` is still an error with only design art given.
for bad in [
json!({"ids": [art.0], "item": "top"}),
json!({"ids": [art.0], "item": fill, "aligned": "yes"}),
json!({"ids": [art.0], "item": fill, "target": "nowhere"}),
json!({"ids": [art.0], "target": "nowhere"}),
] {
assert!(s.execute("paint.invert", &bad).is_err(), "{bad}");
assert!(s.execute("paint.complement", &bad).is_err(), "{bad}");
}
// So is an `item` the art has no row for, in each command that leaves the art out.
let steps = s.doc().unwrap().history.undo.len();
for (cmd, p) in [
("paint.invert", json!({})),
("stroke.set", json!({"weight": 2})),
("stroke.weightUp", json!({})),
("stroke.setAdvanced", json!({"swapArrows": true})),
("paint.editGradient", json!({"kind": "linear"})),
("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})),
("object.setOverprint", json!({"fill": true})),
] {
let mut q = p.clone();
q["ids"] = json!([art.0]);
q["item"] = json!(99);
assert!(s.execute(cmd, &q).is_err(), "{cmd}");
}
// The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing.
let stroke_row = top_row(&s, art, false);
for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] {
let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" };
let mut q = p.clone();
q["ids"] = json!([art.0]);
q["item"] = json!(stroke_row);
s.execute(cmd, &q).unwrap();
}
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
// With nothing selected, the swap still swaps the defaults.
let was = defaults(&s);
s.execute("paint.swap", &json!({})).unwrap();
assert_ne!(defaults(&s), was);
}
/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the
/// default fill is; a bad value is still an error.
#[test]
fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() {
let (mut s, _, _, art, _) = design_art();
for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] {
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.editGradient", &json!({"kind": default})).unwrap();
let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len());
let mut q = p.clone();
q["ids"] = json!([art.0]);
s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}"));
assert_eq!(format!("{:?}", s.paint), was, "{default}");
assert_eq!(look(&s, art), art_was, "{default}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}");
}
assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err());
}
/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a
/// graph design as it is. With `target: "contents"` the group's own fill stays as it is.
#[test]
fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() {
let (mut s, graph, _, art, mark) = design_art();
s.execute("select.set", &json!({"ids": [graph.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
let row = top_row(&s, group, true);
s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap();
let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items);
let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark));
s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap();
assert_ne!(own(&s), own_was, "the group's own fill");
assert_ne!(look(&s, mark), mark_was);
assert_eq!(look(&s, art), art_was);
// The color remembered is the group's own new fill, which the Fill proxy shows.
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else {
panic!("the group's fill is not a solid color")
};
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
let (own_was, mark_was) = (own(&s), look(&s, mark));
s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap();
assert_eq!(own(&s), own_was, "target: contents");
assert_ne!(look(&s, mark), mark_was);
assert_eq!(look(&s, art), art_was);
}
/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and
/// remember that color, as the last color and the newest recent color. With several such groups the color remembered
/// is that of the first group whose fill changed.
#[test]
fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() {
// A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it).
let paint_own = |s: &mut Session, group: NodeId, hex: &str| {
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone();
d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint;
};
// Series 0's group with its own fill painted `hex`.
let painted_series = |hex: &str| {
let (mut s, graph, _, art, _) = design_art();
let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id;
paint_own(&mut s, group, hex);
(s, group, art)
};
for cmd in ["paint.invert", "paint.complement"] {
let (mut s, group, art) = painted_series("#ff0000");
let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone();
let (art_was, fill_was) = (look(&s, art), fill(&s));
s.execute(cmd, &json!({"ids": [group.0]})).unwrap();
assert_eq!(look(&s, art), art_was, "{cmd}");
assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored");
let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") };
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}");
}
// A gray fill is its own complement: nothing changes, and the remembered colors stay as they were.
let (mut s, group, _) = painted_series("#808080");
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors));
let was = remembered(&s);
assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0));
assert_eq!(remembered(&s), was);
// Both series groups hold only the design's art: a gray one first and a red one, given together.
let (mut s, graph, _, _, _) = design_art();
s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap();
let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id);
paint_own(&mut s, groups[0], "#808080");
paint_own(&mut s, groups[1], "#ff0000");
s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap();
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else {
panic!("the red group's fill is not a solid color")
};
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
}
/// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects
/// sets only theirs.
#[test]
@@ -596,6 +778,81 @@ fn expand_appearance_leaves_a_graph_designs_art() {
assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty()));
}
/// `effect` with `params`, as `effect.apply` gives it to an object.
fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect {
let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap();
s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone()
}
/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an
/// image of that effect to the document.
#[test]
fn expand_appearance_lists_no_design_art_and_rasterizes_none() {
let (mut s, id, copy, _, mark) = design_art();
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap();
let copy_was = look(&s, copy);
let images = |s: &Session| s.doc().unwrap().doc.images.len();
let before = images(&s);
s.execute("select.set", &json!({"ids": [mark.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let per_mark = images(&s) - before;
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(expanded["ids"], json!([mark.0]));
assert_eq!(look(&s, copy), copy_was);
assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image");
}
/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the
/// marks.
#[test]
fn expand_appearance_moves_design_art_with_its_series_groups_effect() {
let (mut s, id, copy, _, _) = design_art();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let group = series(&n, 0).id;
let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50}));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift);
let left = |s: &Session| {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0
};
let was = left(&s);
assert_eq!(series(&n, 0).children().unwrap()[0].id, copy);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s));
}
/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand
/// Appearance bakes the series group's effect, as the art they copy does.
#[test]
fn expand_appearance_leaves_the_effects_of_design_art_copies() {
let (mut s, id, copy, _, _) = design_art();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let group = series(&n, 0).id;
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2}));
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(copy).unwrap().appearance.effects.push(shadow);
doc.node_mut(group).unwrap().appearance.effects.push(copies);
let shadows = |s: &Session| {
let mut count = 0;
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count());
count
};
let images = |s: &Session| s.doc().unwrap().doc.images.len();
let before = images(&s);
assert_eq!(shadows(&s), 1);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows");
assert_eq!(images(&s), before, "no shadow becomes an image");
}
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
#[test]
+41 -14
View File
@@ -1314,27 +1314,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
/// no other resource. Hidden layers and objects are written only with
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
/// Always `false` without read roots in force.
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden
/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the
/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny
/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in
/// force.
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool {
if crate::file_access::current().is_none() {
return false;
}
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
if !d.has_placed() && !names_hidden_image(d, base, link) {
return false;
}
// The writer draws placed documents' art with the pixels their files hold.
let placed = d.with_placed_art();
let d = &*placed;
let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect();
let mut out = super::clipboard::Clipboard::gather(d, art).to_document();
let written = |n: &std::sync::Arc<Node>| {
let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty))
};
for s in &mut out.symbols {
s.art = written(&s.art);
}
for g in &mut out.graph_designs {
g.art = written(&g.art);
}
for p in &mut out.patterns {
p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect();
}
names_hidden_image(&out, base, link)
}
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
/// Only layers and groups lose members; other objects keep theirs as they are.
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a
/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled
/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document
/// is the art the writer draws for it. Only layers and groups lose members; other objects keep
/// theirs as they are.
fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option<Node> {
if !(n.visible || hidden) {
return None;
}
if matches!(n.kind, NodeKind::PlacedDocument(_)) {
return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny);
}
let mut n = n.clone();
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
let art = svg_written(&m.art, hidden)?;
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| {
let art = svg_written(d, &m.art, hidden, tiny)?;
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
});
if n.extras().mask.is_some() {
@@ -1343,7 +1370,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
match &mut n.kind {
NodeKind::Layer { template: true, children, .. } => children.clear(),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
*children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect();
}
_ => {}
}
+9 -10
View File
@@ -126,14 +126,18 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<(bool, bool)>> {
.collect()
}
/// Each kind's item target and objects: (fill?, item, ids).
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series
/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit
/// resolves it on the other objects. Without it, the art is read with the other objects.
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>, edit: bool) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
let item = item_target(s, p, cmd)?;
kinds
.into_iter()
.map(|fill| {
let it = item.of_kind(s, fill);
Ok((fill, it, it.targets(s, p)?))
let ids = it.targets(s, p)?;
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
Ok((fill, it, ids))
})
.collect()
}
@@ -159,12 +163,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec<NodeId>), bool);
/// `object.setOverprint` aims, leaving out the art of graph designs drawn in graph series.
pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<OverprintJob>> {
let kinds = kinds(p, cmd, keys)?;
let d = &s.doc()?.doc;
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))?
.into_iter()
.map(|(fill, it, ids)| (fill, it, super::appearance::drop_design_art(d, ids)))
.zip(kinds.iter().map(|k| k.1))
.collect())
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect())
}
/// Apply `jobs` to `d`, adding the objects changed to `changed`.
@@ -203,7 +202,7 @@ fn attributes(s: &Session, p: &Value) -> Result<AttributesInfo> {
let d = &s.doc()?.doc;
let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() };
super::attributes::fill_info(d, &mut info);
for (fill, item, ids) in aims(s, p, C, [true, false])? {
for (fill, item, ids) in aims(s, p, C, [true, false], false)? {
let mut all =
ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten();
let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first));
+82 -7
View File
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -982,7 +982,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize>
}
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
// Only design art was given or selected: nothing changes, the defaults included.
if given && ids.is_empty() {
return ok();
}
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
@@ -1017,7 +1023,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
}
fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
// Only design art was given or selected: nothing changes, the defaults included.
if given && ids.is_empty() {
return ok();
}
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
@@ -1086,10 +1098,26 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
return Ok(json!({ "changed": changed as usize }));
}
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 of = match item {
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
ItemTarget::Top => None,
};
// Read before the check below too: `targets` reads no `target` for the topmost fill or stroke.
let contents = super::appearance::targets_contents(p)?;
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
// Only design art was given or selected: nothing changes, the defaults and remembered colors included.
if ids.is_empty() {
return Ok(json!({ "changed": 0 }));
}
let (r, shown_at) = match item {
ItemTarget::Item { .. } => {
let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
let of = super::appearance::reference_of(s, p, item, cmd)?;
// Only design art was given or selected: nothing changes, the remembered colors included.
if targets.is_empty() {
return Ok(json!({ "changed": 0 }));
}
// The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row.
let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it {
ItemTarget::Item { index, .. } => Some((id, Some(index))),
@@ -1105,9 +1133,56 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
(json!({ "changed": changed }), shown_at)
}
// The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles.
// A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other
// objects change as their paint targets do (a compound path's member stands for the compound path). Design art
// inside a given graph or series group is left out.
ItemTarget::Top => {
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
(super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None)))
let mut roots = vec![];
for id in &ids {
let n = s.doc()?.doc.node(*id);
let group =
!contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape());
if group {
roots.push(*id);
} else {
roots.extend(leaf_targets(s, &[*id])?);
}
}
let d = &s.doc()?.doc;
let mut seen = std::collections::HashSet::new();
roots.retain(|id| seen.insert(*id));
let roots = super::appearance::drop_design_art(d, roots);
if roots.is_empty() {
return Ok(json!({ "changed": 0 }));
}
let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
// The fill or stroke the proxy shows of each group among the roots, before the edit.
let own = |d: &Document, id: NodeId| {
d.node(id)
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
.and_then(|n| n.proxy_paint_only(stroke, None))
.cloned()
};
let own_before: std::collections::HashMap<NodeId, Paint> = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect();
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>()});
let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?;
// As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it
// that is not design art (which keeps its paint). The first object given that has either shows it.
let d = &s.doc()?.doc;
let mut shown_at = None;
for id in &ids {
if let Some(was) = own_before.get(id)
&& own(d, *id).as_ref() != Some(was)
{
shown_at = Some((*id, None));
break;
}
if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
shown_at = Some((*leaf, None));
break;
}
}
(r, shown_at)
}
};
// The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+9 -4
View File
@@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
let item = item_target(s, p, C)?.of_kind(s, false);
let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? };
let new_art = no_targets(&ids, p);
let given = !ids.is_empty();
// The art of a graph design in a series keeps the design's stroke.
ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
// With only design art, the weight for new art stays as it is too.
let only_design_art = given && ids.is_empty();
if item == ItemTarget::Top {
// Images and symbol instances take no stroke from the panel.
let d = &s.doc()?.doc;
@@ -329,7 +332,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
})?;
// Commit the new-art template only after the complete request is validated
// and the selected artwork edit has succeeded.
if let Some(w) = change.weight {
if let Some(w) = change.weight
&& !only_design_art
{
s.paint.stroke_width = w;
}
if new_art && let Some(st) = s.new_art_stroke_mut() {
@@ -372,7 +377,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
}
return Ok(json!({"objects": 0}));
}
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?;
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
edit_items(s, &ids, item, None, c, label, false, |n, index| {
if index.is_none()
@@ -517,7 +522,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
let ids = item.targets(s, p)?;
let new_art = no_targets(&ids, p);
// The art of a graph design in a series keeps the design's stroke.
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
let arrows_and_profile = |st: &mut StrokeLayer| {
if let Some(sc) = scale {
st.arrow_scale = sc;
File diff suppressed because one or more lines are too long
+26
View File
@@ -11,6 +11,7 @@
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
//! variables and data sets of a variable library, the XML file of the reference app's Save
//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension.
//! Agents reach every command through `run_command`, like all engine commands.
use std::collections::{BTreeMap, BTreeSet};
@@ -865,6 +866,22 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result<Value> {
apply_dataset(s, &name)
}
/// The Variables panel's Import…: a data source file read by its extension, a CSV, TSV or TXT
/// file as `dataset.import` reads it and an XML file as `variable.loadLibrary` reads it. The
/// result is that command's, with `format` set to `csv` or `xml`.
fn variable_import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "variable.import";
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let (format, mut out) = match ext.as_deref() {
Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?),
Some("xml") => ("xml", load_library(s, &json!({"path": path}))?),
_ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")),
};
out["format"] = json!(format);
Ok(out)
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -1057,6 +1074,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
dataset_import
),
cmd!(
"variable.import",
"Import…",
["Window", "Variables"],
None,
"{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`",
has_doc,
variable_import
),
cmd!(
query "dataset.export",
"Export Data Sets…",