#8068: clear cancelled borrowed sampler state

This commit is contained in:
yoriswind committed 2026-11-16 18:35:34 -08:00
commit 6ac1c8458f
75 files changed
+4467 -361

No files matched your search

+15 -6
View File
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
// are written mirrored about the seam instead.
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
let stop = |s: &crate::GradientStop| {
let at = if mirrored { 1.0 - s.offset } else { s.offset };
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
let stop = |&(t, c, o): &(f32, Color, f32)| {
let at = if mirrored { 1.0 - t } else { t };
format!("{} {}%", css_color(&c, o), at * 100.0)
};
// Stops that repeat or reflect run that many times across the box.
// Stops that repeat or reflect run that many times across the box. CSS mixes
// hex colors evenly in sRGB between two stops
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
// midpoint and the curve of a Perceptual or hue gradient are written as stops
// of their own, each with its color and opacity. A gradient that would need
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
let unrolled = g.gradient.unrolled();
let stops: Vec<String> =
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
unrolled.expanded_stops()
} else {
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
};
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
match g.gradient.kind {
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
+93
View File
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
}
}
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
/// last the end colors hold.
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
let stops: Vec<([f64; 3], f64, f64)> = list
.split(", ")
.map(|stop| {
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
let at: f64 = at.trim_end_matches('%').parse().unwrap();
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
})
.collect();
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
let a = a0 + (a1 - a0) * w;
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
(c, a)
}
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
/// own, also on a reflected and a mirrored conic swatch.
#[test]
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
for i in 0..64 {
let p = (f64::from(i) + 0.5) / 64.0;
let (css, css_alpha) = css_gradient_at(value, p);
let (color, opacity) = gp.gradient.sample(at(p) as f32);
let want = color.to_rgb();
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
}
};
let ramp = |method| Gradient {
method,
..Gradient::new(
GradientKind::Linear,
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
)
};
for method in crate::GradientMethod::ALL {
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
}
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
let fade = Gradient::new(
GradientKind::Linear,
vec![
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
],
);
check("fade", GradientPaint::new(fade), &|p| p);
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
let spread = reflected.spreader();
check("reflect", GradientPaint::new(reflected), &spread);
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
check("mirrored conic", conic, &|p| 1.0 - p);
}
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
/// own stops.
#[test]
fn css_gradient_swatches_keep_their_stop_count_bounded() {
let n = 4000;
let stops = (0..n)
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
.collect();
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
}
#[test]
fn holds_counts_the_swatches_each_format_writes() {
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
+61 -23
View File
@@ -1,4 +1,4 @@
//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects.
//! Use Preview Bounds: objects measured as they are drawn, with geometry and projected 3D effects.
//!
//! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path
//! or compound path is given as its effected geometry, and a fill or stroke with geometry effects
@@ -11,12 +11,15 @@
//! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or
//! layer whose clipping path has strokes with geometry effects is given as that path's geometry
//! before its effects, which the renderer clips by, and those strokes as drawn. Fills and
//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`],
//! strokes that paint nothing (hidden, or painted None) are left out. Extrude & Bevel, Revolve,
//! Inflate and Rotate are measured by the same projected vector art the renderer draws, with
//! any geometry effects after projection applied to that art; [`drawn_art`], which clicks and
//! marquees use, leaves 3D effects unprojected. [`bounds_of`],
//! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes
//! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and
//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows,
//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured
//! with its geometry effects, and the other instances in it are measured without them.
//! with its geometry and 3D effects, and the other instances in it are measured without them.
//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and,
//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds).
@@ -31,12 +34,12 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt};
use crate::group::has_own_paint;
use crate::reshape::{geometry_effects, leaf_geometry};
use crate::{
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art,
needs_outline, outline_art, paints, reshape,
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_revolve,
has_solid, has_transform_art, needs_outline, outline_art, paints, reshape, revolve_art_in, solid_art_in,
};
/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects:
/// past it, the other instances in the object are measured without geometry effects.
/// Most symbol instances in one object whose art [`Drawn`] measures with geometry or 3D effects:
/// past it, the other instances in the object are measured without those effects.
const MAX_INSTANCES: usize = 4096;
/// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else
@@ -191,8 +194,8 @@ pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::
.fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box())))
}
/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else
/// [`Node::visual_bounds_with`].
/// The visual bounds of `n` as drawn: those of its [`drawn_art`] with its 3D effects projected,
/// else [`Node::visual_bounds_with`].
pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
Drawn::new(symbols).visual_bounds(n)
}
@@ -204,31 +207,45 @@ pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option<Rect> {
}
/// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances
/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a
/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a
/// group of its clipping path without strokes and the drawn art of the path's strokes, when they
/// have one. `None` when no geometry effect in `n` changes what it draws.
/// measured by `symbols`, for clicks and marquees. Raster effects stay on the art. A group, layer or
/// intertwine without a clip is rebuilt with the drawn art of each member that has one. A clip group
/// or layer becomes a group of its clipping path without strokes and the drawn art of the path's
/// strokes, when they have one. 3D effects stay on the art unprojected, so each object in it keeps
/// its own id. `None` when no geometry effect in `n` changes what it draws.
pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option<Node> {
Drawn::new(symbols).drawn_art(n)
Drawn::without_3d(symbols).drawn_art(n)
}
/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol
/// instance in `n` counts when its symbol's art has a geometry effect.
/// Whether `n` is measured by art of its own with Use Preview Bounds, or an object in it is: a
/// geometry or 3D effect in it changes what it draws. A symbol instance in `n` counts when its
/// symbol's art has geometry or 3D effects.
pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool {
Drawn::new(symbols).draws_geometry(n)
}
/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name,
/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]).
/// One measurement: whether each symbol checked so far draws geometry or 3D art, by symbol name,
/// and how many more instances it measures with those effects in the current object ([`MAX_INSTANCES`]).
/// With `three_d` false, 3D effects are left on the art unprojected ([`drawn_art`]).
struct Drawn<'s, 'd> {
symbols: &'s SymbolBoxes<'d>,
draws: RefCell<HashMap<String, bool>>,
left: Cell<usize>,
three_d: bool,
}
impl<'s, 'd> Drawn<'s, 'd> {
fn new(symbols: &'s SymbolBoxes<'d>) -> Self {
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) }
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES), three_d: true }
}
/// A measurement that projects no 3D effect, for clicks and marquees ([`drawn_art`]).
fn without_3d(symbols: &'s SymbolBoxes<'d>) -> Self {
Drawn { three_d: false, ..Self::new(symbols) }
}
/// Whether `n` has a 3D effect of its own that this measurement projects.
fn projects(&self, n: &Node) -> bool {
self.three_d && (has_revolve(n) || has_solid(n))
}
/// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object.
@@ -273,6 +290,7 @@ impl<'s, 'd> Drawn<'s, 'd> {
let mut found = false;
n.walk(&mut |c| {
found = found
|| self.projects(c)
|| match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol),
_ => reshapes(c),
@@ -292,14 +310,29 @@ impl<'s, 'd> Drawn<'s, 'd> {
d
}
/// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the
/// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that
/// The art the geometry or 3D effects of `n` itself give it, or that a symbol instance gets from
/// those effects in its symbol's art, with the instance's appearance overrides applied.
/// A group or layer with fills or strokes of its own that
/// paint, around members with geometry effects, is evaluated too: its fills and strokes paint
/// the members' geometry before their effects. A blend, envelope or repeat whose objects have
/// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and
/// the objects in its evaluated art keep their geometry effects. `None` when it has none, and
/// for a symbol instance past [`MAX_INSTANCES`].
fn own_art(&self, n: &Node) -> Option<Node> {
let doc = Some(self.symbols.document());
// A symbol instance with a 3D effect of its own counts toward MAX_INSTANCES before its art is built.
let counted = matches!(n.kind, NodeKind::SymbolInstance { .. }) && self.projects(n);
if counted {
let left = self.left.get().checked_sub(1)?;
self.left.set(left);
}
if self.three_d
&& let Some(art) = revolve_art_in(doc, n).or_else(|| solid_art_in(doc, n))
{
// The builders retain later geometry on the projected group. Measure it after that
// geometry too; item-level effects are handled by the ordinary member traversal.
return Some(self.own_art(&art).unwrap_or(art));
}
let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c)));
let painted = || has_own_paint(n) && inner();
match &n.kind {
@@ -312,9 +345,14 @@ impl<'s, 'd> Drawn<'s, 'd> {
if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) {
return None;
}
let left = self.left.get().checked_sub(1)?;
self.left.set(left);
if !counted {
let left = self.left.get().checked_sub(1)?;
self.left.set(left);
}
let art = self.symbols.measure_art(symbol, Arc::clone)?;
// Paint overrides can remove a projected surface or change its stroke outline.
let art =
if n.extras().symbol_overrides.is_empty() { art } else { Arc::new(vectorcraft_doc::symbol_overrides::dynamic_art(&art, n)) };
// An instance in perspective is projected by `reshape`.
let doc = Some(self.symbols.document());
reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art)))
+92 -2
View File
@@ -5,15 +5,16 @@ use super::{
// ---------- brushes ----------
/// Brushable nodes (paths and compound paths) under `ids`.
/// Brushable nodes (paths and compound paths) under `ids`, in walk order, each listed once where it is first reached.
pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out = vec![];
let mut seen = std::collections::HashSet::new();
for id in ids {
let Some(n) = d.node(*id) else { continue };
n.walk(&mut |c| {
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
if own && !in_compound && !out.contains(&c.id) {
if own && !in_compound && seen.insert(c.id) {
out.push(c.id);
}
});
@@ -748,3 +749,92 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
let checked = crate::schemas::check(spec, p, s.replaying())?;
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_doc::Appearance;
use vectorcraft_geom::PathData;
/// The collector with a linear search of its output, kept to compare results with.
fn listed_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out = vec![];
for id in ids {
let Some(n) = d.node(*id) else { continue };
n.walk(&mut |c| {
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
if own && !in_compound && !out.contains(&c.id) {
out.push(c.id);
}
});
}
out
}
fn path(d: &mut Document) -> Node {
Node::path(d.alloc_id(), PathData::default(), Appearance::default())
}
fn compound(d: &mut Document, children: Vec<Node>) -> Node {
Node::new(d.alloc_id(), NodeKind::Compound { children: children.into_iter().map(Arc::new).collect(), rule: Default::default() })
}
fn add(d: &mut Document, node: Node) -> NodeId {
let layer = d.layers.first().map(|l| l.id);
d.insert(layer, usize::MAX, node).unwrap()
}
#[test]
fn brush_targets_list_each_target_once_in_first_reached_order() {
let mut d = Document::new(400.0, 300.0);
let a = path(&mut d);
let a = add(&mut d, a);
let mut guide = path(&mut d);
if let NodeKind::Path { guide: g, .. } = &mut guide.kind {
*g = true;
}
let guide = add(&mut d, guide);
let mut clip = path(&mut d);
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let clip = add(&mut d, clip);
// A group holding a path and a compound path of two members.
let p1 = path(&mut d);
let p1_id = p1.id;
let (m1, m2) = (path(&mut d), path(&mut d));
let m1_id = m1.id;
let cp1 = compound(&mut d, vec![m1, m2]);
let cp1_id = cp1.id;
let group = Node::group(d.alloc_id(), vec![Arc::new(p1), Arc::new(cp1)]);
let group = add(&mut d, group);
// A compound path holding a compound path.
let m3 = path(&mut d);
let cp3 = compound(&mut d, vec![m3]);
let cp3_id = cp3.id;
let cp2 = compound(&mut d, vec![cp3]);
let cp2 = add(&mut d, cp2);
let ids = [cp1_id, a, group, p1_id, a, guide, clip, m1_id, cp2, cp3_id, NodeId(u64::MAX)];
let got = brush_targets(&d, &ids);
assert_eq!(got, [cp1_id, a, p1_id, cp2], "repeats keep their first place; guides, clipping paths and compound members are left out");
assert_eq!(got, listed_targets(&d, &ids));
assert!(brush_targets(&d, &[]).is_empty());
// Many paths in groups, each group listed with some of its members.
let mut ids = vec![];
for _ in 0..50 {
let members: Vec<Node> = (0..20).map(|_| path(&mut d)).collect();
let member_ids: Vec<NodeId> = members.iter().map(|m| m.id).collect();
let g = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect());
let g = add(&mut d, g);
ids.push(member_ids[7]);
ids.push(g);
ids.push(member_ids[3]);
}
let got = brush_targets(&d, &ids);
assert_eq!(got.len(), 50 * 20);
assert_eq!(got, listed_targets(&d, &ids));
}
}
+1 -1
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file Line truncated
has_doc,
screens::export_for_screens
),
+63 -18
View File
@@ -209,6 +209,8 @@ struct Row {
options: Value,
/// What makes two rows the same file: format, size, suffix and options.
key: String,
/// The row or the format's settings set `bleed` (a PDF row's own bleed, zero included).
bleed_given: bool,
}
impl Row {
@@ -248,12 +250,19 @@ impl Row {
}
// A file per artboard is for viewing: it doesn't carry the whole document to edit.
options.entry("preserveEditing").or_insert(json!(false));
let bleed_given = options.get("bleed").is_some_and(|b| !b.is_null());
let options = Value::Object(options);
// A PDF preset (built-in or saved) becomes its settings.
let options = if format.id == "pdf" { super::pdf::expand_preset(s, C, &options)?.into_owned() } else { options };
// Two rows that would write the same bytes under the same name are one file.
let key = format!("{}|{}|{suffix}|{options}", format.id, size.label());
Ok(Self { format, size, suffix, folder, options, key })
let mut row = Self { format, size, suffix, folder, options, key: String::new(), bleed_given };
row.key = row.file_key();
Ok(row)
}
/// What makes two rows the same file: two rows that would write the same bytes under the same
/// name are one file.
fn file_key(&self) -> String {
format!("{}|{}|{}|{}", self.format.id, self.size.label(), self.suffix, self.options)
}
/// Formats that hold a whole document to edit (native, Illustrator, EPS): written from a
@@ -525,6 +534,8 @@ fn rows_of(s: &Session, p: &Value, preset: Option<&str>) -> Result<Vec<Row>> {
if let Some(m) = r.options.as_object_mut() {
m.entry("antiAlias").or_insert_with(|| aa.clone());
}
// Two rows whose options are now the same are one file.
r.key = r.file_key();
}
}
Ok(rows)
@@ -1137,17 +1148,22 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
let doc = s.doc()?.doc.clone();
let original = s.doc()?.doc.clone();
// Include Bleed: each artboard grown by the document's bleed.
let doc = if o.include_bleed && doc.setup.has_bleed() {
let mut d = (*doc).clone();
let grown = o.include_bleed && original.setup.has_bleed();
let doc = if grown {
let mut d = (*original).clone();
for a in &mut d.artboards {
a.rect = doc.setup.bleed_rect(a.rect);
a.rect = original.setup.bleed_rect(a.rect);
}
Arc::new(d)
} else {
doc
original.clone()
};
// A PDF page of an artboard keeps the artboard as its TrimBox and puts its row's bleed around
// it once: it is written from the document with the artboards as they are. Assets, layers and
// a selection are written on a page of their own bounds, which Include Bleed doesn't grow.
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
// Before the folder is made or any row is written, with the artboards each file holds.
@@ -1164,8 +1180,26 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
// Appearance of Black › Printing / Exporting for RGB raster rows.
// Include Artboard Fill off: the encoders leave the background colors out.
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None };
let rows = rows
.into_iter()
.map(|mut r| {
// Include Bleed: a PDF row that sets no bleed of its own, and whose preset gives none,
// puts the document's bleed around the artboard, and is the same file as a row that
// asks for the document's bleed. A saved preset's bleed values stay, as they do in
// that row.
if ungrown.is_some() && r.format.id == "pdf" && !r.bleed_given && !pdf_bleeds(&r.options) {
match r.options.get_mut("bleed").and_then(Value::as_object_mut) {
Some(b) => {
b.insert("useDocument".into(), json!(true));
}
None => r.options["bleed"] = json!({ "useDocument": true }),
}
r.key = r.file_key();
}
Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }
})
.collect();
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None, ungrown };
match &mut s.screens_hand_off {
Some(slot) => {
*slot = Some(export);
@@ -1175,6 +1209,14 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
}
}
/// Do the PDF `options` (a built-in preset's settings under them) give the pages a bleed: the
/// document's, or a value above 0 on some side? Options the PDF encoder refuses count as giving
/// one, so they are left as they are for the encoder to refuse.
fn pdf_bleeds(options: &Value) -> bool {
super::pdf::settings(C, options)
.map_or(true, |s| s.bleed.use_document || [s.bleed.top, s.bleed.bottom, s.bleed.left, s.bleed.right].iter().any(|b| *b > 0.0))
}
/// An export as `document.exportForScreens` and `assets.export` take it from the session: the
/// params, the format rows, the naming, and each item with the document it writes
/// ([`Session::prepare_screen_export`]). [`ScreenExport::write`] encodes and writes its files
@@ -1192,6 +1234,9 @@ pub struct ScreenExport {
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
hidden: Option<(String, String)>,
/// Include Bleed with artboards: the document with the artboards as they are, which PDF rows
/// write (the items hold the artboards grown by the bleed).
ungrown: Option<Arc<Document>>,
}
impl Session {
@@ -1252,7 +1297,7 @@ impl ScreenExport {
/// [`ScreenExport::write`].
fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let ScreenExport { o, rows, naming, items, unused, .. } = export;
let ScreenExport { o, rows, naming, items, unused, ungrown, .. } = export;
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
if let Some(dir) = folder {
create_dir(dir)?;
@@ -1263,13 +1308,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
for text in unused {
add_note(&mut notes, Note::setting(text));
}
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
// written on a page of their own bounds, which it doesn't grow.
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
// The document a PDF row writes: with Include Bleed, the artboards as they are.
let pdf_doc = ungrown.as_deref();
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) {
for n in given {
add_note(&mut notes, n);
}
Ok(bytes)
@@ -1306,12 +1350,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
let bytes = if let Some(boards) = single {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
write(&item.doc, "pdf", &options)?
write(pdf_doc.unwrap_or(&item.doc), "pdf", &options)?
} else if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) {
// One page per artboard.
let mut options = r.options.clone();
options["range"] = json!("all");
write(all, "pdf", &options)?
write(pdf_doc.unwrap_or(all), "pdf", &options)?
} else if r.whole_document() && item.artboard.is_some() {
let b = item.artboard.unwrap_or(0);
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
@@ -1334,7 +1378,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
}
write(&d, r.format.id, &options)?
} else {
write(&item.doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
let doc = if r.format.id == "pdf" { pdf_doc.unwrap_or(&item.doc) } else { &item.doc };
write(doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
};
out.put(folder, o.zip, name, bytes, writer)?;
files += 1;
+94 -1
View File
@@ -594,7 +594,8 @@ fn include_bleed_grows_each_artboard() {
assert_eq!(size(&files(&r)[0].1), (40, 30), "without it, the artboard alone");
}
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the bleed out.
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the
/// bleed out, unless the row sets a bleed of 0 itself.
#[test]
fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
let mut s = session(1);
@@ -603,11 +604,103 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
let row = json!([{"format": "pdf", "standard": "pdfX4"}]);
assert!(warned(&export(&mut s, json!({"formats": row}))));
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
let zero = json!([{"format": "pdf", "standard": "pdfX4", "bleed": {"top": 0, "bottom": 0, "left": 0, "right": 0}}]);
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": zero}))), "the row's own bleed of 0 leaves the bleed out");
// A selection is written on a page of its own bounds, which Include Bleed doesn't grow.
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
}
/// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read
/// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries).
fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> {
let text = String::from_utf8_lossy(pdf);
text.match_indices(key)
.map(|(at, _)| {
let mut words = text[at + key.len()..].split(|c: char| c.is_whitespace() || matches!(c, '[' | ']')).filter(|w| !w.is_empty());
std::array::from_fn(|_| words.next().and_then(|w| w.parse().ok()).unwrap_or(f64::NAN))
})
.collect()
}
/// A page's MediaBox, BleedBox and TrimBox sizes `(width, height)` in points, and the trim's
/// distance from the bleed box's left and bottom edges.
type PageSizes = ((f64, f64), (f64, f64), (f64, f64), (f64, f64));
/// [`PageSizes`] of each page of `pdf`.
fn page_sizes(pdf: &[u8]) -> Vec<PageSizes> {
let size = |b: &[f64; 4]| (b[2] - b[0], b[3] - b[1]);
let (media, bleed, trim) = (raw_boxes(pdf, "/MediaBox"), raw_boxes(pdf, "/BleedBox"), raw_boxes(pdf, "/TrimBox"));
assert!(!trim.is_empty() && media.len() == trim.len() && bleed.len() == trim.len(), "a MediaBox, BleedBox and TrimBox per page");
(0..trim.len()).map(|i| (size(&media[i]), size(&bleed[i]), size(&trim[i]), (trim[i][0] - bleed[i][0], trim[i][1] - bleed[i][1]))).collect()
}
/// With Include Bleed, a PDF page keeps the artboard as its TrimBox and puts the bleed around it
/// once (PDF 32000-1:2008, 14.11.2: the trim box is the finished page, the bleed box holds it): the
/// document's bleed when the row asks for it or sets none, else the row's own values.
#[test]
fn include_bleed_pdf_pages_trim_at_the_artboard() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("document.setup", &json!({"bleed": 9})).unwrap();
let pages = |s: &mut Session, p: Value| -> Vec<PageSizes> {
let r = export(s, p);
files(&r).iter().filter(|(n, _)| n.ends_with(".pdf")).flat_map(|(_, b)| page_sizes(b)).collect()
};
let one = |media: f64, bleed: f64, trim: f64| ((media, media), (bleed, bleed), (trim, trim), ((bleed - trim) / 2.0, (bleed - trim) / 2.0));
let document = json!({"format": "pdf", "bleed": {"useDocument": true}});
let sides = |b: f64| json!({"top": b, "bottom": b, "left": b, "right": b});
for (p, want) in [
(json!({"includeBleed": true, "artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "preset": "High Quality Print"}]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(3.0)}]}), one(106.0, 106.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(0.0)}]}), one(100.0, 100.0, 100.0)),
(json!({"artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
(json!({"artboard": 0, "formats": [{"format": "pdf"}]}), one(100.0, 100.0, 100.0)),
] {
assert_eq!(pages(&mut s, p.clone()), [want], "{p}");
}
// Every page of a single file and of the Full Document, each artboard its own trim.
for p in [
json!({"includeBleed": true, "pdfs": "single", "formats": [document]}),
json!({"includeBleed": true, "fullDocument": true, "formats": [document]}),
] {
assert_eq!(pages(&mut s, p.clone()), [one(118.0, 118.0, 100.0); 2], "{p}");
}
// A row with printer's marks: the sheet grows past the bleed box for them, around the same trim.
let marked = pages(
&mut s,
json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": {"useDocument": true}, "marks": {"trim": true}}]}),
);
let [(media, bleed, trim, at)] = marked[..] else { panic!("one page: {marked:?}") };
assert_eq!((bleed, trim, at), ((118.0, 118.0), (100.0, 100.0), (9.0, 9.0)));
assert!(media.0 > 118.0 && media.1 > 118.0, "{media:?}");
// A row that sets no bleed writes the same file as one that asks for the document's: one file.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}, document]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
// So does it with a top-level anti-aliasing mode, which both rows take.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "antiAlias": "art", "formats": [{"format": "pdf"}, document]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
// And with a saved PDF preset, which writes out every bleed value for both rows.
s.execute("pdf.preset.save", &json!({"name": "Saved Default"})).unwrap();
let saved = |bleed: Option<Value>| {
let mut row = json!({"format": "pdf", "preset": "Saved Default"});
if let Some(b) = bleed {
row["bleed"] = b;
}
row
};
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None), saved(Some(json!({"useDocument": true})))]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
assert_eq!(pages(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None)]})), [one(118.0, 118.0, 100.0)]);
// A raster row of the same export still holds the bleed in its pixels.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [document, {"format": "png"}]}));
let png = files(&r).into_iter().find(|(n, _)| n.ends_with(".png")).unwrap().1;
assert_eq!(size(&png), (118, 118));
}
#[test]
fn png_8_rows_write_indexed_colour() {
let mut s = session(1);
+91 -16
View File
@@ -26,7 +26,9 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces_in, faces_of, is_intertwine, nonempty, painted_areas};
use vectorcraft_tools::intertwine::{
Face, drawn_order, face_at, faces_in, faces_of, in_intertwine, is_intertwine, nonempty, painted_areas, refused_member,
};
use super::edit::selected_roots;
use super::pathops::Beside;
@@ -106,17 +108,7 @@ fn refused(d: &Document, n: &Node) -> Option<&'static str> {
if around.iter().filter(|a| **a != n.id).filter_map(|a| d.node(*a)).any(is_intertwine) {
return Some("an object already in an Intertwine group");
}
let mut why = None;
n.walk(&mut |c| {
why = why.or(match &c.kind {
NodeKind::Intertwine { .. } => Some("an Intertwine group"),
NodeKind::Repeat(_) => Some("a Repeat"),
NodeKind::Group { .. } if c.extras().graph.is_some() => Some("a graph"),
NodeKind::Group { .. } if vectorcraft_tools::builder::is_live_paint(c) => Some("a Live Paint group"),
_ => None,
});
});
why
refused_member(n)
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
@@ -179,10 +171,7 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
.flatten()
.map(|c| {
let mut c = (**c).clone();
let mut e = c.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
drop(e);
without_areas(&mut c);
c
})
.collect();
@@ -196,6 +185,92 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
// ---------- members that come and go ----------
/// Why `n` can't go into `parent`, an Intertwine group or a container inside one, if it can't
/// ([`refused_member`]). Other containers take it as they did.
pub(crate) fn refused_in(d: &Document, parent: Option<NodeId>, n: &Node) -> Option<&'static str> {
parent.filter(|p| in_intertwine(d, *p)).and_then(|_| refused_member(n))
}
/// The Intertwine groups that `ids` are members of, each once.
pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut seen = std::collections::HashSet::new();
ids.iter().filter_map(|i| d.parent_of(*i)).filter(|g| d.node(*g).is_some_and(is_intertwine) && seen.insert(*g)).collect()
}
/// `n` without the areas it is drawn over other members in.
fn without_areas(n: &mut Node) {
if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() {
let mut e = n.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
}
}
/// Whether Intertwine group `g` has nothing of its own that changes how its members are drawn:
/// it is visible and unlocked, with full opacity, normal blending, no appearance and no extras
/// (an opacity mask among them).
fn bare(g: &Node) -> bool {
let plain = Node::new(g.id, NodeKind::Intertwine { children: vec![] });
(g.visible, g.locked, g.opacity, g.blend, g.isolate, g.knockout, g.knockout_shape)
== (plain.visible, plain.locked, plain.opacity, plain.blend, plain.isolate, plain.knockout, plain.knockout_shape)
&& g.appearance == plain.appearance
&& *g.extras() == *plain.extras()
}
/// After objects moved in the Layers panel: each of `placed` (the objects now in place, each with
/// the container it came from, None for a copy) that is not in the container it came from loses
/// the areas it was drawn over other members in, so it joins an Intertwine group at no tier and
/// leaves one as ordinary art. Then each of `left` (the Intertwine groups objects came from) that
/// has fewer than two members is taken apart: its one member goes in its place without areas, and
/// an empty one is removed. A group with one member and something of its own ([`bare`]) becomes a
/// plain group of that member instead, keeping its id and all it has. The other members keep their
/// areas.
pub(crate) fn settle_members(d: &mut Document, placed: &[(NodeId, Option<NodeId>)], left: &[NodeId]) -> Result<()> {
for (id, from) in placed {
if d.node(*id).is_some_and(|n| n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty())
&& from.is_none_or(|f| d.parent_of(*id) != Some(f))
{
without_areas(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?);
}
}
let lone: Vec<NodeId> =
left.iter().copied().filter(|g| d.node(*g).is_some_and(|n| is_intertwine(n) && n.children().is_none_or(|c| c.len() < 2))).collect();
let (kept, lone): (Vec<NodeId>, Vec<NodeId>) =
lone.into_iter().partition(|g| d.node(*g).is_some_and(|n| n.children().is_some_and(|c| c.len() == 1) && !bare(n)));
for g in &kept {
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
if let NodeKind::Intertwine { children } = &mut n.kind {
let children = std::mem::take(children)
.into_iter()
.map(|c| {
let mut c = (*c).clone();
without_areas(&mut c);
Arc::new(c)
})
.collect();
n.kind = NodeKind::Group { children, clip: false };
}
}
let mut apart = Beside::replacing(d, &lone);
for g in &lone {
let Some(n) = d.node(*g) else { continue };
let members: Vec<Node> = n
.children()
.into_iter()
.flatten()
.map(|c| {
let mut c = (**c).clone();
without_areas(&mut c);
c
})
.collect();
apart.put(d, *g, members)?;
}
apart.finish(d)
}
// ---------- Expand ----------
/// Replace Intertwine group `id` by a plain group of the art it draws
+21 -4
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Rows",
[],
None,
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer or group (on top of its contents). Layers go only in layers or at the top level, objects in layers and groups; an object placed beside a top-level layer goes inside it. A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
has_doc,
move_rows
),
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder",
[],
None,
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers), deselecting every selected object left hidden or locked (the key object too)",
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)",
has_doc,
move_node
),
@@ -242,14 +242,15 @@ pub(crate) fn row_roots(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
}
/// Whether `parent` (None: the top level) can hold `n`: layers go at the top level or in layers,
/// anything else in layers and groups.
/// anything else in layers, groups and Intertwine groups (which also check what the object holds:
/// [`super::intertwine::refused_in`]).
pub(crate) fn accepts(d: &Document, parent: Option<NodeId>, n: &Node) -> bool {
match parent {
None => n.is_layer(),
Some(p) => match d.node(p).map(|x| &x.kind) {
Some(NodeKind::Layer { .. }) => true,
// A ruler guide stays directly in a layer or sublayer.
Some(NodeKind::Group { .. }) => !n.is_layer() && !n.is_ruler_guide(),
Some(NodeKind::Group { .. } | NodeKind::Intertwine { .. }) => !n.is_layer() && !n.is_ruler_guide(),
_ => false,
},
}
@@ -791,10 +792,17 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() });
return Err(bad(C, format!("{} can't go into {into}", n.display_name())));
}
if let Some(what) = nodes.iter().find_map(|n| super::intertwine::refused_in(d, parent, n)) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
if parent.is_some_and(|p| locked_within(d, p)) {
return Err(EngineError::Other("the layer or group is locked".into()));
}
let label = if copy { "Duplicate Rows" } else { "Move Rows" };
// Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the
// Intertwine groups it leaves.
let from: std::collections::HashMap<NodeId, Option<NodeId>> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect();
let left = if copy { vec![] } else { super::intertwine::groups_of(d, &ids) };
let moved = s.edit(label, |d, sel| {
let nodes = if copy {
let mut nodes = vec![];
@@ -829,6 +837,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if copy {
super::typecmd::refresh_bounds_of(d, &out);
}
let placed: Vec<(NodeId, Option<NodeId>)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect();
super::intertwine::settle_members(d, &placed, &left)?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(out)
@@ -848,8 +858,15 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
if !accepts(d, parent, n) {
return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups"));
}
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
let from = d.parent_of(id);
let left = super::intertwine::groups_of(d, &[id]);
s.edit("Reorder", |d, sel| {
d.move_node(id, parent, index)?;
super::intertwine::settle_members(d, &[(id, from)], &left)?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(())
})?;
+6 -1
View File
@@ -80,11 +80,16 @@ pub(super) fn send_to_current_layer(s: &mut Session, _: &Value) -> Result<Value>
if st.doc.children(Some(layer)).is_some_and(|c| c.iter().rev().filter(art).map(|n| n.id).take(ids.len()).eq(ids.iter().rev().copied())) {
return ok();
}
s.edit("Send to Current Layer", |d, _| {
let placed: Vec<(NodeId, Option<NodeId>)> = ids.iter().map(|i| (*i, st.doc.parent_of(*i))).collect();
let left = crate::cmd::intertwine::groups_of(&st.doc, &ids);
s.edit("Send to Current Layer", |d, sel| {
let moved = d.remove_many(&ids)?;
let ch = d.children_mut(Some(layer))?;
let at = Node::guide_run_start(ch);
ch.splice(at..at, moved);
// Members sent out of an Intertwine group leave it as ordinary art.
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
sel.prune(d);
Ok(())
})?;
ok()
+3 -3
View File
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Align",
["Window", "Align"],
None,
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
has_selection_or_guides,
align
),
@@ -269,7 +269,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Distribute",
["Window", "Align"],
None,
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
can_distribute,
distribute
),
@@ -278,7 +278,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Distribute Spacing",
["Window", "Align"],
None,
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
can_distribute,
distribute_spacing
),
+231
View File
@@ -452,6 +452,237 @@ fn what_cannot_be_intertwined_is_refused_with_a_reason() {
assert!(e.to_string().contains("not an Intertwine group"), "{e}");
}
// ---------- members dragged in and out in the Layers panel ----------
/// A green rectangle (84..96 × 46..54) that crosses ring B's stroke at (90, 50) and no part of A.
fn green_bar(s: &mut Session) -> NodeId {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": 84, "y": 46, "width": 12, "height": 8})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
id
}
fn kids(s: &Session, g: NodeId) -> Vec<NodeId> {
s.doc().unwrap().doc.node(g).and_then(vectorcraft_doc::Node::children).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default()
}
fn rows(s: &mut Session, ids: &[NodeId], target: NodeId, place: &str, copy: bool) -> Result<Value> {
s.execute("layer.move", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "target": target.0, "place": place, "copy": copy}))
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn has_areas(s: &Session, id: NodeId) -> bool {
let n = s.doc().unwrap().doc.node(id).unwrap();
n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty()
}
fn parent(s: &Session, id: NodeId) -> Option<NodeId> {
s.doc().unwrap().doc.parent_of(id)
}
/// The help page: "You can drag additional objects into the group later."
#[test]
fn layer_move_adds_a_member_without_losing_existing_weave() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let c = green_bar(&mut s);
let undo = undo_len(&s);
rows(&mut s, &[c], g, "inside", false).unwrap();
assert_eq!(kids(&s, g), [a, b, c], "on top of the group's objects");
assert_eq!(undo_len(&s), undo + 1, "one undo step");
assert!(area(&s, a).is_some(), "the arranged overlap is kept");
let r = render(&s);
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "the rings are woven as before");
assert!(green(&r, 90, 50), "the new member is drawn in its own order");
// A live member: its overlap with B can be arranged.
assert_eq!(arrange(&mut s, json!({"id": g.0, "at": [90, 50]}))["count"], 1);
assert!(blue(&render(&s), 90, 50));
for format in ["vectorcraft", "svg"] {
let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone();
let mut o = Session::new();
o.execute("document.open", &json!({"name": format!("woven.{format}"), "dataBase64": data})).unwrap();
let r = render(&o);
assert!(red(&r, 50, 30) && blue(&r, 50, 70) && blue(&r, 90, 50), "{format}");
}
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b]);
assert_eq!(parent(&s, c), parent(&s, g));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b, c]);
}
/// An object that overlaps no member still joins the group, beside a member's row too; Alt-drag
/// adds a copy, which starts drawn in its own order everywhere.
#[test]
fn layer_move_accepts_nonoverlapping_member() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let c = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
rows(&mut s, &[c], a, "above", false).unwrap();
assert_eq!(kids(&s, g), [a, c, b], "above member A");
let v = rows(&mut s, &[a], g, "inside", true).unwrap();
let copy = NodeId(v["ids"][0].as_u64().unwrap());
assert_eq!(kids(&s, g), [a, c, b, copy]);
assert!(has_areas(&s, a) && !has_areas(&s, copy), "the copy has no arranged areas");
let r = render(&s);
assert!(red(&r, 50, 30) && red(&r, 50, 70), "the copy of A is drawn over B at both crossings");
}
#[test]
fn layer_move_rejects_unsupported_intertwine_members_atomically() {
let mut s = session();
let (a, b) = rings(&mut s);
let p = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
select(&mut s, &[p]);
let pg = id_of(&s.execute("object.group", &json!({})).unwrap());
select(&mut s, &[a, b, pg]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
select(&mut s, &[d, e]);
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let f = id_of(&s.execute("shape.rectangle", &json!({"x": 180, "y": 180, "width": 5, "height": 5})).unwrap());
select(&mut s, &[g2, f]);
let holder = id_of(&s.execute("object.group", &json!({})).unwrap());
let layer = s.doc().unwrap().doc.layer_of(g).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = undo_len(&s);
// No nested Intertwine groups: not as a member, inside a member's group, beside a member's
// row, nor held in a group.
for (ids, target, place) in [(g2, g, "inside"), (g2, pg, "inside"), (g2, a, "above"), (holder, g, "inside"), (holder, b, "below")] {
let err = rows(&mut s, &[ids], target, place, false).unwrap_err();
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{place} {}: {err}", target.0);
let err = rows(&mut s, &[ids], target, place, true).unwrap_err();
assert!(err.to_string().contains("can't be intertwined"), "copy: {err}");
}
let err = s.execute("node.move", &json!({"id": holder.0, "parent": g.0, "index": 0})).unwrap_err();
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{err}");
let err = rows(&mut s, &[layer], g, "inside", false).unwrap_err();
assert!(err.to_string().contains("can't go into"), "{err}");
assert_eq!(undo_len(&s), undo, "no undo step");
assert!(s.doc().unwrap().doc == before, "the document is as it was");
// A plain object goes into the group inside the Intertwine group.
rows(&mut s, &[f], pg, "inside", false).unwrap();
assert_eq!(kids(&s, pg), [p, f]);
}
#[test]
fn layer_move_clears_areas_when_member_leaves() {
let mut s = session();
let (a, b) = rings(&mut s);
let c = green_bar(&mut s);
select(&mut s, &[a, b, c]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
arrange(&mut s, json!({"at": [50, 30]}));
assert!(has_areas(&s, a));
rows(&mut s, &[a], g, "above", false).unwrap();
assert_eq!(parent(&s, a), parent(&s, g));
assert!(!has_areas(&s, a), "ordinary art again");
assert_eq!(kids(&s, g), [b, c], "two members stay an Intertwine group");
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
let r = render(&s);
assert!(red(&r, 50, 30) && red(&r, 50, 70) && green(&r, 90, 50), "A is above the group at both crossings");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b, c]);
assert!(has_areas(&s, a));
assert!(red(&render(&s), 50, 30));
}
#[test]
fn layer_move_between_intertwines_drops_old_areas() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
select(&mut s, &[d, e]);
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
rows(&mut s, &[a], g2, "inside", false).unwrap();
assert_eq!(kids(&s, g2), [d, e, a]);
assert!(!has_areas(&s, a), "the areas of the group it left do not come along");
assert!(s.doc().unwrap().doc.node(g).is_none(), "the group A left has one member and is taken apart");
assert_eq!(parent(&s, b), parent(&s, g2));
}
#[test]
fn layer_move_dissolves_a_group_left_with_one_member() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let layer = parent(&s, g).unwrap();
let top = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
select(&mut s, &[g]);
let undo = undo_len(&s);
rows(&mut s, &[b], top, "above", false).unwrap();
assert_eq!(undo_len(&s), undo + 1, "one undo step");
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [a, top, b], "the one member left is in the group's place");
assert!(!has_areas(&s, a), "with no other member it has no areas");
assert!(!s.doc().unwrap().selection.contains(g));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, layer), [g, top]);
assert_eq!(kids(&s, g), [a, b]);
let r = render(&s);
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "woven as before");
// Both members out: the empty group is removed.
rows(&mut s, &[a, b], g, "above", false).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [a, b, top]);
assert!(!has_areas(&s, a) && !has_areas(&s, b));
}
/// A group left with one member that has an opacity of its own stays, as a plain group of that
/// member, so the member is drawn as before.
#[test]
fn layer_move_keeps_a_lone_members_group_with_its_own_opacity() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
s.execute("object.setProps", &json!({"ids": [g.0], "opacity": 40})).unwrap();
let layer = parent(&s, g).unwrap();
rows(&mut s, &[b], g, "above", false).unwrap();
assert_eq!(kids(&s, layer), [g, b]);
assert_eq!(kids(&s, g), [a]);
let n = s.doc().unwrap().doc.node(g).unwrap().clone();
assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "a plain group");
assert!((n.opacity - 0.4).abs() < 1e-6, "{}", n.opacity);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
assert_eq!(kids(&s, g), [a, b]);
}
#[test]
fn node_move_and_send_to_current_layer_clean_up_membership() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let layer = parent(&s, g).unwrap();
s.execute("node.move", &json!({"id": b.0, "parent": layer.0, "index": 0})).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [b, a]);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b]);
// A member sent to the current layer leaves the group the same way.
select(&mut s, &[a]);
s.execute("object.arrange.sendToCurrentLayer", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [b, a]);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
// node.move puts an object into an Intertwine group.
let c = green_bar(&mut s);
s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 1})).unwrap();
assert_eq!(kids(&s, g), [a, c, b]);
}
// ---------- on the canvas ----------
fn press(s: &mut Session, pts: &[(f64, f64)], shift: bool) -> Vec<UiRequest> {
+279 -1
View File
@@ -1,5 +1,5 @@
//! Use Preview Bounds: the Transform panel values, the bounding box, Align and Distribute measure
//! visual bounds (strokes and geometry effects included) when it is on.
//! visual bounds (strokes, geometry and projected 3D effects included) when it is on.
use std::sync::Arc;
@@ -103,6 +103,284 @@ fn near(a: Rect, b: Rect, tolerance: f64) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tolerance)
}
const PREVIEW_3D: [&str; 4] = ["threeD.extrude", "threeD.revolve", "threeD.inflate", "threeD.rotate"];
/// A live projected rectangle, with the effect on the object or its painted fill.
fn projected_rect(s: &mut Session, effect: &str, item: bool) -> NodeId {
let id = rect(s, 100.0, 80.0, 0.0);
run(s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect), "item": if item { json!(0) } else { Value::Null }}));
id
}
/// Settings for `effect` that turn the art and give it depth.
fn params_3d(effect: &str) -> Value {
let mut params = json!({"rotationX": -20, "rotationY": 35, "rotationZ": 15, "perspectiveAngle": 0, "shade": false});
match effect {
"threeD.revolve" => {
params["segments"] = json!(8);
params["angle"] = json!(240);
params["offset"] = json!(12);
}
"threeD.extrude" => {
params["depth"] = json!(40);
params["bevel"] = json!("rounded");
}
"threeD.inflate" => params["depth"] = json!(20),
_ => {}
}
params
}
/// Measure the renderer's projected vector art, including any geometry effects left after 3D.
fn projected(s: &Session, id: NodeId) -> Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap()
}
/// All four projected effects contribute at object and item scope; off and hidden keep source bounds.
#[test]
fn preview_3d_measures_the_projected_art_at_object_and_item_scope() {
for effect in PREVIEW_3D {
for item in [false, true] {
let mut s = session();
let id = projected_rect(&mut s, effect, item);
let expected = projected(&s, id);
let source = geometric(&s, id);
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
preview(&mut s, false);
assert_eq!(s.transform_bounds(&[id]), Some(source));
preview(&mut s, true);
run(&mut s, "effect.setParams", json!({"ids": [id.0], "index": 0, "item": if item { json!(0) } else { Value::Null }, "visible": false}));
assert_eq!(s.transform_bounds(&[id]), Some(source), "hidden {effect}, item={item}");
}
}
}
/// Align and spacing use projected edges, with one undo step and no repeat-alignment edit.
#[test]
fn preview_3d_align_and_spacing_measure_projected_edges() {
for effect in PREVIEW_3D {
let mut s = session();
let a = projected_rect(&mut s, effect, false);
let b = rect(&mut s, 20.0, 30.0, 0.0);
preview(&mut s, true);
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = s.doc().unwrap().doc.clone();
let history = s.doc().unwrap().history.undo.len();
run(&mut s, "object.align", json!({"horizontal": "left"}));
assert!((projected(&s, a).x0 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
let aligned = s.doc().unwrap().doc.clone();
run(&mut s, "object.align", json!({"horizontal": "left"}));
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "already aligned {effect}");
assert_eq!(s.doc().unwrap().doc, aligned);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.doc().unwrap().doc, aligned);
let mut s = session();
let a = projected_rect(&mut s, effect, false);
let b = rect(&mut s, 350.0, 30.0, 0.0);
preview(&mut s, true);
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = s.doc().unwrap().doc.clone();
run(&mut s, "object.distributeSpacing", json!({"axis": "horizontal", "spacing": 0}));
assert!((projected(&s, a).x1 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
}
}
/// A group's and a symbol's projected members are measured as art rather than flat source paths.
#[test]
fn preview_3d_measures_projected_group_and_symbol_members() {
for effect in PREVIEW_3D {
let mut source = session();
let source_id = projected_rect(&mut source, effect, false);
let expected = projected(&source, source_id);
let mut d = Document::new(600.0, 400.0);
let mut shape = source.doc().unwrap().doc.node(source_id).unwrap().clone();
shape.id = d.alloc_id();
let group = Node::group(d.alloc_id(), vec![Arc::new(shape.clone())]);
let group_id = group.id;
let layer = d.layers[0].id;
d.insert(Some(layer), 0, group).unwrap();
shape.id = d.alloc_id();
d.symbols.push(Symbol { dynamic: false, name: "3D / Bounds".into(), art: Arc::new(shape) });
let shift = Affine::translate((250.0, 0.0));
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Bounds".into(), xf: shift });
let instance_id = instance.id;
d.insert(Some(layer), 1, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
preview(&mut s, true);
assert!(near(s.transform_bounds(&[group_id]).unwrap(), expected, 1e-6), "group {effect}");
assert!(near(s.transform_bounds(&[instance_id]).unwrap(), shift.transform_rect_bbox(expected), 1e-6), "symbol {effect}");
}
}
/// A symbol instance with a 3D effect of its own is measured by the art the renderer projects from its symbol.
#[test]
fn preview_3d_measures_an_instance_with_its_own_effect() {
for effect in PREVIEW_3D {
let mut d = Document::new(600.0, 400.0);
let square = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 80.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
d.symbols.push(Symbol { dynamic: false, name: "3D / Own".into(), art: Arc::new(square) });
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Own".into(), xf: Affine::translate((50.0, 40.0)) });
let (layer, id) = (d.layers[0].id, instance.id);
d.insert(Some(layer), 0, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect)}));
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art_in(Some(d), n).or_else(|| vectorcraft_render::effects::solid_art_in(Some(d), n)).unwrap();
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
let source = geometric(&s, id);
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}");
}
}
/// Dynamic instance overrides are applied before deciding which painted 3D surfaces remain.
#[test]
fn preview_3d_dynamic_symbol_overrides_precede_projection() {
for effect in PREVIEW_3D {
let mut source = session();
let source_id = projected_rect(&mut source, effect, false);
let full = projected(&source, source_id);
let mut d = Document::new(600.0, 400.0);
let mut art = source.doc().unwrap().doc.node(source_id).unwrap().clone();
art.id = d.alloc_id();
d.symbols.push(Symbol { dynamic: true, name: "3D / Dynamic".into(), art: Arc::new(art) });
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Dynamic".into(), xf: Affine::IDENTITY });
instance
.extras_mut()
.symbol_overrides
.push(vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(Paint::None), ..Default::default() });
let id = instance.id;
let changed = vectorcraft_doc::symbol_overrides::dynamic_art(&d.symbols[0].art, &instance);
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &changed);
if effect == "threeD.extrude" {
assert!(expected.is_some(), "the Extrude fixture must retain its source bounds");
}
assert!(expected.is_none_or(|b| !near(b, full, 1e-3)), "the override must remove the projected surface: {effect}");
let layer = d.layers[0].id;
d.insert(Some(layer), 0, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
preview(&mut s, true);
let actual = s.transform_bounds(&[id]);
assert!(
match (actual, expected) {
(Some(a), Some(b)) => near(a, b, 1e-6),
(None, None) => true,
_ => false,
},
"overridden {effect}: {actual:?}, expected {expected:?}"
);
run(&mut s, "symbol.instance.reset", json!({"ids": [id.0]}));
assert!(near(s.transform_bounds(&[id]).unwrap(), full, 1e-6), "reset {effect}");
}
}
/// Geometry after projection remains part of the measured stack at object and item scope.
#[test]
fn preview_3d_applies_geometry_after_the_projected_surface() {
for effect in PREVIEW_3D {
for item in [false, true] {
let mut s = session();
let id = projected_rect(&mut s, effect, item);
run(
&mut s,
"effect.apply",
json!({"ids": [id.0], "effect": "path.offsetPath", "params": {"offset": 5}, "item": if item { json!(0) } else { Value::Null }}),
);
let expected = projected(&s, id);
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
}
}
}
/// Typed width sizes the projected art and remains one undoable edit.
#[test]
fn preview_3d_set_bounds_sizes_the_projected_width() {
for effect in PREVIEW_3D {
let mut s = session();
let id = projected_rect(&mut s, effect, false);
let target = projected(&s, id).width() * 1.25;
preview(&mut s, true);
let before = s.doc().unwrap().doc.clone();
let history = s.doc().unwrap().history.undo.len();
run(&mut s, "object.setBounds", json!({"width": target, "reference": 0, "proportional": true, "strokes": false}));
assert!((projected(&s, id).width() - target).abs() < 1e-4, "{effect}: {:?}, target {target}", projected(&s, id));
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
}
}
/// A rotated selection measures the projected surface in its own bounding-box frame.
#[test]
fn preview_3d_oriented_box_follows_projected_art() {
for effect in PREVIEW_3D {
let mut s = session();
let id = projected_rect(&mut s, effect, false);
run(&mut s, "object.rotate", json!({"angle": 30}));
let d = &s.doc().unwrap().doc;
let angle = d.bbox_angle(&[id]);
assert!(angle.abs() > 0.1);
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
let frame = vectorcraft_doc::OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse();
let expected = vectorcraft_render::effects::preview::bounds_in(&d.symbol_boxes(), &art, frame).unwrap();
preview(&mut s, true);
let measured = s.transform_box(&[id]).unwrap();
assert_eq!(measured.angle, angle);
assert!(near(measured.rect, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
}
}
/// A click on a member of a layer with a 3D effect selects that member, with Use Preview Bounds on
/// or off, and the layer is still measured by its projected art.
#[test]
fn a_click_selects_the_member_of_a_layer_with_a_3d_effect() {
for effect in PREVIEW_3D {
for on in [false, true] {
let mut s = session();
let id = rect(&mut s, 100.0, 80.0, 0.0);
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
let layer = s.doc().unwrap().doc.layers[0].id;
run(&mut s, "effect.apply", json!({"ids": [layer.0], "effect": effect, "params": params_3d(effect), "item": null}));
preview(&mut s, on);
run(&mut s, "select.none", json!({}));
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 140.0, 125.0), v).unwrap();
}
assert_eq!(s.active().unwrap().selection.objects, [id], "{effect}, preview={on}");
let d = &s.doc().unwrap().doc;
let art =
vectorcraft_render::effects::revolve_art(&d.layers[0]).or_else(|| vectorcraft_render::effects::solid_art(&d.layers[0])).unwrap();
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
let measured = vectorcraft_render::effects::preview::bounds_of(d, &[layer], true).unwrap();
assert!(near(measured, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
}
}
}
#[test]
fn a_square_with_offset_path_is_measured_by_the_offset_shape() {
let mut s = session();
+128
View File
@@ -1805,6 +1805,134 @@ fn linear_picks_show_and_snap_to_smart_guides() {
assert_eq!(text(&s, id), "60.02 pt");
}
/// A shape with a curve at each top corner, for the tests of where Linear picks land.
const CURVED_TOP: &str = "M130 358 C185 358 230 315 230 260 L425 260 C490 260 541 305 541 358 L541 440 L130 440 Z";
/// Where the next Linear click lands (the last marker the overlays draw, and its size) and the
/// labels shown, with the pointer at (`x`, `y`).
fn linear_marker(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> (Option<(vectorcraft_geom::Point, f32)>, Vec<String>) {
use vectorcraft_engine::tools::Overlay;
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap();
let o = s.overlays(view);
let at = o.iter().filter_map(|o| if let Overlay::Anchor { p, size, .. } = o { Some((*p, *size)) } else { None }).next_back();
let labels = o.iter().filter_map(|o| if let Overlay::Label { text, .. } = o { Some(text.clone()) } else { None }).collect();
(at, labels)
}
/// A plain click at (`x`, `y`): the pointer moves there, then presses and releases.
fn linear_click(s: &mut Session, view: ViewInfo, x: f64, y: f64) {
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
}
/// Linear picks land on the anchors and paths of the art with an "anchor" or "path" label, and on
/// the ends and lines of dimensions already drawn, from as far as on the art's anchors: zoomed in,
/// a dimension started a few pixels from the end of another starts exactly at that end.
#[test]
fn linear_picks_land_on_anchors_paths_and_drawn_dimensions() {
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
let mut s = session();
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let pt = vectorcraft_geom::Point::new;
let hover = |s: &mut Session, view: ViewInfo, x: f64, y: f64| {
let (at, labels) = linear_marker(s, view, x, y);
(at.map(|(p, _)| p), labels)
};
// Beside the end of the curve: on the anchor, labeled.
assert_eq!(hover(&mut s, plain, 231.0, 262.0), (Some(pt(230.0, 260.0)), vec!["anchor".to_string()]));
// Beside the curve: on its closest point, labeled.
let (at, labels) = hover(&mut s, plain, 200.0, 337.0);
assert!(at.is_some_and(|q| q.distance(pt(200.0, 337.0)) < 6.0 && q != pt(200.0, 337.0)), "{at:?}");
assert_eq!(labels, ["path"]);
// A first dimension from the bottom of the curve to its top, placed above the art.
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 230.0, 260.0);
linear_click(&mut s, plain, 180.0, 207.0);
let first = s.doc().unwrap().selection.objects[0].0;
assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(130.0, 358.0), pt(230.0, 260.0)));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", zoomed).unwrap();
// Zoomed in, 5.8 pixels from the end of its dimension line: on that end, marked as an anchor.
assert_eq!(linear_marker(&mut s, zoomed, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec!["anchor".to_string()]));
// 6.4 pixels beside its extension line: on the line.
let (at, labels) = hover(&mut s, zoomed, 230.8, 230.0);
assert!(at.is_some_and(|q| (q.x - 230.0).abs() < 1e-6 && (q.y - 230.0).abs() < 1e-6), "{at:?}");
assert_eq!(labels, ["path"]);
// The next dimension starts where the first one's line ends.
linear_click(&mut s, zoomed, 230.6, 207.4);
linear_click(&mut s, zoomed, 425.0, 260.0);
linear_click(&mut s, zoomed, 330.0, 207.0);
let second = s.doc().unwrap().selection.objects[0].0;
assert_ne!(second, first);
let d = recipe(&s, second);
assert!(near(d.a, pt(230.0, 207.0)) && near(d.b, pt(425.0, 260.0)), "{:?} {:?}", d.a, d.b);
}
/// An anchor of the art that a dimension already measures takes a point picked beside it, not the
/// end of the extension line a few points off it. A locked dimension pulls no point, and with
/// Smart Guides and Snap to Point off no dimension pulls a point and no label shows. A press on
/// the end of a dimension's line over a segment of the art that moves a few pixels before the
/// release picks that end, as a press on an anchor does.
#[test]
fn an_anchor_beside_a_drawn_dimension_takes_the_point() {
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
let off = ViewInfo { smart_guides: false, snap_to_point: false, ..zoomed };
let mut s = session();
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let pt = vectorcraft_geom::Point::new;
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 230.0, 260.0);
linear_click(&mut s, plain, 180.0, 207.0);
let first = s.doc().unwrap().selection.objects[0].0;
// Locked, the first dimension's line end does not pull a point 5.8 pixels away.
run(&mut s, "object.lock", json!({}));
let (at, _) = linear_marker(&mut s, zoomed, 230.6, 207.4);
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)), "a locked dimension: {at:?}");
run(&mut s, "object.unlockAll", json!({}));
run(&mut s, "select.none", json!({}));
// 2.5 pixels above the curve's top anchor and 1.5 pixels below the end of the extension line
// that starts 4 points above it: on the anchor, linked to the art.
assert_eq!(linear_marker(&mut s, plain, 230.0, 257.5), (Some((pt(230.0, 260.0), 10.0)), vec!["anchor".to_string()]));
// Smart Guides and Snap to Point off: no pull to the dimension's line end, and no labels.
let (at, labels) = linear_marker(&mut s, off, 230.6, 207.4);
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)) && labels.is_empty(), "{at:?} {labels:?}");
let (at, labels) = linear_marker(&mut s, off, 230.1, 260.1);
assert!(at.is_some_and(|(p, _)| p == pt(230.0, 260.0)) && labels.is_empty(), "{at:?} {labels:?}");
// Snap to Point on and Smart Guides off: the line end takes the point, and no label shows.
assert_eq!(linear_marker(&mut s, ViewInfo { snap_to_point: true, ..off }, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec![]));
// A second dimension whose line lies on the bottom edge, from x 425 to x 541.
linear_click(&mut s, plain, 425.0, 260.0);
linear_click(&mut s, plain, 541.0, 358.0);
linear_click(&mut s, plain, 480.0, 440.0);
let second = s.doc().unwrap().selection.objects[0].0;
assert_ne!(second, first);
run(&mut s, "select.none", json!({}));
// A press 1.4 pixels from its line's left end, on the bottom edge, moved 5 pixels: the end is
// picked, and no dimension of the edge is dragged out.
for (kind, x) in [(PointerKind::Move, 426.0), (PointerKind::Down, 426.0), (PointerKind::Drag, 431.0), (PointerKind::Up, 431.0)] {
s.pointer(&PointerEvent::new(kind, x, 441.0), plain).unwrap();
}
linear_click(&mut s, plain, 541.0, 440.0);
linear_click(&mut s, plain, 480.0, 470.0);
let third = s.doc().unwrap().selection.objects[0].0;
assert_ne!(third, second);
let d = recipe(&s, third);
assert!(near(d.a, pt(425.0, 440.0)) && near(d.b, pt(541.0, 440.0)), "{:?} {:?}", d.a, d.b);
// A dimension of the left edge whose line lies 4 points off it, where its extension lines
// start: zoomed in, the end of its line still takes a point 4.7 pixels away.
run(&mut s, "select.none", json!({}));
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 130.0, 440.0);
linear_click(&mut s, plain, 126.0, 400.0);
run(&mut s, "select.none", json!({}));
assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()]));
}
/// The page content streams of exported PDF `v`, inflated.
fn pdf_content(v: &Value) -> String {
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
+3 -2
View File
@@ -158,8 +158,9 @@
//! art, the character and paragraph attributes the text document doesn't hold, freeform gradients, gradients
//! along or across a stroke and gradients without stops, with more than 256 stops or without extent
//! as their average color
//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked
//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
//! (gradients that dither are written without dither's noise, Perceptual gradients and gradients
//! mixed around the hue wheel as the stops on their curve in process colors, at most 256, and
//! gradient stops linked to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut
//! to the shape, clipping groups and clipping layers whose clipping object isn't a path,
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
+142 -18
View File
@@ -2734,23 +2734,29 @@ fn a_clipping_path_keeps_its_gradient() {
#[test]
fn freeform_gradients_are_written_as_their_average_color() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let g = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]);
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings);
let back = read_back(&doc);
assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5))));
use vectorcraft_color::gradient::GradientMethod;
// The average of its points' colors, whatever its method.
for method in [GradientMethod::Classic, GradientMethod::Perceptual, GradientMethod::HueClockwise] {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut g = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]);
g.method = method;
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENTS], "{method:?}");
let back = read_back(&doc);
assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5))), "{method:?}");
}
}
/// A gradient that dithers or mixes perceptually is written as a classic one; a stop linked to a
/// global process color is written as its color; each with a warning.
/// A gradient that dithers is written without its noise; a Perceptual gradient or one mixed around
/// the hue wheel as the stops on its curve; a stop linked to a global process color as its color;
/// each with a warning.
#[test]
fn gradient_options_and_links_the_data_cant_hold_are_reported() {
let mut doc = Document::new(200.0, 100.0);
@@ -2764,7 +2770,7 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_MIX]);
assert_eq!(out.warnings, [writer::GRADIENT_DITHER]);
// A swatch of such a gradient that nothing uses.
let mut swatch_only = Document::new(200.0, 100.0);
let mut dithered = sunset();
@@ -2773,7 +2779,7 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
swatches.push(Swatch { name: "Dithered".into(), paint: gradient_paint(dithered, None, None), global: false, spot: false });
swatch_only.swatches = swatches.into();
let out = export_ai_editing(&swatch_only, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_MIX), "{:?}", out.warnings);
assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_DITHER), "{:?}", out.warnings);
// A gradient along a stroke: the stroke's outline in its average color.
let mut along = Document::new(200.0, 100.0);
let layer = along.layers[0].id;
@@ -2800,7 +2806,7 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_MIX, writer::STOP_LINKS]);
assert_eq!(out.warnings, [writer::GRADIENT_PERCEPTUAL, writer::STOP_LINKS]);
let back = read_back(&doc);
let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
assert_eq!((color(&g.gradient.stops[0].color), g.gradient.stops[0].swatch.as_deref()), (color(&BRAND), None));
@@ -2834,6 +2840,124 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
}
}
/// Do `got`'s colors and opacities lie within 0.03 of `want`'s along the whole ramp?
fn same_curve(want: &Gradient, got: &Gradient, what: &str) {
for k in 0..=100 {
let t = k as f32 / 100.0;
let ((a, ao), (b, bo)) = (want.sample(t), got.sample(t));
let (a, b) = (a.to_rgb(), b.to_rgb());
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03) && (ao - bo).abs() < 0.03, "{what} at {t}: {a:?} {ao} vs {b:?} {bo}");
}
}
/// The data's gradients mix their stops' colors directly: a Perceptual gradient swatch is written
/// under its name as a classic gradient of the stops on its curve, no more than the reader reads,
/// and art painted with it uses that definition; both open with the colors they had, with a
/// warning. With Dither, dither's loss is reported as well. A Classic gradient keeps its own stops
/// without either warning.
#[test]
fn perceptual_gradients_are_written_with_the_stops_on_their_curve() {
use vectorcraft_color::gradient::GradientMethod;
let classic = sunset();
let want = Gradient { method: GradientMethod::Perceptual, ..classic.clone() };
// The same stops mixed directly stray from the Perceptual curve.
assert!(
(0..=100).any(|k| {
let t = k as f32 / 100.0;
want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05)
}),
"the methods mix alike"
);
let gradient_names =
|doc: &Document| -> Vec<String> { program(doc).lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).map(String::from).collect() };
let with = |g: &Gradient, swatch: Option<&str>| {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
swatches.push(Swatch { name: "Dusk".into(), paint: gradient_paint(g.clone(), None, None), global: false, spot: false });
doc.swatches = swatches.into();
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g.clone(), None, swatch)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
doc
};
let doc = with(&want, Some("Dusk"));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_PERCEPTUAL]);
let names = gradient_names(&doc);
assert!(names.iter().any(|n| n == "(Dusk)") && !names.iter().any(|n| n == "(Gradient)"), "the art uses the swatch's definition: {names:?}");
let back = read_back(&doc);
let Some(Paint::Gradient(swatch)) = back.swatch("Dusk").map(|s| &s.paint) else { panic!("the swatch is lost") };
assert!(swatch.gradient.method.is_classic());
let written = swatch.gradient.stops.len();
assert!((want.stops.len() + 1..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops");
same_curve(&want, &swatch.gradient, "the swatch");
let Paint::Gradient(fill) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
assert_eq!(fill.gradient.stops.len(), written);
same_curve(&want, &fill.gradient, "the fill");
// Perceptual with Dither: both losses.
let dithered = Gradient { dither: true, ..want.clone() };
let doc = with(&dithered, None);
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_PERCEPTUAL, writer::GRADIENT_DITHER]);
let back = read_back(&doc);
let Paint::Gradient(fill) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
same_curve(&want, &fill.gradient, "the dithered fill");
// More stops than the reader reads: the average of its own stops, as a classic gradient's.
for method in [GradientMethod::Perceptual, GradientMethod::HueClockwise] {
let stops = (0..300)
.map(|i| GradientStop::new(i as f32 / 299.0, if i % 2 == 0 { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }))
.collect();
let many = Gradient { method, ..Gradient::new(GradientKind::Linear, stops) };
let doc = with(&many, None);
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_SHAPES), "{method:?}: {:?}", out.warnings);
assert!(!out.warnings.iter().any(|w| w == writer::GRADIENT_PERCEPTUAL || w == writer::GRADIENT_HUE), "{method:?}: {:?}", out.warnings);
let back = read_back(&doc);
assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.0, 0.5))), "{method:?}");
}
// Classic: its own stops, under the swatch's name, without a warning.
let doc = with(&classic, Some("Dusk"));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let back = read_back(&doc);
let Some(Paint::Gradient(swatch)) = back.swatch("Dusk").map(|s| &s.paint) else { panic!("the swatch is lost") };
assert_eq!(swatch.gradient.stops.len(), classic.stops.len());
let Paint::Gradient(fill) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
assert_eq!(fill.gradient.stops.len(), classic.stops.len());
}
/// A gradient mixed around the hue wheel whose stop is linked to a global process color loses the
/// link with its stops on the curve, and says so.
#[test]
fn hue_gradients_report_the_links_their_curve_drops() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
swatches.push(Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false });
doc.swatches = swatches.into();
let mut g = sunset();
g.method = vectorcraft_color::gradient::GradientMethod::HueClockwise;
if let Some(s) = g.stops.first_mut() {
s.set_color(BRAND, Some(("Brand".into(), 1.0)));
}
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_HUE, writer::STOP_LINKS]);
}
/// A pattern whose art reaches past its tile is written as its tiles cut to the shape: a definition
/// would cut its art off at the tile's edge.
#[test]
+3 -1
View File
@@ -37,7 +37,9 @@ pub(super) use images::PAYLOAD;
#[cfg(test)]
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
#[cfg(test)]
pub(super) use paints::{GRADIENT_HUE, GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name};
pub(super) use paints::{
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
};
#[cfg(test)]
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
#[cfg(test)]
+47 -20
View File
@@ -19,8 +19,8 @@ pub(in crate::ai_editing) const GRADIENTS: &str =
pub(in crate::ai_editing) const GRADIENT_SHAPES: &str = "gradients without stops or with more than 256, gradients whose ramp has no length and radial gradients flattened to a line are written as their average color in the editing data for other apps";
pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str =
"the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_MIX: &str =
"gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_DITHER: &str = "gradients that dither are written without dither's noise in the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_PERCEPTUAL: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_HUE: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps";
pub(in crate::ai_editing) const CONIC: &str =
"conic gradients are written as linear gradients along their vector, with the same stops, in the editing data for other apps";
@@ -57,13 +57,14 @@ fn writable_gradient(g: &Gradient) -> bool {
g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS
}
/// `g` as the data holds its colors: one mixed around the hue wheel (the data's gradients mix
/// their stops' colors directly) as a classic gradient of the stops on its curve
/// ([`Gradient::as_classic_curve`]), no more than the `.ai` reader reads when it pads
/// ([`GRADIENT_HUE`]); others as they are.
fn hue_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> {
/// `g` as the data holds its colors: one mixed by the Perceptual method or around the hue wheel
/// (the data's gradients mix their stops' colors directly) as a classic gradient of the stops on
/// its curve in process colors ([`Gradient::as_classic_curve`]), no more than the `.ai` reader
/// reads when it pads ([`GRADIENT_PERCEPTUAL`], [`GRADIENT_HUE`]); a classic one, and one the
/// data can't hold as a gradient ([`writable_gradient`]), as it is.
fn curve_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if !g.method.is_hue() {
if g.method.is_classic() || !writable_gradient(g) {
return Cow::Borrowed(g);
}
let curve = g.as_classic_curve();
@@ -88,6 +89,16 @@ pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl
}
}
/// Is `stop` linked to a global process color of `doc` (one [`Writer::stop_color`] writes as its
/// color, [`STOP_LINKS`])?
fn links_global_process(doc: &vectorcraft_doc::Document, stop: &GradientStop) -> bool {
stop.swatch
.as_deref()
.filter(|n| *n != REGISTRATION)
.and_then(|name| doc.swatch(name))
.is_some_and(|sw| matches!(sw.paint, Paint::Solid { swatch: None, .. }) && !sw.spot && sw.global)
}
/// The stops of `g` in order of their place on the ramp.
fn sorted_stops(g: &Gradient) -> Vec<&GradientStop> {
let mut stops: Vec<&GradientStop> = g.stops.iter().collect();
@@ -100,10 +111,11 @@ impl Writer<'_> {
pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) {
let doc = self.doc;
for sw in doc.swatches_iter() {
// As `swatch_paint` writes it: one mixed around the hue wheel as the stops on its curve,
// and the stops of one that repeats or reflects repeated.
// As `swatch_paint` writes it: one mixed by the Perceptual method or around the hue
// wheel as the stops on its curve, and the stops of one that repeats or reflects
// repeated.
if let Paint::Gradient(g) = &sw.paint
&& let stops = hue_as_stops(&g.gradient)
&& let stops = curve_as_stops(&g.gradient)
&& let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
&& writable_gradient(&gradient)
&& !self.gradients.iter().any(|d| d.name == sw.name)
@@ -165,9 +177,11 @@ impl Writer<'_> {
// The data has no spread: a gradient that repeats or reflects is written with its stops
// repeated over `area` (a conic one, written linear, around its turn).
let mut g: GradientPaint = (**g).clone();
if g.gradient.method.is_hue() {
self.warn(GRADIENT_HUE);
g.gradient = hue_as_stops(&g.gradient).into_owned();
// A gradient written as its average color (a freeform one, or one without stops or with
// more than the reader reads) keeps its own stops.
if !g.gradient.method.is_classic() && writable_gradient(&g.gradient) {
self.warn_curve(&g.gradient);
g.gradient = curve_as_stops(&g.gradient).into_owned();
}
if g.gradient.is_spread() {
self.warn(SPREAD);
@@ -192,6 +206,18 @@ impl Writer<'_> {
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..g }))
}
/// The warnings for gradient `g`, mixed by the Perceptual method or around the hue wheel,
/// written as the stops on its curve ([`curve_as_stops`]): [`GRADIENT_PERCEPTUAL`] or
/// [`GRADIENT_HUE`], and [`STOP_LINKS`] when one of its stops is linked to a global process
/// color (the stops on the curve hold no links).
fn warn_curve(&mut self, g: &Gradient) {
self.warn(if g.method.is_hue() { GRADIENT_HUE } else { GRADIENT_PERCEPTUAL });
let doc = self.doc;
if g.stops.iter().any(|s| links_global_process(doc, s)) {
self.warn(STOP_LINKS);
}
}
/// The fills and strokes of `n` that paint (outline `bp`), their gradients placed
/// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints, the stops
/// of one that repeats or reflects repeated over the box the stroke paints, miter spikes
@@ -363,8 +389,8 @@ impl Writer<'_> {
/// linear gradient's from the last to the first and a radial one's from the first to the last,
/// `BD`, `%AI5_EndGradient`.
fn gradient_def(&mut self, s: &mut String, d: &GradientDef) {
if d.gradient.dither || !d.gradient.method.is_classic() {
self.warn(GRADIENT_MIX);
if d.gradient.dither {
self.warn(GRADIENT_DITHER);
}
if d.gradient.kind == GradientKind::Conic {
self.warn(CONIC);
@@ -587,16 +613,17 @@ impl Writer<'_> {
/// be written.
pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool {
// A swatch has no placement: one that repeats or reflects holds its stops repeated along
// its vector, and one mixed around the hue wheel the stops on its curve.
// its vector, and one mixed by the Perceptual method or around the hue wheel the stops on
// its curve.
let stops = match &sw.paint {
Paint::Gradient(g) => Some(hue_as_stops(&g.gradient)),
Paint::Gradient(g) => Some(curve_as_stops(&g.gradient)),
_ => None,
};
let unrolled = stops.as_deref().map(|g| g.unrolled_within(crate::import::MAX_GRADIENT_STOPS));
match &sw.paint {
Paint::Gradient(g) if unrolled.as_deref().is_some_and(writable_gradient) => {
if g.gradient.method.is_hue() {
self.warn(GRADIENT_HUE);
if !g.gradient.method.is_classic() {
self.warn_curve(&g.gradient);
}
if g.gradient.is_spread() {
self.warn(SPREAD);
+14
View File
@@ -1555,6 +1555,20 @@ fn headless_backend_methods() {
let selected = h.call("ui.tool.select", json!({"tool": tool.id})).unwrap();
assert_eq!(selected["tool"], tool.id);
}
// The Trim at Crossings Tool is listed once, in the Scissors tool's group after the Knife.
let trim = vectorcraft_tools::addons::trim::ID;
let with_trim: Vec<_> =
groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == trim)).collect();
assert_eq!(with_trim.len(), 1, "{trim} is in one group");
let ids: Vec<_> = with_trim[0].iter().map(|entry| entry["id"].clone()).collect();
let knife = ids.iter().position(|id| *id == "knife").expect("the Knife in the same group");
assert!(ids.contains(&json!("scissors")), "the Scissors tool's group: {ids:?}");
assert_eq!(ids.get(knife + 1), Some(&json!(trim)));
assert_eq!(ids.iter().filter(|id| **id == trim).count(), 1);
let entry = with_trim[0].iter().find(|entry| entry["id"] == trim).unwrap();
assert_eq!(entry["label"], "Trim at Crossings Tool");
assert!(entry["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim);
let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso");
assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool")));
assert!(h.call("ui.resize", json!({})).is_err());
+33 -13
View File
@@ -142,12 +142,15 @@ impl Renderer {
}
// One paint box for the line and the heads, so a gradient runs on into the heads.
let paint_bounds = bounds.inflate(st.width / 2.0, st.width / 2.0);
// A width profile's outline is fitted through samples, and fitted again differently when
// it is outlined near the view only: its curves are drawn as they are.
let fine = st.profile.is_none() && crate::stroke::fine(f.view * xf, f.px);
if let Some(g) = st.path_gradient() {
self.fill_path_gradient(ctx, f, bp, rule, st, chars, &pieces, width, &g.gradient);
self.fill_path_gradient(ctx, f, bp, rule, st, chars, &pieces, width, fine, &g.gradient);
} else {
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) {
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width, fine) {
Some(o) => o,
None => Arc::new(crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)),
None => Arc::new(uncached_outline(&pieces.line, st, width, f.px * 0.25, fine)),
};
// Miters, caps and heads can reach past the paint box: a paint drawn as pixels covers
// them too.
@@ -191,7 +194,8 @@ impl Renderer {
/// piece clips the slices, grown a pixel into each other and each replacing what it covers, so
/// neighbours meet without seams and translucent colours paint once. The slices of a stroke
/// of `self.cur` are kept in `stroke_slices`, and a moved copy of the object draws the slices
/// made before it moved, moved by the same offset ([`Self::moved_slices`]).
/// made before it moved, moved by the same offset ([`Self::moved_slices`]). `fine` is passed on
/// to [`Self::cached_stroke`].
#[allow(clippy::too_many_arguments)]
fn fill_path_gradient(
&mut self,
@@ -203,6 +207,7 @@ impl Renderer {
chars: Option<(&Arc<TextGeom>, usize)>,
pieces: &effects::stroke::StrokePieces,
width: f64,
fine: bool,
g: &vectorcraft_color::Gradient,
) {
let level = (f.px * 0.25).log2().floor() as i32;
@@ -255,9 +260,9 @@ impl Renderer {
}
None => (make(), kurbo::Vec2::ZERO),
};
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) {
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width, fine) {
Some(o) => o,
None => Arc::new(crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)),
None => Arc::new(uncached_outline(&pieces.line, st, width, f.px * 0.25, fine)),
};
ctx.set_fill_rule(peniko::Fill::NonZero);
for clip in std::iter::once(&*line).chain(pieces.heads.iter().map(|h| &h.outline)) {
@@ -293,6 +298,9 @@ impl Renderer {
/// tolerance (vello's 0.25 device px) is bucketed to powers of two, never coarser than needed,
/// so zooming reuses outlines until the level changes. Other strokes aren't cached: for them
/// this returns `None`. `line` is the line of `st` along `path` ([`effects::stroke::stroke_pieces`]).
/// With `fine` ([`crate::stroke::fine`]) a wide stroke's long curves are drawn as lines
/// ([`crate::stroke::wide`]); the keys keep the two kinds of outline apart.
#[allow(clippy::too_many_arguments)]
fn cached_stroke(
&mut self,
f: &Frame,
@@ -301,11 +309,16 @@ impl Renderer {
line: &BezPath,
st: &StrokeLayer,
width: f64,
fine: bool,
) -> Option<Arc<BezPath>> {
let level = (f.px * 0.25).log2().floor() as i32;
let expand = || Arc::new(crate::stroke::outline(line, st, width, 2f64.powi(level)));
let tol = 2f64.powi(level);
// The keys' last field: the tolerance level, and whether long curves are drawn as lines.
let slot = level.saturating_mul(2).saturating_add(i32::from(fine));
let refined = |outline: BezPath| if fine { crate::stroke::wide(outline, width, tol) } else { outline };
let expand = || Arc::new(refined(crate::stroke::outline(line, st, width, tol)));
if let Some((g, run)) = chars {
let key = (self.stroke_owner(Arc::as_ptr(g) as usize), run, width.to_bits(), level);
let key = (self.stroke_owner(Arc::as_ptr(g) as usize), run, width.to_bits(), slot);
if let Some((kept, outline)) = self.char_strokes.get(&key, self.stamp)
&& Arc::ptr_eq(kept, g)
{
@@ -316,7 +329,7 @@ impl Renderer {
return Some(outline);
}
let node = self.cur.clone().filter(|n| owns_stroke(n, st))?;
let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, width.to_bits(), level);
let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, width.to_bits(), slot);
let v = f.visible;
let holds = |crop: Option<Rect>| crop.is_none_or(|r| r.x0 <= v.x0 && r.y0 <= v.y0 && r.x1 >= v.x1 && r.y1 >= v.y1);
if let Some(e) = self.strokes.get_mut(&key)
@@ -329,7 +342,7 @@ impl Renderer {
// Under its object's id, the stroke's place and the outline's width and tolerance, the key
// of the stroke's latest outline is kept, except for art made again in every frame.
let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st)));
let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), level));
let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), slot));
let own = moved.is_some() && self.own_path(&node, path);
if let Some(mk) = moved
&& let Some((outline, crop)) = self.moved_outline(mk, &node, st, line, v)
@@ -342,7 +355,6 @@ impl Renderer {
// A long stroke is outlined only in and around the view, with a margin of the view's
// own size on each side. Width profiles keep their positions on the whole path.
let region = v.inflate(v.width(), v.height());
let tol = 2f64.powi(level);
if crops()
&& line.elements().len() > CROP_ELEMENTS
&& st.dash.is_none()
@@ -364,7 +376,7 @@ impl Renderer {
&& st.profile.is_none()
&& let Some(outline) = crop_dashed(line, st, width, region, crop_reach(st, width, f.px, tol), tol)
{
let outline = Arc::new(outline);
let outline = Arc::new(refined(outline));
self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), own }, moved);
return Some(outline);
}
@@ -372,7 +384,7 @@ impl Renderer {
.then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width))
.flatten();
let (outline, crop) = match cropped {
Some(part) => (Arc::new(crate::stroke::outline(&part, st, width, tol)), Some(region)),
Some(part) => (Arc::new(refined(crate::stroke::outline(&part, st, width, tol))), Some(region)),
None => (expand(), None),
};
self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved);
@@ -619,6 +631,14 @@ fn crops() -> bool {
true
}
/// The outline of the line `line` of stroke `st` at `width` and tolerance `tol`, for a stroke that
/// [`Renderer::cached_stroke`] does not keep; with `fine`, its long curves drawn as lines
/// ([`crate::stroke::wide`]).
fn uncached_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64, fine: bool) -> BezPath {
let outline = crate::stroke::outline(line, st, width, tol);
if fine { crate::stroke::wide(outline, width, tol) } else { outline }
}
/// How far stroke `st` at `width` can paint from its path, at a join or a cap, with two output
/// pixels (`px`) and the outline's tolerance `tol` added.
pub(crate) fn crop_reach(st: &StrokeLayer, width: f64, px: f64, tol: f64) -> f64 {
+303 -1
View File
@@ -1,6 +1,8 @@
//! Raster-only stroke fitting: preserve thin curved bands through fill flattening.
//! Raster-only stroke fitting: preserve thin curved bands through fill flattening, and draw the
//! rims of wide curved strokes as lines centered on their curves.
use crate::effects;
use crate::kurbo::{Affine, CubicBez, Line, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Point, QuadBez, Vec2};
use vectorcraft_doc::StrokeLayer;
use vectorcraft_geom::BezPath;
@@ -19,3 +21,303 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) ->
vectorcraft_geom::flatten(outline.iter(), fine, |el| flat.push(el));
flat
}
/// Strokes at least this many tolerances wide (8 device pixels at a tolerance of 0.25 px) have
/// their long curves drawn as lines by [`wide`].
const WIDE: f64 = 32.0;
/// A curve of a wide stroke's outline is drawn as lines when its control points span at least this
/// many tolerances (32 device pixels at 0.25 px) across or down.
const SPAN: f64 = 128.0;
/// The chords [`wide`] draws a curve with lie within about this many tolerances of it, before
/// their ends are moved out.
const CHORD: f64 = 0.8;
/// The most lines [`wide`] draws one outline's curves with. An outline that would take more is
/// drawn as it is.
const MAX_LINES: usize = 1 << 20;
/// Two curves meet smoothly when the sine of the angle between their tangents where they meet is
/// at most this.
const SMOOTH: f64 = 0.01;
/// Whether an outline made in the space `m` maps to device pixels, with a tolerance of at most a
/// quarter of `px` (the size of a device pixel in that space, [`crate::frame::Frame::px`]), stays
/// within that tolerance on the device: whether `m` stretches no length by more than `1 / px`.
/// `false` for a transform that collapses or isn't finite.
pub(crate) fn fine(m: Affine, px: f64) -> bool {
let [a, b, c, d, _, _] = m.as_coeffs();
let (sum, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
// The largest singular value of the linear part.
let most = ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt();
det != 0.0 && most.is_finite() && px.is_finite() && px > 0.0 && most * px <= 1.0 + 1e-9
}
/// `outline`, the outline of a stroke `width` wide made at tolerance `tol`, with its long curves
/// ([`SPAN`]) drawn as lines that lie within about half of `tol` on either side of the curve, when
/// the stroke is at least [`WIDE`] tolerances wide. Vello draws a curve with chords that all lie
/// on its inner side, up to 0.25 device pixels in, which leaves a wide stroke's rims too light
/// outside and too dark inside. Here each line end is moved out by half the gap between the curve
/// and its chords, and the lines cross the curve. Where two such curves meet smoothly the shared
/// end moves too; elsewhere (a corner, a line, a short curve) the end stays on the curve and the
/// first or last line is half as long. Narrower strokes, outlines with no long curve and outlines
/// that would take more than [`MAX_LINES`] lines are returned as they are.
pub(crate) fn wide(outline: BezPath, width: f64, tol: f64) -> BezPath {
if !(tol > 0.0 && tol.is_finite() && width >= tol * WIDE) {
return outline;
}
lines(&outline, tol).unwrap_or(outline)
}
/// One subpath: where it starts, its segments, each with the most steps it is drawn with as lines
/// ([`steps`]; 0: drawn as it is), and whether it is closed.
struct Sub {
start: Point,
segs: Vec<(PathSeg, usize)>,
closed: bool,
}
/// `path` with its long curves drawn as lines ([`wide`]); `None` when it has no long curve, would
/// take more than [`MAX_LINES`] lines, or does not start each subpath with a move.
fn lines(path: &BezPath, tol: f64) -> Option<BezPath> {
let chord = tol * CHORD;
let subs = subpaths(path.elements(), tol, chord)?;
let mut total = 0usize;
for (_, steps) in subs.iter().flat_map(|s| &s.segs) {
if *steps > 0 {
total = total.saturating_add(steps.saturating_add(2));
}
}
if total == 0 || total > MAX_LINES {
return None;
}
let mut out = BezPath::new();
for sub in &subs {
draw_sub(&mut out, sub, chord);
}
Some(out)
}
/// The subpaths of `els`, each segment with its steps ([`steps`]). A close adds a line back to the
/// start when the subpath ends elsewhere. `None` when a segment comes before any move or after a
/// close without a move.
fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option<Vec<Sub>> {
let mut subs: Vec<Sub> = Vec::new();
for el in els {
if let PathEl::MoveTo(p) = *el {
subs.push(Sub { start: p, segs: Vec::new(), closed: false });
continue;
}
let sub = subs.last_mut()?;
if sub.closed {
return None;
}
let last = sub.segs.last().map_or(sub.start, |(s, _)| s.end());
let seg = match *el {
PathEl::LineTo(p) => PathSeg::Line(Line::new(last, p)),
PathEl::QuadTo(a, b) => PathSeg::Quad(QuadBez::new(last, a, b)),
PathEl::CurveTo(a, b, c) => PathSeg::Cubic(CubicBez::new(last, a, b, c)),
PathEl::ClosePath | PathEl::MoveTo(_) => {
if last != sub.start {
sub.segs.push((PathSeg::Line(Line::new(last, sub.start)), 0));
}
sub.closed = true;
continue;
}
};
sub.segs.push((seg, steps(seg, tol, chord)));
}
Some(subs)
}
/// The cubic that draws curve `seg`; `None` for a line.
fn cubic(seg: PathSeg) -> Option<CubicBez> {
match seg {
PathSeg::Cubic(c) => Some(c),
PathSeg::Quad(q) => Some(q.raise()),
PathSeg::Line(_) => None,
}
}
/// How many equal steps of its parameter keep the chords of curve `seg` within `chord` of it (by
/// the second differences of its control points), when its control points span at least [`SPAN`]
/// times `tol`; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a curve
/// that would take more than [`MAX_LINES`] steps.
fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize {
let Some(c) = cubic(seg) else { return 0 };
let pts = [c.p0, c.p1, c.p2, c.p3];
if !pts.iter().all(|p| p.is_finite()) {
return 0;
}
let (lo, hi) = pts.iter().fold((Point::new(f64::INFINITY, f64::INFINITY), Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| {
(Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))
});
let span = (hi.x - lo.x).max(hi.y - lo.y);
if !span.is_finite() || span < tol * SPAN {
return 0;
}
let second = |a: Point, b: Point, c: Point| (a.to_vec2() - b.to_vec2() * 2.0 + c.to_vec2()).hypot();
let bend = second(c.p0, c.p1, c.p2).max(second(c.p1, c.p2, c.p3));
let n = (0.75 * bend / chord).sqrt().ceil().max(1.0);
if !n.is_finite() || n > MAX_LINES as f64 {
return 0;
}
n as usize
}
/// The direction curve `c` leaves its start in, or `None` when all its points are at its start.
fn start_tangent(c: &CubicBez) -> Option<Vec2> {
[c.p1, c.p2, c.p3].into_iter().map(|p| p - c.p0).find(|v| v.hypot2() > 0.0)
}
/// The direction curve `c` reaches its end in, or `None` when all its points are at its end.
fn end_tangent(c: &CubicBez) -> Option<Vec2> {
[c.p2, c.p1, c.p0].into_iter().map(|p| c.p3 - p).find(|v| v.hypot2() > 0.0)
}
/// How many pieces of a curve [`params`] measures its bending on.
const SAMPLES: usize = 32;
/// The parameters curve `c` has its line ends at, and whether its first and its last step are
/// halves. Each step holds an equal share of the curve's bending (the integral of the square root
/// of its curvature along it), and there are as many as keep each chord within about `chord` of the
/// curve, at most `most` (its equal steps, [`steps`]). The steps are equal when the bending can't
/// be measured (a cusp, or a point that isn't finite) or is 0. The first or last step is halved
/// when that end stays on the curve (`pin_start`, `pin_end`); a curve of one step is then drawn
/// in two halves.
fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool) -> (Vec<f64>, (bool, bool)) {
let (d1, d2) = (c.deriv(), c.deriv().deriv());
let bend = |u: f64| {
let (v, a) = (d1.eval(u).to_vec2(), d2.eval(u).to_vec2());
(v.cross(a).abs() / v.hypot()).sqrt()
};
let mut sums = [0.0; SAMPLES + 1];
let mut before = bend(0.0);
for j in 1..=SAMPLES {
let here = bend(j as f64 / SAMPLES as f64);
sums[j] = sums[j - 1] + (before + here) / 2.0;
before = here;
}
let total = sums[SAMPLES];
let most = most.max(1);
let n = if total.is_finite() && total > 0.0 { ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most) } else { most };
// The parameter at which a share `s` (0 to 1) of the bending lies before it.
let at = |s: f64| -> f64 {
if !(total.is_finite() && total > 0.0) {
return s;
}
let want = s * total;
let j = sums.partition_point(|&x| x <= want).clamp(1, SAMPLES);
let (lo, hi) = (sums[j - 1], sums[j]);
let part = if hi > lo { ((want - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 };
(j as f64 - 1.0 + part) / SAMPLES as f64
};
if n == 1 && (pin_start || pin_end) {
return (vec![0.0, at(0.5), 1.0], (true, true));
}
let h = 1.0 / n as f64;
let mut t = Vec::with_capacity(n + 3);
t.push(0.0);
if pin_start {
t.push(at(h / 2.0));
}
t.extend((1..n).map(|k| at(k as f64 * h)));
if pin_end {
t.push(at(1.0 - h / 2.0));
}
t.push(1.0);
(t, (pin_start, pin_end))
}
/// How far the curve `c` lies from the chord between parameters `a` and `b`, at its parameter
/// midway: the curve's point there minus the chord's middle.
fn bulge(c: &CubicBez, a: f64, b: f64) -> Vec2 {
c.eval((a + b) / 2.0) - c.eval(a).midpoint(c.eval(b))
}
/// A curve of a subpath drawn as lines: the curve, its line ends' parameters, whether its first and
/// its last step are halves ([`params`]), and how far the curve lies from its first and last
/// chords ([`bulge`]).
struct Drawn {
curve: CubicBez,
t: Vec<f64>,
halves: (bool, bool),
first: Vec2,
last: Vec2,
}
/// Draws `sub` into `out`, its curves with steps as lines ([`wide`]) with chords within about
/// `chord` of them, and its other segments as they are.
fn draw_sub(out: &mut BezPath, sub: &Sub, chord: f64) {
let n = sub.segs.len();
let curve = |i: usize| sub.segs.get(i).filter(|(_, steps)| *steps > 0).and_then(|(s, _)| cubic(*s));
// Whether segment `i` starts where the one before it ends, both drawn as lines and meeting
// smoothly: there the shared end moves off the curve with both.
let smooth: Vec<bool> = (0..n)
.map(|i| {
let before = if i == 0 { sub.closed.then(|| n - 1) } else { Some(i - 1) };
let (Some(a), Some(b)) = (before.and_then(curve), curve(i)) else { return false };
match (end_tangent(&a), start_tangent(&b)) {
(Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(),
_ => false,
}
})
.collect();
// Whether segment `i` ends where the next one starts, as above; the last one's next is the
// first, which starts smoothly only on a closed subpath.
let meets = |i: usize| smooth.get((i + 1) % n).copied().unwrap_or(false);
let drawn: Vec<Option<Drawn>> = (0..n)
.map(|i| {
let c = curve(i)?;
let steps = sub.segs.get(i).map_or(1, |(_, s)| *s);
let (t, halves) = params(&c, steps, chord, !smooth.get(i).copied().unwrap_or(false), !meets(i));
let (first, last) = match (t.first().zip(t.get(1)), t.len().checked_sub(2).and_then(|k| t.get(k).zip(t.last()))) {
(Some((a, b)), Some((c2, d))) => (bulge(&c, *a, *b), bulge(&c, *c2, *d)),
_ => (Vec2::ZERO, Vec2::ZERO),
};
Some(Drawn { curve: c, t, halves, first, last })
})
.collect();
// How far the start of segment `i` moves: half the curve's gap from the chords on either side.
let moved = |i: usize| -> Vec2 {
if !smooth.get(i).copied().unwrap_or(false) {
return Vec2::ZERO;
}
let before = if i == 0 { n - 1 } else { i - 1 };
match (drawn.get(before).and_then(Option::as_ref), drawn.get(i).and_then(Option::as_ref)) {
(Some(a), Some(b)) => (a.last + b.first) / 4.0,
_ => Vec2::ZERO,
}
};
out.move_to(sub.start + moved(0));
for (i, (seg, _)) in sub.segs.iter().enumerate() {
let end = seg.end() + moved((i + 1) % n);
match (drawn.get(i).and_then(Option::as_ref), seg) {
(Some(d), _) => draw_lines(out, d, end),
(None, PathSeg::Line(_)) => out.line_to(end),
(None, PathSeg::Quad(q)) => out.quad_to(q.p1, end),
(None, PathSeg::Cubic(c)) => out.curve_to(c.p1, c.p2, end),
}
}
if sub.closed {
out.close_path();
}
}
/// Draws curve `d` into `out` as lines to its inner line ends, each moved out by half the curve's
/// gap from the chords beside it, and a line to `end`. Beside a halved step, which lies a quarter
/// as far from the curve, the whole step's gap is used: half the other chord's gap, or the two
/// halves' gaps together.
fn draw_lines(out: &mut BezPath, d: &Drawn, end: Point) {
let t = &d.t;
let last = t.len().saturating_sub(2);
for k in 1..t.len().saturating_sub(1) {
let (Some(&a), Some(&u), Some(&b)) = (t.get(k - 1), t.get(k), t.get(k + 1)) else { continue };
let (before, after) = (bulge(&d.curve, a, u), bulge(&d.curve, u, b));
let shift = match (d.halves.0 && k == 1, d.halves.1 && k == last) {
(true, true) => before + after,
(true, false) => after / 2.0,
(false, true) => before / 2.0,
(false, false) => (before + after) / 4.0,
};
out.line_to(d.curve.eval(u) + shift);
}
out.line_to(end);
}
+1
View File
@@ -15,6 +15,7 @@ mod cmykblend;
mod colorize;
mod colrglyphs;
mod container;
mod curvedstrokeedges;
mod dither;
pub(super) mod fontchange;
mod freeform;
@@ -0,0 +1,248 @@
//! Wide strokes along curves: both rims cover their edge pixels close to the exact coverage of
//! the curves they follow, and narrow strokes, short curves and straight outlines are drawn as
//! they were.
use super::*;
use crate::stroke::{fine, wide};
use vectorcraft_doc::{AppearanceItem, StrokeGradientMode, StrokeLayer};
/// The share of pixel (`px`, `py`) inside the circle at `c` with radius `r`, integrated over 512
/// columns of the pixel.
fn disc_coverage(c: kurbo::Point, r: f64, px: u32, py: u32) -> f64 {
const COLUMNS: u32 = 512;
let (top, bottom) = (f64::from(py), f64::from(py) + 1.0);
(0..COLUMNS)
.map(|k| {
let x = f64::from(px) + (f64::from(k) + 0.5) / f64::from(COLUMNS);
let u = (x - c.x) / r;
if u.abs() >= 1.0 {
return 0.0;
}
let h = r * (1.0 - u * u).sqrt();
((c.y + h).min(bottom) - (c.y - h).max(top)).max(0.0)
})
.sum::<f64>()
/ f64::from(COLUMNS)
}
/// A circle of radius `r` at `c`, as eight cubics, each an eighth of it, within five millionths
/// of `r` of it.
fn circle(c: (f64, f64), r: f64) -> BezPath {
let c = kurbo::Point::new(c.0, c.1);
let at = |a: f64| c + kurbo::Vec2::from_angle(a) * r;
let step = std::f64::consts::FRAC_PI_4;
let handle = r * 4.0 / 3.0 * (step / 4.0).tan();
let mut p = BezPath::new();
p.move_to(at(0.0));
for k in 0..8 {
let (a, b) = (f64::from(k) * step, f64::from(k + 1) * step);
let tangent = |a: f64| kurbo::Vec2::from_angle(a + std::f64::consts::FRAC_PI_2) * handle;
p.curve_to(at(a) + tangent(a), at(b) - tangent(b), at(b));
}
p.close_path();
p
}
/// A document of 1200 points holding a circle of radius 400 at its middle, stroked 80 pt with
/// `paint` at `opacity`. A gradient is laid along the stroke.
fn ring(paint: Paint, opacity: f32) -> Document {
let mut d = Document::new(1200.0, 1200.0);
let path = vectorcraft_geom::PathData::from_bezpath(&circle((600.0, 600.0), 400.0));
let mut node = Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, paint, 80.0));
for item in &mut node.appearance.items {
if let AppearanceItem::Stroke(st) = item {
st.opacity = opacity;
st.gradient_mode = StrokeGradientMode::Along;
}
}
let l = d.layers[0].id;
d.insert(Some(l), 0, node).unwrap();
d
}
/// The worst edge pixel of one rim: how many alpha levels it is off, where, and how many edge
/// pixels the rim has.
#[derive(Debug, Default)]
struct Rim {
worst: u8,
pixels: usize,
at: String,
}
/// The rims of the ring of [`ring`] (outer radius 440, inner 360) drawn through `view`, which
/// scales by `scale`, at `side`×`side`, with `paint` and `opacity`. An edge pixel is one whose
/// exact coverage by the circle of its rim is between 2% and 98%; its alpha is compared with that
/// coverage of the alpha the ring paints.
fn ring_rims(view: Affine, side: u32, scale: f64, paint: Paint, opacity: f32) -> (Rim, Rim) {
let opts = RenderOptions { background: None, artboards: false, ..Default::default() };
let got = Renderer::new().render(&ring(paint, opacity), side, side, view, &opts);
let c = view * kurbo::Point::new(600.0, 600.0);
let full = 255.0 * f64::from(opacity);
let (mut outer, mut inner) = (Rim::default(), Rim::default());
for y in 0..side {
for x in 0..side {
let from = (kurbo::Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5) - c).hypot();
for (rim, r, outside) in [(&mut outer, 440.0 * scale, true), (&mut inner, 360.0 * scale, false)] {
// Only pixels within two pixels of a rim can be crossed by it.
if (from - r).abs() >= 2.0 {
continue;
}
let e = disc_coverage(c, r, x, y);
if !(0.02..=0.98).contains(&e) {
continue;
}
// Inside the outer rim the ring covers the pixel; inside the inner rim it doesn't.
let want = if outside { e } else { 1.0 - e } * full;
let alpha = f64::from(got.pixel(x, y)[3]);
let diff = (alpha - want).abs().round().min(255.0) as u8;
rim.pixels += 1;
if diff > rim.worst {
rim.worst = diff;
rim.at = format!("({x},{y}) {alpha} vs {want:.1}");
}
}
}
}
(outer, inner)
}
/// Most alpha levels an edge pixel of a wide curved stroke may differ from the exact coverage of
/// its rim.
const EDGE_LEVELS: u8 = 36;
/// A wide stroke along a curve paints both of its rims within [`EDGE_LEVELS`] of their exact
/// coverage: zoomed out and at 1:1, through a turned view, with a gradient laid along it, and
/// translucent (within half as many levels).
#[test]
fn wide_curved_strokes_cover_their_rims_as_the_curves_do() {
let turned = Affine::translate((150.0, 150.0)) * Affine::rotate(0.5) * Affine::scale(0.25) * Affine::translate((-600.0, -600.0));
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
let black = || Paint::solid(Color::BLACK);
let mut off = vec![];
for (name, view, side, scale, paint, opacity) in [
("zoomed out", Affine::scale(0.25), 300, 0.25, black(), 1.0),
("1:1", Affine::translate((-100.0, -100.0)), 1000, 1.0, black(), 1.0),
("turned", turned, 300, 0.25, black(), 1.0),
("gradient", Affine::scale(0.25), 300, 0.25, gradient, 1.0),
("translucent", Affine::scale(0.25), 300, 0.25, black(), 0.5),
] {
let (outer, inner) = ring_rims(view, side, scale, paint, opacity);
let bound = if opacity < 1.0 { EDGE_LEVELS / 2 + 1 } else { EDGE_LEVELS };
for (rim, r) in [("outer", outer), ("inner", inner)] {
assert!(r.pixels > 200, "{name}, {rim} rim: {} edge pixels", r.pixels);
if r.worst > bound {
off.push(format!("{name}, {rim} rim: {} levels off at {} ({} edge pixels)", r.worst, r.at, r.pixels));
}
}
}
assert!(off.is_empty(), "{off:#?}");
}
/// The outline of the 80 pt stroke along a circle of radius 400 about (600, 600), at `tol`.
fn ring_outline(tol: f64) -> BezPath {
let st = StrokeLayer::new(Paint::solid(Color::BLACK), 80.0);
crate::stroke::outline(&circle((600.0, 600.0), 400.0), &st, 80.0, tol)
}
/// How many moves and closes `p` has.
fn moves_and_closes(p: &BezPath) -> (usize, usize) {
let els = p.elements();
(els.iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(), els.iter().filter(|e| matches!(e, kurbo::PathEl::ClosePath)).count())
}
/// A wide stroke's outline has its long curves drawn as lines that cross them: the line ends lie
/// outside the circles, the lines' middles inside, all within half of the tolerance, with its
/// subpaths kept.
#[test]
fn wide_outlines_draw_their_curves_as_lines_across_them() {
for tol in [1.0, 0.25] {
let raw = ring_outline(tol);
let lines = wide(raw.clone(), 80.0, tol);
assert_eq!(moves_and_closes(&lines), moves_and_closes(&raw), "tolerance {tol}");
assert!(lines.elements().iter().all(|e| matches!(e, kurbo::PathEl::MoveTo(_) | kurbo::PathEl::LineTo(_) | kurbo::PathEl::ClosePath)));
let c = kurbo::Point::new(600.0, 600.0);
// How far a point is outside the rim it is nearest to.
let off = |p: kurbo::Point| {
let r = (p - c).hypot();
if r > 400.0 { r - 440.0 } else { r - 360.0 }
};
let (mut ends, mut middles) = (vec![], vec![]);
for seg in lines.segments() {
if let kurbo::PathSeg::Line(l) = seg
&& l.p1 != l.p0
{
ends.push(off(l.p1));
middles.push(off(l.p0.midpoint(l.p1)));
}
}
assert!(ends.len() > 100, "tolerance {tol}: {} lines", ends.len());
let most = ends.iter().chain(&middles).fold(0.0_f64, |m, d| m.max(d.abs()));
assert!(most <= tol / 2.0, "tolerance {tol}: a line {most} from its curve");
assert!(ends.iter().filter(|d| **d > tol * 0.1).count() > ends.len() / 2, "tolerance {tol}: line ends outside the curves");
assert!(middles.iter().filter(|d| **d < -tol * 0.1).count() > middles.len() / 2, "tolerance {tol}: line middles inside the curves");
}
}
/// Outlines of strokes narrower than 32 tolerances, outlines without a curve spanning 128
/// tolerances, and outlines that would take more than a million lines are kept as they are.
#[test]
fn narrow_short_straight_or_huge_outlines_are_kept() {
let tol = 0.25;
let st = |w: f64| StrokeLayer::new(Paint::solid(Color::BLACK), w);
let narrow = crate::stroke::outline(&circle((600.0, 600.0), 400.0), &st(7.0), 7.0, tol);
let small = crate::stroke::outline(&circle((50.0, 50.0), 10.0), &st(9.0), 9.0, tol);
let straight = crate::stroke::outline(&Rect::new(0.0, 0.0, 400.0, 300.0).to_path(0.1), &st(20.0), 20.0, tol);
// Eight curves of about 200,000 lines each.
let huge = circle((0.0, 0.0), 1e11);
for (name, p, width) in [("narrow", narrow, 7.0), ("small curves", small, 9.0), ("straight", straight, 20.0), ("huge", huge, 20.0)] {
assert!(p.elements().len() > 1, "{name}");
assert_eq!(wide(p.clone(), width, tol).elements(), p.elements(), "{name}: kept");
}
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
let raw = ring_outline(1.0);
assert_eq!(wide(raw.clone(), 80.0, bad).elements(), raw.elements(), "tolerance {bad}");
}
}
/// Where a long curve meets a corner, a line or a curve that isn't finite, its end stays where it
/// was, and the segments that aren't long curves are kept as they are.
#[test]
fn curve_ends_at_corners_lines_and_bad_curves_stay_put() {
let mut p = BezPath::new();
p.move_to((0.0, 0.0));
p.curve_to((0.0, 100.0), (100.0, 200.0), (200.0, 200.0));
p.line_to((300.0, 200.0));
p.curve_to((300.0, 100.0), (400.0, 0.0), (500.0, 0.0));
p.curve_to((f64::NAN, 0.0), (600.0, 0.0), (700.0, 0.0));
p.curve_to((700.0, 300.0), (900.0, 300.0), (900.0, 0.0));
p.quad_to((905.0, 5.0), (910.0, 0.0));
let lines = wide(p.clone(), 40.0, 0.25);
let points: Vec<_> = lines.elements().iter().filter_map(|e| e.end_point()).collect();
for corner in [(0.0, 0.0), (200.0, 200.0), (300.0, 200.0), (500.0, 0.0), (700.0, 0.0), (900.0, 0.0), (910.0, 0.0)] {
assert!(points.contains(&kurbo::Point::from(corner)), "{corner:?} kept: {lines:?}");
}
let curves: Vec<_> = lines.elements().iter().filter(|e| matches!(e, kurbo::PathEl::CurveTo(..) | kurbo::PathEl::QuadTo(..))).collect();
assert_eq!(curves.len(), 2, "the curve that isn't finite and the short curve are kept: {curves:?}");
assert!(lines.elements().len() > 40, "{} elements", lines.elements().len());
}
/// An outline is drawn with lines through a view that stretches no length by more than the frame's
/// pixel size allows: one that zooms, turns or shrinks the stroke's space, and not one that
/// stretches it unevenly, enlarges it beyond the frame's pixels, collapses it or isn't finite.
#[test]
fn outlines_are_drawn_as_lines_only_through_even_views() {
let px = |v: Affine| 1.0 / v.determinant().abs().sqrt();
for (name, m, px, want) in [
("zoomed out", Affine::scale(0.25), px(Affine::scale(0.25)), true),
("turned", Affine::rotate(0.5) * Affine::scale(3.0), px(Affine::scale(3.0)), true),
("flipped", Affine::FLIP_X, 1.0, true),
("text made smaller", Affine::scale(0.5), 1.0, true),
("stretched", Affine::scale_non_uniform(0.25, 0.2), px(Affine::scale_non_uniform(0.25, 0.2)), false),
("text made larger", Affine::scale(2.0), 1.0, false),
("collapsed", Affine::scale(0.0), 1.0, false),
("not a number", Affine::scale(f64::NAN), 1.0, false),
("no pixel size", Affine::IDENTITY, f64::INFINITY, false),
] {
assert_eq!(fine(m, px), want, "{name}");
}
}
+50
View File
@@ -199,6 +199,56 @@ fn a_long_dashed_stroke_draws_the_same_pixels_outlined_near_the_view() {
}
}
/// 600 half circles of radius 60 in a row along y = 0, from x = 0, each as two quarter circles and
/// alternately above and below the row.
fn waves() -> BezPath {
let k = 60.0 * 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan();
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
for i in 0..600 {
let (x, s) = (f64::from(i) * 120.0, if i % 2 == 0 { -1.0 } else { 1.0 });
bp.curve_to((x, s * k), (x + 60.0 - k, s * 60.0), (x + 60.0, s * 60.0));
bp.curve_to((x + 60.0 + k, s * 60.0), (x + 120.0, s * k), (x + 120.0, 0.0));
}
bp
}
/// Whether `outline` has a curve whose control points span 32 pt or more across or down.
fn has_long_curve(outline: &BezPath) -> bool {
outline.segments().any(|s| {
let pts = match s {
kurbo::PathSeg::Line(_) => return false,
kurbo::PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2],
kurbo::PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3],
};
let b = pts.iter().fold(kurbo::Rect::from_points(pts[0], pts[0]), |b, p| b.union_pt(*p));
b.width().max(b.height()) >= 32.0
})
}
/// A long wide stroke along curves, solid or dashed, outlined near the view has its long curves
/// drawn as lines and draws the same pixels as when it is outlined whole. With a width profile,
/// the outline made near the view keeps its curves.
#[test]
fn a_long_wide_curved_stroke_draws_the_same_pixels_outlined_near_the_view() {
let at = Point::new(36_030.0, 0.0);
let solid = stroke(24.0, LineJoin::Miter, LineCap::Butt);
for (what, d) in [("solid", doc(&waves(), solid.clone())), ("dashed", doc(&waves(), dashed(solid.clone(), &[150.0, 40.0], 0.0, false)))] {
let mut r = Renderer::new();
let near = render(&mut r, &d, at);
assert!(r.strokes.values().any(|e| e.crop.is_some()), "{what}: outlined near the view");
assert!(r.strokes.values().all(|e| !has_long_curve(&e.outline)), "{what}: its long curves drawn as lines");
assert!(near.pixels == whole(&d, at).pixels, "{what}: the same pixels as the whole outline");
assert!(near.pixels.chunks(4).any(|p| p[0] < 128), "{what}: the stroke shows");
}
let mut lens = solid;
lens.profile = WidthProfile::preset("lens");
let mut r = Renderer::new();
render(&mut r, &doc(&waves(), lens), at);
assert!(r.strokes.values().any(|e| e.crop.is_some()), "lens profile: outlined near the view");
assert!(r.strokes.values().all(|e| has_long_curve(&e.outline)), "lens profile: its curves kept");
}
#[test]
fn a_long_dashed_stroke_draws_the_same_pixels_after_its_path_changes() {
let st = dashed(stroke(5.0, LineJoin::Miter, LineCap::Butt), &[18.0, 7.0], 3.0, false);
+5
View File
@@ -292,6 +292,11 @@ impl Writer<'_> {
self.warn("type on a path with Tsume is outlined to keep its look");
return self.text_outlines(n, t);
}
// Justification…'s Desired word and letter spacing and glyph scaling do too.
if (0..t.paragraph_count()).any(|i| !t.layout_justification(t.para_at(i)).desired_is_default()) {
self.warn("type on a path with Justification spacing or glyph scaling is outlined to keep its look");
return self.text_outlines(n, t);
}
// A `<textPath>` holds the characters of the text, not the bullets or numbers drawn
// before them.
if !lay.markers.is_empty() {
+564 -14
View File
@@ -2,6 +2,7 @@
//! it, made as the importer makes art of any SVG file. The text crate asks for it through the
//! reader the app registers ([`vectorcraft_text::set_svg_glyph_reader`]).
use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
@@ -20,6 +21,8 @@ const MAX_SVG_GLYPH_BYTES: u64 = 1 << 20;
/// embedded content and scripts (and images of SVG documents, in [`glyph`]).
const LEFT_OUT: [&str; 3] = ["text", "foreignObject", "script"];
const XLINK: &str = "http://www.w3.org/1999/xlink";
/// Glyph `gid`'s art from its SVG `document` (possibly gzipped), in a font of `upem` units per em:
/// its element `glyph<gid>` (or the whole document when that is its root), in font units (y down),
/// the root's `viewBox` (or else its size) fitted into the em square by its larger side, centred.
@@ -28,6 +31,11 @@ const LEFT_OUT: [&str; 3] = ["text", "foreignObject", "script"];
/// ([`own_art`]). With the art, whether it uses the text's colours. `None` when the document doesn't read, is too large or has
/// no such element.
pub fn glyph_art(document: &[u8], gid: u32, upem: f64, fill: Color, stroke: Option<Color>) -> Option<(Node, bool)> {
glyph_art_with(document, gid, upem, fill, stroke, true)
}
/// [`glyph_art`], the importer reading only what the glyph refers to when `reduce` ([`glyph`]).
fn glyph_art_with(document: &[u8], gid: u32, upem: f64, fill: Color, stroke: Option<Color>, reduce: bool) -> Option<(Node, bool)> {
// The SVGZ budget left is the glyph's cap.
let unpacked = AtomicU64::new(crate::MAX_SVGZ.saturating_sub(MAX_SVG_GLYPH_BYTES));
let text = crate::text_within(document, &unpacked).ok()?;
@@ -39,7 +47,7 @@ pub fn glyph_art(document: &[u8], gid: u32, upem: f64, fill: Color, stroke: Opti
let [r, g, b, _] = c.to_rgba8(1.0);
format!("#{r:02x}{g:02x}{b:02x}")
};
let Glyph { svg, whole, frame } = glyph(&text, &id, &hex(fill))?;
let Glyph { svg, whole, frame } = glyph(&text, &id, &hex(fill), reduce)?;
let coloured = ["currentColor", "currentcolor", "context-fill", "context-stroke"].iter().any(|k| svg.contains(k));
// usvg resolves `context-fill` and `context-stroke` only for markers.
let svg = svg.replace("context-fill", &hex(fill)).replace("context-stroke", &stroke.map_or_else(|| "none".into(), hex));
@@ -86,9 +94,10 @@ struct Glyph {
/// `svg` with only what glyph `id` draws, as if the root `use`d it: the rest of the document (a
/// font may keep all its glyphs in one) only defines what it refers to, and what its parents apply
/// doesn't reach it. Without the [`LEFT_OUT`] elements and event attributes, the root without a
/// size (the em square is its frame) and in the text's colour `color`. `None` when it doesn't read
/// or has no element `id`.
fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
/// size (the em square is its frame) and in the text's color `color`. With `reduce`, the `defs`
/// hold only what the glyph refers to ([`referred`]), when that can be followed; else the whole
/// rest of the document. `None` when it doesn't read or has no element `id`.
fn glyph(svg: &str, id: &str, color: &str, reduce: bool) -> Option<Glyph> {
// Before the XML reader: it nests by recursion and expands entities without a total limit.
if crate::import::xml_too_deep(svg) || crate::entities::expansion_too_large(svg) {
return None;
@@ -105,8 +114,7 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
// data URL not typed as a raster goes too: the importer reads an untyped one (`text/plain`) as
// SVG, SVGZ as well, when its bytes aren't a raster.
let svg_image = |n: &roxmltree::Node| {
let href = n.attribute("href").or_else(|| n.attribute(("http://www.w3.org/1999/xlink", "href")));
let data = href.map(|h| h.trim_start()).filter(|h| h.get(..5).is_some_and(|v| v.eq_ignore_ascii_case("data:")));
let data = link(*n).map(|h| h.value()).map(|h| h.trim_start()).filter(|h| h.get(..5).is_some_and(|v| v.eq_ignore_ascii_case("data:")));
let raster = |h: &str| {
["data:image/png", "data:image/jpeg", "data:image/jpg", "data:image/gif", "data:image/webp"]
.iter()
@@ -114,7 +122,8 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
};
n.tag_name().name() == "image" && data.is_some_and(|h| !raster(h))
};
for n in root.descendants().filter(|n| n.is_element() && (LEFT_OUT.contains(&n.tag_name().name()) || svg_image(n))) {
let cut = |n: &roxmltree::Node| n.is_element() && (LEFT_OUT.contains(&n.tag_name().name()) || svg_image(n));
for n in root.descendants().filter(cut) {
edits.push((n.range(), String::new()));
}
for a in root.attributes().filter(|a| matches!(a.name(), "width" | "height" | "color")) {
@@ -128,10 +137,18 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
let start = root.range().start + 1;
let name = start + svg.get(start..)?.find(|c: char| c.is_whitespace() || c == '>' || c == '/')?;
edits.push((name..name, format!(" color=\"{color}\"")));
// The namespaces the glyph's parents declare, which it leaves: the root declares them too.
// The namespaces the glyph's parents declare, which it leaves: the root declares them too, or the
// glyph itself, where the root gives the prefix (or the default) another one.
let own = target.range().start + 1;
let own = own + svg.get(own..)?.find(|c: char| c.is_whitespace() || c == '>' || c == '/')?;
for ns in target.namespaces() {
if let Some(prefix) = ns.name().filter(|p| root.lookup_namespace_uri(Some(p)).is_none()) {
edits.push((name..name, format!(" xmlns:{prefix}=\"{}\"", crate::xml_escape(ns.uri()))));
let uri = crate::xml_escape(ns.uri());
let at_root = root.lookup_namespace_uri(ns.name());
match ns.name() {
Some(prefix) if at_root.is_none() => edits.push((name..name, format!(" xmlns:{prefix}=\"{uri}\""))),
_ if whole || at_root == Some(ns.uri()) || declares(svg, target, ns.name())? => {}
Some(prefix) => edits.push((own..own, format!(" xmlns:{prefix}=\"{uri}\""))),
None => edits.push((own..own, format!(" xmlns=\"{uri}\""))),
}
}
edits.sort_by_key(|(r, _)| (r.start, r.end));
@@ -141,11 +158,14 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
// The root's content goes in `defs`, and the glyph after it, on its own.
let content = root.first_child()?.range().start;
let close = svg.get(..root.range().end)?.rfind("</")?;
let defs = match reduce.then(|| referred(svg, &xml, target, cut)).flatten() {
Some(pieces) => pieces.into_iter().map(|r| edited(svg, r, &edits)).collect::<Option<String>>()?,
None => [edited(svg, content..at.start, &edits)?, edited(svg, at.end..close, &edits)?].concat(),
};
[
edited(svg, 0..content, &edits)?,
"<defs>".into(),
edited(svg, content..at.start, &edits)?,
edited(svg, at.end..close, &edits)?,
defs,
"</defs>".into(),
edited(svg, at.clone(), &edits)?,
edited(svg, close..svg.len(), &edits)?,
@@ -164,12 +184,265 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
Some(Glyph { svg: out, whole, frame: view_box.or_else(size) })
}
/// Whether the start tag of `element` in `svg` declares namespace `prefix` (`None`: the default
/// one). `None` when the tag doesn't read.
fn declares(svg: &str, element: roxmltree::Node, prefix: Option<&str>) -> Option<bool> {
let want = prefix.map_or_else(|| "xmlns".to_string(), |p| format!("xmlns:{p}"));
let tag = svg.get(element.range().start + 1..)?;
let mut rest = tag.trim_start_matches(|c: char| !(c.is_whitespace() || c == '>' || c == '/'));
loop {
rest = rest.trim_start();
if rest.is_empty() || rest.starts_with(['>', '/']) {
return Some(false);
}
let eq = rest.find('=')?;
let value = rest.get(eq + 1..)?.trim_start();
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
let close = 1 + value.get(1..)?.find(quote)?;
if rest.get(..eq)?.trim_end() == want {
return Some(true);
}
rest = value.get(close + 1..)?;
}
}
/// The byte ranges of `svg` (whose XML is `xml`) that the `defs` of glyph element `target` need, in
/// order: the elements it refers to with `url(#id)` (in an attribute, a `style` or a sheet) or
/// `href="#id"`, those they refer to in turn, and every `<style>` sheet, each whole, with the start
/// and end tags of the elements holding them (and what those refer to), so what they inherit and the
/// sheets' rules match as in the whole document. `None` when that can't be followed and the whole
/// rest of the document goes in: a document with a DTD or an `xml:base`, ids used twice, a
/// reference to an element that isn't there, holds the glyph or is inside one `cut` takes out, a
/// link to another file, a reference with an escape, or a sheet with selectors that look at
/// siblings ([`plain_sheet`]). Each element is queued and read at most once.
fn referred<'a, 'i>(
svg: &str,
xml: &'a roxmltree::Document<'i>,
target: roxmltree::Node<'a, 'i>,
cut: impl Fn(&roxmltree::Node<'a, 'i>) -> bool,
) -> Option<Vec<Range<usize>>> {
if svg.contains("<!DOCTYPE") || target.ancestors().skip(1).any(|a| cut(&a)) {
return None;
}
let root = xml.root_element();
// Whether element `inner` is `outer` or inside it.
let within =
|outer: roxmltree::Node, inner: roxmltree::Node| outer.range().start <= inner.range().start && inner.range().end <= outer.range().end;
let mut ids = HashMap::new();
let mut wanted = vec![];
// The elements `cut` takes out with what they hold, found in document order.
let mut left_out = HashSet::new();
let mut cut_end = 0;
for n in xml.descendants().filter(|n| n.is_element()) {
if n.attribute(("http://www.w3.org/XML/1998/namespace", "base")).is_some() {
return None;
}
if let Some(id) = n.attribute("id")
&& ids.insert(id, n).is_some()
{
return None;
}
if n.range().start >= cut_end && cut(&n) {
cut_end = n.range().end;
}
if n.range().start < cut_end {
left_out.insert(n.id());
} else if n.tag_name().name() == "style" && !within(target, n) {
wanted.push(n);
}
}
let mut refs = vec![];
for a in root.attributes() {
refer(root, a, &mut refs)?;
}
// Elements whose whole subtree is read, those queued to be, the elements kept whole and the
// elements holding them.
let mut read = HashSet::new();
let mut queued: HashSet<_> = wanted.iter().map(|n| n.id()).collect();
queued.insert(target.id());
let mut holders = HashSet::new();
let mut kept = wanted.clone();
let mut queue = wanted;
queue.push(target);
while let Some(n) = queue.pop() {
// The elements holding a kept one go in around it: what they refer to goes in too. Above
// one already held, all are.
if n != target {
for a in n.ancestors().skip(1).take_while(|a| *a != root) {
if !holders.insert(a.id()) {
break;
}
for at in a.attributes() {
refer(a, at, &mut refs)?;
}
}
}
let mut stack = vec![n];
while let Some(m) = stack.pop() {
if !m.is_element() || !read.insert(m.id()) {
continue;
}
for a in m.attributes() {
refer(m, a, &mut refs)?;
}
if m.tag_name().name() == "style" {
let sheet: String = m.children().filter_map(|c| c.text()).collect();
if !plain_sheet(&sheet) || m.children().filter_map(|c| c.text()).try_for_each(|t| urls(t, &mut refs)).is_none() {
return None;
}
}
stack.extend(m.children());
}
for id in refs.drain(..) {
let r = *ids.get(id)?;
if within(target, r) {
continue;
}
if within(r, target) || left_out.contains(&r.id()) {
return None;
}
if !read.contains(&r.id()) && queued.insert(r.id()) {
kept.push(r);
queue.push(r);
}
}
}
kept.sort_by_key(|n| n.range().start);
let mut tags = HashSet::new();
let mut pieces = vec![];
// The end of the last element kept whole: one starting before it is inside it, in its range.
let mut end = 0;
for n in kept {
if n.range().start < end {
continue;
}
end = n.range().end;
pieces.push(n.range());
for a in n.ancestors().skip(1).take_while(|a| *a != root) {
if !tags.insert(a.id()) {
break;
}
let (first, last) = (a.first_child()?.range(), a.last_child()?.range());
pieces.push(a.range().start..first.start);
pieces.push(last.end..a.range().end);
}
}
pieces.sort_by_key(|r| r.start);
Some(pieces)
}
/// Adds to `refs` the ids attribute `a` of element `n` refers to: an `href`'s `#id`, a value's
/// `url(#id)`s ([`urls`]). Of the links, only the one the importer follows: a plain `href`, else an
/// `xlink:href`. `None` when it refers to anything else, other than an image's or a link's file or
/// a data URL.
fn refer<'a>(n: roxmltree::Node, a: roxmltree::Attribute<'a, '_>, refs: &mut Vec<&'a str>) -> Option<()> {
if a.name() != "href" {
return urls(a.value(), refs);
}
if link(n).map(|l| l.range()) != Some(a.range()) {
return Some(());
}
let v = a.value().trim_matches(|c: char| c.is_ascii_whitespace());
match v.strip_prefix('#') {
Some(id) => refs.push(plain_id(id)?),
None if v.is_empty() || starts_with_ignoring_case(v, "data:") || matches!(n.tag_name().name(), "image" | "a") => {}
None => return None,
}
Some(())
}
/// Element `n`'s link as the importer follows it (SVG 2): its plain `href`, else its `xlink:href`.
fn link<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> Option<roxmltree::Attribute<'a, 'i>> {
let href = |ns: Option<&str>| n.attributes().find(|a| a.name() == "href" && a.namespace() == ns);
href(None).or_else(|| href(Some(XLINK)))
}
/// Adds to `refs` the ids of the `url(#id)`s in CSS or attribute value `v` (in any case, the id
/// quoted or not), passing data URLs by. `None` when one is of another form: another file, an
/// escape, a URL that doesn't close.
fn urls<'a>(v: &'a str, refs: &mut Vec<&'a str>) -> Option<()> {
// An escape can spell `url(` or an id in another way.
if v.contains('\\') {
return None;
}
let space = |c: char| c.is_ascii_whitespace();
let mut from = 0;
while let Some(at) = v.get(from..)?.as_bytes().windows(4).position(|w| w.eq_ignore_ascii_case(b"url(")) {
from += at + 4;
let rest = v.get(from..)?.trim_start_matches(space);
let (quote, rest) = match rest.chars().next() {
Some(q @ ('"' | '\'')) => (Some(q), rest.get(1..)?),
_ => (None, rest),
};
if starts_with_ignoring_case(rest, "data:") {
continue;
}
let id = rest.strip_prefix('#')?;
let end = id.find(|c: char| space(c) || matches!(c, ')' | '"' | '\'')).unwrap_or(id.len());
let mut tail = id.get(end..)?.trim_start_matches(space);
if let Some(q) = quote {
tail = tail.strip_prefix(q)?.trim_start_matches(space);
}
if !tail.starts_with(')') {
return None;
}
refs.push(plain_id(id.get(..end)?)?);
}
Some(())
}
/// `id` when it is matched as it is written: not empty, and without an escape (`\`), a percent
/// escape or a space.
fn plain_id(id: &str) -> Option<&str> {
(!id.is_empty() && !id.contains(|c: char| matches!(c, '\\' | '%') || c.is_whitespace())).then_some(id)
}
fn starts_with_ignoring_case(s: &str, prefix: &str) -> bool {
s.get(..prefix.len()).is_some_and(|p| p.eq_ignore_ascii_case(prefix))
}
/// Whether the rules of style sheet `css` are matched by each element and its ancestors alone, so
/// they match as before when other elements are left out: selectors of type, `*`, `#id` and
/// `.class`, joined by descendant and child (`>`) combinators, in lists. No pseudo-classes
/// (`:nth-child`, `:has`), sibling combinators, attribute selectors, escapes or at-rules.
fn plain_sheet(css: &str) -> bool {
let mut text = String::new();
let mut rest = css;
while let Some(at) = rest.find("/*") {
text.push_str(&rest[..at]);
let Some(end) = rest[at + 2..].find("*/") else { return false };
text.push(' ');
rest = &rest[at + 2 + end + 2..];
}
text.push_str(rest);
if text.contains(['@', '\\']) {
return false;
}
let mut rest = text.as_str();
while let Some(open) = rest.find('{') {
let selectors = &rest[..open];
if !selectors.chars().all(|c| c.is_ascii_alphanumeric() || c.is_ascii_whitespace() || matches!(c, '_' | '-' | '.' | '#' | '*' | '>' | ',')) {
return false;
}
let body = &rest[open + 1..];
let Some(close) = body.find('}') else { return false };
if body[..close].contains('{') {
return false;
}
rest = &body[close + 1..];
}
rest.trim().is_empty()
}
/// `svg[range]` with the `edits` (in order) that lie in it made: one around the range (a left-out
/// element holding the glyph) isn't, so it stays whole, defining only.
/// element holding the glyph) isn't, so it stays whole, defining only. The `edits` are sorted by
/// where they start.
fn edited(svg: &str, range: Range<usize>, edits: &[(Range<usize>, String)]) -> Option<String> {
let mut out = String::new();
let mut at = range.start;
for (r, with) in edits.iter().filter(|(r, _)| range.start <= r.start && r.end <= range.end) {
let first = edits.partition_point(|(r, _)| r.start < range.start);
let within = edits.get(first..)?.iter().take_while(|(r, _)| r.start <= range.end);
for (r, with) in within.filter(|(r, _)| r.end <= range.end) {
// An element inside one already cut goes with it.
if r.start < at {
continue;
@@ -205,3 +478,280 @@ fn own_art(n: &Node, doc: &Document) -> Option<Node> {
}
Some(n)
}
#[cfg(test)]
mod tests {
use super::*;
/// A document of `n` glyphs `glyph0`… that share one gradient, each two paths.
fn shared(n: usize) -> String {
let glyphs: String = (0..n)
.map(|i| {
format!(
r##"<g id="glyph{i}"><path fill="url(#shade)" d="M{i} 0c100 -200 300 -200 400 0s-100 300 -400 0z"/><path fill="#{:06x}" d="M0 0h50v-50z"/></g>"##,
i * 97 % 0xff_ffff
)
})
.collect();
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000"><defs><linearGradient id="shade"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>{glyphs}</svg>"##
)
}
fn rewrite(svg: &str, gid: u32, reduce: bool) -> String {
glyph(svg, &format!("glyph{gid}"), "#000000", reduce).unwrap().svg
}
fn art(svg: &str, gid: u32, reduce: bool) -> Node {
glyph_art_with(svg.as_bytes(), gid, 1000.0, Color::BLACK, None, reduce).unwrap().0
}
#[test]
fn a_glyph_of_a_shared_document_hands_the_importer_only_what_it_refers_to() {
let (small, large) = (shared(20), shared(2000));
assert!(large.len() > 100 << 10 && (large.len() as u64) < MAX_SVG_GLYPH_BYTES, "{}", large.len());
let one = rewrite(&large, 10, true);
assert_eq!(one, rewrite(&small, 10, true), "the same, however many other glyphs the document holds");
let middle = rewrite(&large, 1000, true);
assert!(middle.len() < 2 << 10, "{} bytes", middle.len());
assert!(middle.contains(r#"id="shade""#) && middle.contains(r#"id="glyph1000""#), "{middle}");
assert!(!middle.contains(r#"id="glyph999""#) && !middle.contains(r#"id="glyph1001""#), "{middle}");
assert_eq!(art(&large, 1000, true), art(&large, 1000, false));
}
/// Documents whose glyph refers to art across them, each one drawn the same from the `defs`
/// left after reducing as from the whole document.
#[test]
fn a_reduced_document_draws_the_glyph_as_the_whole_one_does() {
let other = r##"<g id="glyph8"><path fill="#123456" d="M0 0h900v-900z"/></g>"##;
let docs = [
// A gradient inside another glyph, inheriting from one in `defs`, under a fill.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="glyph3" fill="#0f0"><linearGradient id="g" href="#base"/><path d="M0 0h10v-10z"/></g>
<defs><linearGradient id="base"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>
<g id="glyph1"><path fill="url(#g)" d="M0 0h500v-500z"/></g>{other}</svg>"##
),
// `<use>` by `href`, `xlink:href` and a prefix declared on the glyph's parent.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g xmlns:l="http://www.w3.org/1999/xlink"><defs><path id="a" d="M0 0h100v-100z"/><path id="b" d="M0 0h300v-300z"/><path id="c" d="M0 0h7v-7z"/></defs>
<g id="glyph1"><use href="#a" xlink:href="#b" fill="#f00"/><use l:href="#b" x="400" fill="#0f0"/></g></g>{other}</svg>"##
),
// A sheet's rules: a `url()` they give, a gradient's chain, a class on another glyph's group.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><style><![CDATA[ .p {{ fill: url( '#g1' ) }} .warm > linearGradient stop, #x {{ stop-color: #f80 }} /* {{}}@ */ ]]></style>
<g id="glyph2" class="warm"><linearGradient id="g1" href="#g2"/><linearGradient id="g2"><stop offset="0"/><stop offset="1" stop-color="#00f"/></linearGradient></g>
<g id="glyph1"><path class="p" d="M0 0h500v-500z"/></g>{other}</svg>"##
),
// Clip paths, masks, filters, markers and patterns, a cycle, the glyph using itself, a
// non-ASCII id.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="c"><rect width="300" height="300"/></clipPath>
<mask id="m"><rect width="500" height="500" fill="#fff"/></mask><filter id="f"><feGaussianBlur stdDeviation="2"/></filter>
<marker id="k" markerWidth="4" markerHeight="4"><circle r="2" fill="url(#pat)"/></marker>
<pattern id="pat" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="5" height="5" fill="#0f0"/></pattern>
<linearGradient id="loop1" href="#loop2"/><linearGradient id="loop2" href="#loop1"><stop offset="0" stop-color="#f0f"/></linearGradient>
<linearGradient id="ü"><stop offset="0" stop-color="#ff0"/></linearGradient></defs>
<g id="glyph1"><path style="clip-path:url(#c);mask:URL(&quot;#m&quot;)" filter="url(#f)" marker-start="url(#k)" fill="url(#pat)" stroke="url(#loop1)" d="M0 0L300 300"/>
<rect fill="url(#ü)" width="9" height="9"/><use href="#glyph1"/></g>{other}</svg>"##
),
// A rule on the glyph's own parent, which it leaves either way; a quoted, spaced URL to
// an id with punctuation in it.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><style>.outer .p {{ fill: #f00 }} .outer > g {{ stroke-width: 9 }}</style>
<linearGradient id="a;b"><stop offset="0" stop-color="#0ff"/></linearGradient>
<g class="outer"><g id="glyph1"><path class="p" stroke='url( "#a;b" )' d="M0 0h500v-500z"/></g></g>{other}</svg>"##
),
// A pattern whose art takes its paint from the group holding it.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="p2"><stop offset="0" stop-color="#f0f"/></linearGradient></defs>
<g fill="url(#p2)"><pattern id="pat" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="5" height="5"/></pattern></g>
<g id="glyph1"><path fill="url(#pat)" d="M0 0h500v-500z"/></g>{other}</svg>"##
),
];
for doc in &docs {
let (reduced, whole) = (rewrite(doc, 1, true), rewrite(doc, 1, false));
assert!(reduced.len() < whole.len() && !reduced.contains("#123456"), "reduced: {reduced}");
assert_eq!(art(doc, 1, true), art(doc, 1, false), "{reduced}");
}
}
/// Whatever the reduction can't follow keeps the whole document in the `defs`.
#[test]
fn what_cant_be_followed_keeps_the_whole_document() {
let glyph = |defs: &str, art: &str| {
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">{defs}<g id="glyph1">{art}</g><g id="glyph2"><path fill="#123456" d="M0 0h9v-9z"/></g></svg>"##
)
};
let gradient = r##"<linearGradient id="g"><stop offset="0" stop-color="#f00"/></linearGradient>"##;
let path = |fill: &str| format!(r##"<path fill="{fill}" d="M0 0h500v-500z"/>"##);
let docs = [
glyph("<style>path:nth-child(1) { fill: #f00 }</style>", &path("#000")),
glyph("<style>g + g path { fill: #f00 }</style>", &path("#000")),
glyph("<style>[fill] { stroke: #f00 }</style>", &path("#000")),
glyph("<style>@import url(x.css);</style>", &path("#000")),
glyph(r"<style>.a { fill: url(#g\31) }</style>", &path("#000")),
glyph("<style>path { fill: #f00 </style>", &path("#000")),
glyph(gradient, &path(r"url(#\67)")),
glyph(gradient, r#"<path style="fill:u\72l(#g)" d="M0 0h5v-5z"/>"#),
glyph(gradient, &path("url(#%67)")),
glyph(gradient, &path("url('#g)")),
glyph(gradient, &path("url(#g) url(#g x)")),
glyph(gradient, &path("url(#nothing)")),
glyph(gradient, &path("url(other.svg#g)")),
glyph(gradient, r##"<use href="other.svg#g"/>"##),
glyph(&format!("{gradient}{gradient}"), &path("url(#g)")),
glyph(&format!(r#"<g xml:base="x/">{gradient}</g>"#), &path("url(#g)")),
glyph(&format!("<text>{gradient}</text>"), &path("url(#g)")),
r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="outer"><g id="glyph1"><use href="#outer"/></g></g><g id="glyph2"><path d="M0 0h9v-9z"/></g></svg>"##
.to_string(),
r##"<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY e "#f00">]><svg xmlns="http://www.w3.org/2000/svg"><g id="glyph1"><path fill="&e;" d="M0 0h5v-5z"/></g><g id="glyph2"/></svg>"##
.to_string(),
];
for doc in &docs {
assert_eq!(rewrite(doc, 1, true), rewrite(doc, 1, false), "{doc}");
}
}
#[test]
fn edits_apply_inside_the_range_asked_for() {
let edits = vec![(0..1, "A".to_string()), (2..2, "B".into()), (3..5, String::new()), (4..6, "C".into())];
// An edit overlapping one already made is passed by; one not inside the range is not made.
assert_eq!(edited("0123456", 0..7, &edits).as_deref(), Some("A1B256"));
assert_eq!(edited("0123456", 2..5, &edits).as_deref(), Some("B2"));
assert_eq!(edited("0123456", 4..7, &edits).as_deref(), Some("C6"));
assert_eq!(edited("0123456", 1..2, &edits).as_deref(), Some("1B"));
}
/// Of an element's `href` and `xlink:href`, only the plain one is followed, as the importer
/// follows it: the other's element stays out, and one that isn't there doesn't keep the whole
/// document.
#[test]
fn only_the_link_the_importer_follows_is_kept() {
let doc = |xlink: &str| {
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><path id="a" d="M0 0h100v-100z"/><path id="b" d="M0 0h300v-300z"/></defs>
<g id="glyph1"><use xlink:href="{xlink}" href="#a" fill="#f00"/><use xlink:href="#b" fill="#0f0"/></g><g id="glyph2"><path fill="#123456" d="M0 0h9v-9z"/></g></svg>"##
)
};
for xlink in ["#nothing", "other.svg#b"] {
let doc = doc(xlink);
let reduced = rewrite(&doc, 1, true);
assert!(reduced.len() < rewrite(&doc, 1, false).len() && !reduced.contains("#123456"), "{reduced}");
assert_eq!(art(&doc, 1, true), art(&doc, 1, false));
}
let doc = doc("#b").replace(r##"<use xlink:href="#b" fill="#0f0"/>"##, "");
let reduced = rewrite(&doc, 1, true);
assert!(reduced.contains(r#"id="a""#) && !reduced.contains(r#"id="b""#), "{reduced}");
assert_eq!(art(&doc, 1, true), art(&doc, 1, false));
}
/// A glyph inside an element that gives a prefix (or the default namespace) another namespace
/// than the root does keeps its own after it leaves that element.
#[test]
fn a_glyph_keeps_its_namespaces_when_the_root_gives_them_others() {
let flat = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:v="http://www.w3.org/1999/xlink"><defs><path id="a" d="M0 0h100v-100z"/></defs>
<g id="glyph1"><use v:href="#a" fill="#f00"/></g><g id="glyph2"/></svg>"##;
let nested = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:v="urn:other"><defs><path id="a" d="M0 0h100v-100z"/></defs>
<g xmlns:v="http://www.w3.org/1999/xlink"><g id="glyph1"><use v:href="#a" fill="#f00"/></g></g><g id="glyph2"/></svg>"##;
// The glyph declaring the prefix itself keeps it as it is.
let declared = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:v="urn:other"><defs><path id="a" d="M0 0h100v-100z"/></defs>
<g xmlns:v="http://www.w3.org/1999/xlink"><g xmlns:v='http://www.w3.org/1999/xlink' id="glyph1"><use v:href="#a" fill="#f00"/></g></g><g id="glyph2"/></svg>"##;
for reduce in [true, false] {
assert_eq!(art(nested, 1, reduce), art(flat, 1, reduce), "{}", rewrite(nested, 1, reduce));
assert_eq!(art(declared, 1, reduce), art(flat, 1, reduce), "{}", rewrite(declared, 1, reduce));
}
assert_eq!(rewrite(declared, 1, true).matches("xmlns:v=").count(), 2);
// A path in another default namespace is no SVG path, out of that element too.
let other = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:s="http://www.w3.org/2000/svg">
<s:g xmlns="urn:other"><s:g id="glyph1"><s:path fill="#f00" d="M0 0h5v-5z"/><path fill="#0f0" d="M0 0h9v-9z"/></s:g></s:g><s:g id="glyph2"/></svg>"##;
let only = r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="glyph1"><path fill="#f00" d="M0 0h5v-5z"/></g><g id="glyph2"/></svg>"##;
for reduce in [true, false] {
assert_eq!(art(other, 1, reduce), art(only, 1, reduce), "{}", rewrite(other, 1, reduce));
}
}
/// Many references to the same elements keep each of them once.
#[test]
fn repeated_references_keep_each_element_once() {
let uses: String = (0..2000).map(|i| format!(r##"<use href="#a" x="{i}"/><path fill="url(#g)" d="M{i} 0h1v-1z"/>"##)).collect();
let doc = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="g"><stop offset="0" stop-color="#f00"/></linearGradient>
<g id="a"><path fill="url(#g)" d="M0 0h5v-5z"/><use href="#b"/><use href="#b"/></g><path id="b" fill="url(#g)" d="M0 0h2v-2z"/></defs>
<g id="glyph1">{uses}</g><g id="glyph2"><path fill="#123456" d="M0 0h9v-9z"/></g></svg>"##
);
let reduced = rewrite(&doc, 1, true);
for id in ["g", "a", "b"] {
assert_eq!(reduced.matches(&format!(r#"id="{id}""#)).count(), 1, "{id}");
}
assert!(!reduced.contains("#123456"));
}
/// An empty document, or one without the glyph, has no art; one of exactly the cap reads, one a
/// byte larger doesn't.
#[test]
fn empty_and_capped_documents() {
assert!(glyph_art(b"", 1, 1000.0, Color::BLACK, None).is_none());
assert!(glyph_art(br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#, 1, 1000.0, Color::BLACK, None).is_none());
let doc = shared(20);
let at = doc.len() - "</svg>".len();
let padded = |len: u64| {
let pad = "x".repeat(len as usize - doc.len() - "<!---->".len());
format!("{}<!--{pad}-->{}", &doc[..at], &doc[at..])
};
let (full, over) = (padded(MAX_SVG_GLYPH_BYTES), padded(MAX_SVG_GLYPH_BYTES + 1));
assert_eq!(full.len() as u64, MAX_SVG_GLYPH_BYTES);
assert_eq!(art(&full, 3, true), art(&doc, 3, true));
assert!(glyph_art(over.as_bytes(), 3, 1000.0, Color::BLACK, None).is_none());
}
/// This thread's CPU time in seconds where the system reports it, else the time since a first
/// call.
fn cpu_seconds() -> f64 {
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok()) {
Some(ns) => ns / 1e9,
None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(),
}
}
/// The importer's time for 50 distinct glyphs of shared documents, read whole and reduced, the
/// two alternating in one process: `cargo test -p vectorcraft-svg --lib glyph::tests::timing --
/// --ignored --nocapture`.
#[test]
#[ignore = "timing, run by hand"]
fn timing() {
for n in [100, 500, 2000] {
let doc = shared(n);
let gids: Vec<u32> = (0..50).map(|i| (i * n / 50) as u32).collect();
let run = |reduce: bool| {
let t = cpu_seconds();
for g in &gids {
assert!(glyph_art_with(doc.as_bytes(), *g, 1000.0, Color::BLACK, None, reduce).is_some());
}
cpu_seconds() - t
};
run(false);
run(true);
let (mut whole, mut reduced) = (vec![], vec![]);
for round in 0..9 {
if round % 2 == 0 {
whole.push(run(false));
reduced.push(run(true));
} else {
reduced.push(run(true));
whole.push(run(false));
}
}
let median = |v: &mut Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::<Vec<_>>().join(" ");
println!("{n} glyphs, {} bytes: whole {} ms, reduced {} ms", doc.len(), ms(&whole), ms(&reduced));
println!("{n} glyphs: median whole {:.1} ms, reduced {:.1} ms", median(&mut whole) * 1e3, median(&mut reduced) * 1e3);
}
}
}
+36 -7
View File
@@ -241,13 +241,10 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() {
let svg = vectorcraft_svg::base64_encode(
br##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" fill="#f00"/></svg>"##,
);
let image = |href: &str, xlink: &str| {
format!(
r##"<image width="500" height="500" href="data:image/{href};base64,{}" xlink:href="data:image/{xlink};base64,{}"/>"##,
if href == "png" { &png } else { &svg },
if xlink == "png" { &png } else { &svg }
)
};
let data = |kind: &str| format!("data:image/{kind};base64,{}", if kind == "png" { &png } else { &svg });
let image = |href: &str, xlink: &str| format!(r##"<image width="500" height="500" href="{}" xlink:href="{}"/>"##, data(href), data(xlink));
// The same, `xlink:href` written first.
let xlink_first = |href: &str, xlink: &str| format!(r##"<image width="500" height="500" xlink:href="{}" href="{}"/>"##, data(xlink), data(href));
let images = |inner: String| {
let doc = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="glyph1"><path d="M0 0h1v-1z"/>{inner}</g></svg>"##
@@ -258,6 +255,38 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() {
};
assert_eq!(images(image("png", "svg+xml")), 1, "the PNG stays");
assert_eq!(images(image("svg+xml", "png")), 0, "the document goes");
assert_eq!(images(xlink_first("png", "svg+xml")), 1, "the PNG stays, its link written last");
assert_eq!(images(xlink_first("svg+xml", "png")), 0, "the document goes, its link written last");
}
/// A glyph draws what it refers to wherever its document defines it: here a sheet's `url()` to a
/// gradient inside another glyph's element, which takes its stops from one in `defs`. The other
/// glyph's own art is not drawn.
#[test]
fn a_glyph_draws_what_it_refers_to_from_anywhere_in_its_document() {
let doc = r##"<svg xmlns="http://www.w3.org/2000/svg"><style>.p { fill: url(#g) }</style>
<defs><linearGradient id="stops"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>
<g id="glyph2"><linearGradient id="g" href="#stops"/><path fill="#0f0" d="M0 0h10v-10z"/></g>
<g id="glyph5"><path class="p" d="M0 0h500v-500z"/></g>
</svg>"##;
let fills = fills(&art(doc, 5).unwrap());
let stops = fills.iter().find_map(|p| match p {
Paint::Gradient(g) => Some(g.gradient.stops.iter().map(|s| s.color).collect::<Vec<_>>()),
_ => None,
});
assert_eq!(stops, Some(vec![Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)]), "{fills:?}");
assert!(!fills.contains(&Paint::solid(Color::rgb8(0, 255, 0))), "not the other glyph's art: {fills:?}");
}
/// A glyph in colors of its own doesn't use the text's because another glyph of its document does.
#[test]
fn another_glyphs_current_color_does_not_color_a_glyph() {
let doc = r##"<svg xmlns="http://www.w3.org/2000/svg">
<g id="glyph1"><path fill="#f00" d="M0 0h500v-500z"/></g>
<g id="glyph2"><path fill="currentColor" d="M0 0h500v-500z"/></g>
</svg>"##;
assert!(!glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1);
assert!(glyph_art(doc.as_bytes(), 2, 1000.0, BLUE, None).unwrap().1);
}
/// A glyph's `<a>` draws its art but keeps no link: outlined text must not export a
+31
View File
@@ -671,6 +671,37 @@ fn justification_spacing_and_glyph_scaling_are_drawn_in_place() {
}
}
/// Type on a path with Justification…'s Desired word or letter spacing or glyph scaling is outlined
/// with a warning, since a `<textPath>` places its characters one after the other at their own
/// advances. With the default Desired values it stays a `<textPath>`.
#[test]
fn justification_spacing_on_a_path_is_outlined() {
use vectorcraft_doc::JustificationOptions;
let doc = |j: JustificationOptions| {
let mut t = TextObject::point(Point::ZERO, "HO HO", style(12.0));
t.para.justification = j;
let mut line = BezPath::new();
line.move_to((20.0, 100.0));
line.line_to((280.0, 100.0));
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
let mut d = Document::new(300.0, 200.0);
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
vectorcraft_svg::export_full(&d, &ExportOptions::default(), None)
};
let out = doc(JustificationOptions::default());
assert!(out.svg.contains("<textPath") && out.warnings.is_empty(), "{:?}", out.warnings);
for j in [
JustificationOptions { word_spacing: [0.0, 200.0, 300.0], ..JustificationOptions::default() },
JustificationOptions { letter_spacing: [0.0, 50.0, 50.0], ..JustificationOptions::default() },
JustificationOptions { glyph_scaling: [50.0, 150.0, 200.0], ..JustificationOptions::default() },
] {
let out = doc(j);
assert!(!out.svg.contains("<textPath") && out.warnings.iter().any(|w| w.contains("Justification")), "{:?}", out.warnings);
}
}
/// Justified and Mojikumi lines whose characters a reader draws where the layout does are written
/// as before: a segment per style run, and per word on a justified line.
#[test]
+26 -1
View File
@@ -4,9 +4,10 @@ use super::flow::{list_markers, repeat_mark_glyph};
use super::region::in_range;
use super::{
Affine, ArcPath, BezPath, Ctx, GlyphBend, Justify, LineInfo, ListMarker, ParamCurve, PathAlign, PathData, PathEffect, PathEl, Point, Range,
SGlyph, Shape, TextObject, Vec2, style_metrics,
SGlyph, Shape, TextObject, Vec2, apply_desired, style_metrics,
};
use crate::fontdb::PathAlignHeights;
use std::collections::HashMap;
use unicode_bidi::{BidiClass, BidiInfo};
/// The distance along type on a path each glyph takes: its advance measured `spacing` points above
@@ -425,6 +426,25 @@ fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range<usize>, glyphs: &m
Some((g.byte, c))
}
/// Justification…: paragraph `pi`'s glyphs at its Desired word and letter spacing and glyph scaling
/// (vertical type is not glyph scaled), with the Desired Glyph Scaling of each glyph it scales put
/// in `scales` by byte offset. Type on a path is one line that is never justified to a width, so
/// Minimum and Maximum are not used.
fn set_desired(cx: &Ctx<'_>, t: &TextObject, pi: usize, glyphs: &mut [SGlyph], scales: &mut HashMap<usize, f64>) {
let flex = apply_desired(glyphs, &t.layout_justification(t.para_at(pi)), !cx.vertical);
scales.extend(glyphs.iter().zip(&flex).filter(|(_, f)| f.scale != 1.0).map(|(g, f)| (g.byte, f.scale)));
}
/// Records on the glyph just drawn for `g` the Desired Glyph Scaling it is drawn at (`scales`, by
/// byte offset). A list marker's glyphs (no length) share their paragraph's first byte and are not
/// scaled.
fn record_scale(cx: &mut Ctx<'_>, g: &SGlyph, scales: &HashMap<usize, f64>) {
let scale = if g.len > 0 { scales.get(&g.byte).copied() } else { None };
if let (Some(scale), Some(out)) = (scale, cx.out.glyphs.last_mut()) {
out.scale = scale;
}
}
/// Lay type on a path out along `path` (text space), between its brackets.
pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, path: &PathData) {
cx.out.on_path = true;
@@ -434,11 +454,15 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject,
let mut rtl = None;
let mut shaped = Vec::new();
let markers = list_markers(t, paras);
// The Desired Glyph Scaling each scaled glyph is drawn at, by its byte offset.
let mut scales = HashMap::new();
for (pi, pr) in paras.iter().enumerate() {
let text = cx.text;
let bidi = para_bidi_with(text.get(pr.clone()).unwrap_or_default(), para.direction, &cx.char_directions(pr));
rtl.get_or_insert(is_rtl(bidi.as_ref()) && !cx.vertical);
let mut glyphs = cx.shape_para(pr.clone(), bidi.as_ref(), t.para_at(pi));
// Justification…, before anything measures the glyphs along the path.
set_desired(cx, t, pi, &mut glyphs, &mut scales);
// Bullets and numbers: a list paragraph's text starts after its marker here too, unless
// the paragraph continues from the frame before in its thread.
if pi > 0 || !t.first_para_continues {
@@ -727,6 +751,7 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject,
}
let at = cx.out.glyphs.len();
cx.emit(g, pre, origin, angle, g.adv, 0);
record_scale(cx, g, &scales);
let hidden = hide_before_open_path(cx, &ap, lead, at, s + step * 0.5, rise);
if !hidden && let Some(mark) = repeat.take_if(|&mut (byte, _)| g.len > 0 && g.byte == byte) {
cx.out.repeat_marks.push(mark);
+99
View File
@@ -64,6 +64,105 @@ fn desired_spacing_and_scaling_apply_to_every_line() {
assert!((at(&scaled, 2).advance - space).abs() < 1e-6, "word spaces aren't scaled");
}
/// Type on a straight open path `len` long, from the origin along x.
fn on_path(text: &str, len: f64, j: JustificationOptions) -> TextObject {
let mut t = point(text, j);
let mut line = kurbo::BezPath::new();
line.move_to((0.0, 0.0));
line.line_to((len, 0.0));
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
t
}
/// Desired values apply to type on a path as to point and area type: word spaces are that share of
/// the font's space, letters are followed by that share of a space, and glyphs are drawn that wide,
/// and the glyphs after a wider gap start further along the path.
#[test]
fn type_on_a_path_takes_desired_spacing_and_scaling() {
let plain = layout(db(), &on_path("ab cd", 1000.0, JustificationOptions::default()));
assert!(plain.on_path && !plain.overflow);
let space = at(&plain, 2).advance;
let a = at(&plain, 0).advance;
assert!(space > 0.0 && a > 0.0);
let words =
layout(db(), &on_path("ab cd", 1000.0, JustificationOptions { word_spacing: [0.0, 200.0, 300.0], ..JustificationOptions::default() }));
assert!((at(&words, 2).advance - 2.0 * space).abs() < 1e-6, "a word space at 200%");
assert!((at(&words, 1).origin.x - at(&plain, 1).origin.x).abs() < 1e-6, "the glyphs before it stay");
assert!((at(&words, 3).origin.x - at(&plain, 3).origin.x - space).abs() < 1e-6, "the glyphs after it start a space later");
let letters =
layout(db(), &on_path("ab cd", 1000.0, JustificationOptions { letter_spacing: [0.0, 50.0, 50.0], ..JustificationOptions::default() }));
assert!((at(&letters, 0).advance - (a + 0.5 * space)).abs() < 1e-6, "half a space after a");
assert!((at(&letters, 1).advance - at(&plain, 1).advance).abs() < 1e-6, "no letter spacing before a word space");
assert!((at(&letters, 4).advance - at(&plain, 4).advance).abs() < 1e-6, "nor after the last letter");
let scaled =
layout(db(), &on_path("ab cd", 1000.0, JustificationOptions { glyph_scaling: [50.0, 150.0, 200.0], ..JustificationOptions::default() }));
assert!((at(&scaled, 0).advance - 1.5 * a).abs() < 1e-6, "advance at 150%");
assert!((width(at(&scaled, 0)) - 1.5 * width(at(&plain, 0))).abs() < 1e-6, "outline at 150%");
assert!((at(&scaled, 0).scale - 1.5).abs() < 1e-9 && at(&scaled, 2).scale == 1.0, "the glyph records its scaling");
assert!((at(&scaled, 2).advance - space).abs() < 1e-6, "word spaces aren't scaled");
}
/// A right-aligned line on a path is aligned by its length at the Desired values, and a line that
/// fits at 100% word spacing runs past the end of a path it no longer fits.
#[test]
fn type_on_a_path_is_aligned_and_fitted_at_desired_spacing() {
let plain = layout(db(), &on_path("ab cd", 1000.0, JustificationOptions::default()));
let space = at(&plain, 2).advance;
let end = |l: &TextLayout| at(l, 4).origin.x + at(l, 4).advance;
let wide = JustificationOptions { word_spacing: [0.0, 300.0, 300.0], ..JustificationOptions::default() };
let mut t = on_path("ab cd", 1000.0, wide.clone());
t.para.justify = Justify::Right;
let right = layout(db(), &t);
assert!((end(&right) - 1000.0).abs() < 1e-6, "the line ends at the path's end: {}", end(&right));
let mut t = on_path("ab cd", 1000.0, JustificationOptions::default());
t.para.justify = Justify::Right;
let right_plain = layout(db(), &t);
assert!((at(&right_plain, 0).origin.x - at(&right, 0).origin.x - 2.0 * space).abs() < 1e-6, "it starts two spaces earlier");
let len = end(&plain) + 0.5 * space;
assert!(!layout(db(), &on_path("ab cd", len, JustificationOptions::default())).overflow);
let over = layout(db(), &on_path("ab cd", len, wide));
assert!(over.overflow, "the wider word space no longer fits");
}
/// Vertical type on a path takes Desired word spacing but is not glyph scaled, as in area type;
/// a list marker before the text keeps its width.
#[test]
fn vertical_type_and_list_markers_on_a_path_are_not_glyph_scaled() {
let scaling = JustificationOptions { glyph_scaling: [50.0, 150.0, 200.0], ..JustificationOptions::default() };
let vertical = |j: JustificationOptions| {
let mut t = on_path("ab cd", 1000.0, j);
t.vertical = true;
layout(db(), &t)
};
let plain = vertical(JustificationOptions::default());
let scaled = vertical(scaling.clone());
assert!((at(&scaled, 0).advance - at(&plain, 0).advance).abs() < 1e-6, "vertical glyphs keep their advance");
assert!((width(at(&scaled, 0)) - width(at(&plain, 0))).abs() < 1e-6, "and their outline");
let words = vertical(JustificationOptions { word_spacing: [0.0, 200.0, 300.0], ..JustificationOptions::default() });
assert!((at(&words, 2).advance - 2.0 * at(&plain, 2).advance).abs() < 1e-6, "a vertical word space at 200%");
use vectorcraft_doc::text::{Bullet, ParaList};
let listed = |j: JustificationOptions| {
let mut t = on_path("ab cd", 1000.0, j);
t.para.list = Some(ParaList::bulleted(Bullet::Dot));
layout(db(), &t)
};
let (plain, scaled) = (listed(JustificationOptions::default()), listed(scaling));
let marker = |l: &TextLayout| -> Vec<f64> {
let m = l.markers.first().expect("a list marker");
l.glyphs.get(m.glyphs.clone()).unwrap_or_default().iter().map(|g| g.advance * g.scale).collect()
};
assert!(!marker(&plain).is_empty());
assert_eq!(marker(&scaled), marker(&plain), "the marker keeps its width");
// The marker's glyphs have the paragraph's first byte too, with no length.
let first = |l: &TextLayout| l.glyphs.iter().find(|g| g.byte == 0 && g.len > 0).map_or(0.0, |g| g.advance);
assert!(first(&plain) > 0.0 && (first(&scaled) - 1.5 * first(&plain)).abs() < 1e-6, "the text after it is scaled");
}
/// The line's text from a layout, one string per line.
fn lines(l: &TextLayout, text: &str) -> Vec<String> {
l.lines.iter().map(|li| text.get(li.start..li.end).unwrap_or_default().trim_end().to_string()).collect()
+22 -3
View File
@@ -1,6 +1,8 @@
//! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All
//! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's
//! submenu selects them. Tool gestures emit engine commands.
//! submenu selects them. Tool gestures emit engine commands. The Trim at Crossings Tool is the
//! exception: it is in the Scissors tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and
//! the All Tools drawer show it, as well as in Path Precision Tools' submenu.
pub mod anchor_eraser;
pub mod box3d;
@@ -18,7 +20,8 @@ pub mod trim;
use crate::{Tool, ToolInfo};
/// Path Precision Tools' tools, one flyout group.
/// Path Precision Tools' tools, one flyout group. Its Trim at Crossings Tool ([`trim::ID`]) is in
/// the Scissors tool's group instead.
pub const PATH_TOOLS: &[ToolInfo] = &[
ToolInfo { id: anchor_eraser::ID, label: "Anchor Eraser Brush", shortcut: None, icon: "dc-remove-brush" },
ToolInfo { id: extend_path::ID, label: "Extend Path Tool", shortcut: None, icon: "dc-arrow-extend" },
@@ -27,7 +30,6 @@ pub const PATH_TOOLS: &[ToolInfo] = &[
ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-rounded-rect" },
ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-anchor" },
ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-join" },
ToolInfo { id: trim::ID, label: "Trim at Crossings Tool", shortcut: None, icon: "dc-pf-trim" },
];
/// Smart Pen's tool, a flyout group of its own.
@@ -103,4 +105,21 @@ mod tests {
assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID));
assert!(create("pen").is_none() && heading("pen").is_none());
}
/// The Trim at Crossings Tool is the add-on tool in a built-in group: the Scissors tool's,
/// after the Knife, with no default shortcut, listed once, and still made by its add-on.
#[test]
fn trim_at_crossings_is_in_the_scissors_group_once() {
let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == trim::ID)).collect();
assert_eq!(groups.len(), 1);
let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect();
let knife = ids.iter().position(|id| *id == "knife").expect("the Knife's group");
assert!(ids.contains(&"scissors"));
assert_eq!(ids.get(knife + 1), Some(&trim::ID));
let info = crate::tool_info(trim::ID).expect("catalogued");
assert_eq!((info.label, info.shortcut, info.icon), ("Trim at Crossings Tool", None, "dc-pf-trim"));
assert_eq!(create(trim::ID).map(|tool| tool.id()), Some(trim::ID));
assert!(!GROUPS.iter().any(|g| g.iter().any(|t| t.id == trim::ID)), "not listed again under the add-on");
assert_eq!(crate::catalog::all_tools().filter(|t| t.id == trim::ID).count(), 1);
}
}
+3 -2
View File
@@ -258,7 +258,7 @@ impl Tool for TrimTool {
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::Crosshair
Cursor::Knife
}
}
@@ -287,7 +287,8 @@ mod tests {
let up = t.pointer(&cx, &ev(PointerKind::Up, 100.5, 100.0));
assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [100.0, 100.0], "tolerance": 2.0}))], "4 px at 200%");
assert!(!t.busy());
assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::Crosshair);
assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::Knife, "the Knife's cursor, the blade's point on the pointer");
assert_eq!(Cursor::Knife.precise(), Cursor::Crosshair, "Use Precise Cursors shows the crosshair");
}
#[test]
+3
View File
@@ -68,6 +68,9 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[
t("eraser", "Eraser Tool", Some("Shift+E"), "tool-eraser"),
t("scissors", "Scissors Tool", Some("C"), "tool-scissors"),
t("knife", "Knife", None, "tool-knife"),
// Path Precision Tools' Trim at Crossings Tool, kept out of `addons::PATH_TOOLS` so that
// `all_tools` lists it once.
t(crate::addons::trim::ID, "Trim at Crossings Tool", None, "dc-pf-trim"),
t("mirrorCut", "Mirror & Cut Tool", None, "tool-mirror-cut"),
t("lineCut", "Line Cut Tool", None, "tool-line-cut"),
t("rectCut", "Rectangle Cut Tool", None, "tool-rect-cut"),
+1 -2
View File
@@ -139,7 +139,7 @@ pub enum Cursor {
PathEraser,
/// The Join tool.
Join,
/// The Knife tool.
/// The Knife tool and the Trim at Crossings Tool.
Knife,
/// The Shaper tool.
Shaper,
@@ -339,7 +339,6 @@ impl Cursor {
| Cursor::Smooth
| Cursor::PathEraser
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::Measure
| Cursor::ObjectsOnPath
+5 -1
View File
@@ -721,8 +721,12 @@ hotspot = "The tip."
[[cursor]]
id = "Knife"
group = "Drawing and editing tools"
shown_when = ["The Knife tool: a freehand drag cuts objects along the line."]
shown_when = [
"The Knife tool: a freehand drag cuts objects along the line.",
"The Trim at Crossings Tool: a click removes the stretch of path under the pointer between its crossings, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses.",
]
hotspot = "The blade's point."
look = "A knife pointing down-left: a white blade with a straight back and a curved edge, and a black handle."
[[cursor]]
id = "Scissors"
+116 -11
View File
@@ -67,6 +67,9 @@ pub struct DimensionTool {
snap: crate::guides::DrawSnap,
/// Where the next Linear pick lands, as last worked out for the pointer (for the overlays).
snapped: Option<(Point, Option<PointRef>)>,
/// Whether the last Linear pick worked out landed on the end of a line of a dimension already
/// drawn (shown as an anchor).
on_end: bool,
/// Whether the press under way began on an anchor a Linear click picks.
press_on_anchor: bool,
/// The second point clicked for the Linear dimension being placed, and where the pointer was
@@ -199,6 +202,89 @@ fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> {
best.map(|(_, at, r)| (at, r))
}
/// Where a pick at `p` lands on the artwork of the visible, unlocked dimensions already drawn,
/// with no link to it: the nearest end of one of their lines (dimension and extension lines)
/// within the anchor reach, as an anchor (`true`); else the nearest point of one of those lines
/// within 8 pixels (`false`). The end of an extension line next to the point it measures is not
/// an end here: it lies a few points off that point. Only with Smart Guides or Snap to Point on.
/// Bounded work, and the topmost dimension wins a tie, as in [`anchor_under`].
fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> {
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveNearest};
#[derive(Default)]
struct Best {
end: Option<(f64, Point)>,
line: Option<(f64, Point)>,
}
/// `measured`: a linear dimension's measured points and how far its extension lines start
/// from them.
fn lines(n: &Node, measured: Option<([Point; 2], f64)>, p: Point, reach: [f64; 2], budget: &mut usize, best: &mut Best) {
if *budget == 0 || !n.visible || n.locked {
return;
}
if let Some(path) = n.path_data() {
// Open subpaths only: the lines, not a filled arrowhead.
for sp in path.subpaths.iter().filter(|sp| !sp.closed) {
// An extension line starts at the offset from its measured point and runs straight
// away from it; the dimension line runs across that direction. With no offset its
// start is the measured point itself, and stays an end.
let extension_start = |a: Point, b: Point| {
measured.is_some_and(|(points, offset)| {
points.iter().any(|m| {
let (out, along) = (a - *m, b - a);
offset > 1e-6 && (out.hypot() - offset).abs() <= 1e-6 && out.dot(along) >= (1.0 - 1e-6) * out.hypot() * along.hypot()
})
})
};
let (Some(first), Some(last)) = (sp.anchors.first(), sp.anchors.last()) else { continue };
let skip_first = extension_start(first.p, last.p);
for a in [first, last].into_iter().skip(usize::from(skip_first)) {
let d = a.p.distance(p);
if d <= reach[0] && best.end.is_none_or(|(near, _)| d < near) {
best.end = Some((d, a.p));
}
}
for i in 0..sp.segment_count() {
if *budget == 0 {
return;
}
*budget -= 1;
let c = sp.segment(i);
let q = c.eval(c.nearest(p, 1e-4).t);
let d = q.distance(p);
if q.x.is_finite() && q.y.is_finite() && d <= reach[1] && best.line.is_none_or(|(near, _)| d < near) {
best.line = Some((d, q));
}
}
}
}
for c in n.children().into_iter().flatten().rev() {
lines(c, measured, p, reach, budget, best);
}
}
fn visit(n: &Node, p: Point, reach: [f64; 2], budget: &mut usize, best: &mut Best) {
if *budget == 0 || !n.visible || n.locked {
return;
}
*budget -= 1;
if let Some(d) = &n.extras().dimension {
let measured = (d.mode == DimensionMode::Linear).then_some(([d.a, d.b], d.options.extension_offset));
lines(n, measured, p, reach, budget, best);
return;
}
for c in n.children().into_iter().flatten().rev() {
visit(c, p, reach, budget, best);
}
}
if !(cx.smart_guides || cx.snap_to_point) {
return None;
}
let (reach, mut budget, mut best) = ([cx.tol(ANCHOR_REACH), cx.tol(8.0)], 20_000usize, Best::default());
for n in cx.doc.layers.iter().rev() {
visit(n, p, reach, &mut budget, &mut best);
}
best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false)))
}
/// The point of `edge` closest to `p`.
fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
@@ -239,12 +325,13 @@ fn points_source(cx: &ToolContext, (a, ra): (Point, &Option<PointRef>), (b, rb):
impl DimensionTool {
/// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as
/// a link to its path); else where Smart Guides put it (another object's anchor or centre, in
/// a link to its path), labeled "anchor"; else on the nearest end of a line of a dimension
/// already drawn, within the same reach (no link), also labeled "anchor"; else where Smart Guides put it (another object's anchor or centre, in
/// line with one, or for the second point square to a segment or grazing a curve from the
/// first with Snap to Perpendicular or Snap to Tangent on, or on a construction guide through
/// a first point picked on an anchor), its guides showing; else on the closest point of the
/// line under the pointer; else `p` itself. A first point not on an anchor has no
/// construction guides through it.
/// line under the pointer, of the art or of a dimension, labeled "path"; else `p` itself. A
/// first point not on an anchor has no construction guides through it.
/// A point the guides leave where the pointer is (right on a guide line) stays there, and with
/// Snap to Pixel or Snap to Grid on a point stays where they place it.
fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option<PointRef>) {
@@ -253,15 +340,31 @@ impl DimensionTool {
None => crate::guides::Leave::contact(*first),
});
let guided = self.snap.hover(cx, p, &[], leave.as_ref());
self.on_end = false;
if let Some((point, reference)) = anchor_under(cx, p) {
self.snap.clear();
self.snap.label(point, "anchor");
return (point, Some(reference));
}
let drawn = on_dimensions(cx, p);
if let Some((q, true)) = drawn {
self.on_end = true;
self.snap.label(q, "anchor");
return (q, None);
}
if guided.distance(p) > 1e-9 || !self.snap.guides().is_empty() || cx.snap_to_pixel || cx.snap_to_grid {
return (guided, None);
}
// Not on an anchor or a guide: snap to the closest point of the line (#2432).
(pick(cx, p).and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None)
// Not on an anchor or a guide: snap to the closest point of the line (#2432), of the art
// or of a dimension already drawn.
let art = pick(cx, p).and_then(|e| nearest_on(cx, &e, p));
let line = drawn.map(|(q, _)| q);
match art.into_iter().chain(line).min_by(|a, b| a.distance(p).total_cmp(&b.distance(p))) {
Some(q) => {
self.snap.label(q, "path");
(q, None)
}
None => (p, None),
}
}
fn target(&self, cx: &ToolContext, p: Point) -> Option<Target> {
let edge = pick(cx, p)?;
@@ -384,6 +487,7 @@ impl DimensionTool {
self.pending = None;
self.press = None;
self.press_on_anchor = false;
self.on_end = false;
self.points.clear();
self.lines.clear();
self.dragging = false;
@@ -498,10 +602,11 @@ impl Tool for DimensionTool {
self.press = Some((ev.pos, None));
return self.preview(cx, ev.pos);
}
// A Linear press on an anchor picks the anchor unless it drags past the anchor's
// reach: moving a few pixels before the release does not drag out the dimension of
// a segment under the pointer.
self.press_on_anchor = self.kind == Kind::Linear && anchor_under(cx, ev.pos).is_some();
// A Linear press on an anchor, or on the end of a dimension's line, picks it unless
// it drags past the anchor's reach: moving a few pixels before the release does not
// drag out the dimension of a segment under the pointer.
self.press_on_anchor =
self.kind == Kind::Linear && (anchor_under(cx, ev.pos).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end));
self.press = Some((ev.pos, self.target(cx, ev.pos)));
vec![]
}
@@ -617,7 +722,7 @@ impl Tool for DimensionTool {
if let Some((q, reference)) = &snapped
&& (reference.is_some() || q.distance(self.at) > 1e-9)
{
let on_anchor = reference.is_some();
let on_anchor = reference.is_some() || self.on_end;
out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } });
}
if let Some((p, _)) = self.points.last() {
+11
View File
@@ -485,6 +485,17 @@ impl DrawSnap {
self.guides.clear();
}
/// Replace the guides with one label `text` at `p`, for a point a tool placed by a rule of its
/// own (an anchor or a path it found itself). The label uses the style of the targets the last
/// snap gathered. No label shows when Smart Guides or Anchor/Path Labels are off (Snap to Point
/// alone gathers targets without labels), or when the last snap gathered no targets.
pub(crate) fn label(&mut self, p: Point, text: &str) {
self.guides = match &self.targets {
Some((_, PointSnap { targets: Some((t, _)), .. })) => t.label(p, text).into_iter().collect(),
_ => vec![],
};
}
fn gather(&mut self, cx: &ToolContext, key: SnapKey) {
let snap = PointSnap::new(cx, || Targets::for_drawing(cx.doc, &key.exclude, visible(cx), key.snap_to_glyph));
self.targets = Some((Some(key), snap));
+1 -1
View File
@@ -509,7 +509,7 @@ impl Targets {
}
/// A label `text` at `p`, unless Anchor/Path Labels are off.
fn label(&self, p: Point, text: &str) -> Option<Overlay> {
pub(super) fn label(&self, p: Point, text: &str) -> Option<Overlay> {
self.style.labels.then(|| Overlay::Label { p, text: text.into(), color: self.style.color })
}
+21
View File
@@ -177,6 +177,27 @@ pub fn is_intertwine(n: &Node) -> bool {
matches!(n.kind, NodeKind::Intertwine { .. })
}
/// Why `n` can't be in an Intertwine group, if it can't: it is or holds an Intertwine group, a
/// Repeat, a graph or a Live Paint group (the help page's limits).
pub fn refused_member(n: &Node) -> Option<&'static str> {
let mut why = None;
n.walk(&mut |c| {
why = why.or(match &c.kind {
NodeKind::Intertwine { .. } => Some("an Intertwine group"),
NodeKind::Repeat(_) => Some("a Repeat"),
NodeKind::Group { .. } if c.extras().graph.is_some() => Some("a graph"),
NodeKind::Group { .. } if crate::builder::is_live_paint(c) => Some("a Live Paint group"),
_ => None,
});
});
why
}
/// Whether `id` is an Intertwine group or lies inside one.
pub fn in_intertwine(doc: &Document, id: NodeId) -> bool {
doc.ancestry(id).unwrap_or_default().iter().any(|a| doc.node(*a).is_some_and(is_intertwine))
}
// ---------- the tool ----------
/// The overlap areas of an Intertwine group, kept for the document revision they were found in.
+3 -2
View File
@@ -696,6 +696,7 @@ mod cursor_tests {
("pathEraser", Cursor::PathEraser),
("join", Cursor::Join),
("knife", Cursor::Knife),
(addons::trim::ID, Cursor::Knife),
("shaper", Cursor::Shaper),
("livePaintBucket", Cursor::LivePaintBucket),
("measure", Cursor::Measure),
@@ -713,10 +714,10 @@ mod cursor_tests {
assert_eq!(cursor_of(id), c, "{id}");
assert_eq!(c.precise(), Cursor::Crosshair, "{id}");
// The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it. The
// Live Paint Bucket's bucket is drawn.
// Live Paint Bucket's bucket and the Knife's knife are drawn.
let stand_in = match id {
"mesh" => Some(Cursor::PenAdd),
"blobBrush" | "eraser" | "livePaintBucket" => None,
"blobBrush" | "eraser" | "livePaintBucket" | "knife" | addons::trim::ID => None,
_ => Some(Cursor::Crosshair),
};
assert_eq!(c.stand_in(), stand_in, "{id}");
+35 -15
View File
@@ -206,14 +206,14 @@ enum DistanceTo {
}
/// Distance Guides: with Smart Guides and Smart Guides → Invoke Distance Guides on, something
/// selected and Alt held (`m`), the object under `p` unless it is selected, or over no object the
/// artboard `p` is on.
/// selected and Alt held (`m`), the object under `p` unless it or selected art inside it is under
/// `p` ([`selected_under`]), or over no object the artboard `p` is on.
fn distance_target(cx: &ToolContext, p: Point, m: Mods) -> Option<DistanceTo> {
if !(cx.smart_guides && cx.distance_guides && m.alt) || cx.selection.objects.is_empty() {
return None;
}
match hit_test(cx.doc, p, cx.selection_hit_options()).map(|h| h.top_object(cx.isolation)) {
Some(id) => (!cx.selection.contains(id)).then_some(DistanceTo::Object(id)),
match hit_test(cx.doc, p, cx.selection_hit_options()).map(|h| (h.top_object(cx.isolation), h)) {
Some((id, h)) => selected_under(cx, &h, id).is_none().then_some(DistanceTo::Object(id)),
None => cx.doc.artboard_at(p).map(DistanceTo::Artboard),
}
}
@@ -686,12 +686,16 @@ impl SelectionTool {
return None;
}
let reach = cx.tol(HOVER_REACH);
let under = hit_test(cx.doc, p, cx.selection_hit_options()).map(|h| h.top_object(cx.isolation));
let hit = hit_test(cx.doc, p, cx.selection_hit_options());
let under = hit.as_ref().map(|h| h.top_object(cx.isolation));
let nearest = |points: &mut dyn Iterator<Item = Point>| {
points.filter(|q| q.distance(p) <= reach).min_by(|a, b| a.distance(p).total_cmp(&b.distance(p)))
};
// A press on an unselected object selects it alone: the selected ones stay behind.
let selected = if under.is_none_or(|u| cx.selection.contains(u)) { &cx.selection.objects[..] } else { &[] };
// A press on an unselected object selects it alone: the selected ones stay behind. A press
// on selected art inside it keeps the selection, and that art is the object grabbed.
let kept = hit.as_ref().zip(under).and_then(|(h, u)| selected_under(cx, h, u));
let under = kept.or(under);
let selected = if hit.is_none() || kept.is_some() { &cx.selection.objects[..] } else { &[] };
with_object_bounds(cx, |bounds| {
under.into_iter().chain(selected.iter().copied()).find_map(|id| {
let n = cx.doc.node(id)?;
@@ -1008,10 +1012,12 @@ impl Tool for SelectionTool {
let (mut deselect, mut key, mut exclude) = (None, None, None);
if m.shift {
(deselect, exclude) = shift_press(cx, &h, top, &mut out);
} else if !cx.selection.contains(top) {
} else if let Some(picked) = selected_under(cx, &h, top) {
if (cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty()) && !m.cmd && !m.alt {
key = Some(picked);
}
} else {
out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] })));
} else if (cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty()) && !m.cmd && !m.alt {
key = Some(top);
}
// Grabbed by no anchor or centre, a press on a path's stroke or beside its
// edge holds the path there, and that point of it snaps (#3701).
@@ -1324,7 +1330,7 @@ impl Tool for SelectionTool {
return Cursor::Move;
}
if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) {
if cx.selection.contains(h.top_object(cx.isolation)) || m.alt {
if selected_under(cx, &h, h.top_object(cx.isolation)).is_some() || m.alt {
return Cursor::Move;
}
return Cursor::Arrow;
@@ -1341,16 +1347,30 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option<NodeId> {
stack.get(next).or(stack.first()).copied()
}
/// A Shift-press on `top` (hit by `h`): a Shift-click takes a selected object out of the selection
/// when it is released, and a Shift-drag moves the selection, constrained. On an object of the
/// The selected object a press on `h` lands on: `top` when it is selected, else the outermost
/// object selected whole between it and the art under the pointer, such as members of a group
/// picked with Group Selection. A press there keeps the selection and a drag moves it (#8047). A
/// member with only some anchors or segments selected does not count: the press selects `top`.
fn selected_under(cx: &ToolContext, h: &Hit, top: NodeId) -> Option<NodeId> {
if cx.selection.contains(top) {
return Some(top);
}
let whole = |id: NodeId| cx.selection.contains(id) && cx.selection.partial(id).is_none() && !cx.selection.segments.contains_key(&id);
let below = h.ancestry.iter().position(|id| *id == top).map_or(&[][..], |i| h.ancestry.get(i..).unwrap_or_default());
below.iter().copied().chain(std::iter::once(h.leaf)).find(|id| whole(*id))
}
/// A Shift-press on `top` (hit by `h`): a Shift-click takes a selected object, or the selected art
/// inside it that the press lands on ([`selected_under`]), out of the selection when it is
/// released, and a Shift-drag moves the selection, constrained. On an object of the
/// Global Edit that is highlighted, the release leaves that object out of the edit instead, and a
/// drag selects `top` when it starts. Returns the object to deselect and the object to leave out
/// on release (with `top`); adds to `out` the action that selects `top` at once.
fn shift_press(cx: &ToolContext, h: &Hit, top: NodeId, out: &mut Vec<Action>) -> (Option<NodeId>, Option<(NodeId, NodeId)>) {
if let Some(member) = global_edit_member(cx, h) {
(None, Some((member, top)))
} else if cx.selection.contains(top) {
(Some(top), None)
} else if let Some(picked) = selected_under(cx, h, top) {
(Some(picked), None)
} else {
out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 })));
(None, None)
+61
View File
@@ -2665,3 +2665,64 @@ fn outline_view_marquees_measure_a_clip_group_by_its_plain_clipping_path() {
assert_eq!(marquee(true), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]);
assert_eq!(marquee(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]);
}
/// Objects selected inside a group (with Group Selection, say) stay selected when the Selection
/// tool presses on one of them: the press shows the move pointer and a drag moves only them, not
/// the group around them. A press on a member that is not selected still selects the whole group.
#[test]
fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
use vectorcraft_doc::{Appearance, Document, Node};
use vectorcraft_geom::shapes;
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let (outer, inner, a, b, c) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
let path = |id: NodeId, x: f64| Node::path(id, shapes::rectangle(Rect::new(x, 100.0, x + 50.0, 150.0)), Appearance::default_art());
d.insert(Some(l), 0, Node::group(outer, vec![])).unwrap();
d.insert(Some(outer), 0, Node::group(inner, vec![])).unwrap();
d.insert(Some(inner), 0, path(a, 100.0)).unwrap();
d.insert(Some(inner), 1, path(b, 200.0)).unwrap();
d.insert(Some(outer), 1, path(c, 300.0)).unwrap();
let p = paint();
let is_select = |out: &[Action]| out.iter().any(|a| matches!(a, Action::Exec(id, _) if id.starts_with("select.")));
for picked in [vec![a], vec![a, b], vec![inner]] {
let mut s = Selection::default();
s.set(picked.iter().copied());
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "{picked:?}");
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "{picked:?}: {down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 125.0));
assert!(drag.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "object.transform")), "{picked:?}: {drag:?}");
// Shift: a drag moves the selected members, constrained, and a click takes the member
// pressed (or the selected group holding it) out of the selection, not the outer group.
let shift = |kind, x, y| ev(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() });
let mut t = SelectionTool::default();
let down = t.pointer(&c, &shift(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "Shift, {picked:?}: {down:?}");
let drag = t.pointer(&c, &shift(PointerKind::Drag, 145.0, 125.0));
assert!(drag.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "object.transform")), "Shift, {picked:?}: {drag:?}");
let mut t = SelectionTool::default();
t.pointer(&c, &shift(PointerKind::Down, 125.0, 125.0));
let up = t.pointer(&c, &shift(PointerKind::Up, 125.0, 125.0));
assert_eq!(up, vec![Action::Exec("select.toggle".into(), json!({"id": picked[0].0}))], "Shift-click, {picked:?}");
// Alt over a selected member measures no Distance Guides to the group holding it.
let mut t = SelectionTool::default();
t.pointer(&c, &alt(PointerKind::Move, 125.0, 125.0));
assert!(distances(&t, &c).0.is_empty(), "Alt over a selected member, {picked:?}");
}
// A member that is not selected: the press selects the outermost group.
let mut s = Selection::default();
s.set([a]);
let c = cx(&d, &s, &p);
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 325.0, 125.0));
assert_eq!(down, vec![Action::Exec("select.set".into(), json!({"ids": [outer.0]}))]);
// A member with only some anchors selected (a Direct Selection marquee) is not selected whole:
// the press selects the outermost group, as before.
let mut s = Selection::default();
s.set([a]);
s.anchors.insert(a, [(0, 0)].into_iter().collect());
let c = cx(&d, &s, &p);
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert_eq!(down, vec![Action::Exec("select.set".into(), json!({"ids": [outer.0]}))]);
}
+87 -23
View File
@@ -17,6 +17,9 @@
//! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into
//! the open dialog (`brushKeyColor` UI request) and switches back.
//!
//! Escape ends an armed pick without sampling and switches back to that tool. With no pick
//! armed, Escape is left to the application.
//!
//! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which
//! samples the original image pixels; this tool changes neither paint nor selection.
@@ -508,23 +511,6 @@ impl Tool for EyedropperTool {
out
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key != ToolKey::Escape {
return vec![];
}
let Some(binding) = self.image_trace_ignore_color.take() else { return vec![] };
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)]
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
self.image_trace_ignore_color.is_some() && key == ToolKey::Escape
}
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
self.image_trace_ignore_color.is_some()
}
/// Expose a transient text range alongside gradient-stop and brush-key sampling state.
fn options(&self) -> Value {
let selected = self.text_selection.options();
@@ -563,6 +549,41 @@ impl Tool for EyedropperTool {
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
Cursor::Eyedropper
}
/// Escape ends the armed pick without sampling; Image Trace receives its cancellation reply.
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key != ToolKey::Escape || !self.picking() {
return vec![];
}
if let Some(binding) = self.image_trace_ignore_color.take() {
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)];
}
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
self.brush_key_color = false;
vec![Action::SwitchTool(back)]
}
/// A dropped press (a long or canceled touch) leaves an armed pick waiting for its click.
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
vec![]
}
/// Escape is the tool's while a pick is armed, so it switches back and ends nothing else.
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
key == ToolKey::Escape && self.picking()
}
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
self.picking()
}
}
impl EyedropperTool {
/// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed?
fn picking(&self) -> bool {
self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some()
}
}
#[cfg(test)]
@@ -652,6 +673,41 @@ mod tests {
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only");
}
/// #8024: Escape ends a gradient stop's pick and a Key Color pick without sampling and
/// switches back; the plain Eyedropper leaves Escape alone.
#[test]
fn escape_ends_a_pick_and_switches_back() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let mut cx = cx(&d, &s, &p);
cx.gradient_stop = Some(1);
let none = Mods::default();
let mut t = EyedropperTool::default();
assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx), "nothing armed");
assert!(t.key(&cx, ToolKey::Escape, none).is_empty());
t.set_option("stop", &json!("gradient"));
assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx));
assert!(!t.claims_key(&cx, ToolKey::Enter));
assert!(t.drop_press(&cx).is_empty(), "a dropped press leaves the pick armed");
assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("gradient".into())]);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
assert!(!t.claims_key(&cx, ToolKey::Escape) && t.key(&cx, ToolKey::Escape, none).is_empty(), "one cancel only");
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0));
assert!(!a.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("stop").is_some())), "no stop sample after the cancel: {a:?}");
t.set_option("brushKeyColor", &json!(true));
t.set_option("stop", &json!("paintbrush"));
assert!(t.claims_key(&cx, ToolKey::Escape));
assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("paintbrush".into())]);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
// A Key Color pick with no tool to return to goes back to the Selection tool.
t.set_option("brushKeyColor", &json!(true));
assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("selection".into())]);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
}
#[test]
fn brush_key_color_samples_into_the_dialog_then_switches_back() {
let (d, _) = doc_with_rect();
@@ -669,7 +725,6 @@ mod tests {
assert_eq!(t.options(), json!({ "stop": null, "brushKeyColor": false }));
}
/// The panel samples the bound original raster, even on empty canvas or with modifiers held.
#[test]
fn image_trace_sampling_forwards_its_binding_and_document_point_once() {
let (d, id) = doc_with_rect();
@@ -697,7 +752,6 @@ mod tests {
}
}
/// Escape's UI request is claimed only while this one-shot target is armed.
#[test]
fn image_trace_escape_cancels_its_binding_and_restores_the_tool_once() {
let (d, id) = doc_with_rect();
@@ -715,6 +769,8 @@ mod tests {
assert!(!t.claims_key(&cx, ToolKey::Enter));
assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
assert_eq!(t.options()["imageTraceIgnoreColor"], binding);
assert!(t.drop_press(&cx).is_empty(), "a dropped press leaves this pick waiting too");
assert_eq!(t.options()["imageTraceIgnoreColor"], binding);
assert_eq!(
t.key(&cx, ToolKey::Escape, Mods::default()),
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())]
@@ -723,9 +779,16 @@ mod tests {
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
// A binding without a saved tool still claims its one Escape and returns to Selection.
t.set_option("imageTraceIgnoreColor", &binding);
assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx));
assert_eq!(
t.key(&cx, ToolKey::Escape, Mods::default()),
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())]
);
assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx));
}
/// A cleared Image Trace request leaves the existing brush/stop options and keys alone.
#[test]
fn clearing_image_trace_sampling_preserves_existing_brush_and_stop_options() {
let (d, _) = doc_with_rect();
@@ -738,9 +801,10 @@ mod tests {
t.set_option("imageTraceIgnoreColor", &json!({"doc": 7, "target": 8, "revision": 11}));
t.set_option("imageTraceIgnoreColor", &Value::Null);
assert_eq!(t.options(), original);
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
// Clearing Trace leaves the ordinary Brush pick armed, including its upstream Escape.
assert!(t.claims_key(&cx, ToolKey::Escape));
assert!(t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
assert_eq!(t.options(), original);
assert_eq!(
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)),
+23 -10
View File
@@ -4,8 +4,9 @@
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each
//! with a Select button; the list is kept until the document changes.
//! with a Select button; each document's list is kept until that document changes.
use std::collections::HashMap;
use std::sync::{Arc, Weak};
use egui::{Align, Layout, Sense, Ui, vec2};
@@ -31,7 +32,7 @@ pub const ROLES: &[(&str, &str)] =
/// Where the panel keeps the last `addon.packaging.roles` answer (panel state).
const STATE: &str = "fold-lines";
/// Where the panel keeps the last check (panel state).
/// Where the panel keeps the last check of each document (panel state, a [`Checks`]).
const CHECKED: &str = "fold-lines-check";
/// Object › Plug-ins › Packaging Tools.
@@ -103,6 +104,10 @@ impl Checked {
}
}
/// The last check of each document, by the document's id. The checks are shared, so reading the
/// map for a frame copies no issue lists.
type Checks = HashMap<u64, Arc<Checked>>;
/// The active document's [`DocKey`].
fn doc_key(app: &VectorcraftApp) -> Option<DocKey> {
app.session.active().map(|st| (st.uid, Arc::downgrade(&st.doc)))
@@ -110,11 +115,17 @@ fn doc_key(app: &VectorcraftApp) -> Option<DocKey> {
/// Runs `addon.packaging.check` with `p` and shows its summary in the status bar → the check, kept
/// in `ctx` for the panel.
fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option<Checked> {
fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option<Arc<Checked>> {
let r = app.run(CHECK, p).map_err(|e| app.status(e)).ok()?;
let checked = Checked::of(doc_key(app)?, &r);
let key = doc_key(app)?;
let uid = key.0;
let checked = Arc::new(Checked::of(key, &r));
app.status(checked.summary());
set_pstate(ctx, CHECKED, checked.clone());
let mut checks: Checks = pstate(ctx, CHECKED);
// A check of a document that has since changed or closed can never be shown again.
checks.retain(|_, c| c.key.as_ref().is_some_and(|(_, doc)| doc.strong_count() > 0));
checks.insert(uid, Arc::clone(&checked));
set_pstate(ctx, CHECKED, checks);
Some(checked)
}
@@ -130,11 +141,13 @@ pub(crate) fn check(app: &mut VectorcraftApp, p: Value) {
}
/// The last check of the active document, while the document has not changed since.
fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option<Checked> {
let checked: Checked = pstate(ctx, CHECKED);
let same = match (&checked.key, doc_key(app)) {
(Some((uid, doc)), Some((now, current))) => *uid == now && doc.ptr_eq(&current),
_ => false,
fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option<Arc<Checked>> {
let (now, current) = doc_key(app)?;
let mut checks: Checks = pstate(ctx, CHECKED);
let checked = checks.remove(&now)?;
let same = match &checked.key {
Some((uid, doc)) => *uid == now && doc.ptr_eq(&current),
None => false,
};
same.then_some(checked)
}
@@ -212,6 +212,28 @@ fn the_check_button_checks_and_clicking_an_issue_selects_its_lines() {
assert!(text.contains("No issues found.") && text.contains("Panels: 2, hinges: 1, errors: 0, warnings: 0"), "{text}");
}
#[test]
fn each_document_keeps_its_own_check() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, _) = blank();
let ctx = egui::Context::default();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
// A second document, checked too: it has no cut lines.
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("No cut lines are in the document.") && !text.contains("A cut line ends"), "{text}");
// Back on the first document, unchanged since its check: its issues are still listed.
assert!(app.session.set_active(0));
let text = frames(&mut app, &ctx, None);
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
assert!(text.contains("Panels: 2, hinges: 1, errors: 1, warnings: 0"), "{text}");
// And the second document's check stays its own.
assert!(app.session.set_active(1));
let text = frames(&mut app, &ctx, None);
assert!(text.contains("No cut lines are in the document.") && !text.contains("A cut line ends"), "{text}");
}
#[test]
fn issues_and_the_summary_show_in_the_interface_language() {
let (mut app, _) = blank();
@@ -25,6 +25,7 @@ fn the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector() {
("Trim at Crossings Tool", "trimAtCrossings"),
] {
let e = under(label).expect(label);
assert_eq!(vectorcraft_tools::tool_info(tool).map(|t| t.label), Some(label), "the toolbar's label");
assert_eq!((e.command.as_deref(), &e.params), (Some("tool.select"), &json!({ "tool": tool })));
menus::invoke(&mut app, "tool.select", e.params.clone());
assert_eq!(app.session.tool_id(), tool);
+2 -1
View File
@@ -127,6 +127,8 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
// The system has no tip outline to go round: its crosshair aims as well.
Cursor::BlobBrush | Cursor::Eraser => C::Crosshair,
Cursor::LivePaintBucket | Cursor::LivePaintBucketFace | Cursor::LivePaintBucketEdge => C::Crosshair,
// The system has no knife: its crosshair aims at the blade's point.
Cursor::Knife => C::Crosshair,
// Not drawn yet: the cursor each borrows.
Cursor::Lasso
| Cursor::MagicWand
@@ -135,7 +137,6 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
| Cursor::Smooth
| Cursor::PathEraser
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::Measure
| Cursor::PrintTiling
+18
View File
@@ -468,6 +468,23 @@ fn paint_brush(p: &mut Ink, o: Pos2) {
}
}
/// The Knife and the Trim at Crossings Tool: a knife, the blade's point on the hotspot, the white
/// blade with its straight back and curved edge, then the black handle running up-right.
fn knife(p: &mut Ink, o: Pos2) {
let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized());
let at = |u: f32, v: f32| o + u * d + v * n;
let blade = vec![at(0.0, 0.0), at(11.0, -2.5), at(11.0, 3.0), at(6.0, 2.8), at(2.5, 1.6)];
let handle = vec![at(11.0, -2.0), at(20.0, -1.8), at(21.0, 0.2), at(20.0, 2.2), at(11.0, 2.5)];
// Both halos first, so neither covers the other's outline.
for part in [&blade, &handle] {
p.add(Shape::closed_line(part.clone(), Stroke::new(3.0, HALO)));
}
for (part, fill) in [(blade, HALO), (handle, INK)] {
p.add(Shape::convex_polygon(part.clone(), fill, Stroke::NONE));
p.add(Shape::closed_line(part, Stroke::new(1.0, INK)));
}
}
/// Live Paint Selection: the solid arrow with a badge at its lower right saying what a click
/// selects: a filled square over a face ([`Cursor::LivePaintSelectFace`]), a short line between two
/// anchor marks over an edge ([`Cursor::LivePaintSelectEdge`]), an x where it selects nothing.
@@ -732,6 +749,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Cursor::LivePaintBucket => paint_bucket(ink, p, false),
Cursor::LivePaintBucketFace => paint_bucket(ink, p, true),
Cursor::LivePaintBucketEdge => paint_brush(ink, p),
Cursor::Knife => knife(ink, p),
Cursor::LivePaintSelectFace | Cursor::LivePaintSelectEdge | Cursor::LivePaintSelectOutside => live_paint_select(ink, p, c),
Cursor::Hand => hand(ink, p, false),
Cursor::HandGrab => hand(ink, p, true),
+28
View File
@@ -336,6 +336,34 @@ fn the_live_paint_bucket_shows_a_bucket_or_a_brush() {
}
}
/// The Knife's cursor, which the Trim at Crossings Tool shows too, is drawn, not the crosshair: a
/// knife with the blade's point on the hotspot, the white blade, then the black handle up-right.
#[test]
fn the_knife_shows_a_knife_with_its_point_on_the_hotspot() {
for ppp in [1.0f32, 2.0] {
let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let (cross, knife, brush) = (img(Cursor::Crosshair), img(Cursor::Knife), img(Cursor::LivePaintBucketEdge));
// The pixel nearest the point `u` points up-right of the hotspot and `v` down-right across.
let at = |img: &CustomCursorImage, u: f32, v: f32| {
let s = std::f32::consts::FRAC_1_SQRT_2;
let [hx, hy] = img.hotspot.map(f32::from);
let (x, y) = ((hx + (u + v) * s * ppp - 0.5).round(), (hy + (v - u) * s * ppp - 0.5).round());
let inside = x >= 0.0 && y >= 0.0 && x < f32::from(img.size[0]) && y < f32::from(img.size[1]);
if inside { pixel(img, x as usize, y as usize) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
let white = |p: [u8; 4]| p[3] > 200 && p[0] > 192;
assert!(at(&knife, 0.0, 0.0)[3] > 0, "the point covers the hotspot at {ppp}");
assert!(white(at(&knife, 8.0, 0.5)), "the white blade at {ppp}");
assert!(inked(at(&knife, 16.0, 0.2)), "the black handle at {ppp}");
assert!(!inked(at(&knife, -4.0, 0.0)), "nothing beyond the point at {ppp}");
assert!(Cursor::Knife.stand_in().is_none(), "the Knife is drawn");
assert_ne!(knife, cross, "the Knife is not the crosshair at {ppp}");
assert_ne!(knife, brush, "the Knife is not the Live Paint brush at {ppp}");
assert_eq!(rasterize(Cursor::Knife.precise(), ppp).as_ref(), Some(&cross), "with Use Precise Cursors at {ppp}");
}
}
/// Live Paint Selection's cursors are the solid arrow, its tip on the hotspot, with a badge at its
/// lower right: a filled square over a face, a line between two anchor marks over an edge, and an x
/// where a click selects nothing.
+6
View File
@@ -704,6 +704,12 @@ pub fn cancel(app: &mut VectorcraftApp) {
script_run::notice_cancel(app, &d);
}
missing_links::cancelled(app, &d);
// Find Font's next open starts with an empty replacement search.
if d.kind == "findFont"
&& let Some(ctx) = app.ui_ctx.clone()
{
crate::find_font::clear_search(&ctx);
}
// Toolbar-only Flare options start no preview and must not cancel a gesture
// that was already active before opening them. The generic parameter dialog has a spec
// without a preview, yet previews some commands (Grid Repeat Options) when asked to.
@@ -204,6 +204,27 @@ fn brush_key_color_eyedropper_updates_the_open_dialog() {
assert_eq!(app.session.tool_id(), back);
}
/// #8024: the first Escape ends the Key Color pick and returns to the tool that armed it, leaving
/// Brush Options open with its Key Color; a new press then cancels the dialog.
#[test]
fn escape_ends_the_key_color_pick_and_leaves_brush_options_open() {
let (mut app, ctx) = (app(), ctx());
app.select_tool("paintbrush");
app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap();
set(&mut app, json!({"colorization": "hueShift"}));
let before = app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned());
app.select_tool("eyedropper");
app.session.set_tool_option("brushKeyColor", &json!(true));
app.session.set_tool_option("stop", &json!("paintbrush"));
frame(&ctx, &mut app, vec![], "");
escape(&ctx, &mut app);
assert!(app.ui.dialog.is_some(), "Brush Options stays open");
assert_eq!(app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned()), before, "the Key Color stays");
assert_eq!(app.session.tool_id(), "paintbrush");
escape(&ctx, &mut app);
assert!(app.ui.dialog.is_none(), "a new press cancels Brush Options");
}
#[test]
fn art_options_set_width_scale_direction_flips_and_colorization() {
let mut app = app();
+51 -4
View File
@@ -629,8 +629,56 @@ fn drop_targets_follow_the_buttons_edges() {
assert_eq!(drop_target(&[], pos2(0.0, 0.0), 1), (None, Place::Before));
}
/// The add-ons' tools are in neither toolbar as they ship: the drawer lists them under their
/// add-on's heading, and they can be added from there.
/// The Trim at Crossings Tool is in the Scissors tool's flyout in both toolbars, after the Knife,
/// once in the All Tools drawer and in Keyboard Shortcuts' list, with no shortcut; Reset Toolbar
/// keeps it there.
#[test]
fn trim_at_crossings_is_in_the_scissors_flyout() {
let mut app = app();
let trim = vectorcraft_tools::addons::trim::ID;
for advanced in [false, true] {
if advanced {
app.run("window.toolbarAdvanced", json!({})).unwrap();
}
let s = slots(&app);
let slot = slot_of(&app, "scissors").map(|i| s[i].clone()).expect("a Scissors slot");
let knife = slot.iter().position(|id| *id == "knife").expect("the Knife beside the Scissors");
assert_eq!(slot.get(knife + 1), Some(&trim), "advanced: {advanced}");
assert_eq!(s.iter().filter(|ids| ids.contains(&trim)).count(), 1, "advanced: {advanced}");
}
assert_eq!(sections().iter().flat_map(|(_, tools)| tools.iter()).filter(|t| t.id == trim).count(), 1, "listed once in the drawer");
assert_eq!(vectorcraft_tools::catalog::all_tools().filter(|t| t.id == trim).count(), 1, "listed once for Keyboard Shortcuts");
assert_eq!(vectorcraft_tools::tool_info(trim).map(|t| (t.label, t.shortcut)), Some(("Trim at Crossings Tool", None)));
app.run("tool.select", json!({"tool": trim})).unwrap();
assert_eq!(app.session.tool_id(), trim);
let shown = slot_of(&app, trim).map(|i| crate::toolbar::shown_tool(&app, &slots(&app)[i]));
assert_eq!(shown, Some(trim), "the slot's button shows the tool once chosen");
app.run("toolbar.removeTool", json!({"tool": trim})).unwrap();
assert!(slot_of(&app, trim).is_none(), "it can be taken out");
app.run("toolbar.reset", json!({})).unwrap();
let after_reset = slot_of(&app, "scissors").map(|i| slots(&app)[i].contains(&trim));
assert_eq!(after_reset, Some(true), "Reset Toolbar puts it back");
}
/// A toolbar edited and saved before the Trim at Crossings Tool joined the Scissors group keeps
/// its saved layout: the tool stays in the drawer until Reset Toolbar or a drag adds it.
#[test]
fn a_saved_toolbar_without_trim_at_crossings_keeps_its_layout() {
let mut app = app();
let trim = vectorcraft_tools::addons::trim::ID;
let saved = ToolbarCategory { name: Some("Draw".into()), slots: vec![["eraser", "scissors", "knife"].iter().map(|id| id.to_string()).collect()] };
app.ui.toolbar_edits = ToolbarEdits { basic: Some(vec![saved]), advanced: None };
app.ui = std::mem::take(&mut app.ui).sanitized();
assert_eq!(slots(&app), [["eraser", "scissors", "knife"]]);
assert!(slot_of(&app, trim).is_none());
app.run("toolbar.reset", json!({})).unwrap();
let slot = slot_of(&app, "scissors").map(|i| slots(&app)[i].clone());
assert!(slot.is_some_and(|s| s.contains(&trim)), "Reset Toolbar adds it");
}
/// The add-ons' tools are in neither toolbar as they ship (the Trim at Crossings Tool, in the
/// Scissors tool's group, aside): the drawer lists them under their add-on's heading, and they can
/// be added from there.
#[test]
fn addon_tools_are_in_the_drawer_not_the_toolbars() {
let mut app = app();
@@ -649,7 +697,6 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
"cornerTool",
"slideAnchor",
"sharedEdge",
"trimAtCrossings",
"smartPen",
enclosing,
contour,
@@ -666,7 +713,7 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
let listed = |id: &str| {
sections().iter().find(|(_, tools)| tools.iter().any(|t| t.id == id)).map(|(h, tools)| (*h, tools.iter().map(|t| t.id).collect::<Vec<_>>()))
};
assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..8].to_vec())));
assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec())));
assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"])));
assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing])));
assert_eq!(listed(contour), Some(("Contour", vec![contour])));
+153 -5
View File
@@ -261,7 +261,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result<Value, String> {
}
/// Forget the replacement search: the next open starts with an empty one.
fn clear_search(ctx: &egui::Context) {
pub(crate) fn clear_search(ctx: &egui::Context) {
let (source_key, query_id) = (egui::Id::unique("ff-search-source"), egui::Id::unique("ff-search"));
ctx.data_mut(|m| {
m.remove::<String>(source_key);
@@ -286,6 +286,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let mut close = false;
let mut find_in_folder = false;
let mut act: Option<&str> = None;
// Escape over an open dropdown list closes only the list, which closes itself while it is drawn.
let popup_open = egui::Popup::is_any_open(ctx);
// The replacement-font search, kept in egui memory: cleared when the dialog closes, and when
// the source changes.
let source_key = egui::Id::unique("ff-search-source");
@@ -421,16 +423,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
Err(e) => app.ui.status = e,
}
}
if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if close || (!popup_open && crate::shortcuts::pressed_anew(ctx, egui::Key::Escape)) {
app.ui.dialog = None;
// The next open starts with an empty search.
clear_search(ctx);
} else if app.ui.dialog.is_some() {
app.ui.dialog = Some(d);
}
// Missing Fonts takes the dialog's place, searching the folder picked.
if find_in_folder && let Err(e) = app.run("ui.findFontsInFolder", json!({})) {
app.ui.status = e;
// Missing Fonts takes the dialog's place, searching the folder picked; the next Find Font
// starts with an empty search.
if find_in_folder {
match app.run("ui.findFontsInFolder", json!({})) {
Ok(_) => clear_search(ctx),
Err(e) => app.ui.status = e,
}
}
}
@@ -1012,6 +1018,148 @@ mod tests {
assert_eq!(ctx.data(|m| m.get_temp::<String>(source_id)), None, "the source it was typed under is gone");
}
/// A context with the app's fonts and theme that the app knows as its own, for [`app_frame`].
fn app_ctx(app: &mut VectorcraftApp) -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx, Default::default());
app.ui_ctx = Some(ctx.clone());
ctx
}
/// One 1200 × 900 frame with `events` through the app's key handling and then the dialogs, as
/// the app runs them; the center of the text `label` if the frame shows it.
fn app_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, label: &str) -> Option<egui::Pos2> {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0));
let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
crate::shortcuts::handle(app, ui.ctx());
crate::dialogs::show(app, ui.ctx());
});
out.textures_delta.clear();
out.shapes.iter().find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == label => Some(egui::Rect::from_min_size(t.pos, t.galley.size()).center()),
_ => None,
})
}
/// Clicks the text `label` through [`app_frame`].
fn app_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) {
app_frame(ctx, app, vec![], label);
let at = app_frame(ctx, app, vec![], label).unwrap_or_else(|| panic!("no {label:?} shown"));
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
app_frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true)], label);
app_frame(ctx, app, vec![button(false)], label);
app_frame(ctx, app, vec![], label);
}
/// An Escape key event: pressed, or let go.
fn escape_key(pressed: bool, repeat: bool) -> egui::Event {
egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat, modifiers: Default::default() }
}
/// Presses and lets go of Escape through [`app_frame`].
fn app_escape(ctx: &egui::Context, app: &mut VectorcraftApp) {
app_frame(ctx, app, vec![escape_key(true, false)], "");
app_frame(ctx, app, vec![escape_key(false, false)], "");
}
/// Types `query` into the replacement search under the dialog's source, as the search field
/// keeps it.
fn seed_search(ctx: &egui::Context, app: &VectorcraftApp, query: &str) {
let source = app.ui.dialog.as_ref().expect("Find Font is open").str("replaceFrom");
ctx.data_mut(|m| {
m.insert_temp(egui::Id::unique("ff-search-source"), source);
m.insert_temp(egui::Id::unique("ff-search"), query.to_string());
});
}
/// The replacement search and the source it was typed under, as egui memory keeps them.
fn search_state(ctx: &egui::Context) -> (Option<String>, Option<String>) {
ctx.data(|m| (m.get_temp::<String>(egui::Id::unique("ff-search")), m.get_temp::<String>(egui::Id::unique("ff-search-source"))))
}
/// Escape with Replace With Font From's or Find In's list open closes only the list: Find Font
/// stays open with its source and its search, holding Escape down leaves it open, and the next
/// press closes it and forgets the search.
#[test]
fn escape_over_an_open_dropdown_closes_only_the_dropdown() {
for current in ["System", "Document"] {
let mut app = two_font_document();
let ctx = app_ctx(&mut app);
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
seed_search(&ctx, &app, "inter");
app_click(&ctx, &mut app, current);
assert!(egui::Popup::is_any_open(&ctx), "{current}: the list is open");
app_frame(&ctx, &mut app, vec![escape_key(true, false)], "");
for _ in 0..3 {
app_frame(&ctx, &mut app, vec![escape_key(true, true)], "");
}
app_frame(&ctx, &mut app, vec![escape_key(false, false)], "");
assert!(!egui::Popup::is_any_open(&ctx), "{current}: Escape closes the list");
let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{current}: Find Font stays open"));
assert_eq!((d.kind.as_str(), d.str("replaceFrom"), d.str("findIn")), ("findFont", "system".into(), "document".into()), "{current}");
assert_eq!(search_state(&ctx), (Some("inter".into()), Some("system".into())), "{current}: the search is kept");
app_escape(&ctx, &mut app);
assert!(app.ui.dialog.is_none(), "{current}: the next Escape closes Find Font");
assert_eq!(search_state(&ctx), (None, None), "{current}: closing forgets the search");
}
}
/// Escape and Done, through the app's key handling, each close Find Font and forget the
/// replacement search and its source.
#[test]
fn escape_and_done_through_the_app_clear_the_replacement_search() {
for how in ["Escape", "Done"] {
let mut app = two_font_document();
let ctx = app_ctx(&mut app);
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
seed_search(&ctx, &app, "inter");
if how == "Escape" {
app_escape(&ctx, &mut app);
} else {
app_click(&ctx, &mut app, "Done");
}
assert!(app.ui.dialog.is_none(), "{how} closes Find Font");
assert_eq!(search_state(&ctx), (None, None), "{how} forgets the search");
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
assert_eq!(search_state(&ctx), (Some(String::new()), Some("system".into())), "{how}: the next open starts with an empty search");
}
}
/// Find in Folder… that opens Missing Fonts forgets Find Font's search; with no folder picked,
/// Find Font stays open with its search.
#[test]
fn find_in_folder_forgets_the_search_once_missing_fonts_opens() {
let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder-search")).unwrap();
for picks in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.search_rules = Some(vectorcraft_engine::cmd::findfiles::Rules { user_content: vec![dir.clone()], ..Default::default() });
app.session.search_threads = Some(1);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
let picked = picks.then(|| dir.to_string_lossy().into_owned());
app.services.pick_folder = Some(Box::new(move || picked.clone()));
let ctx = app_ctx(&mut app);
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
seed_search(&ctx, &app, "inter");
app_click(&ctx, &mut app, "Find in Folder…");
let kind = app.ui.dialog.as_ref().map(|d| d.kind.clone());
if picks {
assert_eq!(kind.as_deref(), Some(crate::dialogs::missing_fonts::KIND), "Missing Fonts takes Find Font's place");
assert_eq!(search_state(&ctx), (None, None), "the search is forgotten");
crate::dialogs::cancel(&mut app);
} else {
assert_eq!(kind.as_deref(), Some("findFont"), "with no folder picked, Find Font stays open");
assert_eq!(search_state(&ctx), (Some("inter".into()), Some("system".into())), "and keeps its search");
}
}
}
/// The wheel over the rows scrolls them, and leaves the document's font list where it was: two
/// lists, two scrollbars.
#[test]
+89 -33
View File
@@ -467,29 +467,30 @@ fn footer(listed: usize, total: usize) -> String {
}
}
/// How many times each key that moves the highlighted result was pressed this frame.
/// The keys that move the highlighted result, in the order they were pressed this frame.
#[derive(Default)]
struct Moves {
down: usize,
up: usize,
page_down: usize,
page_up: usize,
}
struct Moves(Vec<egui::Key>);
impl Moves {
/// The keys that move the highlighted result.
const KEYS: [egui::Key; 4] = [egui::Key::ArrowDown, egui::Key::ArrowUp, egui::Key::PageDown, egui::Key::PageUp];
fn any(&self) -> bool {
self.down + self.up + self.page_down + self.page_up > 0
!self.0.is_empty()
}
/// The highlighted result of `n` after these moves from `sel`, a page being `page` rows: Up and
/// Down wrap at the ends, Page Up and Page Down stop at them.
/// The highlighted result of `n` after these moves from `sel`, taken in the order they were
/// pressed, a page being `page` rows: Up and Down wrap at the ends, Page Up and Page Down stop
/// at them.
fn apply(&self, sel: usize, n: usize, page: usize) -> usize {
let Some(last) = n.checked_sub(1) else { return 0 };
let sel = sel.min(last);
let sel = (sel + self.down % n) % n;
let sel = (sel + n - self.up % n) % n;
let sel = sel.saturating_add(page.saturating_mul(self.page_down)).min(last);
sel.saturating_sub(page.saturating_mul(self.page_up))
self.0.iter().fold(sel.min(last), |sel, key| match key {
egui::Key::ArrowDown => (sel + 1) % n,
egui::Key::ArrowUp => (sel + last) % n,
egui::Key::PageDown => sel.saturating_add(page).min(last),
egui::Key::PageUp => sel.saturating_sub(page),
_ => sel,
})
}
}
@@ -655,13 +656,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let mut moves = Moves::default();
if n > 0 && !list_open {
ctx.input_mut(|i| {
let mut key = |k| i.count_and_consume_key(egui::Modifiers::NONE, k);
moves = Moves {
down: key(egui::Key::ArrowDown),
up: key(egui::Key::ArrowUp),
page_down: key(egui::Key::PageDown),
page_up: key(egui::Key::PageUp),
};
i.events.retain(|e| match e {
egui::Event::Key { key, pressed: true, modifiers, .. }
if Moves::KEYS.contains(key) && modifiers.matches_logically(egui::Modifiers::NONE) =>
{
moves.0.push(*key);
false
}
_ => true,
});
});
}
let screen = ctx.content_rect();
@@ -778,9 +781,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
});
let before = offset;
offset = out.state.clamped_offset().y;
// After a scroll with the wheel or the scroll bar, the highlight moves to the
// nearest row in view, so Enter runs a result that can be seen.
if !new_query && !moves.any() && (offset - before).abs() > 0.5 {
// After a scroll with the wheel or the scroll bar, by any amount, the highlight
// moves to the nearest row in view, so Enter runs a result that can be seen.
if !new_query && !moves.any() && (offset - before).abs() > 0.0 {
sel = nearest_in_view(sel, offset, view, n);
}
});
@@ -2044,14 +2047,17 @@ mod tests {
/// Down wrap.
#[test]
fn page_keys_move_by_a_page_without_wrapping() {
let moves = |down, up, page_down, page_up| Moves { down, up, page_down, page_up };
assert_eq!(moves(0, 0, 1, 0).apply(0, 50, 12), 12);
assert_eq!(moves(0, 0, 1, 0).apply(45, 50, 12), 49);
assert_eq!(moves(0, 0, 0, 1).apply(5, 50, 12), 0);
assert_eq!(moves(1, 0, 0, 0).apply(49, 50, 12), 0);
assert_eq!(moves(0, 1, 0, 0).apply(0, 50, 12), 49);
assert_eq!(moves(3, 0, 0, 0).apply(48, 50, 12), 1);
assert_eq!(moves(1, 0, 0, 0).apply(0, 0, 12), 0);
use egui::Key::{ArrowDown, ArrowUp, PageDown, PageUp};
let moves = |keys: &[egui::Key]| Moves(keys.to_vec());
assert_eq!(moves(&[PageDown]).apply(0, 50, 12), 12);
assert_eq!(moves(&[PageDown]).apply(45, 50, 12), 49);
assert_eq!(moves(&[PageUp]).apply(5, 50, 12), 0);
assert_eq!(moves(&[ArrowDown]).apply(49, 50, 12), 0);
assert_eq!(moves(&[ArrowUp]).apply(0, 50, 12), 49);
assert_eq!(moves(&[ArrowDown; 3]).apply(48, 50, 12), 1);
assert_eq!(moves(&[ArrowDown]).apply(0, 0, 12), 0);
assert_eq!(moves(&[PageDown, ArrowUp]).apply(0, 50, 12), 11, "in the order pressed");
assert_eq!(moves(&[ArrowUp, PageDown]).apply(0, 50, 12), 49, "in the order pressed");
let mut open = Open::new("select", WINDOW);
open.press(egui::Key::PageDown, 1);
assert_eq!(open.highlighted(), VISIBLE_ROWS);
@@ -2103,6 +2109,56 @@ mod tests {
assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap()));
}
/// Page Down, Up and Enter pressed in one frame move the highlight in that order, and Enter
/// runs the result they moved it to.
#[test]
fn keys_in_one_frame_move_the_highlight_in_the_order_pressed() {
let mut open = Open::new("show panel", WINDOW);
let listed = open.listed();
assert!(listed.len() > VISIBLE_ROWS, "{listed:?}");
let panel = listed[VISIBLE_ROWS - 1].strip_prefix("panel:").expect("a panel's result").to_string();
assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}");
let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
open.frame(vec![key(egui::Key::PageDown), key(egui::Key::ArrowUp), key(egui::Key::Enter)]);
assert!(!open.app.ui.palette_open);
assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status);
}
/// A scroll in steps of less than half a point a frame still moves the highlight onto a row in
/// view once the highlighted row leaves it.
#[test]
fn a_scroll_in_small_steps_keeps_the_highlight_in_view() {
let mut open = Open::new("select", WINDOW);
let nodes = open.frame(vec![]);
let first = rows(&nodes).into_iter().next().unwrap();
let at = egui::pos2(open.popup().center().x, ((first.2 + first.3) / 2.0) as f32);
open.frame(vec![egui::Event::PointerMoved(at)]);
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -0.4),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
modifiers: egui::Modifiers::NONE,
};
let mut nodes = Vec::new();
for _ in 0..200 {
nodes = open.frame(vec![wheel.clone()]);
}
for _ in 0..120 {
if !open.repaint {
break;
}
nodes = open.frame(vec![]);
}
let offset = open.ctx.data(|d| d.get_temp::<Highlight>(egui::Id::unique("palette-selected"))).unwrap().2;
assert!(offset > ROW_HEIGHT, "the list scrolled past the first row: {offset}");
assert!(open.highlighted() > 0, "the highlight left the row scrolled out of view");
let popup = open.popup();
let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect();
assert_eq!(lit.len(), 1, "{lit:?}");
assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}");
}
/// When the window shrinks so the list shows fewer rows, the list scrolls to keep the
/// highlighted result in view, and Enter runs that result.
#[test]
+21 -7
View File
@@ -618,13 +618,16 @@ pub(crate) fn label_or_name(s: &str, built_in: bool) -> &str {
crate::i18n::label_or_name(crate::i18n::current(), s, built_in)
}
/// "Recent Colors" header + rows of chips (the Session's recent colours, which every paint
/// command feeds), wrapped onto as many rows as the panel's width needs; returns the one clicked,
/// for the caller to apply. A chip drags its color as a solid paint, which the Swatches panel
/// makes a swatch of.
pub(crate) fn recent_colors_row(app: &VectorcraftApp, ui: &mut Ui) -> Option<Color> {
/// Rows of chips (the Session's recent colors, which every paint command feeds), wrapped onto as
/// many rows as the panel's width needs, under a "Recent Colors" header when `heading` is set;
/// returns the one clicked, for the caller to apply. The chips sit in a group that, without the
/// header, screen readers name "Recent Colors". A chip drags its color as a solid paint, which
/// the Swatches panel makes a swatch of.
pub(crate) fn recent_colors_row(app: &VectorcraftApp, ui: &mut Ui, heading: bool) -> Option<Color> {
let t = Tokens::get(ui.ctx());
crate::widgets::subheader(ui, tl!("Recent Colors"));
if heading {
crate::widgets::subheader(ui, tl!("Recent Colors"));
}
let width = ui.available_width();
let colors = &app.session.recent_colors;
// Chips are 16 px on a 19 px pitch, inset 3 px, with 2 px kept clear of the right edge.
@@ -632,11 +635,22 @@ pub(crate) fn recent_colors_row(app: &VectorcraftApp, ui: &mut Ui) -> Option<Col
let rows = colors.len().div_ceil(per_row).max(1);
let (r, _) = ui.allocate_exact_size(vec2(width, 3.0 + rows as f32 * 19.0), Sense::hover());
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside);
// The chips go in a child `Ui` over the box, so screen readers find them inside its group;
// their ids stay under the caller's scope.
let scope = ui.scope_id();
let mut builder = egui::UiBuilder::new().max_rect(r).accessibility_role(egui::accesskit::Role::Group);
if !heading {
builder = builder.accessibility_label(tl!("Recent Colors"));
}
let ui = &mut ui.new_child(builder);
ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
node.set_bounds(egui::accesskit::Rect { x0: r.min.x.into(), y0: r.min.y.into(), x1: r.max.x.into(), y1: r.max.y.into() });
});
let mut chosen = None;
for (i, c) in colors.iter().enumerate() {
let (row, col) = (i / per_row, i % per_row);
let cell = Rect::from_min_size(r.min + vec2(3.0 + col as f32 * 19.0, 3.0 + row as f32 * 19.0), vec2(16.0, 16.0));
let resp = ui.interact(cell, ui.scope_id().with(("recent", i)), Sense::click_and_drag());
let resp = ui.interact(cell, scope.with(("recent", i)), Sense::click_and_drag());
crate::widgets::drag_source(ui, &resp, || crate::widgets::PanelDrag::paint(Paint::solid(*c)));
crate::widgets::swatch_tile(ui, cell, &Paint::solid(*c), false, resp.hovered());
if resp.on_hover_text(c.to_hex()).clicked() {
+1 -1
View File
@@ -712,7 +712,7 @@ pub(crate) fn show_sized(app: &mut VectorcraftApp, ui: &mut Ui, height: f32) {
// Show Recent Colors draws the Recent Colors row; the Swatches panel's row does not read it.
let mut recent = None;
if app.ui.color_show_recent_colors {
recent = super::recent_colors_row(app, ui);
recent = super::recent_colors_row(app, ui, true);
widgets::divider(ui);
}
// An edit of the active colour with its displayed components (`new`), or a colour clicked with
@@ -711,6 +711,27 @@ fn the_stop_eyedropper_arms_the_eyedropper_for_the_stop() {
assert_eq!((app.session.tool_id(), app.session.tool_options()), ("eyedropper", json!({"stop": "gradient", "brushKeyColor": false})));
}
/// #8024: Escape ends the stop eyedropper's pick and returns to the Gradient tool. The stop keeps
/// its color, the selection stays, and a held Escape's repeats end nothing else.
#[test]
fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() {
let mut app = app(json!({"gradient": {}}));
crate::shortcut_editor::sync(&app.ui);
app.select_tool("gradient");
app.run("gradient.selectStop", json!({"index": 0})).unwrap();
let (paint, selected) = (current(&app), app.session.active().unwrap().selection.objects.clone());
stop_eyedropper(&mut app);
let key = |pressed, repeat| Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat, modifiers: Modifiers::NONE };
let ctx = egui::Context::default();
for events in [vec![key(true, false)], vec![key(true, true)], vec![key(false, false)]] {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx()));
out.textures_delta.clear();
}
assert_eq!(app.session.tool_id(), "gradient");
assert_eq!(current(&app), paint, "the stop keeps its color");
assert_eq!(app.session.active().unwrap().selection.objects, selected, "the selection stays");
}
/// The gradient panel names its Angle and Aspect Ratio inputs.
#[test]
fn angle_and_aspect_fields_are_named() {
+4 -4
View File
@@ -260,10 +260,10 @@ fn sampler_tool_active(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSample
/// Clear only this temporary mode. An explicit tool choice keeps the tool the user chose.
pub(crate) fn cancel_ignore_sampler(app: &mut VectorcraftApp, restore: bool) {
let Some(s) = app.ui.trace_ignore_sampler.take() else { return };
if sampler_tool_active(app, &s) {
app.session.set_tool_option("imageTraceIgnoreColor", &Value::Null);
app.session.set_tool_option("stop", &Value::Null);
}
// This UI session owns these transient fields even while Cmd/Ctrl parks the eyedropper
// behind a borrowed selection tool. The named setter also updates that stored lender.
let options = serde_json::Map::from_iter([("imageTraceIgnoreColor".into(), Value::Null), ("stop".into(), Value::Null)]);
app.session.set_tool_options(Some("eyedropper"), &options);
if restore && app.session.tool_id() == "eyedropper" {
app.return_to_tool(&s.back);
}
+21 -8
View File
@@ -5,6 +5,7 @@ use super::{
Arc, COLUMN, Color32, ColumnDrag, Document, INDENT, LayersDrag, Node, NodeId, NodeKind, Out, PanelDrag, ROW_KEYS, SQUARE_X, Sense, Stroke,
StrokeKind, TARGET_X, Tokens, Ui, Value, View, icons, json, vec2, widgets,
};
use vectorcraft_tools::intertwine::{in_intertwine, refused_member};
/// Stable id for the layers panel's per-name UI state.
pub(super) fn key(name: &str) -> egui::Id {
@@ -109,15 +110,20 @@ pub(super) fn resolve_click(ui: &Ui, view: &View, list: &[Row], out: &mut Out) {
});
}
/// Whether row `n` can take `drag` inside it.
fn takes(n: &Node, drag: &LayersDrag, doc: &Document) -> bool {
/// Whether row `n` can take `drag` (the rows or objects `moving`) inside it. A group or an
/// Intertwine group takes objects; an Intertwine group, or a group in one, only objects that can
/// be intertwined.
fn takes(n: &Node, drag: &LayersDrag, moving: &[NodeId], doc: &Document) -> bool {
match n.kind {
NodeKind::Layer { .. } => true,
NodeKind::Group { .. } => match drag {
LayersDrag::Rows(ids) => !ids.iter().any(|i| doc.node(*i).is_some_and(Node::is_layer)),
LayersDrag::Art => true,
LayersDrag::Guides(_) => false,
},
NodeKind::Group { .. } | NodeKind::Intertwine { .. } => {
let objects = match drag {
LayersDrag::Rows(ids) => !ids.iter().any(|i| doc.node(*i).is_some_and(Node::is_layer)),
LayersDrag::Art => true,
LayersDrag::Guides(_) => false,
};
objects && (!in_intertwine(doc, n.id) || moving.iter().filter_map(|i| doc.node(*i)).all(|m| refused_member(m).is_none()))
}
_ => false,
}
}
@@ -677,7 +683,7 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open:
}
let Some(p) = ui.input(|i| i.pointer.hover_pos()) else { return };
let rel = (p.y - r.top()) / r.height().max(1.0);
let inside = takes(n, &drag, doc);
let inside = takes(n, &drag, &moving, doc);
let place = match &*drag {
LayersDrag::Art if inside => Place::Inside,
LayersDrag::Art => Place::Above,
@@ -685,6 +691,13 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open:
LayersDrag::Rows(_) if rel < 0.5 => Place::Above,
LayersDrag::Rows(_) | LayersDrag::Guides(_) => Place::Below,
};
// Beside a member of an Intertwine group (or a row in one) only what can be intertwined goes.
if place != Place::Inside
&& doc.parent_of(n.id).is_some_and(|p| in_intertwine(doc, p))
&& moving.iter().filter_map(|i| doc.node(*i)).any(|m| refused_member(m).is_some())
{
return;
}
let stroke = Stroke::new(2.0, view.t.accent);
match place {
Place::Above => {
+72
View File
@@ -1493,6 +1493,78 @@ fn dragging_rows_moves_them_into_other_layers_and_alt_copies() {
let _ = (layer, c);
}
/// An Intertwine group's row takes a dragged row inside it, as a group's does, and the object
/// becomes a member; a row that can't be intertwined gets no inside box and goes beside it.
#[test]
fn dragging_a_row_into_an_intertwine_adds_a_member() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
let rect = |app: &mut VectorcraftApp, x: f64| {
NodeId(run(app, "shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap())
};
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let (a, b) = (rect(&mut app, 0.0), rect(&mut app, 10.0));
run(&mut app, "select.set", json!({"ids": [a.0, b.0]}));
let g = NodeId(run(&mut app, "object.intertwine.make", json!({}))["id"].as_u64().unwrap());
let (d, e) = (rect(&mut app, 100.0), rect(&mut app, 110.0));
run(&mut app, "select.set", json!({"ids": [d.0, e.0]}));
let g2 = NodeId(run(&mut app, "object.intertwine.make", json!({}))["id"].as_u64().unwrap());
let c = rect(&mut app, 50.0);
run(&mut app, "select.none", json!({}));
let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone();
let ids = |nodes: Option<&Vec<Arc<Node>>>| nodes.map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>()).unwrap_or_default();
let layer = doc(&app).layers[0].id;
let ctx = egui::Context::default();
// Rows: Layer 1, c, the second Intertwine group, the first.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 4);
// c onto the middle of the first Intertwine group's row: into it, on top.
drag(&mut app, &ctx, egui::pos2(150.0, circles[1].y), egui::pos2(150.0, circles[3].y + 3.0), false);
assert_eq!(ids(doc(&app).node(g).and_then(Node::children)), [a, b, c]);
// Rows: Layer 1, the second Intertwine group, the first (open on its moved row), c, b, a. The
// second just below the middle of the first's row: no nested Intertwine groups, so the row has
// no inside box and it goes below the group, beside it.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6);
drag(&mut app, &ctx, egui::pos2(150.0, circles[1].y), egui::pos2(150.0, circles[2].y + 3.0), false);
let now = doc(&app);
assert_eq!(ids(now.node(layer).and_then(Node::children)), [g2, g]);
assert_eq!(ids(now.node(g2).and_then(Node::children)), [d, e]);
assert_eq!(ids(now.node(g).and_then(Node::children)), [a, b, c]);
// Rows: Layer 1, the first (open), c, b, a, the second. Held over member b's row, the second
// shows no line or box, as it can't go beside a member either; over the first's own row it
// shows the line below it.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6);
let accent = Tokens::get(&ctx).accent;
let from = egui::pos2(150.0, circles[5].y);
let marks_over = |app: &mut VectorcraftApp, to: egui::Pos2| {
frame(app, &ctx, vec![egui::Event::PointerMoved(from)], false);
frame(app, &ctx, vec![button(from, true)], false);
frame(app, &ctx, vec![egui::Event::PointerMoved(from + vec2(0.0, 6.0))], false);
frame(app, &ctx, vec![egui::Event::PointerMoved(to)], false);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
let marks = out
.shapes
.iter()
.filter(|c| match &c.shape {
egui::Shape::LineSegment { stroke, .. } => stroke.color == accent,
egui::Shape::Rect(r) => r.stroke.color == accent,
_ => false,
})
.count();
frame(app, &ctx, vec![egui::Event::PointerMoved(from)], false);
frame(app, &ctx, vec![button(from, false)], false);
frame(app, &ctx, vec![], false);
marks
};
let beside_member = marks_over(&mut app, egui::pos2(150.0, circles[3].y + 3.0));
let beside_group = marks_over(&mut app, egui::pos2(150.0, circles[1].y + 3.0));
assert_eq!(beside_group, beside_member + 1);
assert_eq!(ids(doc(&app).node(g).and_then(Node::children)), [a, b, c]);
}
/// One headless frame of the panel on a short screen (300 × 260) with `events` (Alt held when
/// `alt`): for every row name painted inside the list's view, its center, and the view.
fn short_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, alt: bool) -> (HashMap<String, egui::Pos2>, egui::Rect) {
+128 -5
View File
@@ -66,9 +66,14 @@ pub(crate) fn operands(app: &VectorcraftApp) -> usize {
}
/// An operation's button, lit while `selected`, greyed out and saying what it needs unless the
/// selection has `min` operands.
fn button(ui: &mut Ui, icon: &str, tip: &str, selected: bool, n: usize, min: usize) -> bool {
/// selection has `min` operands. While `mixed` it carries a question mark, and screen readers
/// report its pressed state as mixed.
fn button(ui: &mut Ui, icon: &str, tip: &str, selected: bool, mixed: bool, n: usize, min: usize) -> bool {
let resp = widgets::icon_button_enabled(ui, icon, tip, selected, n >= min, 34.0);
if mixed {
mixed_mark(ui, resp.rect);
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_toggled(egui::accesskit::Toggled::Mixed));
}
if n < min {
resp.on_hover_text(tl!("Select two or more objects, or a group"));
return false;
@@ -76,6 +81,18 @@ fn button(ui: &mut Ui, icon: &str, tip: &str, selected: bool, n: usize, min: usi
resp.clicked()
}
/// The question mark in the lower right corner of a button `rect`, on a disc of the panel color so
/// it reads over the icon.
fn mixed_mark(ui: &Ui, rect: egui::Rect) {
let t = crate::theme::Tokens::get(ui.ctx());
let side = (rect.width() * 0.42).round();
let mark = egui::Rect::from_min_size(rect.right_bottom() - egui::vec2(side, side), egui::vec2(side, side));
let painter = ui.painter().with_clip_rect(rect);
painter.circle_filled(mark.center(), side * 0.5, t.panel);
painter.circle_stroke(mark.center(), side * 0.5, egui::Stroke::new(1.0, t.border));
painter.text(mark.center(), egui::Align2::CENTER_CENTER, "?", egui::FontId::proportional(side * 0.8), t.text_strong);
}
/// A Shape Mode button clicked: Alt makes a compound shape of the selection in `mode`; with
/// members of compound shapes selected they take `mode`; otherwise operation `op` runs. With the
/// Compound Shapes add-on's setting on, a click on the selection (not on members) makes the
@@ -98,9 +115,10 @@ fn shape_mode(app: &mut VectorcraftApp, ui: &Ui, op: &str, mode: ShapeMode, memb
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let n = operands(app);
// The modes of the compound-shape members selected: their Shape Mode button lights when they
// share one.
// share one, and every Shape Mode button shows a question mark when they differ.
let modes = vectorcraft_engine::cmd::selected_member_modes(&app.session);
let shared = modes.first().copied().filter(|m| modes.iter().all(|x| x == m));
let mixed = !modes.is_empty() && shared.is_none();
let expand = crate::menus::enabled(app, "object.compoundShape.expand");
widgets::subheader(ui, tl!("Shape Modes:"));
ui.horizontal(|ui| {
@@ -108,7 +126,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// Selected members can always take a mode.
let count = if modes.is_empty() { n } else { n.max(2) };
for ((icon, tip, op), mode) in SHAPE_MODES.into_iter().zip(ShapeMode::ALL) {
if button(ui, icon, tip, shared == Some(mode), count, 2) {
if button(ui, icon, tip, shared == Some(mode), mixed, count, 2) {
shape_mode(app, ui, op, mode, !modes.is_empty());
}
}
@@ -122,7 +140,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.spacing_mut().item_spacing.x = 5.0;
for (icon, tip, op) in PATHFINDERS {
let min = minimum_operands(op);
if button(ui, icon, tip, false, n, min) {
if button(ui, icon, tip, false, false, n, min) {
run(app, op);
}
}
@@ -241,6 +259,111 @@ mod tests {
assert_ne!(role_and_state(&panel, "Unite").1, Some(Toggled::True));
}
/// Two overlapping squares, the first at (`x`, 10), made into a Unite compound shape, which is
/// left selected; returns the ids of its two members.
fn compound_of_two(app: &mut VectorcraftApp, x: f64) -> [Value; 2] {
select_two_squares(app, x);
let ids = app.session.active().unwrap().selection.objects.clone();
app.run("object.compoundShape.make", json!({"mode": "add"})).unwrap();
[json!(ids[0].0), json!(ids[1].0)]
}
/// Selects `members` and gives them `mode`.
fn set_mode(app: &mut VectorcraftApp, members: &[&Value], mode: &str) {
app.run("select.set", json!({"ids": members})).unwrap();
app.run("object.compoundShape.setMode", json!({"mode": mode})).unwrap();
}
/// How many question marks the panel draws.
fn question_marks(app: &mut VectorcraftApp) -> usize {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let texts = crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::<Vec<_>>());
texts.iter().filter(|(t, _)| t == "?").count()
}
/// The pressed state screen readers get for each Shape Mode button.
fn shape_mode_states(app: &mut VectorcraftApp) -> Vec<Option<egui::accesskit::Toggled>> {
let panel = tree(|ui| show(app, ui));
SHAPE_MODES.into_iter().map(|(_, label, _)| role_and_state(&panel, label).1).collect()
}
/// Selected members in different modes put a question mark on each of the four Shape Mode
/// buttons, which stay enabled and which screen readers report as mixed; the Pathfinder buttons
/// are left as they are. A click gives every selected member the clicked mode in one undo step,
/// and the marks go.
#[test]
fn shape_modes_show_a_question_mark_while_the_selected_members_modes_differ() {
use egui::accesskit::Toggled;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let [a, b] = compound_of_two(&mut app, 10.0);
set_mode(&mut app, &[&b], "subtract");
app.run("select.set", json!({"ids": [a, b]})).unwrap();
assert_eq!(shape_mode_states(&mut app), [Some(Toggled::Mixed); 4]);
let panel = tree(|ui| show(&mut app, ui));
for (_, label, _) in SHAPE_MODES {
assert!(!named(&panel, label).is_disabled(), "{label}");
}
for (_, label, _) in PATHFINDERS {
assert_eq!(named(&panel, label).toggled(), None, "{label}");
}
assert_eq!(question_marks(&mut app), 4);
let undo = app.session.doc().unwrap().history.undo.len();
click_button(&mut app, "Intersect");
assert_eq!(vectorcraft_engine::cmd::selected_member_modes(&app.session), [ShapeMode::Intersect; 2]);
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert_eq!(question_marks(&mut app), 0);
assert_eq!(shape_mode_states(&mut app), [None, None, Some(Toggled::True), None]);
}
/// Members of two compound shapes are compared together: in different modes the buttons carry
/// question marks, and in one mode that mode's button is lit.
#[test]
fn members_of_two_compound_shapes_are_compared_together() {
use egui::accesskit::Toggled;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let [a, _] = compound_of_two(&mut app, 10.0);
let [c, _] = compound_of_two(&mut app, 110.0);
set_mode(&mut app, &[&c], "exclude");
app.run("select.set", json!({"ids": [a, c]})).unwrap();
assert_eq!(question_marks(&mut app), 4);
assert_eq!(shape_mode_states(&mut app), [Some(Toggled::Mixed); 4]);
set_mode(&mut app, &[&a, &c], "exclude");
assert_eq!(question_marks(&mut app), 0);
assert_eq!(shape_mode_states(&mut app), [None, None, None, Some(Toggled::True)]);
}
/// No question marks without members in different modes: nothing selected, plain objects, a
/// whole compound shape, one member, members sharing a mode, and a whole compound shape with
/// one of its members.
#[test]
fn shape_modes_show_no_question_mark_without_mixed_members() {
use egui::accesskit::Toggled;
let mut app = two_squares();
assert_eq!((question_marks(&mut app), shape_mode_states(&mut app)), (0, vec![None; 4]), "two plain objects");
let [a, b] = compound_of_two(&mut app, 110.0);
let shape = app.session.active().unwrap().selection.objects[0];
set_mode(&mut app, &[&b], "subtract");
app.run("select.set", json!({"ids": [shape.0]})).unwrap();
assert_eq!((question_marks(&mut app), shape_mode_states(&mut app)), (0, vec![None; 4]), "the whole compound shape");
app.run("select.set", json!({"ids": [b]})).unwrap();
let lit = vec![None, Some(Toggled::True), None, None];
assert_eq!((question_marks(&mut app), shape_mode_states(&mut app)), (0, lit.clone()), "one member");
set_mode(&mut app, &[&a, &b], "subtract");
assert_eq!((question_marks(&mut app), shape_mode_states(&mut app)), (0, lit.clone()), "two members in one mode");
set_mode(&mut app, &[&a], "add");
app.run("select.set", json!({"ids": [shape.0, b]})).unwrap();
assert_eq!((question_marks(&mut app), shape_mode_states(&mut app)), (0, lit), "the shape and one member");
app.run("select.none", json!({})).unwrap();
assert_eq!(question_marks(&mut app), 0, "nothing selected");
}
/// The panel menu's Trap… is enabled for two objects and opens the Trap options; OK adds the
/// trap above them as one selected group in one undo step.
#[test]
+17 -7
View File
@@ -36,14 +36,14 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) {
ui.add_space(4.0);
// A recent colour paints the active proxy (Alt: the inactive one), as a swatch does, and
// becomes the Color Guide's base color. The panel menu's Show Recent Colors hides the row.
if app.ui.swatches_show_recent_colors {
if let Some(c) = crate::panels::recent_colors_row(app, ui) {
crate::panels::color_guide::choose_base(app, c);
crate::panels::apply_click(app, ui, json!({"color": crate::panels::color_json(&c)}));
}
widgets::divider(ui);
// Neither the row nor the list has a visible heading (#8041): the list sits under the row, or
// under the proxy row while the row is hidden.
if app.ui.swatches_show_recent_colors
&& let Some(c) = crate::panels::recent_colors_row(app, ui, false)
{
crate::panels::color_guide::choose_base(app, c);
crate::panels::apply_click(app, ui, json!({"color": crate::panels::color_json(&c)}));
}
widgets::subheader(ui, tl!("Swatch Tiles"));
let query = if pstate(ui.ctx(), "swatch-show-find") { widgets::search_field(ui, find_id(), tl!("Find")) } else { String::new() };
let items = entries(app, kind, &query);
let active_swatch = kept_swatch(app, ui, active_swatch(app));
@@ -60,6 +60,12 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) {
let fixed = widgets::panel_footer_bottom(ui).is_some();
let list_height = widgets::panel_list_height(ui, if view == View::LargeThumb { 200.0 } else { 150.0 }, 2.0 + ui.spacing().item_spacing.y);
widgets::list_box(ui, |ui| {
// Screen readers read the box that holds the tiles as the "Swatch Tiles" list, with the
// box's bounds set below once the tiles are laid out.
ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
node.set_role(egui::accesskit::Role::List);
node.set_label(tl!("Swatch Tiles"));
});
let scroll = egui::ScrollArea::vertical()
.id_salt("swatch-scroll")
.max_height(list_height)
@@ -112,6 +118,10 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) {
});
let zone = ui.interact(out.inner_rect, ui.scope_id().with("swatch-drop"), Sense::hover());
zone_input(ui, &zone, &mut ev);
let r = ui.min_rect();
ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
node.set_bounds(egui::accesskit::Rect { x0: r.min.x.into(), y0: r.min.y.into(), x1: r.max.x.into(), y1: r.max.y.into() });
});
});
match ev.edit {
Some(Entry::Folder(g)) => edit_group(app, &g),
@@ -1040,6 +1040,80 @@ fn show_recent_colors_hides_and_shows_the_swatches_row() {
assert_eq!((saved(json!(false)), saved(json!(true)), saved(json!("no"))), (false, true, true));
}
/// The panel, and the Fill/Stroke chip popover that shows the same body, draw no "Recent Colors"
/// or "Swatch Tiles" heading (#8041): the Recent Colors row sits under the proxy row, empty or not,
/// the swatch list just under it, and the list moves up under the proxy row when Show Recent
/// Colors hides the row. Screen readers find both parts by those names, with the chips in the
/// Recent Colors group and the tiles in the Swatch Tiles list.
#[test]
fn the_list_sits_under_the_recent_colors_row_without_headings() {
fn texts(shapes: &[egui::Shape], out: &mut Vec<String>) {
for s in shapes {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => texts(v, out),
_ => {}
}
}
}
// The visible texts, and the bounds of the parts screen readers name "Recent Colors" and
// "Swatch Tiles", of the second of two frames.
let look = |app: &mut VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut Ui), salt: &'static str| {
crate::i18n::set_current(crate::i18n::Lang::EN);
let ctx = context();
ctx.enable_accesskit();
let mut last = None;
for time in [0.0, 0.5] {
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0)));
let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect, ..Default::default() }, |ui| draw(app, ui));
out.textures_delta.clear();
last = Some(out);
}
let out = last.expect("a frame");
let mut shown = vec![];
texts(&out.shapes.iter().map(|c| c.shape.clone()).collect::<Vec<_>>(), &mut shown);
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
let named =
|label: &str| nodes.iter().find(|(_, n)| n.label() == Some(label)).and_then(|(_, n)| n.bounds()).map(|b| (b.y0 as f32, b.y1 as f32));
// The list is the node that holds the tiles, not an empty node beside them: the first
// tile's node is inside it.
let (list, node) = nodes.iter().find(|(_, n)| n.label() == Some("Swatch Tiles")).expect("screen readers find the swatch list");
assert_eq!(node.role(), egui::accesskit::Role::List);
let first = entries(app, Kind::All, "").first().map(|e| tiles::tile_id(salt, e).accesskit_id()).expect("the document has swatches");
let (mut inside, mut stack) = (false, vec![*list]);
while let Some(id) = stack.pop() {
inside |= id == first;
stack.extend(nodes.iter().filter(|(n, _)| *n == id).flat_map(|(_, n)| n.children().iter().copied()));
}
assert!(inside, "the list holds the tiles");
// Likewise the Recent Colors group holds its chips, one child per recent color.
let chips = nodes.iter().find(|(_, n)| n.label() == Some("Recent Colors")).map(|(_, n)| n.children().len());
if let Some(chips) = chips {
assert_eq!(chips, app.session.recent_colors.len(), "the group holds the chips");
}
(shown, named("Recent Colors"), named("Swatch Tiles"))
};
for (draw, salt) in [(show as fn(&mut VectorcraftApp, &mut Ui), TILE), (popover, POPOVER_TILE)] {
let mut app = app();
for applied in [false, true] {
if applied {
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
}
let (shown, recent, list) = look(&mut app, draw, salt);
assert!(!shown.iter().any(|t| t == "Recent Colors" || t == "Swatch Tiles"), "{salt}: no headings: {shown:?}");
let (row_top, row_bottom) = recent.expect("screen readers find the Recent Colors row");
let (top, _) = list.expect("screen readers find the swatch list");
assert!(row_top < 50.0, "{salt}: the row sits under the proxy row: {row_top}");
assert!(top > row_bottom && top - row_bottom < 12.0, "{salt}: the list sits under the row: {row_bottom} {top}");
}
app.ui.swatches_show_recent_colors = false;
let (_, recent, list) = look(&mut app, draw, salt);
assert_eq!(recent, None, "{salt}: Show Recent Colors unchecked hides the row");
let (top, _) = list.expect("screen readers find the swatch list");
assert!(top < 50.0, "{salt}: the list starts under the proxy row: {top}");
}
}
/// In a panel made taller the swatch list fills the space above the panel's footer instead of
/// scrolling inside 150 or 200 pt (#1638); outside a sized panel it keeps those heights.
#[test]
+338 -32
View File
@@ -8,9 +8,14 @@
//! the document then no longer matches the active dataset, and "Update Data Set" writes the
//! art back into it.
use std::cell::RefCell;
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::{Arc, Weak};
use egui::{Rect, Response, Sense, Ui, pos2, vec2};
use serde_json::json;
use vectorcraft_doc::{NodeId, NodeKind, VariableKind};
use vectorcraft_doc::{Document, NodeId, NodeKind, VariableKind};
use vectorcraft_engine::DocState;
use vectorcraft_engine::cmd::{VariableSort, VariableSortKey, variable_order};
@@ -120,6 +125,7 @@ fn variable_row(ui: &mut Ui, row: &VarRow, selected: bool) -> Response {
}
/// One variable row: its kind's icon, its name, and the object it drives.
#[derive(Debug, PartialEq)]
struct VarRow {
name: String,
kind: VariableKind,
@@ -129,6 +135,7 @@ struct VarRow {
}
/// One dataset row: its name and how many values it carries.
#[derive(Debug, PartialEq)]
struct SetRow {
name: String,
values: usize,
@@ -137,6 +144,107 @@ struct SetRow {
matches: bool,
}
/// The panel's two lists: the variables in the order `variable.sort` set, and the data sets.
#[derive(Debug, PartialEq)]
struct Rows {
vars: Vec<VarRow>,
sets: Vec<SetRow>,
}
/// Build the panel's rows. `xml_id` names a variable's one object by its XML id, as Identify
/// Objects By › XML ID does.
fn build_rows(st: &DocState, xml_id: bool) -> Rows {
#[cfg(test)]
BUILT.with(|n| n.set(n.get() + 1));
// In the order `variable.sort` set, which `variable.list` reports too.
let all = &st.doc.variables.variables;
let vars: Vec<VarRow> = variable_order(st, xml_id)
.into_iter()
.filter_map(|i| all.get(i))
.map(|v| {
let bound: Vec<u64> = st.doc.variables.objects_of(&v.name).iter().map(|i| i.0).collect();
let object = match bound.as_slice() {
[] => String::new(),
[one] => st.doc.node(NodeId(*one)).map(|n| n.identify_label(xml_id)).unwrap_or_default(),
_ => tl!("Multiple objects").to_string(),
};
VarRow { name: v.name.clone(), kind: v.kind, bound, object }
})
.collect();
// What the art holds now, read once for every row's drift check.
let current = st.doc.captured_values();
let sets: Vec<SetRow> = st
.doc
.variables
.datasets
.iter()
.map(|d| SetRow {
name: d.name.clone(),
values: d.values.len(),
active: st.doc.variables.active_dataset.as_deref() == Some(d.name.as_str()),
matches: d.matches(&current),
})
.collect();
Rows { vars, sets }
}
#[cfg(test)]
thread_local! {
/// How many times [`build_rows`] has run on this thread.
static BUILT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Everything the rows are built from: the document version (its address, which the held
/// [`Weak`] keeps from being reused, and its revision), the list's order, Identify Objects By, the
/// interface language that "Multiple objects" is written in, and the document's new art. New art
/// on a locked artboard is read by a data set's drift check, and selecting or deselecting it
/// changes the set in place without a new revision.
struct RowsKey {
doc: Weak<Document>,
revision: u64,
sort: VariableSort,
xml_id: bool,
lang: crate::i18n::Lang,
new_art: Arc<HashSet<NodeId>>,
}
impl RowsKey {
fn of(st: &DocState, xml_id: bool) -> Self {
RowsKey {
doc: Arc::downgrade(&st.doc),
revision: st.revision,
sort: st.variables_sort,
xml_id,
lang: crate::i18n::current(),
new_art: st.doc.new_art.get(),
}
}
fn same(&self, other: &RowsKey) -> bool {
self.doc.ptr_eq(&other.doc)
&& self.revision == other.revision
&& self.sort == other.sort
&& self.xml_id == other.xml_id
&& self.lang == other.lang
&& Arc::ptr_eq(&self.new_art, &other.new_art)
}
}
/// The panel's rows for `st`, built again only when one of the inputs in [`RowsKey`] changes.
/// The selection and the highlighted row are not among them: the panel reads those every frame.
fn cached_rows(st: &DocState, xml_id: bool) -> Rc<Rows> {
thread_local! {
static ROWS: RefCell<Option<(RowsKey, Rc<Rows>)>> = const { RefCell::new(None) };
}
let key = RowsKey::of(st, xml_id);
if let Some(rows) = ROWS.with(|c| c.borrow().as_ref().filter(|(k, _)| k.same(&key)).map(|(_, rows)| rows.clone())) {
return rows;
}
let rows = Rc::new(build_rows(st, xml_id));
ROWS.with(|c| *c.borrow_mut() = Some((key, rows.clone())));
rows
}
/// The row the panel acts on: Delete, Options… and Select Bound Object all mean it. A name
/// the document no longer defines highlights nothing (deleted from the palette, undone).
fn highlighted_row(st: &DocState) -> Option<String> {
@@ -217,35 +325,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
};
// Owned snapshots: the rows below run commands, which borrow the app mutably.
let xml_id = app.session.prefs.identify_objects_by == "xmlId";
// In the order `variable.sort` set, which `variable.list` reports too.
let all = &st.doc.variables.variables;
let vars: Vec<VarRow> = variable_order(st, xml_id)
.into_iter()
.filter_map(|i| all.get(i))
.map(|v| {
let bound: Vec<u64> = st.doc.variables.objects_of(&v.name).iter().map(|i| i.0).collect();
let object = match bound.as_slice() {
[] => String::new(),
[one] => st.doc.node(NodeId(*one)).map(|n| n.identify_label(xml_id)).unwrap_or_default(),
_ => tl!("Multiple objects").to_string(),
};
VarRow { name: v.name.clone(), kind: v.kind, bound, object }
})
.collect();
// What the art holds now, read once for every row's drift check.
let current = st.doc.captured_values();
let sets: Vec<SetRow> = st
.doc
.variables
.datasets
.iter()
.map(|d| SetRow {
name: d.name.clone(),
values: d.values.len(),
active: st.doc.variables.active_dataset.as_deref() == Some(d.name.as_str()),
matches: d.matches(&current),
})
.collect();
let rows = cached_rows(st, xml_id);
let (vars, sets) = (&rows.vars, &rows.sets);
let active = sets.iter().find(|s| s.active);
let Picked { selected, has_selection, selection_bound, single_type, single_image, selection_graph } = picked(st);
let highlighted = highlighted_row(st);
@@ -298,7 +379,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if vars.is_empty() {
widgets::dim_label(ui, tl!("None"));
}
for row in &vars {
for row in vars {
let r = variable_row(ui, row, highlighted.as_deref() == Some(row.name.as_str()));
// A click highlights the row and selects what it drives; a double click opens
// Variable Options for it.
@@ -314,7 +395,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if sets.is_empty() {
widgets::dim_label(ui, tl!("None"));
}
for row in &sets {
for row in sets {
// The active row is ticked and selected; a row the art has drifted from is in
// italics, so an edit that left the document not matching it is visible.
let label = format!("{}{} · {}", if row.active { "● " } else { "" }, row.name, row.values);
@@ -1042,6 +1123,231 @@ mod tests {
assert!(!entries.iter().any(|e| e.path == ["Window", "Variables"]), "no Variables submenu");
}
/// The rows as the panel built them on every frame before [`cached_rows`] kept them: the
/// identity checks and the timing compare against it.
fn old_rows(st: &DocState, xml_id: bool) -> Rows {
let all = &st.doc.variables.variables;
let vars: Vec<VarRow> = variable_order(st, xml_id)
.into_iter()
.filter_map(|i| all.get(i))
.map(|v| {
let bound: Vec<u64> = st.doc.variables.objects_of(&v.name).iter().map(|i| i.0).collect();
let object = match bound.as_slice() {
[] => String::new(),
[one] => st.doc.node(NodeId(*one)).map(|n| n.identify_label(xml_id)).unwrap_or_default(),
_ => tl!("Multiple objects").to_string(),
};
VarRow { name: v.name.clone(), kind: v.kind, bound, object }
})
.collect();
let current = st.doc.captured_values();
let sets: Vec<SetRow> = st
.doc
.variables
.datasets
.iter()
.map(|d| SetRow {
name: d.name.clone(),
values: d.values.len(),
active: st.doc.variables.active_dataset.as_deref() == Some(d.name.as_str()),
matches: d.matches(&current),
})
.collect();
Rows { vars, sets }
}
fn built() -> u64 {
BUILT.with(|n| n.get())
}
/// Frames drawn while nothing changes build the rows once and draw the same rows after that.
#[test]
fn frames_without_a_change_build_the_rows_once() {
let mut app = app_with_data();
let mut d = Driver::new();
d.frame(&mut app, vec![]);
let before = built();
for _ in 0..5 {
d.frame(&mut app, vec![]);
}
assert_eq!(built(), before, "frames of an unchanged document built the rows again");
let st = app.session.active().unwrap();
assert!(Rc::ptr_eq(&cached_rows(st, false), &cached_rows(st, false)));
assert_eq!(*cached_rows(st, false), old_rows(st, false));
}
/// Draws a frame after `what` changed one of the rows' inputs, checks that the frame built the
/// rows again and that they equal the rows the old per-frame build gives, and returns them.
fn rebuilt(d: &mut Driver, app: &mut VectorcraftApp, what: &str) -> Rc<Rows> {
let before = built();
d.frame(app, vec![]);
assert!(built() > before, "{what}: the frame drew the rows it kept");
let xml_id = app.session.prefs.identify_objects_by == "xmlId";
let st = app.session.active().unwrap();
let rows = cached_rows(st, xml_id);
assert_eq!(*rows, old_rows(st, xml_id), "{what}");
rows
}
fn matches(rows: &Rows, set: &str) -> bool {
rows.sets.iter().find(|s| s.name == set).unwrap_or_else(|| panic!("no data set {set}")).matches
}
/// Each input of the rows builds them again: an edit, the list's order, Identify Objects By,
/// the interface language, new art on a locked artboard selected or deselected without a new
/// revision, Undo, Redo and another document.
#[test]
fn each_input_of_the_rows_builds_them_again() {
let mut app = app_with_data();
let mut d = Driver::new();
d.frame(&mut app, vec![]);
let t = app.session.active().unwrap().doc.variables.objects_of("Name")[0].0;
app.session.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap();
assert_eq!(rebuilt(&mut d, &mut app, "variable.define").vars.len(), 2);
let r = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.session.execute("variable.bind", &json!({"variable": "Shown", "ids": [r]})).unwrap();
let rows = rebuilt(&mut d, &mut app, "variable.bind");
assert_eq!(rows.vars.iter().find(|v| v.name == "Shown").map(|v| v.bound.clone()), Some(vec![r]));
app.session.execute("dataset.capture", &json!({})).unwrap();
assert_eq!(rebuilt(&mut d, &mut app, "dataset.capture").sets.len(), 2);
app.session.execute("text.editRange", &json!({"id": t, "insert": "Bob"})).unwrap();
assert!(!matches(&rebuilt(&mut d, &mut app, "an edit of bound text"), "Data Set 1"));
// On a locked artboard the text is not read, so the data set no longer differs from it.
app.session.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
assert!(matches(&rebuilt(&mut d, &mut app, "artboard lock"), "Data Set 1"));
// New art there is read again; selecting or deselecting it keeps the revision.
let revision = app.session.active().unwrap().revision;
app.session.active().unwrap().doc.new_art.set(Arc::new(HashSet::from([NodeId(t)])));
assert!(!matches(&rebuilt(&mut d, &mut app, "new art selected"), "Data Set 1"));
app.session.active().unwrap().doc.new_art.set(Arc::default());
assert!(matches(&rebuilt(&mut d, &mut app, "new art deselected"), "Data Set 1"));
assert_eq!(app.session.active().unwrap().revision, revision, "new art moved the revision");
app.session.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
assert!(!matches(&rebuilt(&mut d, &mut app, "artboard unlock"), "Data Set 1"));
app.session.execute("variable.sort", &json!({"by": "name", "descending": true})).unwrap();
let names: Vec<String> = rebuilt(&mut d, &mut app, "variable.sort").vars.iter().map(|v| v.name.clone()).collect();
assert_eq!(names, ["Shown", "Name"]);
// Identify Objects By names the one object by its XML id; the preference is not an edit.
app.session.execute("layer.setProps", &json!({"id": r, "name": "My Rect #2"})).unwrap();
rebuilt(&mut d, &mut app, "layer.setProps");
app.session.prefs.identify_objects_by = "xmlId".into();
let rows = rebuilt(&mut d, &mut app, "Identify Objects By");
assert_eq!(rows.vars.iter().find(|v| v.name == "Shown").map(|v| v.object.as_str()), Some("My_Rect__x23_2"));
app.session.prefs.identify_objects_by = "objectName".into();
rebuilt(&mut d, &mut app, "Identify Objects By back");
// A variable bound to more than one object says so in the interface language.
app.session.execute("variable.bind", &json!({"variable": "Shown", "ids": [t]})).unwrap();
rebuilt(&mut d, &mut app, "a second binding");
crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered"));
let rows = rebuilt(&mut d, &mut app, "the language");
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(rows.vars.iter().find(|v| v.name == "Shown").map(|v| v.object.as_str()), Some("Mehrere Objekte"));
let rows = rebuilt(&mut d, &mut app, "the language back");
assert_eq!(rows.vars.iter().find(|v| v.name == "Shown").map(|v| v.object.as_str()), Some("Multiple objects"));
app.session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(rebuilt(&mut d, &mut app, "edit.undo").vars.iter().find(|v| v.name == "Shown").map(|v| v.bound.len()), Some(1));
app.session.execute("edit.redo", &json!({})).unwrap();
assert_eq!(rebuilt(&mut d, &mut app, "edit.redo").vars.iter().find(|v| v.name == "Shown").map(|v| v.bound.len()), Some(2));
// Another document, and back.
app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
assert!(rebuilt(&mut d, &mut app, "another document").vars.is_empty());
assert!(app.session.set_active(0));
assert_eq!(rebuilt(&mut d, &mut app, "the first document again").vars.len(), 2);
}
/// A document for the timing: `threads` stories of four threaded frames with a text variable
/// on each frame, `rects` rectangles with a visibility variable on each but the last tenth
/// (those go to the first visibility variable as well), `graphs` graphs with a graph variable
/// each, and `sets` captured data sets, listed by object.
fn timing_document(threads: usize, rects: usize, graphs: usize, sets: usize) -> VectorcraftApp {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let s = &mut app.session;
s.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap();
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
let bind = |s: &mut vectorcraft_engine::Session, name: String, kind: &str, ids: &[u64]| {
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
s.execute("variable.bind", &json!({"variable": name, "ids": ids})).unwrap();
};
for i in 0..threads {
let (x, y) = ((i % 10) as f64 * 150.0, (i / 10) as f64 * 300.0);
let text = format!("Story {i} with a few words in it that flow from frame to frame");
let mut frame = id(s.execute("text.create", &json!({"x": x, "y": y, "text": text, "area": {"width": 120, "height": 40}})).unwrap());
bind(s, format!("t{i}a"), "text", &[frame]);
for f in ["b", "c", "d"] {
frame = id(s.execute("text.thread.add", &json!({"from": frame, "rect": [x, y + 60.0, 120, 40]})).unwrap());
bind(s, format!("t{i}{f}"), "text", &[frame]);
}
}
let rects: Vec<u64> = (0..rects)
.map(|i| id(s.execute("shape.rectangle", &json!({"x": (i % 20) * 90, "y": 1500 + (i / 20) * 40, "width": 30, "height": 30})).unwrap()))
.collect();
let own = rects.len() - rects.len() / 10;
for (i, r) in rects[..own].iter().enumerate() {
bind(s, format!("v{i}"), "visibility", &[*r]);
}
if own > 0 && own < rects.len() {
s.execute("variable.bind", &json!({"variable": "v0", "ids": &rects[own..]})).unwrap();
}
let csv: String =
std::iter::once(",2024,2025".to_string()).chain((0..20).map(|r| format!("Row {r},{r},{}", r * 2))).collect::<Vec<_>>().join("\n");
for i in 0..graphs {
let g =
id(s.execute("graph.create", &json!({"type": "column", "x": i * 150, "y": 1800, "width": 120, "height": 80, "csv": csv})).unwrap());
bind(s, format!("g{i}"), "graph", &[g]);
}
for _ in 0..sets {
s.execute("dataset.capture", &json!({})).unwrap();
}
s.execute("variable.sort", &json!({"by": "object"})).unwrap();
app
}
/// Per-frame time of the old row build against the kept rows on an unchanged document: seven
/// runs of 600 frames each, the two alternating, on a 30-variable and a 300-variable document.
#[test]
#[ignore = "timing: cargo test --release -p vectorcraft-ui-egui --lib variables::tests::rows_timing -- --ignored --nocapture"]
fn rows_timing() {
fn median(mut v: Vec<f64>) -> f64 {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
}
for app in [timing_document(5, 10, 1, 5), timing_document(50, 100, 10, 50)] {
let st = app.session.active().unwrap();
let rows = cached_rows(st, false);
assert_eq!(*rows, old_rows(st, false));
let (mut old, mut kept) = (vec![], vec![]);
for _ in 0..7 {
let t = std::time::Instant::now();
for _ in 0..600 {
std::hint::black_box(old_rows(std::hint::black_box(st), false));
}
old.push(t.elapsed().as_secs_f64() * 1e6 / 600.0);
let t = std::time::Instant::now();
for _ in 0..600 {
std::hint::black_box(cached_rows(std::hint::black_box(st), false));
}
kept.push(t.elapsed().as_secs_f64() * 1e6 / 600.0);
}
let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.3}")).collect::<Vec<_>>().join(" ");
println!(
"{} variables, {} data sets: old {:.3} us/frame (runs {}), kept {:.3} us/frame (runs {})",
rows.vars.len(),
rows.sets.len(),
median(old.clone()),
runs(&old),
median(kept.clone()),
runs(&kept)
);
}
}
/// A menu item that needs a name opens the dialog rather than running the command with
/// empty params, which would only say "missing `name`".
#[test]
+14
View File
@@ -231,6 +231,14 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) {
|| crate::dialogs::new_document_popup_open(d)
|| crate::dialogs::export_artboard_name_editing(app, d)
});
// Escape ends Brush Options' Key Color pick and leaves the dialog open: the Eyedropper
// switches back to the tool that armed it.
if !popup && pressed_anew(ctx, Key::Escape) && key_color_pick_armed(app) {
let view = app.view_info();
let r = app.session.tool_key(ToolKey::Escape, Mods::default(), view);
crate::canvas::apply_requests(app, r);
return;
}
// Escape in Preferences' search field with text clears the field first.
if !popup && pressed_anew(ctx, Key::Escape) && !crate::prefs_dialog::clear_search_on_escape(app, ctx) {
crate::dialogs::cancel(app);
@@ -387,6 +395,12 @@ pub(crate) fn pressed_anew(ctx: &egui::Context, key: Key) -> bool {
ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, pressed: true, repeat: false, .. } if *k == key)))
}
/// Is Brush Options open with its Key Color eyedropper armed, waiting for a click on the art?
fn key_color_pick_armed(app: &VectorcraftApp) -> bool {
let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::brush_options::KIND);
open && app.session.tool_id() == "eyedropper" && app.session.tool_options()["brushKeyColor"] == true
}
/// Takes this frame's repeats of `key` when the tool claims it: a press acts once, and they stay out
/// of the shortcuts. A chord a command is bound to keeps its repeats.
fn take_claimed_repeat(app: &mut VectorcraftApp, ctx: &egui::Context, key: Key, tool_key: ToolKey, view: ViewInfo) -> bool {
+9 -2
View File
@@ -312,8 +312,15 @@ fn the_popover_swatch_libraries_button_opens_the_libraries_menu() {
click(&mut app, &ctx, fill.center(), Modifiers::NONE, control_bar);
let libraries = *popover_bottom_buttons(&ctx).first().expect("the popover has a bottom bar");
click(&mut app, &ctx, libraries.center(), Modifiers::NONE, control_bar);
let shapes = frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar);
assert!(text_rect(&shapes, "Swatch Tiles").is_some(), "the popover stays open");
// The popover's swatch list has no visible heading; screen readers find it as "Swatch Tiles".
ctx.enable_accesskit();
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 1000.0)));
let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| control_bar(&mut app, ui));
out.textures_delta.clear();
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
let list = nodes.iter().any(|(_, n)| n.label() == Some("Swatch Tiles") && n.role() == egui::accesskit::Role::List);
assert!(list, "the popover stays open");
let shapes: Vec<Shape> = out.shapes.into_iter().map(|c| c.shape).collect();
let defaults = menu_item_rect(&shapes, "Default Swatches").expect("the libraries menu is open");
assert!(menu_item_rect(&shapes, "Other Library…").is_some());
let earth = menu_item_rect(&shapes, "Earth Tones").expect("the menu lists the built-in libraries");
+1 -1
View File
@@ -47,7 +47,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[
"Draw",
&[
&["pencil", "smooth", "pathEraser", "join"],
&["eraser", "scissors", "knife", "mirrorCut", "lineCut", "rectCut"],
&["eraser", "scissors", "knife", "trimAtCrossings", "mirrorCut", "lineCut", "rectCut"],
&["paintbrush", "blobBrush"],
&["pen", "addAnchor", "deleteAnchor", "anchorPoint"],
&["curvature"],
@@ -417,3 +417,109 @@ fn actual_canvas_shows_original_while_armed_then_restores_the_stored_view() {
std::fs::write(dir.join("binding.json"), serde_json::to_vec_pretty(&binding).unwrap()).unwrap();
}
}
/// Cancelling while Cmd/Ctrl borrows Selection also clears the parked eyedropper's one-shot.
#[test]
fn cancelling_a_borrowed_sampler_clears_the_restored_eyedropper() {
fn loan_frame(app: &mut VectorcraftApp, ctx: &egui::Context, mut events: Vec<Event>) -> egui::FullOutput {
events.insert(0, Event::ModifiersChanged(egui::Modifiers { ctrl: true, command: true, ..Default::default() }));
frame(app, ctx, events)
}
fn borrow_and_release(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point, stale: bool) {
let modifiers = vectorcraft_tools::Mods { cmd: true, ..Default::default() };
assert_eq!(app.session.lent_tool_id(&modifiers), Some("selection"), "exercise the real engine loan");
let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point);
assert!(app.canvas_rect.unwrap().contains(at));
let press = |pressed| Event::PointerButton {
pos: at,
button: PointerButton::Primary,
pressed,
modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() },
};
loan_frame(app, ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear();
assert_eq!(app.session.tool_id(), "selection", "the eyedropper is now parked in Session::lender");
if stale {
app.run("select.none", json!({})).unwrap();
}
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let paint = app.session.paint.clone();
loan_frame(app, ctx, vec![]).textures_delta.clear();
assert_eq!(app.session.tool_id(), "selection", "cancellation respects the borrowed gesture");
assert!(app.ui.trace_ignore_sampler.is_none(), "the real frame ends the UI-owned sampler");
let state = app.session.active().unwrap();
assert_eq!(state.doc, document);
assert_eq!(state.selection, selection);
assert_eq!(state.revision, revision);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
assert_eq!(app.session.paint, paint, "cancelling a parked sampler does not paint");
loan_frame(app, ctx, vec![press(false)]).textures_delta.clear();
frame(app, ctx, vec![Event::ModifiersChanged(egui::Modifiers::NONE)]).textures_delta.clear();
assert_eq!(app.session.tool_id(), "eyedropper", "ordinary engine loan restoration is retained");
}
fn ordinary_sample(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) -> (usize, usize, u64) {
app.run("select.none", json!({})).unwrap();
app.run("paint.setFill", json!({"color": "#e020c0"})).unwrap();
assert!(app.session.fill_active);
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let old_paint = app.session.paint.clone();
let view = app.view_info();
let down = PointerEvent::new(PointerKind::Down, point.x, point.y).with_mods(vectorcraft_tools::Mods { shift: true, ..Default::default() });
canvas::dispatch(app, &down, view);
canvas::dispatch(app, &PointerEvent::new(PointerKind::Up, point.x, point.y), view);
frame(app, ctx, vec![]).textures_delta.clear();
assert_eq!(app.session.tool_id(), "eyedropper", "a normal sample does not consume a stale one-shot or switch tools");
assert_ne!(app.session.paint, old_paint, "the normal color sample actually runs");
assert_eq!(app.session.paint.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK));
let state = app.session.active().unwrap();
assert_eq!(state.doc, document, "with no selection a normal sample changes only paint defaults");
assert_eq!(state.selection, selection);
(state.history.undo.len() - history.0, state.history.redo.len().abs_diff(history.1), state.revision - revision)
}
for stale in [false, true] {
// The same ordinary loan is the control for legitimate selection/default/history work.
let (mut control, control_ctx) = fixture(true, [37, 83, 149], false);
let control_point = source_point(&control, 0.25);
let control_target = selected(&control).id;
let control_revision = control.session.active().unwrap().revision;
let control_document = control.session.active().unwrap().doc.clone();
let control_history = {
let state = control.session.active().unwrap();
(state.history.undo.len(), state.history.redo.len())
};
control.select_tool("eyedropper");
borrow_and_release(&mut control, &control_ctx, control_point, stale);
let expected_selection: Vec<bool> = control.session.active().unwrap().selection.objects.iter().map(|id| *id == control_target).collect();
let expected_revision_delta = control.session.active().unwrap().revision - control_revision;
assert_eq!(control.session.active().unwrap().doc, control_document);
assert_eq!((control.session.active().unwrap().history.undo.len(), control.session.active().unwrap().history.redo.len()), control_history);
let expected_paint = control.session.paint.clone();
let expected_sample_effects = ordinary_sample(&mut control, &control_ctx, control_point);
let (mut app, ctx) = fixture(true, [37, 83, 149], false);
let point = source_point(&app, 0.25);
let target = selected(&app).id;
let state = app.session.active().unwrap();
let (document, revision) = (state.doc.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
click_control(&mut app, &ctx, SAMPLE_TIP);
assert_eq!(app.session.tool_id(), "eyedropper");
assert!(!app.session.tool_options()["imageTraceIgnoreColor"].is_null());
borrow_and_release(&mut app, &ctx, point, stale);
assert!(app.session.tool_options()["imageTraceIgnoreColor"].is_null(), "stale={stale}: the returned lender must not stay armed");
assert!(app.session.tool_options()["stop"].is_null(), "stale={stale}: no ghost return-tool action");
let state = app.session.active().unwrap();
assert_eq!(state.doc, document);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
assert_eq!(state.selection.objects.iter().map(|id| *id == target).collect::<Vec<_>>(), expected_selection);
assert_eq!(state.revision - revision, expected_revision_delta);
assert_eq!(app.session.paint, expected_paint, "only the ordinary borrowed gesture's default changes are permitted");
assert_eq!(ordinary_sample(&mut app, &ctx, point), expected_sample_effects, "the next real click follows the ordinary eyedropper path");
}
}
+8 -3
View File
@@ -20,12 +20,17 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers
first point was picked on an anchor, the second also snaps onto the construction guides through
it; any other first point has no construction guides through it. The guides
show while hovering, before each click. VectorCraft's own rules decide where a point lands: an
anchor within 8 pixels takes it first; a point on a guide stays on the guide where the pointer
anchor within 8 pixels takes it first; with Smart Guides or Snap to Point on, the end of a line
of a visible, unlocked dimension already drawn (its dimension line, or the far end of an
extension line) within 8 pixels takes it next, without a link to that dimension; a point on a
guide stays on the guide where the pointer
is, except that it moves onto a segment within the Smart Guides snapping tolerance, or, on a
construction guide or a Snap to Glyph guide that runs at an angle, onto the place where that
guide crosses another object's alignment line within twice that tolerance; a point that no
anchor, guide, grid or pixel snapping places lands on the closest point of a segment within 8
pixels.
anchor, guide, grid or pixel snapping places lands on the closest point of a segment, or of a
line of a dimension already drawn, within 8 pixels. With Smart Guides and Anchor/Path Labels
on, a point on an anchor or a line end shows the "anchor" label, and a point on a segment or
line shows the "path" label. These rules apply to the Linear points.
A linear dimension is aligned, horizontal or vertical, as the
[linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html)
describes: after the second click, clicking again places an aligned dimension, and moving the
+3 -2
View File
@@ -145,8 +145,9 @@ private editing data. VectorCraft:
type with inline graphics, ruby, gradient or pattern paint or an appearance or opacity mask of its own, other patterns, other clipping objects and live
objects (placed documents included) are written as plain filled and stroked paths, and freeform gradients, gradients along
or across a stroke and gradients without stops, with more than 256 stops or without extent as their average
color, each with a warning. Gradients that dither or mix their colors perceptually are written as classic
gradients, and gradient stops linked to global process colors as their colors, each with a warning. The opacity
color, each with a warning. Gradients that dither are written without dither's noise, Perceptual gradients and
gradients mixed around the hue wheel as classic gradients of the stops on their curve in process colors (at most
256), and gradient stops linked to global process colors as their colors, each with a warning. The opacity
and blending mode of single fills and strokes, opacity masks on layers, the placement of pattern swatches that
move, turn or scale their pattern, and the effects of objects written without an art style, other than geometry
effects, are left out.
+6 -3
View File
@@ -420,6 +420,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Improved:** hanging punctuation (Roman Hanging Punctuation and Optical Margin Alignment) keeps its published amounts when justification scales glyphs, and Standard burasagari counts a hung line start as room; paragraph-level tests with both composers; estimate unchanged.
- **Done:** Paragraph panel menu › Justification… (#2755): word and letter spacing, glyph scaling (Minimum, Desired,
Maximum), Auto Leading and Single Word Justification per paragraph, used by both composers; estimate unchanged.
- **Done:** type on a path takes each paragraph's Justification… Desired word spacing, letter spacing and glyph
scaling, as point and area type do; estimate unchanged.
- **Done:** a paragraph's Auto Leading also sets the Leading the Character panel shows for Auto type, the leading the
Alt+↑/↓ nudge steps from and the lines Fill with Placeholder Text counts; estimate unchanged.
- **Missing:** CJK vertical
@@ -474,7 +476,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Implemented and tested (2026-11-15):** Swatches list rows and thumbnail cells have item context menus with Swatch Options…, Duplicate Swatch and Delete Swatch. Right-click selects the target without painting art; actions use that item's name and are disabled for reserved or missing swatches. All 39 Swatches tests pass, covering all five views, command dispatch, selection and Undo; the regression fails with the menu hooks removed. Rendered list and thumbnail menus were inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Other panels without context menus remain in G12; estimate unchanged.
- **Done (2026-11-14):** Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu with Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of the symbol), and Select All Instances, selecting the symbol if unselected. Estimate unchanged.
- **Done (2026-10-29, #4522):** the Pathfinder panel menu's Make, Release and Expand Compound Shape, which were dimmed placeholders, and the panel's Expand button act on live compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html)): Alt-clicking a Shape Mode makes one in that mode, a Shape Mode sets the mode of the members selected, and the compound shape draws, exports and saves as the area its members' modes make (`object.compoundShape.*`, `crates/engine/src/tests/compound_shape.rs`). Left: blends, envelopes and warps as members, question marks on the buttons for mixed member modes, clicks that hit the area rather than the members. Estimate unchanged.
- **Done (2026-10-29, #4522):** the Pathfinder panel menu's Make, Release and Expand Compound Shape, which were dimmed placeholders, and the panel's Expand button act on live compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html)): Alt-clicking a Shape Mode makes one in that mode, a Shape Mode sets the mode of the members selected, and the compound shape draws, exports and saves as the area its members' modes make (`object.compoundShape.*`, `crates/engine/src/tests/compound_shape.rs`). Left: blends, envelopes and warps as members, clicks that hit the area rather than the members. Estimate unchanged.
- **Done (2026-10-25, #3426):** Pathfinder panel › Pathfinder Options… ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): Precision (0.001–10 pt; results are refit to within it and pieces thinner than it are dropped), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (pieces of objects with no fill), kept in the preferences (`object.pathfinder.options`, group `pathfinder`) and used by every Shape Mode and Pathfinder button and Repeat; the page gives no defaults, so ours (0.01 pt, both off) keep the earlier results byte for byte. Trap is left as it was. Estimate unchanged.
- **Done (2026-10-25):** Artboards panel › Delete Empty Artboards ([Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html), [artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html)): `artboard.deleteEmpty` deletes every unlocked artboard with no artwork, with its guides, in one undo step, and keeps artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule). The Artboard tool's canvas context menu lists it too. Estimate unchanged.
- **Done (2026-10-25):** the Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both
@@ -555,8 +557,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
(`object.intertwine.arrange` with `order` front, forward, backward or back;
<https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-intertwined-objects.html>).
The group renders, saves and exports through its live expansion; an object brought over another shows no hairline
of the one below along that object's edges (#5337). Still missing: adding objects to the group by
dragging them in the Layers panel is untested.
of the one below along that object's edges (#5337). Objects dragged into the group in the Layers panel become
members (`layer.move`), and a group left with one member by a drag out is replaced by that member (or a plain group
of it, when the group has an appearance of its own).
- **Done (from users' reports):** Object › Create Gradient Mesh on an embedded image turns it into a mesh over its
rectangle, with the image's transform kept; each point takes the average colour and opacity of the picture around it
(#1676). A linked image is refused, as the public documentation has it.
+28 -12
View File
@@ -3053,6 +3053,14 @@ whose order changed and the id of the object now on top in each. A move that cha
overlap offers Bring to Front, Bring Forward, Send Backward and Send to Back, which run this command for the object
nearest to the pointer.
`layer.move` and `node.move` add objects to an Intertwine group: an object placed inside the group or beside one of its
members becomes a member, drawn in its row's order, with no arranged areas; the other members keep theirs. An object
placed in a group that is a member becomes part of that member and is drawn with it. An object that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused, as
`object.intertwine.make` refuses it, in a group inside the group too, and nothing changes. A member moved out of the group (also by
`object.arrange.sendToCurrentLayer`) drops its arranged areas. A group left with one member is replaced by that member, or
becomes a plain group of that member when the group has an opacity, blending, appearance, opacity mask, lock or hidden
state of its own. A group left with none is removed. Each of these happens in the move's undo step.
## Global Edit
Select › Start Global Edit is `select.globalEdit {appearance?, size?, artboards?, includeCanvas?}`. With one path,
@@ -5370,8 +5378,9 @@ and `layerRows`, the rows highlighted in the panel.
row highlighted, the trash button runs `edit.clear` on the selected guides and art, and guide rows dropped on the
trash are deleted (`guide.remove {indexes}`).
- **Dragging rows**: `layer.move {ids, target, place?: above|below|inside, copy?}` moves rows beside a row or into a
layer or group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves copies. Layers go
only in layers or at the top level and objects in layers and groups (an object placed beside a top-level layer goes
layer, group or Intertwine group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves
copies. Layers go only in layers or at the top level and objects in layers, groups and Intertwine groups (see
Intertwine for the members an Intertwine group takes; an object placed beside a top-level layer goes
inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. Dragging the
selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level
form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group.
@@ -6751,9 +6760,12 @@ also measured by its reshaped art when its symbol's art has geometry effects. A
Pathfinder effects, or with a fill or stroke of its own that has geometry effects or paints members with geometry
effects, is measured by its evaluated art. A blend, envelope or repeat whose objects have geometry effects is
measured by its evaluated art, with those objects measured after their effects. A 100 pt square without a stroke,
with Offset Path 10, measures 120 pt, and type with Outline Object is measured by its glyph outlines. Raster effects such as shadows and glows are not
measured. In one object, the art of at most 4,096 symbol instances is measured with its geometry effects, and the
other instances are measured without them. `object.setBounds` with `width: 100` gives that type a glyph box 100 pt
with Offset Path 10, measures 120 pt, and type with Outline Object is measured by its glyph outlines.
Extrude & Bevel, Revolve, Inflate and Rotate are measured by their projected vector art, including effects on
individual fills or strokes and geometry effects after projection. Groups and symbol instances include their
members' projected art. Raster effects such as shadows and glows are not measured. In one object, the art of at
most 4,096 symbol instances is measured with its geometry or 3D effects, and the other instances are measured
without them. `object.setBounds` with `width: 100` gives that type a glyph box 100 pt
wide.
```json
@@ -8482,7 +8494,9 @@ each file deflated, or stored when deflating does not make it smaller.
A row is `{format, scale?}` where `scale` is a factor (`2`, `"2x"`), a pixel width (`"100w"` or `width: 100`), a
height (`"100h"`) or a resolution (`"72ppi"`); raster rows name their files `@2x`, `@100w`… unless `suffix` says
otherwise. `fullDocument` writes one file per row instead (a PDF of every artboard, other formats the bounds of all
art), `includeBleed` grows each artboard by the document's bleed, `includeArtboardFill: false` (Include Artboard
art), `includeBleed` grows each artboard by the document's bleed (a PDF row's page keeps the artboard as its
TrimBox and puts the row's `bleed` around it once: the row's own values, zero included, else the document's bleed
when the row sets none and its PDF preset gives none or a bleed of 0), `includeArtboardFill: false` (Include Artboard
Fill unchecked) leaves the artboards' background colors out of the files, `pdfs: "single"` (Export PDFs As › Single file)
writes the artboards a PDF row exports as the pages of one PDF named after the document (it is refused with
`assets`, `layers` or `selection: "each"`, whose files each hold one item's art), `subfolders` puts each
@@ -9770,7 +9784,7 @@ paragraphs a `start` / `end` range touches), in percent:
The options are saved with the paragraph (`justification` in `para`) only when they differ from the defaults, and
paragraph styles carry them (`paraStyle.new {attrs: {justification: {auto_leading: 150}}}`). Vertical type isn't glyph
scaled, and type on a path doesn't use them. One undo step. `ui.justification` opens the Justification dialog on the
scaled. Type on a path takes the Desired values and does not use Minimum or Maximum. One undo step. `ui.justification` opens the Justification dialog on the
values the Paragraph panel shows, with Preview; OK sends the values that changed.
```json
@@ -12271,10 +12285,12 @@ type and evening out horizontal scales are not there yet.
Path Precision Tools is a built-in add-on for exact anchor and path work: its commands are `addon.pathtools.*`, and in
the desktop app it lives in Object › Plug-ins › Path Precision Tools, in its Anchor Inspector panel
(`window.panel {panel: "anchorInspector"}`), in its Parametric Shape panel (`window.panel {panel: "parametricShape"}`)
and in eight tools that the toolbars don't show until they are added from the All Tools drawer (or chosen with
`tool.select`): `anchorEraserBrush`, `extendPath`, `measureInspect`, `parametricShape`, `cornerTool`, `slideAnchor`,
`sharedEdge` and `trimAtCrossings`.
None has a shortcut. Each edit is one undo step, and an edit that changes nothing makes no step.
and in eight tools: `anchorEraserBrush`, `extendPath`, `measureInspect`, `parametricShape`, `cornerTool`, `slideAnchor`,
`sharedEdge` and `trimAtCrossings`. The toolbars don't show the first seven until they are added from the All Tools
drawer (or chosen with `tool.select`); `trimAtCrossings` is in the Scissors tool's group in both shipped toolbars,
after the Knife, and `ui.tool.list` lists it there. A toolbar edited before it joined keeps its saved layout until
Reset Toolbar. None has a shortcut; one can be set in Edit › Keyboard Shortcuts › Tools. Each edit is one undo step,
and an edit that changes nothing makes no step.
Tools:
@@ -12335,7 +12351,7 @@ Tools:
line has at most 4,096 points; past those limits it draws none. Once finding the crossings takes more than a
twentieth of the work a release may do, or checking the line against the paths' segments takes more than 1,000,000
box tests, the drag draws none until the next press. A click or a release still removes what it reaches. The tool
has no options.
has no options. Its cursor is the Knife's (`Knife`): a knife whose blade's point is the hotspot.
Commands:
+23 -3
View File
@@ -621,6 +621,7 @@ since 2026-10-01.
**Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it.
**Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it.
**Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it.
**Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it.
**Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it.
**Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it.
**Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling.
@@ -727,6 +728,7 @@ since 2026-10-01.
- **Colour emoji with bitmap glyphs:** `sbix` (Apple Color Emoji) and `CBDT` (Noto Color Emoji) glyphs draw as their largest strike's PNG, placed with the type and unpainted by its fill; PDF writes them in Type 3 glyphs or as images, SVG as images with outlined text, EPS and legacy `.ai` as images, and Create Outlines makes embedded images. Synthetic test fonts in `crates/text/src/test_fonts.rs`; tests `crates/text/src/tests/bitmaps.rs`, `crates/render/src/tests/bitmapglyphs.rs`, `crates/svg/tests/it/colour_glyphs.rs`, `pdf::tests::colour_bitmap_glyphs_export_as_images`, the `eps` `colour_bitmap_glyphs_*` tests and `tests_pathops::create_outlines_turns_bitmap_glyphs_into_images`. COLR and OpenType SVG fonts remain.
- **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, including ones that repeat or reflect, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients, Porter-Duff compositing and radial gradients that repeat or reflect and start at a circle draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated).
- **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated).
- **OpenType SVG glyphs from a shared document:** when one SVG document holds many glyphs, the importer reads only the glyph's element and what it refers to (by `href` or `url(#id)`, through other elements, the elements holding them and every `<style>` sheet); a document whose references or sheets cannot be followed this way is read whole, as before. The art is unchanged. A glyph whose own colors are fixed no longer counts as using the text's color because another glyph in its document does, and a glyph nested where a namespace prefix means something other than at the root keeps its own meaning. For 50 glyphs of a 2,000-glyph document (278 KB), thread CPU time went from 547 ms to 113 ms (medians of 9 alternating runs in one process). Measured by `glyph::tests` in `crates/svg/src/glyph.rs` and `svg/tests/it/svg_glyphs.rs`. Scores unchanged (estimated).
- **Create Outlines keeps the type object's own appearance:** Type › Create Outlines and Object › Expand put the type object's own fills and strokes (the Appearance panel's items around its Characters row) on paths of the whole outline, below or above the glyph paths as that row places them, with one gradient across every glyph, so the outlines draw what the type drew; `object.expand.info` reports those strokes, pattern fills and gradient fills. Outlined characters keep their stroke and fill (the help page, <https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=337>); a type object's appearance is separate from its characters' (the help page, <https://helpx.adobe.com/illustrator/using/appearance-attributes.html>); where the object's items go is VectorCraft's own rule. Measured by `tests::pathops::create_outlines_keeps_the_objects_own_fills_and_strokes`, `tests::objexpand::create_outlines_draws_the_type_objects_own_paint`, `tests::objexpand::type_objects_own_stroke_pattern_and_gradient_are_reported`, `tests::objexpand::type_without_an_outline_reports_no_own_stroke_or_fill`, `tests::objexpand::a_stroke_under_an_unpainted_stroke_is_reported_and_outlined` and `tests::objexpand::expand_keeps_the_type_objects_own_paint`. Scores unchanged (estimated).
- **Create Outlines keeps the type object's own effects and transparency:** Type › Create Outlines gives the group of outlines the type object's own effects, once, in their order, with their settings and hidden effects still hidden, so they stay live and editable and the outlines draw what the type drew (a Warp or Free Distort effect moves a gradient on the characters across the whole outline, as on the type); the effects of the object's own fills and strokes stay on their paths of the whole outline. The group also takes the object's opacity, blend mode, Isolate Blending, Opacity & Mask Define Knockout Shape and opacity mask. Outlined characters keep their stroke and fill (the help page, <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=365>); putting the object's effects on the group is VectorCraft's own rule. Measured by `tests::pathops::create_outlines_keeps_the_objects_own_effects_on_the_group`, `tests::pathops::create_outlines_keeps_the_objects_transparency_and_opacity_mask`, `tests::objexpand::create_outlines_draws_the_type_objects_own_effects` and `tests::objexpand::create_outlines_keeps_a_warped_character_gradient_across_the_type`. Scores unchanged (estimated).
- **Create Outlines keeps the characters' gradients across the type:** Type › Create Outlines and Object › Expand give every glyph, ruby glyph and underline or strikethrough bar the gradient its characters drew with: a gradient with no vector of its own stays fitted to the whole layout rather than to each glyph, and one with a vector keeps its place, both moved, scaled and rotated with the type; the characters' stroke keeps the weight it was drawn at on scaled type. `object.expand.info` measures gradient fills on the same paths. Outlined characters keep their stroke and fill (the help page, <https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=337>); the gradient fitted across the whole layout is VectorCraft's own rule. Measured by `tests::objexpand::create_outlines_keeps_a_character_gradient_across_the_type` and `tests::objexpand::expand_keeps_a_character_gradient_across_the_type`. Scores unchanged (estimated).
@@ -747,6 +749,7 @@ since 2026-10-01.
- **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html).
- **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy `<name> copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html).
- **Auto Leading outside the layout:** a paragraph's Justification… › Auto Leading (<https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>) also sets the Leading the Character panel shows for Auto type (blank where the selected paragraphs differ), the leading the Alt+↑/↓ nudge (`type.step`) steps from, each paragraph's own, and the lines Fill with Placeholder Text counts in area type. Evidence: `ParaStyle::effective_leading` (`crates/doc/src/text.rs` test `paragraph_effective_leading_follows_auto_leading`), `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading`.
- **Justification… on type on a path:** each paragraph's Desired Word Spacing, Letter Spacing and Glyph Scaling set its glyphs on type on a path as on point and area type, so the text after a wider gap starts further along the path, alignment and overflow use the spaced length, and a list marker keeps its width. Minimum and Maximum are not used on a path, and vertical type is not glyph scaled. SVG export writes such type as outlines with a warning. Tests `tests::justify::type_on_a_path_takes_desired_spacing_and_scaling`, `type_on_a_path_is_aligned_and_fitted_at_desired_spacing`, `vertical_type_and_list_markers_on_a_path_are_not_glyph_scaled` and the SVG test `text_layout::justification_spacing_on_a_path_is_outlined`. Public reference: the help page (<https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>).
- **Letter spacing and Full Justify between shaped clusters:** Desired Letter Spacing on any line, the letter spacing range of a justified line, and Single Word Justification's Full Justify add space only between shaped clusters, in horizontal, right-to-left and vertical type, so a combining mark stays on its letter and a Devanagari syllable's glyphs stay together. They add no space next to a zero-width format control (a soft hyphen, a bidi mark, embedding, override or isolate, a zero-width space, a joiner or non-joiner, a word joiner, a variation selector, a tag, the byte order mark), so a word wrapped in an override still reaches both edges of a justified line, and a Kinsoku push-in counts no gap at one either. A zero-width space is a line break opportunity but not a word separator ([CSS Text Level 3](https://www.w3.org/TR/css-text-3/#word-separator) does not list it), so a justified line gives it no share of its room. Desired Letter Spacing between the letters on either side of a zero-width space goes after the zero-width space, so a line that breaks there ends at its last letter, and the line breaker does not measure a gap after it. A line that Full Justify spreads and that ends in a drawn hyphen puts the same gap between its last letter and the hyphen. The cluster boundary is VectorCraft's own rule, based on the typographic character unit of [CSS Text Level 3](https://www.w3.org/TR/css-text-3/#typographic-character-unit). Tests `tests::justify::single_word_full_justify_keeps_combining_mark_with_base`, `desired_and_fitted_letter_spacing_skip_shaped_cluster`, `rtl_single_word_cluster_gap_follows_drawn_order`, `vertical_single_word_cluster_gap_follows_drawn_order`, `single_word_full_justify_keeps_conjunct_cluster`, `desired_letter_spacing_skips_bidi_format_controls`, `letter_spacing_and_full_justify_skip_joiners_and_soft_hyphens`, `format_controls_are_the_zero_width_default_ignorables`, `zero_width_space_takes_no_word_space_room`, `desired_letter_spacing_ends_a_line_broken_at_a_zero_width_space_without_a_gap`, `single_word_full_justify_spreads_up_to_the_drawn_hyphen` and `layout::wrapping_tests::kinsoku_shori_type_counts_no_gap_at_a_format_control`. Public reference: the help page (<https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>).
- **Justified lines with tabs:** a tab is not a word space, so a justified area type line no longer gives it a share of its room that no glyph draws. On a justified line with a tab, the text up to the last tab keeps its spacing, each tab keeps its stop and its leader stays in its gap, and the text after the last tab takes the room (word spaces first, then letter spacing, glyph scaling and the gaps between its letters), so the line ends on the far edge. A tab separates two words, so Single Word Justification does not align a word-tab-word line. Right-to-left lines take the text drawn after the last tab drawn, and vertical lines work down the column. Spreading the room after the last tab is VectorCraft's own rule. Tests `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge`, `a_justified_tab_keeps_its_leader_inside_its_gap`, `a_justified_word_tab_word_line_reaches_the_edge`, `the_last_line_with_a_tab_fills_the_measure_only_with_justify_all`, `a_justified_line_takes_its_room_after_its_last_tab`, `a_justified_vertical_line_with_a_tab_reaches_the_end_of_its_column`, `a_justified_right_to_left_line_with_a_tab_spans_its_measure` and `justified_point_type_with_a_tab_keeps_its_width`. Public reference: the help pages (<https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html>, <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>).
- **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html).
@@ -766,6 +769,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Smooth widths between width points (#5714):** a variable-width stroke changes width along a smooth curve from one width point to the next, where it used to run in a straight line and turn a corner at each point. The public description is that the path "gradually gets wider or narrower from one point to the next" in "a flowing, continuous curve", and that stacked points make a sharp break ([Peachpit, Expressive Strokes](https://www.peachpit.com/articles/article.aspx?p=2979069)); the exact curve is not documented, so each side follows a monotone cubic (Fritsch–Carlson): no kink at a point, flat where a point is wider or narrower than both neighbours, never past the points either side, points on one line kept on it. The outline samples straight runs between width points closely enough to follow the curve to the drawing tolerance (at most 64 samples per span and 4,096 per piece). Presets with a middle point (Lens, Pinch, Teardrop, Wave) look softer; two-point tapers are unchanged. Tests: `appearance::profile::tests::{widths_run_smoothly_through_width_points, widths_never_pass_the_points_either_side, a_step_ends_the_curve_on_each_side, widest_covers_every_width_along_the_profile}`, `stroke::width::tests::{a_straight_run_follows_the_curve_between_width_points, samples_between_width_points_are_capped}`.
- **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes).
- **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`.
- **Wide curved stroke edges:** the canvas and raster exports draw a stroke at least 32 drawing tolerances wide along curves that span 128 tolerances or more with the rims of its outline closer to the curves, so the outer rim no longer draws too light and the inner rim too dark. That is 8 and 32 device pixels at 25% and 1:1, and as little as just over 4 and 16 device pixels at other zooms. At 25% zoom an 80 pt ring's worst edge pixel is 24 levels off the exact coverage at the outer rim and 32 at the inner rim, where it was 54 and 61. Fills, narrower strokes, strokes with a width profile, strokes in an unevenly scaled view and vector exports are unchanged. Tests: `render::tests::curvedstrokeedges`, `render::tests::longstroke::a_long_wide_curved_stroke_draws_the_same_pixels_outlined_near_the_view`.
- **Ruler double-click (#5239):** a double-click (both clicks on that ruler) on the top ruler adds a vertical guide at the pointer's x and one on the left ruler a horizontal guide at its y (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), through `guide.add` in one undo step; the guide is not snapped, is shown even when guides were hidden, and is an artboard guide with the Artboard tool, as a drag from a ruler makes one. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe the gesture, so it follows the request in #5239. egui frame tests cover both rulers, a lone click, Undo, a canvas click before a ruler click, and rotated views.
- **Rulers (#1212):** drag the intersection to preview and set a document zero point, snapped as a drawn point is (with Smart Guides onto the art's and the artboards' anchors, centres, edges and paths or into line with them, with Snap to Point along the ruler guides, else to pixels or the grid), or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html).
- **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html).
@@ -830,6 +834,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Variables: Lock Variables (`variable.lock`, in the Variables panel's bottom bar and menu) stops variables from being defined, deleted or renamed until they are unlocked, while objects can still be bound and unbound and data sets still change and apply; the lock is saved with the document.
- Variables: the Variables panel lists its variables in three columns with headers (type, Variables, Objects), and a click on a header sorts the list by variable type, variable name or bound object name, with a second click reversing the order (`variable.sort`; `variable.list` follows the order), as the [Variable panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/variable-panel-overview.html) describes.
- Variables: the Data Set box at the top of the Variables panel takes typed text, and a new name entered there renames the current data set with `dataset.rename` in one undo step; the same name adds no undo step, an empty or taken name is refused with a status message, and the list button beside the box still chooses a data set.
- Variables: the Variables panel builds its rows (each variable's bound objects and object name in the list's order, and each data set's value count, current mark and italics) once for each version of the document, and again when the list's order, Identify Objects By, the interface language or the new art on a locked artboard changes, instead of on every frame while the panel is open. The rows are the same as before. Tests `frames_without_a_change_build_the_rows_once` and `each_input_of_the_rows_builds_them_again` in `panels::variables`; the ignored test `rows_timing` compares the time of the two.
- Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`.
- Batch…: Override Export writes the files of an Export for Screens or Export Assets step into a folder for each source file or data set inside the destination folder, under the names the export gives them (`action.batch`). The folder and file names drop trailing periods and spaces (`a..svg` gives `a`). When two source files would get the same name that way (compared without case), or a later file's folder or file would take the name of an output an earlier file wrote, of a source file in the destination folder or, for data sets, of a file already there, Batch adds `-2`, `-3`… to the later one's name.
- Batch…: when a step fails on a file or data set, the error names the step by its place in the action's steps, from 1, counting the Open steps the batch skips (`action.batch`). This numbering is VectorCraft's own rule. Tests `cmd::fileio::action_batch::tests::{a_folder_batch_error_names_the_step_in_the_commands_sent, a_recorded_open_that_fails_is_the_first_step, a_data_set_batch_error_names_the_step_in_the_commands_sent, a_redirected_export_that_fails_keeps_its_place, a_source_that_does_not_open_names_no_step}`.
@@ -864,6 +869,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Export for Screens artboard names can be double-clicked to rename them in grid or list view (#7275). Enter, a click outside the field or switching to Assets commits the name; Escape cancels the edit. The dialog stays open, checked artboards stay selected and the rename is undoable. The typed name goes to the artboard that was double-clicked even when the artboards change order while it is typed; the field closes when its artboard is deleted or another document becomes active. Evidence: `dialogs::tests_screens::double_clicking_an_artboard_name_in_export_for_screens_renames_it`, `dialogs::tests_screens::switching_export_tabs_commits_an_artboard_name`, `dialogs::tests_screens::an_artboard_name_follows_its_artboard_while_it_is_typed` and `dialogs::tests_screens::an_artboard_name_stays_with_its_document`.
- Asset Export panel menu: Create Sub-folders (on by default) and Open Location after Export are check items that set the dialog's two checkboxes (`assets.settings.set {subfolders, openLocation}`), and the panel's Export follows them, including a folder per format or item that Export for Screens remembers (3D assets' mesh files go in the folder itself); Format Settings… opens Export for Screens on the first row's format settings ([Asset Export panel](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/collect-and-export-assets-from-asset-export-panel.html)). Tests: `panels::tests_asset_export`.
- Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`.
- Export for Screens with Include Bleed: a PDF row's page keeps the artboard as its TrimBox and puts the bleed around it once as the BleedBox (a 100 pt artboard with a 9 pt document bleed gives a 100 pt TrimBox in a 118 pt BleedBox, in one file per artboard, a single file and the Full Document), so printer's marks line up with the artboard's edge. The bleed is the row's own (zero included, which a PDF/X row warns about), else the document's when the row sets none and its PDF preset gives none or a bleed of 0; raster, SVG and EPS rows still write the grown artboard. Tests: `fileio::tests_screens::include_bleed_pdf_pages_trim_at_the_artboard` and `include_bleed_pdfx_rows_do_not_warn_about_the_bleed`.
- Export for Screens refuses `pdfs: "single"` with `assets`, `layers` or `selection: "each"`, whose files each hold one item's art, instead of writing the first item alone as one PDF named after the document; `pdfs: "multiple"` writes a PDF of each item, and the selection as one file writes one PDF either way. The rule is VectorCraft's own. Tests: `fileio::tests_screens::single_file_pdfs_are_refused_for_assets_layers_and_each_object`.
- Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`).
- Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`).
@@ -1027,7 +1033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`).
- The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`).
- Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8).
- A Recent Commands button beside the Help › Search Commands field lists the last five commands and tools picked from the palette, most recent first, with a command picked again moved to the top. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`).
- A Recent Commands button beside the Help › Search Commands field lists the last five commands, tools, panels and effects picked from the palette, most recent first, with a command picked again moved to the top. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`).
- The Learn panel (Window › Learn, or Explore tutorials beside the search icon on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their progress rings and counts of tutorials finished; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list`, `learn.tab {tab}`, `learn.skill {skill}`, `learn.show {tutorial}` and `learn.back` script it, and the tab buttons, the rows and Back run them ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`).
- A tool's name in a Learn tutorial step is a blue link that shows where the tool is without choosing it (`learn.locateTool {tool}`): its toolbar button is marked, a collapsed group's flyout opens with the tool's row marked, a torn-off strip comes to the front, and a tool no shown toolbar holds is marked in the All Tools drawer. The mark, its 3 seconds and the hidden-toolbar cases are VectorCraft's own rules ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`, the `a_learn_link_*` tests in `toolbar::tests`).
- Under a tutorial's steps, View more opens the tutorial's own practice sample as a new untitled document, and once the tutorial is finished, Next Up moves to the next tutorial in the same skill, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). The samples are VectorCraft's own drawings. A Finish tutorial button that shows once the sample is open, the untitled copy, Back to skills in place of Next Up after a skill's last tutorial, and Next Up showing the next tutorial without opening its sample are VectorCraft's own rules. `learn.openSample`, `learn.finish`, `learn.next` and `learn.skills` (Back to skills) script them. Not done: the help page's short video. Regression tests: `view_more_opens_the_tutorial_s_sample_as_a_new_untitled_document`, `finishing_a_tutorial_offers_next_up_in_its_skill`, `the_practice_controls_work_from_the_keyboard`, `the_last_tutorial_of_a_skill_offers_back_to_skills`, `learn_finish_and_learn_next_follow_the_practice`, `learn_skills_shows_the_list_of_skills`, `the_practice_commands_reject_a_missing_or_unknown_tutorial`, `every_tutorial_has_its_own_readable_sample` and `the_next_tutorial_is_the_next_one_in_the_same_skill` in `crates/ui-egui/src/panels/learn/tests.rs`.
@@ -1166,6 +1172,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
To find those segments, the marquee skips each segment whose anchors and handles all lie past one side of it and tests only the rest exactly, without building a path for each segment. It selects the same segments as before, and a marquee over a path of many anchors finishes sooner.
The Direct Selection and Group Selection marquees, the Lasso and Smart Pen select the anchors they reach (`select.anchorsMany`) with one pass over the selected objects, instead of one pass for each path. The objects, their order and the anchors selected are the same as before. Selecting one anchor on each of 50,000 rectangles takes a median of 29 ms of CPU time instead of 776 ms in a release build on Linux, and on 20,000 rectangles 10 ms instead of 124 ms; on 2,000 rectangles both take about 2 ms or less (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib anchor_items_perf -- --ignored --nocapture`).
With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection.
With members of a group selected whole (with Group Selection, for example), a Selection-tool press on one of them keeps the selection: the pointer shows Move, a drag moves only the selected members (Shift constrains it), a Shift-click takes the pressed member out of the selection, and Alt over it shows no Distance Guides. A press on a member that is not selected, or only partly selected, still selects the outermost group ([Select objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). Test: `select::tests::a_press_on_a_selected_member_of_a_group_moves_the_selected_members`.
The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode.
Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged.
Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged.
@@ -1331,6 +1338,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
With Paste Remembers Layers on, art copied from a sublayer pastes back into that sublayer, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=223) describes art going back to the layer it was copied from: in the same document while the sublayer is still there, two sublayers of the same name in different layers kept apart; in another document by the names of the sublayer and the layers around it. These rules are VectorCraft's own: a missing sublayer is made inside its layer (a missing layer on top, with the sublayer inside it), in the paste's one undo step; of layers with the same names, the topmost chain that matches the most names wins, a shown and unlocked one first; a matched layer that is hidden or locked, or inside one that is, refuses the paste, and nothing is pasted.
The Filter button at the right of Search All keeps the rows that are of an object kind ticked under By Object (paths, shapes, text, images, effects, groups, linked files, guides) and in a state ticked under By Layer (locked, hidden), with the rows that hold them; a section with nothing ticked takes every row. The filter combines with the search, the button is lit while a filter is on, and Clear All in its popup turns the filter off (`ui.layersFilter`). The filter lasts the session.
The panel menu's Save Selection submenu has Save Selection…, Update Selection and Edit Selection…, enabled and run as in the Select menu, and lists the document's saved selections: choosing one selects its objects again (`select.recall`).
Objects dragged onto an Intertwine group's row, or beside one of its members' rows, become members of the group, as [the help page](https://helpx.adobe.com/illustrator/using/intertwine-objects.html) describes adding objects to the group later; Alt-drag adds copies, in one undo step either way (`layer.move`, `node.move`). An object that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group gets no inside box on the group's row and no line beside a member's row, and is refused with the reason, as Make refuses it, and the document is left as it was. As VectorCraft's own rules, a new member has no arranged areas and is drawn in its row's order, the other members keep theirs, a member dragged or sent to the current layer out of the group drops its areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own. Tests: `layer_move_*`, `node_move_and_send_to_current_layer_clean_up_membership` (`crates/engine/src/tests/intertwine.rs`), `panels::layers::tests::dragging_a_row_into_an_intertwine_adds_a_member`.
Deleting rows from the Layers panel (the trash button, rows dragged onto it, the panel menu's Delete Selection, and Delete or Backspace on highlighted rows) asks "Delete this layer and its artwork?" when a layer or sublayer among them holds art, hidden, locked and nested art included, and "Delete the selected items and their artwork?" when several rows are deleted; OK deletes the rows it asked about in one undo step, and Cancel keeps them (`ui.layerDelete`). The help page's shortcut list names the Layers panel as the place where deleting asks for confirmation ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). An empty layer, a layer with only guides, and groups or objects alone are deleted without a question, and `layer.delete` itself does not ask (`panels::layers` tests `deleting_a_layer_that_holds_art_asks_first`, `delete_selection_asks_only_for_layers_with_art`).
The Command Palette lists Window › Layers › Delete Selection once, as the Layers panel's `ui.layerDelete`, so a pick asks the same question; it does not list `layer.delete`, which scripts run without a question. New Brush…, Brush Options…, Symbol Options…, Import SVG Filter… and Convert to Text are also listed once each, as the UI command that opens the dialog or file chooser (`palette` tests `a_wrapped_engine_command_is_listed_once_as_its_ui_command`, `a_pick_of_delete_selection_asks_before_deleting_a_layer_with_art`).
No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Export › Continue in Background and Open › Continue in Background, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`).
@@ -1417,6 +1425,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Without a twist, a tapered Extrude & Bevel wall (and each bevel band) is one flat face; only a twist cuts walls into slices, so no seam between slices paints a light tick or a light line on a tapered, untwisted wall (#7019). Test: `solid::tests::a_tapered_wall_is_one_flat_face_and_a_twisted_one_is_sliced`.
- Extrude & Bevel cuts a corner square where the bevel opens it and its miter would reach past four times the width (a sharp point with the bevel outside, a narrow notch with it inside), so the bevel (and, with the bevel outside, the walls) no longer runs out to a spike that does not line up with the art (#7525). Tests: `solid::tests::a_bevel_cuts_sharp_corners_square`, `solid::tests::a_cap_draws_no_empty_segment_at_a_corner_cut_square`.
- Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715).
- Use Preview Bounds measures Extrude & Bevel, Revolve, Inflate and Rotate by VectorCraft's projected vector art, including fill and stroke effects, group and symbol members, and geometry after projection. Engine regressions cover all four families, hidden effects and the preference off, alignment and spacing with Undo, typed width, and oriented boxes. Raster effects are not measured yet. The [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf) (printed page 95, Info panel) says Use Preview Bounds counts the stroke and other appearance attributes in an object's dimensions.
- Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)).
- Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`).
- The solids of one Extrude & Bevel (both kinds) or Inflate effect on one object, its fill's, its strokes' and a group's members' together, keep up to 163,840 faces (VectorCraft's own limit). Each solid is built in turn; once their faces pass the limit, no later solid is built, the object draws its source art, and applying or editing the effect, Export 3D Object and Expand as Wireframes report that the 3D surface is too complex. Tests `solids::tests::an_objects_solids_count_their_faces_together`, `a_groups_solids_together_past_the_limit_draw_the_source`, `a_fill_and_strokes_together_past_the_limit_draw_the_source`.
@@ -1433,7 +1442,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Pathfinder Options ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the panel menu's Pathfinder Options… sets Precision (0.001–10 pt: results refit to within it, thinner pieces dropped), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (`object.pathfinder.options`, kept in the preferences) for every Shape Mode and Pathfinder operation; the defaults keep the earlier output (`pathops` `precision_drops_pieces_thinner_than_it`, engine `tests_pathops` Pathfinder Options tests, `panels::pathfinder` dialog test).
- Pathfinder on clip groups (#8093): a clip group's members take part in the Shape Modes and Pathfinder buttons (`object.pathfinder.*`) only where its clipping path shows them, so Divide cuts the visible art along the mask and the hidden art goes; nested clip groups cut by each mask, a member the mask hides gives no piece, a cutting line's hidden part cuts nothing, a selected object the masks hide altogether counts as an empty shape where that changes the result (Intersect, Minus Front, Minus Back, Crop), and the clipping path adds no piece of its own (the public documentation doesn't say what Pathfinder does with masked art; our choice, asked on the issue). A cutting line is clipped by sampling, so a part of the mask much narrower than the mask itself can be missed. Make Compound Shape, Trap and the Pathfinder effects still take the members whole. Tests: `crates/engine/src/tests/pathfinder_clip.rs`.
- Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html), [Pathfinder panel](https://helpx.adobe.com/illustrator/using/pathfinder-panel-overview.html)): the Pathfinder panel menu's Trap… (`object.pathfinder.trap`) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add, where two objects' visible areas of different solid colours meet, a strip of the darker one's area along the edge, filled with the lighter colour at the Tint Reduction percentage and set to overprint (Reverse Traps: the darker colour spreads instead, but not a rich black); Thickness 0.01–5000 pt across vertical edges, Height/Width scales it across horizontal ones, Traps with Process Color paints a swatch colour's trap with its CMYK equivalent; the effect also has Precision and Remove Redundant Points. The panel's Trap is one undo step and groups the traps above the topmost selected object, selected; with no adjoining edges of different colours it says so and changes nothing. Tests: `crates/pathops/src/trap.rs`, `crates/effects/src/trap.rs`, `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `crates/engine/src/tests/trap.rs`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`.
- Compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the Pathfinder panel menu's Make Compound Shape (every member in Add) and Alt-clicking a Shape Mode (every member in that mode) make the two or more selected paths, compound paths, groups, compound shapes or type a live compound shape (`object.compoundShape.make`): a group whose members each keep a shape mode and stay editable, drawn, printed and exported (SVG, PDF and the rest through the baked document) as the area the modes make from the backmost member up, open paths closed, painted with its own appearance, taken from the topmost member not subtracting. With members selected (Direct Selection, Layers panel, isolation mode) a Shape Mode button sets theirs (`object.compoundShape.setMode`) and is lit for the mode they share; paint given to a member goes to the compound shape. Release Compound Shape gives the members back as they were (`object.compoundShape.release`); Expand Compound Shape and the panel's Expand button turn it into the path or compound path of its area (`object.compoundShape.expand`). Shape Modes and Pathfinders take a compound shape as its area. Saved files keep it (`compound_shape`, `shape_mode`; an unknown mode reads as Add). Blends, envelopes and objects with a warp or another geometry effect are members as they draw (a blend's steps, an envelope's distorted art, the warped outline), and the area follows an edit of the blend, envelope or warp; Release gives them back as they were. Tests: `crates/engine/src/tests/compound_shape.rs`, `group::tests::compound_shapes_draw_the_area_their_shape_modes_make`, `group::tests::nested_compound_shapes_take_part_as_their_area`, `panels::pathfinder::tests::compound_shape_items_follow_the_selection`, the `CompoundShape` op of the property-test strategies. Not yet: the question marks on mixed member modes, hit-testing by the area (a click hits the members).
- Compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the Pathfinder panel menu's Make Compound Shape (every member in Add) and Alt-clicking a Shape Mode (every member in that mode) make the two or more selected paths, compound paths, groups, compound shapes or type a live compound shape (`object.compoundShape.make`): a group whose members each keep a shape mode and stay editable, drawn, printed and exported (SVG, PDF and the rest through the baked document) as the area the modes make from the backmost member up, open paths closed, painted with its own appearance, taken from the topmost member not subtracting. With members selected (Direct Selection, Layers panel, isolation mode) a Shape Mode button sets theirs (`object.compoundShape.setMode`) and is lit for the mode they share; with members in different modes selected, each of the four Shape Mode buttons carries a question mark and screen readers report it as mixed, and a click gives every selected member that mode in one undo step ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=368)); paint given to a member goes to the compound shape. Release Compound Shape gives the members back as they were (`object.compoundShape.release`); Expand Compound Shape and the panel's Expand button turn it into the path or compound path of its area (`object.compoundShape.expand`). Shape Modes and Pathfinders take a compound shape as its area. Saved files keep it (`compound_shape`, `shape_mode`; an unknown mode reads as Add). Blends, envelopes and objects with a warp or another geometry effect are members as they draw (a blend's steps, an envelope's distorted art, the warped outline), and the area follows an edit of the blend, envelope or warp; Release gives them back as they were. Tests: `crates/engine/src/tests/compound_shape.rs`, `group::tests::compound_shapes_draw_the_area_their_shape_modes_make`, `group::tests::nested_compound_shapes_take_part_as_their_area`, `panels::pathfinder::tests::compound_shape_items_follow_the_selection`, `panels::pathfinder::tests::shape_modes_show_a_question_mark_while_the_selected_members_modes_differ`, `panels::pathfinder::tests::members_of_two_compound_shapes_are_compared_together`, `panels::pathfinder::tests::shape_modes_show_no_question_mark_without_mixed_members`, the `CompoundShape` op of the property-test strategies. Not yet: hit-testing by the area (a click hits the members).
- Effect › Path › Outline Object has no options. Type that carries it is drawn, exported (PDF and SVG as paths, with no font) and expanded as its glyph outlines while it stays editable, and the effects after it reshape those outlines. Paths and images draw as before. With Use Preview Bounds on, type is measured by its glyph outlines. Public reference: [Summary of effects](https://web.archive.org/web/20210901011839/https://helpx.adobe.com/illustrator/using/summary-effects.html) (archived copy).
- A butt cap ends a stroke square at the end of an open path, and a projecting cap extends half the weight past it. VectorCraft's visual box of a butt-capped stroke on an open path does not grow past the path's ends: a straight segment's box comes from the corners of its stroked rectangle, and a curve's box comes from the stroke at its ends and where its tangent is square to an axis. Round and projecting caps and arrowheads still reach past an end. A curve that bends more tightly than half the weight can measure a little larger than it paints, and a butt-dashed path whose first or last dash is a gap is measured to the path's ends. Public reference: [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html).
- A butt-capped curve whose first or last handle sits on its end point also stops at that end: a straight 50 pt curve with a 2 pt stroke and its first handle on its start point measures 50 pt tall, not 51 pt (doc `reach::tests::a_butt_curve_with_a_handle_on_its_end_point_stops_near_that_end`).
@@ -1470,6 +1479,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`.
- **Show Similar Fonts: families without numbers come last:** in a font menu's Show Similar Fonts list and `text.similarFonts`, a family whose faces give none of the numbers the list compares (PANOSE, weight, width, heights, average width, italic angle) in common with the chosen family comes after every family of its script group that shares one, instead of right after the chosen family as an exact match. This is VectorCraft's own rule; the help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describes the list only as fonts that look like the chosen one. Regression tests: `a_family_without_numbers_comes_after_the_measured_ones` and `likeness_is_a_distance` in `crates/text/src/tests/similar.rs`.
- **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, lists the installed families available in the font menu. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`.
- **Find Font: Escape and the replacement search:** Escape with the Replace With Font From or Find In list open closes only the list. The dialog stays open with its choices and its search, also while Escape is held down, and the next press of Escape closes it. Done, Enter, Escape, and Find in Folder… once the Missing Fonts dialog opens, each forget the replacement search, so the next Find Font starts with an empty one; with no folder picked, Find Font stays open with its search. This is VectorCraft's own rule: a dropdown or popover open in a dialog closes before the dialog. Tests: `crates/ui-egui/src/find_font.rs`.
- **Select Text by Font: scope (a VectorCraft addition, #5529):** `select.font` takes `scope`: `"document"` (the default, as before), `{artboards: [index, …]}` or `{layers: [id, …]}` (sublayers included). On an artboard means what All on Active Artboard takes (the bounds overlap it or the center is on it; one shared test, `select::on_artboard`); hidden and locked text stays out as before; a symbol instance counts where the instance is. Type › Find Font…'s Find In dropdown passes the active artboard or the selected layers (else the current layer). Tests: `crates/engine/src/cmd/fonts.rs`, `crates/ui-egui/src/find_font.rs`, `crates/engine/tests/command_sweep.rs`.
- **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`.
- **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`.
@@ -1675,6 +1685,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`).
- **Paint and appearance (M3):**
- **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged.
- **CSS swatch libraries:** a gradient swatch's off-center midpoints and the curve of a Perceptual, Hue Clockwise or Hue Counterclockwise gradient are written as stops of their own, each with its color and opacity, also on repeated, reflected and mirrored conic swatches, so the CSS value draws the colors the swatch has. CSS mixes hex colors evenly in sRGB between two stops ([CSS Color 4 interpolation space](https://www.w3.org/TR/css-color-4/#interpolation-space), [CSS Images 3 gradient line](https://www.w3.org/TR/css-images-3/#coloring-gradient-line)). Regression: `palette_io::tests::css_gradient_swatches_draw_their_midpoints_and_curves`.
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged.
Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included.
@@ -1732,6 +1743,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Hue Clockwise and Hue Counterclockwise, VectorCraft's own gradient methods, in the Gradient panel's Method menu and on `paint.editGradient` and `paint.setFill` (`method`: `hue-clockwise`, `hue-counterclockwise`): a linear, radial, conic or diamond gradient's colors mix around the hue wheel, with hue, saturation and brightness each changing evenly from one stop to the next and the hue angle keeping one direction, as the fixed-direction rules of [CSS Color 4](https://www.w3.org/TR/css-color-4/#hue-interpolation) do: falling with Hue Clockwise (red, magenta, blue), which is clockwise on the color wheels, and rising with Hue Counterclockwise (red, yellow, green). Hues less than half a color level apart count as one hue, so a color and its tint do not turn the wheel. A gray stop takes the hue of the stop it mixes with, and black its saturation too. The canvas and raster exports draw it through stops on that curve, within half a color level; Reverse Gradient turns the method the other way with the stops, so the ramp keeps its colors. SVG and PDF write it as an RGB image, EPS as a shading in process colors, and a legacy `.ai` file and the `.ai` editing data with the colors between its stops as stops of their own, with a warning.
- Gradient spread, VectorCraft's own setting: Pad, Repeat or Reflect, with a Repeats count of 1 to 100, in the Gradient panel and on `paint.editGradient` and `paint.setFill`; Repeat and Reflect run a linear, radial, conic or diamond gradient's stops that many times along the vector and on past its ends, the Gradient tool marks where the runs meet, and SVG writes and reads `spreadMethod`, CSS writes repeating gradients, PDF writes a conic's sweep shading over one run and the other kinds with their stops repeated across the shape, as EPS, legacy `.ai` and the `.ai` editing data do.
- The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681).
Escape ends that eyedropper's pick, and Brush Options' Key Color pick, without sampling and returns to the tool that started it; the stop keeps its color, and Brush Options stays open with its Key Color until a new Escape cancels it (#8024, [Modify gradients, archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=264)).
Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)).
With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke.
- **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own.
@@ -2343,6 +2355,14 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi
`pdf::tests::dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill` and the Gradient panel's
`the_method_menu_makes_the_gradient_perceptual`. Scores and hours unchanged.
A saved `.ai`'s editing data writes a Perceptual gradient, in the art and in the Swatches panel, as a classic gradient of
the stops on its curve in process colors (at most 256, the stops VectorCraft's reader reads), as it writes a gradient
mixed around the hue wheel, so the file opens with the colors between the stops it had; a gradient definition's stops
there hold no interpolation method (`crates/eps/src/import/ai/paint.rs:193-245` reads each `Bs` stop's color, opacity,
midpoint and ramp point). The warning names Perceptual gradients, and a stop linked to a global process color reports
its lost link; Dither's noise is reported as its own loss (VectorCraft's own rules). Test:
`ai_editing::tests::perceptual_gradients_are_written_with_the_stops_on_their_curve`.
PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html); [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html)). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there, or at the stop's mix position between the two colors when that mix's lightness turns back on the way from one color to the other, as from red to blue (VectorCraft's own rule). Dithered fills, freeform gradients, Perceptual gradients that mix a spot color with RGB or Lab stops, and Perceptual gradients whose curve has more than 4,096 stops once expanded (VectorCraft's own limit) are still images, and the export warns that their spot colors are written in process colors. In a CMYK document, or an export that converts colors to a CMYK destination profile, RGB and Lab stops are written in CMYK, so a Perceptual gradient that mixes a spot color with them is a DeviceN shading; an export that converts colors to an RGB destination profile keeps them in RGB. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve`, `ink_mixes_follow_the_perceptual_curve` and `ink_mixes_use_the_mix_position_when_the_lightness_turns_back`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings`, `perceptual_spot_gradients_with_rgb_stops_in_a_cmyk_document_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`.
In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`.
@@ -2572,7 +2592,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
## Path Precision Tools add-on: Trim at Crossings (2026-11-13)
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (kept out of the shipped toolbars, listed in the All Tools drawer, no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on.
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`).
## Document Tools add-on: Save a Timestamped Copy (2026-11-01)
+2 -2
View File
@@ -46,9 +46,9 @@ against Illustrator's public documentation; **estimated** unless noted.
| System Layout | done | Character panel menu › System Layout, `type.systemLayout`: the whole document, off by default and for documents from before it, saved only when on. On, every text object advances by whole points (at least one when a character takes space). New point, area and path type, threaded frames, placed text, graph and dimension labels and pasted plain text inherit it. Evidence: `tests::system_layout_rounds_positive_advances_to_whole_points`, `typecmd::area_tests::system_layout_sets_the_document_and_every_text_object`, `panels::character::tests::system_layout_menu_item_toggles_the_document` |
| Fractional Widths | done | Character panel menu › Fractional Widths, `type.fractionalWidths`: per type object, and every frame of its threads. On by default and for documents from before it; saved only when off. Off, each character that takes space advances by a whole number of points, at least one, so small type does not run together. Evidence: `tests::fractional_widths_off_rounds_positive_advances_to_whole_points`, `typecmd::area_tests::fractional_widths_is_set_per_object_and_saved_only_when_off`, `panels::character::tests::fractional_widths_menu_item_toggles_the_type_object` |
| Roman Hanging Punctuation | done | Paragraph panel menu › Roman Hanging Punctuation, `text.setFormat {romanHangingPunctuation}` (#2756): per paragraph, Optical Margin Alignment's punctuation and amounts without the letters; paragraph styles carry it. Evidence: `tests::roman_hanging_punctuation_hangs_punctuation_but_not_letters`, `typecmd::area_tests::roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on`. Whole paragraphs hang as published with both composers, ragged, centred and justified, with Line-end Punctuation Half Width and bidirectional lines; Justification's Glyph Scaling leaves the hung marks at their width, and Standard burasagari counts what hangs at a line's start as room before hanging a comma (`tests_hang`) |
| Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled; type on a path doesn't use them. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests` |
| Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests` |
| Roman Hanging Punctuation | done | Paragraph panel menu › Roman Hanging Punctuation, `text.setFormat {romanHangingPunctuation}` (#2756): per paragraph, Optical Margin Alignment's punctuation and amounts without the letters; paragraph styles carry it. Evidence: `tests::roman_hanging_punctuation_hangs_punctuation_but_not_letters`, `typecmd::area_tests::roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on` |
| Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled; type on a path doesn't use them. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` |
| Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` |
| Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred lines are still aligned as a whole); in justified area type the text up to a line's last tab keeps its spacing and its tabs their stops, and the text after the last tab takes the line's room to the far edge, VectorCraft's own rule (evidence: `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge` and the other tab tests in `crates/text/src/tests/justify.rs`) |
| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` |
| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). |
+4 -3
View File
@@ -170,6 +170,7 @@ tools, never checked side by side) isn't captured row by row.
| Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it |
| Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview |
| Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed |
| Knife cursor | done | a knife, the blade's point on the hotspot, white blade and black handle, for the Knife and the Trim at Crossings Tool; the crosshair with Use Precise Cursors; `the_knife_shows_a_knife_with_its_point_on_the_hotspot`, `drawing_tools_show_their_own_cursor` |
| Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). |
| Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes lose the rectangle's area, open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` |
| Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) |
@@ -450,7 +451,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Pathfinder Divide: an open cutting line splits a filled path | done | #1307; straight, crossed, bent and curved cutters, holes and frontmost appearance regression-tested; native automation: independent piece movement, one Undo/Redo, saved-document round trip and window capture; existing bounded-map fallback remains |
| Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) |
| Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) |
| Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: question marks for mixed modes, hit-testing by the area |
| Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit, and members in different modes put a question mark on each Shape Mode button; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: hit-testing by the area |
| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: guide and blend spine rows have no menu, and other panels have none |
| Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. |
| Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. |
@@ -485,10 +486,10 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app |
| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored |
| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its eight tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its eight tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (in the All Tools drawer under the add-on's heading, in neither toolbar as shipped, no shortcut) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag every stretch its rectangle touches, an Alt-drag every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored |
| Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored |