From ba3c5b0a3c7a159d099db6d217029ae068c2f039 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:04:08 -0800 Subject: [PATCH 01/11] .ai save: a top object with uneven sides stays a live envelope A top object whose top and bottom sides, or left and right sides, have different numbers of segments was written to the editing data as its distorted art. The writer now splits the side with fewer segments into as many as the side across from it has, each segment into equal spans of its curve, up to the 50 columns or rows the grid holds. The reader opens the grid's edge as the top object's outline with the same corners and the same mapping of the contents; the outline holds the added anchors. A split that would share out the contents another way, or a side of more than 50 segments, still writes the envelope as its art with the warning. --- crates/eps/src/ai_editing/tests.rs | 121 ++++++++++++++++-- crates/eps/src/ai_editing/writer/envelopes.rs | 90 ++++++++++--- docs/target-app-parity.md | 1 + 3 files changed, 184 insertions(+), 28 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 967c982ad4..bc9d3a5332 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -9689,7 +9689,7 @@ fn an_envelope_is_written_in_the_order_the_reader_reads_it() { /// Envelopes the reader would open in another shape, or not at all, are written as their distorted /// art with a warning, and open as that art: an envelope of type, one in a turned frame, a warp drawn /// without its style's net, a mesh the reader would lay out the other way round, a top object -/// whose sides don't pair up, a Fidelity that isn't a whole number and bounds margins kept with +/// with a side of more segments than the grid has columns, a Fidelity that isn't a whole number and bounds margins kept with /// Distort Appearance off. Other live objects keep their own warning. #[test] fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { @@ -9726,15 +9726,10 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { **kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: transpose(points, 3, 2), handles: vec![] }; } }); - let mut uneven = kurbo::BezPath::new(); - uneven.move_to((30.0, 10.0)); - for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] { - uneven.line_to(p); - } - uneven.close_path(); - let lopsided = change(&|k| { + // A top side of 51 segments: more grid columns than the reader reads. + let crowded = change(&|k| { if let NodeKind::Envelope { kind, .. } = k { - **kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven), corners: None }; + **kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven_top_object(51)), corners: None }; } }); let fractional = change(&|k| { @@ -9753,7 +9748,7 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { ("turned", turned), ("old warp", old_warp), ("sideways mesh", sideways), - ("lopsided top object", lopsided), + ("top object past the grid's limit", crowded), ("fractional fidelity", fractional), ("margin kept", margin_kept), ]; @@ -9774,6 +9769,112 @@ fn transpose(points: Vec, rows: usize, cols: usize) -> Vec kurbo::BezPath { + let mut path = kurbo::BezPath::new(); + path.move_to((30.0, 10.0)); + for k in 1..top { + path.line_to((30.0 + 140.0 * k as f64 / top as f64, if k % 2 == 1 { 20.0 } else { 10.0 })); + } + for p in [(170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] { + path.line_to(p); + } + path.close_path(); + path +} + +/// Do the patches of top objects `a` and `b` lie within 0.001 pt of each other at every place of a +/// 32 × 32 grid? +fn same_top_object_patch(a: &vectorcraft_doc::live::EnvelopeKind, b: &vectorcraft_doc::live::EnvelopeKind) -> bool { + use vectorcraft_doc::live::{Coons, EnvelopeKind}; + let (EnvelopeKind::TopObject { path, corners }, EnvelopeKind::TopObject { path: p, corners: c }) = (a, b) else { return false }; + let (Some(a), Some(b)) = (Coons::from_top_object(path, *corners), Coons::from_top_object(p, *c)) else { return false }; + let at = |i: u32| f64::from(i) / 32.0; + (0..=32).all(|j| (0..=32).all(|i| a.eval(at(i), at(j)).distance(b.eval(at(i), at(j))) < 1e-3)) +} + +/// A top object whose top and bottom sides have different numbers of segments is written live, its +/// side with fewer segments split into as many as the side across from it has, with Edit Contents off +/// and on: two straight segments over one straight one, three over one, and two over one curve. +/// VectorCraft's reader opens it as a top object with its corners on the same four points, the same +/// patch, contents, Fidelity, Edit Contents and Envelope Options, and saved again it opens the same. +#[test] +fn a_top_object_with_uneven_sides_is_read_back_live() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut curved = kurbo::BezPath::new(); + curved.move_to((30.0, 10.0)); + curved.line_to((100.0, 0.0)); + curved.line_to((170.0, 10.0)); + curved.line_to((170.0, 90.0)); + curved.curve_to((130.0, 105.0), (70.0, 105.0), (30.0, 90.0)); + curved.close_path(); + let shapes = [("two over one", uneven_top_object(2), 6), ("three over one", uneven_top_object(3), 8), ("two over a curve", curved, 6)]; + for (name, path, anchors) in shapes { + let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&path), corners: None }; + for editing in [false, true] { + let what = format!("{name}, editing {editing}"); + let doc = envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW); + let text = program(&doc); + assert!(text.contains("AIDeformOptionsKey") && text.contains("%_3 /Int (AIDeformStyle) ,\n"), "{what}: {text}"); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}"); + let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { panic!("{what}: {back:#?}") }; + assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}"); + let EnvelopeKind::TopObject { path: outline, corners: Some(corners) } = &**got else { panic!("{what}: {got:?}") }; + let sp = &outline.subpaths[0]; + assert_eq!(sp.anchors.len(), anchors, "{what}: {outline:?}"); + let points = corners.map(|i| sp.anchors[i as usize].p); + let want = [(30.0, 10.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)].map(kurbo::Point::from); + assert!(points.iter().zip(want).all(|(a, b)| a.distance(b) < 1e-6), "{what}: {points:?}"); + assert!(same_top_object_patch(&kind, got), "{what}: {got:?}"); + let colors: Vec> = content.iter().map(|c| c.appearance.fill_paint().color()).collect(); + assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}"); + let mut again = Document::new(200.0, 100.0); + let layer = again.layers[0].id; + again.insert(Some(layer), usize::MAX, back.clone()).unwrap(); + let (twice, warnings, notes) = envelope_back(&again); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}"); + let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") }; + assert!(same_top_object_patch(&kind, twice), "{what}, saved again: {twice:?}"); + } + } +} + +/// A top object with a top side of 50 segments over a bottom side of one is written live with a grid +/// of 50 columns, the most the reader reads. +#[test] +fn a_top_object_split_to_the_grids_limit_is_read_back_live() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven_top_object(50)), corners: None }; + let doc = envelope_doc(kind.clone(), 50.0, false, EnvelopeOptions::NEW); + let text = program(&doc); + assert!(text.contains("[50 1] /Size X#"), "{text}"); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let NodeKind::Envelope { kind: got, .. } = &back.kind else { panic!("{back:#?} {notes:?}") }; + assert!(same_top_object_patch(&kind, got), "{got:?}"); +} + +/// A top object whose side with fewer segments would share out the content another way once split +/// (two curves that aren't one curve, under three segments) is written as its art, with a warning. +#[test] +fn a_top_object_whose_split_side_would_map_another_way_is_written_as_its_art() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut path = uneven_top_object(3); + path.truncate(5); + path.curve_to((150.0, 110.0), (120.0, 110.0), (100.0, 90.0)); + path.curve_to((80.0, 95.0), (40.0, 80.0), (30.0, 90.0)); + path.close_path(); + let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&path), corners: None }; + let doc = envelope_doc(kind, 50.0, false, EnvelopeOptions::NEW); + assert!(!program(&doc).contains("AIDeformOptionsKey")); + let (back, warnings, _) = envelope_back(&doc); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + assert!(matches!(back.kind, NodeKind::Group { .. }), "{back:#?}"); +} + /// An envelope with its contents in an opacity mask's art is written as its art there, and an /// envelope in a group stays live. #[test] diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index dcd7274291..bf01c276de 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -8,13 +8,14 @@ //! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the //! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain //! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written -//! for it, one grid edge to each segment of its sides. An envelope the reader would open in another -//! shape is written as its distorted art. +//! for it, one grid edge to each segment of its sides, a side with fewer segments than the side +//! across from it split into more. An envelope the reader would open in another shape is written as +//! its distorted art. use std::fmt::Write; use std::sync::Arc; -use kurbo::{Point, Vec2}; +use kurbo::{CubicBez, ParamCurve, Point, Vec2}; use vectorcraft_doc::live::{ Coons, EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint, PreserveShape, WARP_NET, envelope_content_boxes, envelope_grid, envelope_stroke_margin, warp_grid, @@ -173,11 +174,44 @@ fn reads_as_written(rows: usize, cols: usize, pts: &[GridPoint]) -> bool { envelope_upright(&mesh).is_some_and(|(r, c, read)| (r as usize, c as usize) == (rows, cols) && read == pts) } +/// `pieces`, one side of a top object, split into `n` pieces: each piece is split into equal spans +/// of its curve parameter, the extra pieces going one at a time to the piece with the longest +/// control polygon for each of its spans. `None` where `n` is fewer pieces than it has, more than +/// [`MAX_GRID`], or a split leaves a piece of no length. +fn split_to(pieces: &[CubicBez], n: usize) -> Option> { + if n < pieces.len() || n > MAX_GRID { + return None; + } + if n == pieces.len() { + return Some(pieces.to_vec()); + } + let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3); + let lengths: Vec = pieces.iter().map(polygon).collect(); + let mut parts = vec![1usize; pieces.len()]; + for _ in pieces.len()..n { + let most = (0..pieces.len()).max_by(|a, b| (lengths[*a] / parts[*a] as f64).total_cmp(&(lengths[*b] / parts[*b] as f64)))?; + parts[most] += 1; + } + let mut out = Vec::with_capacity(n); + for (c, p) in pieces.iter().zip(parts) { + for j in 0..p { + let piece = c.subsegment(j as f64 / p as f64..(j + 1) as f64 / p as f64); + if [piece.p1, piece.p2, piece.p3].iter().all(|q| q.distance(piece.p0) <= 1e-9) { + return None; + } + out.push(piece); + } + } + Some(out) +} + /// The grid a top object with outline `path` and corners `corners` is written with: its edge runs -/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment, so -/// the top and bottom sides need as many segments as each other, as do the left and right sides; -/// the points inside blend the sides. `None` where that grid's edge, read back as the top object's -/// outline, doesn't give the same patch ([`Coons::from_top_object`]) at every place checked. +/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment, +/// the points inside blending the sides. The top and bottom sides need as many grid edges as each +/// other, as do the left and right sides, so where one side of a pair has fewer segments than the +/// other, its segments are split ([`split_to`]) without changing its shape. `None` where that +/// grid's edge, read back as the top object's outline, doesn't give the same patch +/// ([`Coons::from_top_object`]) at every place checked. fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, usize, Vec)> { let coons = Coons::from_top_object(path, corners)?; // The outline, as the patch takes it: the largest subpath. @@ -214,10 +248,35 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, } }; let gap = |k: usize| (at[(k + 1) % 4] + count - at[k]) % count; - let (cols, rows) = (gap(0), gap(1)); - if gap(2) != cols || gap(3) != rows || cols > MAX_GRID || rows > MAX_GRID { + if (0..4).any(|k| gap(k) > MAX_GRID) { return None; } + // Each side's segments from its corner on, a straight one as a cubic with its handles a third of + // the way along, which the patch spreads evenly along, as it does a straight segment. + let side = |k: usize| -> Vec { + (0..gap(k)) + .map(|j| { + let i = (at[k] + j) % count; + let seg = sp.segment(i); + if sp.segment_is_line(i) { + CubicBez::new(seg.p0, seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0), seg.p3) + } else { + seg + } + }) + .collect() + }; + let mut sides = [side(0), side(1), side(2), side(3)]; + // Opposite sides take as many segments as each other: the one with fewer has some split. + for k in 0..2 { + let n = sides[k].len().max(sides[k + 2].len()); + for s in [k, k + 2] { + sides[s] = split_to(&sides[s], n)?; + } + } + let (cols, rows) = (sides[0].len(), sides[1].len()); + let edge: Vec = sides.concat(); + let total = edge.len(); let width = cols + 1; let mut pts: Vec = vec![(Point::ZERO, [Vec2::ZERO; 4]); (rows + 1) * width]; // Where the `k`th anchor from the top left corner goes, and the slots of the handles of the @@ -233,20 +292,15 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, (rows - (k - 2 * cols - rows), 0, H_UP, H_DOWN) } }; - for k in 0..count { - let i = (at[0] + k) % count; - let seg = sp.segment(i); - // A straight segment's patch spreads evenly along it, as a cubic's with its handles a third - // of the way does. - let (p1, p2) = if sp.segment_is_line(i) { (seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0)) } else { (seg.p1, seg.p2) }; + for (k, seg) in edge.iter().enumerate() { let (r, c, out, into) = place(k); - let (nr, nc, _, _) = place((k + 1) % count); + let (nr, nc, _, _) = place((k + 1) % total); if let Some(q) = pts.get_mut(r * width + c) { q.0 = seg.p0; - q.1[out] = p1 - seg.p0; + q.1[out] = seg.p1 - seg.p0; } if let Some(q) = pts.get_mut(nr * width + nc) { - q.1[into] = p2 - seg.p3; + q.1[into] = seg.p2 - seg.p3; } } // The points inside, blended from the sides. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 296bd84b2b..342eb492b2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1639,6 +1639,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps defines every symbol in its editing copy with its art, registration point and place in the Symbols panel's order, and writes its instances as symbol instances, which VectorCraft's `.ai` reader opens as symbols and instances again (`symbols_and_their_instances_are_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the instances written as their art). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps envelopes made with a warp, a mesh or a top object editable: its editing copy holds each envelope's contents, shape, Fidelity, Envelope Options and Edit Contents state in the form VectorCraft's `.ai` envelope reader reads, beside its distorted art, so the file opens with the same live envelope, Edit Contents still switching between the contents and the envelope ([Edit the contents of envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html)). Envelopes of type, envelopes in opacity masks, pattern tiles or another envelope's contents, and envelopes the reader would open with another shape or other settings (a Fidelity that isn't a whole number, bounds margins kept with Distort Appearance off), and envelopes after the first 256 in a file are written as their distorted art, with a warning (`envelopes_are_read_back_live` and `envelopes_the_reader_cannot_open_live_are_written_as_their_art` in `crates/eps/src/ai_editing/tests.rs`). + A top object whose top and bottom sides, or left and right sides, have different numbers of segments is also saved live: the side with fewer segments is split into as many as the side across from it has (each segment into equal spans of its curve, a straight one at even steps), up to the 50 a side the grid holds, so the file opens with the same corners and the same mapping of the contents, its outline holding the added anchors. Where the split side would share out the contents another way, as a side of two curves that aren't one curve can, or a side has more than 50 segments, the envelope is written as its distorted art, with the warning (`a_top_object_with_uneven_sides_is_read_back_live`, `a_top_object_split_to_the_grids_limit_is_read_back_live` and `a_top_object_whose_split_side_would_map_another_way_is_written_as_its_art` in `crates/eps/src/ai_editing/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes eligible paths, compound paths and groups with live effects with an art style when the writer supports their appearance and effects (not a filled path that uses the even-odd rule, and none on a large canvas), which VectorCraft's `.ai` reader opens as the same appearance with its effects live (`objects_with_live_effects_are_read_back` and `every_effect_setting_written_on_an_object_is_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the objects written without one and the effects they lose). The same holds for the objects of an opacity mask's art, a mask inside another mask's art and a hidden art root included, so a mask whose art has Offset Path opens drawing the image it masks as it did, with the effect live; geometry effects that no art style holds on a mask's art, such as Roughen, are written applied to the art, which opens drawing what it drew (`a_masked_image_with_live_offset_path_round_trips`, `hidden_and_nested_mask_art_keep_live_offset_path` and `a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws` in `crates/eps/src/ai_editing/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes point type, area type and type on a path as type in its editing copy, and objects next to it keep their own transparency (`crates/eps/src/ai_editing/tests.rs`, `cmd::fileio::tests_pdfedit::type_comes_back_from_the_editing_copy`; [file-format-parity.md](file-format-parity.md) lists what is written as outlines). From 90a2bd0494ed1997e4f169baad01747e7b10161e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:54:28 -0800 Subject: [PATCH 02/11] Graphs: aligned paint and stroke rows given with a design's art are rows of its stack paint.setFill, paint.setStroke, paint.invert and paint.complement with an item, stroke.set, stroke.setAdvanced, paint.editGradient, paint.setGradientGeom and the paint.freeform edits read an item given with aligned: true and the art of a graph design in a series first as a row of the art's stack, as appearance.setItem and transparency.set do. Each other object edits the row equal to it and an object without one is left as it is. A row the art does not have, a row of the other kind, or a row no other object has is an error, also when the art is the only object given, and the document and its undo history stay as they are. Without stroke, the gradient commands edit the kind of the art's row. The objects and ids the commands report, a gradient spanning the selection, and the last color and last gradient count only the objects whose row was edited. --- crates/engine/src/cmd/appearance.rs | 63 ++++++++-- crates/engine/src/cmd/effectcmd.rs | 12 +- crates/engine/src/cmd/freeform.rs | 8 +- crates/engine/src/cmd/gradient.rs | 20 +++- crates/engine/src/cmd/graph/tests.rs | 167 +++++++++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 35 ++++-- crates/engine/src/cmd/stroke.rs | 11 +- docs/mcp.md | 10 +- 8 files changed, 280 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 09b03f2d63..439661b209 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -422,6 +422,15 @@ pub(crate) fn design_reference(s: &Session, p: &Value, cmd: &str) -> Result Result> { + if matches!(item, ItemTarget::Item { explicit: false, .. }) { + return Ok(None); + } + design_reference(s, p, cmd) +} + /// `ids` after `of` (see [`design_reference`]), when there is one. pub(crate) fn with_reference(of: Option, ids: &[NodeId]) -> Vec { of.into_iter().chain(ids.iter().copied()).collect() @@ -606,16 +615,22 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { /// What the edit changes on the topmost visible fill and stroke of graph series marks is stored on /// their graphs in the same step ([`capture_series_changes`]). Nothing targeted is not an edit, and /// when `f` leaves every target as it was, the document and its undo history stay as they are. +/// With `of` (see [`reference_of`]), an explicit aligned `item` is a row of the stack of `of`, which +/// is not among `ids`: it must be there and of the edited kind, each target edits the row equal to +/// it, a target without one is left as it is, and no target with one is an error. Returns the +/// targets `f` was aimed at, in the order of `ids`. +#[allow(clippy::too_many_arguments)] pub(crate) fn edit_items( s: &mut Session, ids: &[NodeId], item: ItemTarget, + of: Option, cmd: &str, label: &str, fill: bool, f: impl FnMut(&mut Node, Option) -> Result<()>, -) -> Result<()> { - edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| Ok(capture_series_changes(before, d, edited))) +) -> Result> { + edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| Ok(capture_series_changes(before, d, edited))) } /// [`edit_items`], then `after` on the document as it was before the edit, the edited document and @@ -627,17 +642,29 @@ pub(crate) fn edit_items_then( s: &mut Session, ids: &[NodeId], item: ItemTarget, + of: Option, cmd: &str, label: &str, fill: bool, mut f: impl FnMut(&mut Node, Option) -> Result<()>, mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result, -) -> Result<()> { - if ids.is_empty() { - return Ok(()); - } +) -> Result> { + let art = of.and_then(|of| s.doc().ok()?.doc.node(of).map(|n| n.appearance.clone())); + let per = match (item, art) { + // Checked even when the art is the only object given, which leaves `ids` empty. + (ItemTarget::Item { index, explicit: true, aligned: true }, Some(art)) => { + item.resolve(&art, fill, cmd)?; + let per = item.per_target_of(s, of, ids); + if per.iter().all(Option::is_none) { + return Err(bad(cmd, format!("no appearance item {index}"))); + } + per + } + _ if ids.is_empty() => return Ok(Vec::new()), + _ => item.per_target(s, ids), + }; + let aimed: Vec = ids.iter().zip(&per).filter(|(_, item)| item.is_some()).map(|(id, _)| *id).collect(); let before = s.doc()?.doc.clone(); - let per = item.per_target(s, ids); super::overprint::edit_counted(s, label, |d| { let mut edited = Vec::new(); // The objects whose rows `f` edited: on type, no row means its characters. @@ -656,7 +683,13 @@ pub(crate) fn edit_items_then( let labels = super::graph::capture_label_rows(d, &rows); Ok(count_changed(d, &before, &edited) + usize::from(more || labels)) })?; - Ok(()) + Ok(aimed) +} + +/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it +/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is. +pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> { + ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?))) } /// How many of `ids` differ in `d` from `before`. @@ -665,8 +698,8 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_ } /// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the -/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or -/// null is an error of command `cmd`. +/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`] and [`reference_of`]), else `default`. A `stroke` other than +/// true, false or null is an error of command `cmd`. pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result { check_switches(p, &["stroke"], cmd)?; if let Some(b) = p.get("stroke").and_then(Value::as_bool) { @@ -674,8 +707,14 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo } let ItemTarget::Item { index, .. } = item else { return Ok(default) }; let d = &s.doc()?.doc; - let ids = drop_design_art(d, appearance_targets(s, p)?); - Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) + let holder = match reference_of(s, p, item, cmd)? { + Some(of) => Some(of), + None => { + let ids = drop_design_art(d, appearance_targets(s, p)?); + ids.get(item.anchor(s, &ids)).copied() + } + }; + Ok(holder.and_then(|id| d.node(id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) } /// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`]. diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 7619444c74..798b635e65 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -14,7 +14,8 @@ use vectorcraft_geom::{FillRule, PathData}; use vectorcraft_render::effects; use super::appearance::{ - ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, with_reference, + ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, reference_of, + with_reference, }; use super::expand::has_seeded; use super::rasterfx; @@ -336,15 +337,6 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us /// have. const APPENDED: usize = usize::MAX; -/// The [`design_reference`] of an effect edit aimed at `item`: none for the Appearance panel's active row, which is a -/// row of the first selected object's stack. -fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result> { - if matches!(item, ItemTarget::Item { explicit: false, .. }) { - return Ok(None); - } - design_reference(s, p, cmd) -} - #[allow(clippy::too_many_arguments)] fn edit_effects( s: &mut Session, diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index a37cce38d0..c0cb1b5292 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -201,7 +201,9 @@ fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor first.get_or_insert(r); Ok(()) }; - edit_items(s, &ids, item, cmd, "Gradient", !stroke, |n, index| { + let of = super::appearance::reference_of(s, p, item, cmd)?; + let shown_at = super::appearance::first_edited(s, item, of, &ids); + edit_items(s, &ids, item, of, cmd, "Gradient", !stroke, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { @@ -222,7 +224,9 @@ fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor })?; let r = first.ok_or_else(|| bad(cmd, NOT_FREEFORM))?; // The edited gradient is the last one used (`paint.lastGradient`). - let shown = s.doc()?.doc.node(ids[0]).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten())); + let shown = shown_at.and_then(|(id, item)| { + s.doc().ok()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten())) + }); if let Some(p) = shown { s.remember_paint(&p); } diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 7c7724f0f9..a3ebacf42f 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -580,7 +580,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model) .map_err(|e| bad(C, e))?; let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); - edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| { + let of = super::appearance::reference_of(s, p, item, C)?; + let shown_at = super::appearance::first_edited(s, item, of, &ids); + // The objects returned: with a design's art, those with a row equal to the art's. + let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { @@ -616,9 +619,12 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { st.gradient_mode = m; } // The last gradient is the one the first object now shows (the defaults' without objects). - let shown = match ids.first() { - Some(id) => s.doc()?.doc.node(*id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten())), - None => Some(new_default.clone()), + let shown = match shown_at { + Some((id, item)) => { + s.doc()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten())) + } + None if ids.is_empty() => Some(new_default.clone()), + None => None, }; if let Some(shown) = shown { s.remember_paint(&shown); @@ -628,7 +634,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { } else { s.paint.fill = new_default; } - Ok(json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + Ok(json!({"ids": edited.iter().map(|i| i.0).collect::>()})) } /// A painted stroke on a type run without a weight gets 1 pt. @@ -766,7 +772,9 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { } let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets); let model = super::paint::new_color_model(s, &Value::Null); - edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| { + let of = super::appearance::reference_of(s, p, item, C)?; + // The objects returned: with a design's art, those with a row equal to the art's. + let targets = edit_items(s, &targets, item, of, C, "Gradient", !stroke, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index df002ae526..ba059aac4a 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -859,6 +859,173 @@ fn aligned_rows_of_a_graph_designs_art_and_a_different_stack_are_not_moved() { assert_eq!(paints, [art_was.items[1].paint().clone(), art_was.items[0].paint().clone(), art_was.items[1].paint().clone()]); } +/// An `item` given with `aligned: true` and the art of a graph design in a series first is a row of the art's stack in the +/// paint and stroke commands: each other object edits the row equal to it, and a row the art does not have as a fill or +/// stroke as edited, or that no other object has, is an error that leaves the document and its undo history as they are. +#[test] +fn aligned_paint_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_objects() { + let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone(); + let green = Paint::solid(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0)); + // The art's row 1 is the blue fill the mark has as row 0, and its row 2 the black stroke the mark has as row 1. + let (mut s, _, art, mark) = aligned_design_art(); + let black = rows(&s, mark).items[1].clone(); + s.edit("Stroke", |d, _| { + d.node_mut(art).unwrap().appearance.items.push(black.clone()); + Ok(()) + }) + .unwrap(); + let (art_was, mark_was) = (rows(&s, art), rows(&s, mark)); + let fill = |s: &mut Session, cmd: &str, p: serde_json::Value| { + s.execute(cmd, &p).unwrap(); + let now = rows(s, mark); + assert_eq!(rows(s, art), art_was, "{cmd}"); + assert_ne!(now.items[0], mark_was.items[0], "{cmd} edits the mark's blue fill"); + assert_eq!(now.items[1], mark_was.items[1], "{cmd} leaves the mark's stroke"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(rows(s, mark), mark_was, "{cmd} is one undo step"); + now + }; + let ids = [art.0, mark.0]; + let now = fill(&mut s, "paint.setFill", json!({"ids": ids, "item": 1, "aligned": true, "color": "#00ff00"})); + assert_eq!(now.items[0].paint(), &green); + let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 1, "aligned": true})); + assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the inverted color is the last color, not the art's"); + let now = fill(&mut s, "paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"})); + let Paint::Gradient(g) = now.items[0].paint() else { panic!("{:?}", now.items[0].paint()) }; + assert_eq!(&s.last_gradient, &**g, "the mark's new gradient is the last gradient"); + + let stroke = |s: &mut Session, cmd: &str, p: serde_json::Value| { + s.execute(cmd, &p).unwrap(); + let now = rows(s, mark); + assert_eq!(rows(s, art), art_was, "{cmd}"); + assert_eq!(now.items[0], mark_was.items[0], "{cmd} leaves the mark's fill"); + assert_ne!(now.items[1], mark_was.items[1], "{cmd} edits the mark's stroke"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(rows(s, mark), mark_was, "{cmd} is one undo step"); + now + }; + let now = stroke(&mut s, "paint.setStroke", json!({"ids": ids, "item": 2, "aligned": true, "color": "#00ff00"})); + assert_eq!(now.items[1].paint(), &green); + let now = stroke(&mut s, "stroke.set", json!({"ids": ids, "item": 2, "aligned": true, "weight": 5})); + assert_eq!(now.stroke_at(Some(1)).unwrap().width, 5.0); + let now = stroke(&mut s, "stroke.setAdvanced", json!({"ids": ids, "item": 2, "aligned": true, "arrowScale": [200, 200]})); + assert_eq!(now.stroke_at(Some(1)).unwrap().arrow_scale, (200.0, 200.0)); + // Without `stroke`, the kind of the art's row is edited. + let now = stroke(&mut s, "paint.editGradient", json!({"ids": ids, "item": 2, "aligned": true, "kind": "linear"})); + assert!(matches!(now.items[1].paint(), Paint::Gradient(_))); + fill(&mut s, "paint.complement", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false})); + + let steps = s.doc().unwrap().history.undo.len(); + for (cmd, p, said) in [ + ("stroke.set", json!({"ids": ids, "item": 1, "aligned": true, "weight": 5}), "appearance item 1 is not a stroke"), + ("paint.setFill", json!({"ids": ids, "item": 2, "aligned": true, "color": "#00ff00"}), "appearance item 2 is not a fill"), + ("paint.setFill", json!({"ids": ids, "item": 0, "aligned": true, "color": "#00ff00"}), "no appearance item 0"), + ("paint.setFill", json!({"ids": ids, "item": 9, "aligned": true, "color": "#00ff00"}), "no appearance item 9"), + // The art alone: no other object has the row. + ("paint.setFill", json!({"ids": [art.0], "item": 9, "aligned": true, "color": "#00ff00"}), "no appearance item 9"), + ("paint.setFill", json!({"ids": [art.0], "item": 1, "aligned": true, "color": "#00ff00"}), "no appearance item 1"), + ("stroke.set", json!({"ids": [art.0], "item": 1, "aligned": true, "weight": 5}), "appearance item 1 is not a stroke"), + ("paint.editGradient", json!({"ids": [art.0], "item": 1, "aligned": true, "kind": "linear"}), "no appearance item 1"), + ] { + let defaults = format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient)); + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains(said), "{cmd}: {e}"); + assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}"); + assert_eq!(format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient)), defaults, "{cmd}"); + } + + // An object with no row equal to the art's is left out of what the commands report as edited. + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let rect = *s.doc().unwrap().selection.subjects().first().unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff00ff"})).unwrap(); + let rect_was = rows(&s, rect); + let ids = [art.0, mark.0, rect.0]; + for (cmd, p, key, said) in [ + ("paint.setFill", json!({"ids": ids, "item": 1, "aligned": true, "color": "#00ff00"}), "objects", json!(1)), + ("stroke.set", json!({"ids": ids, "item": 2, "aligned": true, "weight": 5}), "objects", json!(1)), + ("paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"}), "ids", json!([mark.0])), + ("paint.setGradientGeom", json!({"ids": ids, "item": 1, "aligned": true, "start": [0, 0], "end": [10, 40]}), "ids", json!([mark.0])), + ] { + if cmd == "paint.setGradientGeom" { + s.execute("paint.editGradient", &json!({"ids": [mark.0], "item": 0, "kind": "linear"})).unwrap(); + let gradient = rows(&s, mark).items[0].clone(); + s.edit("Gradient", |d, _| { + d.node_mut(art).unwrap().appearance.items[1] = gradient.clone(); + Ok(()) + }) + .unwrap(); + } + let r = s.execute(cmd, &p).unwrap(); + assert_eq!(r[key], said, "{cmd}: {r}"); + assert_eq!(rows(&s, rect), rect_was, "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + + // A gradient spanning the selection spans only the objects that take it: a distant object without an equal row does + // not move it. + s.execute("shape.rectangle", &json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap(); + let far = *s.doc().unwrap().selection.subjects().first().unwrap(); + s.execute("paint.setFill", &json!({"ids": [far.0], "color": "#ff00ff"})).unwrap(); + let far_was = rows(&s, far); + let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]}); + let mut placed = Vec::new(); + for ids in [vec![art.0, mark.0], vec![art.0, mark.0, far.0]] { + s.execute("paint.setFill", &json!({"ids": ids, "item": 1, "aligned": true, "gradient": gradient, "span": "selection"})).unwrap(); + placed.push(rows(&s, mark).items[0].clone()); + assert_eq!(rows(&s, far), far_was); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(matches!(placed[0].paint(), Paint::Gradient(_))); + assert_eq!(placed[1], placed[0]); +} + +/// The gradient and freeform gradient commands read an `item` given with `aligned: true` and the art of a graph design in +/// a series first as a row of the art's stack, as the paint commands do. +#[test] +fn aligned_gradient_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_objects() { + let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone(); + for kind in ["linear", "freeform"] { + let (mut s, _, art, mark) = aligned_design_art(); + // The mark's fill and the art's equal row become the same gradient. + s.execute("paint.editGradient", &json!({"ids": [mark.0], "item": 0, "kind": kind})).unwrap(); + let gradient = rows(&s, mark).items[0].clone(); + // A yellow fill above the mark's gradient is the mark's row 1, as the gradient is the art's row 1. + let mut yellow = gradient.clone(); + *yellow.paint_mut() = Paint::solid(vectorcraft_color::Color::rgb(1.0, 1.0, 0.0)); + s.edit("Gradient", |d, _| { + d.node_mut(art).unwrap().appearance.items[1] = gradient.clone(); + d.node_mut(mark).unwrap().appearance.items.insert(1, yellow.clone()); + Ok(()) + }) + .unwrap(); + let ids = [art.0, mark.0]; + let edits = if kind == "linear" { + vec![ + ("paint.setGradientGeom", json!({"ids": ids, "item": 1, "aligned": true, "start": [0, 0], "end": [10, 40]})), + ("paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "radial"})), + ] + } else { + vec![("paint.freeform.addPoint", json!({"ids": ids, "item": 1, "aligned": true, "at": [5, 5]}))] + }; + for (cmd, p) in edits { + let (art_was, mark_was) = (rows(&s, art), rows(&s, mark)); + s.execute(cmd, &p).unwrap(); + let now = rows(&s, mark); + assert_eq!(rows(&s, art), art_was, "{cmd}"); + assert_ne!(now.items[0], mark_was.items[0], "{cmd} edits the mark's gradient fill"); + assert_eq!(now.items[1..], mark_was.items[1..], "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + // The edited gradient is the last gradient (paint.setGradientGeom does not set it). + if cmd != "paint.setGradientGeom" { + let Paint::Gradient(g) = now.items[0].paint() else { panic!("{cmd}") }; + assert_eq!(&s.last_gradient, &**g, "{cmd}: the mark's edited gradient is the last gradient"); + } + } + } +} + /// The paint commands leave the art of a graph design in a series out, a copy of the design given by id with an item /// included. #[test] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 02875517f7..b4090cad29 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -538,7 +538,14 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) let item = item_target(s, p, cmd)?.of_kind(s, fill); let selected = item.targets(s, p)?; let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); - let paint = if span { placed_across(&s.doc()?.doc, &ids, paint, p, fill) } else { paint }; + let of = super::appearance::reference_of(s, p, item, cmd)?; + let paint = if span { + // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. + let spanned: Vec = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect(); + placed_across(&s.doc()?.doc, &spanned, paint, p, fill) + } else { + paint + }; // The gradient mesh points picked with the Mesh tool or Direct Selection: a solid fill // recolours just those points of their meshes. let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] }; @@ -555,10 +562,12 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) // The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep // for their characters; a row edit is kept with the label's rows. let characters = std::cell::RefCell::new(Vec::new()); - edit_items_then( + // The objects counted: with a design's art, those with a row equal to the art's. + let ids = edit_items_then( s, &ids, item, + of, cmd, label, fill, @@ -1004,26 +1013,34 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( return Ok(json!({ "changed": changed as usize })); } let item = item_target(s, p, cmd)?.of_kind(s, !stroke); - let (r, shown_item) = match item { + let (r, shown_at) = match item { ItemTarget::Item { index, .. } => { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?); + let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?); + let of = super::appearance::reference_of(s, p, item, cmd)?; + // With design art first, the row shown is the one edited in the first object that has it. + let shown_at = match of { + Some(_) => super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it { + ItemTarget::Item { index, .. } => Some((id, Some(index))), + ItemTarget::Top => None, + }), + None => ids.first().map(|id| (*id, Some(index))), + }; let mut changed = 0; - edit_items(s, &ids, item, cmd, label, !stroke, |n, i| { + edit_items(s, &targets, item, of, cmd, label, !stroke, |n, i| { let paint = if stroke { n.appearance.stroke_at_mut(i).map(|l| &mut l.paint) } else { n.appearance.fill_at_mut(i).map(|l| &mut l.paint) }; changed += paint.is_some_and(|paint| super::colorcmds::map_paint(paint, f)) as usize; Ok(()) })?; - (json!({ "changed": changed }), Some(index)) + (json!({ "changed": changed }), shown_at) } // The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles. ItemTarget::Top => { let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::>()}); - (super::colorcmds::recolor(s, &q, cmd, label, f)?, None) + (super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None))) } }; - let shown_ids = if shown_item.is_some() { ids } else { leaf_targets(s, &ids)? }; - if let Some(shown) = shown_ids.first().and_then(|id| s.doc().ok()?.doc.node(*id).map(|n| proxy_paint(n, stroke, shown_item))) { + if let Some(shown) = shown_at.and_then(|(id, at)| s.doc().ok()?.doc.node(id).map(|n| proxy_paint(n, stroke, at))) { s.remember_paint(&shown); } Ok(r) diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 2a0159930d..5ee137b399 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -303,7 +303,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { st.profile = pr.clone(); } }; - edit_items(s, &ids, item, C, "Stroke", false, |n, index| { + let of = super::appearance::reference_of(s, p, item, C)?; + // The objects counted: with a design's art, those with a row equal to the art's. + let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { @@ -372,7 +374,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result { } let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" }; - edit_items(s, &ids, item, c, label, false, |n, index| { + edit_items(s, &ids, item, None, c, label, false, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { @@ -535,7 +537,8 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { { arrows_and_profile(st); } - edit_items(s, &ids, item, C, "Stroke", false, |n, index| { + let of = super::appearance::reference_of(s, p, item, C)?; + edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| { let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) }; arrows_and_profile(st); if let Some(b) = &brush { diff --git a/docs/mcp.md b/docs/mcp.md index 7b13e9eb68..435e1d9629 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -829,9 +829,13 @@ given), `threeD.mapGraphic`, do not use the Appearance panel's active row. When the first object given is design art, rows and effects given with `aligned: true` are rows of its stack in `appearance.setItem`, `appearance.removeItem`, `appearance.duplicateItem`, `transparency.set` with an `item`, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, -move or remove an effect: each other object edits the row or effect equal to it, and an object without one is left as -it is. When no object has one, `appearance.setItem` and `appearance.removeItem` leave the document as it is, as they do -for a row no object has, and the other commands are an error. `appearance.moveItem`, `effect.move` and +move or remove an effect, `paint.setFill`, `paint.setStroke`, `paint.invert` and `paint.complement` with an `item`, +`stroke.set`, `stroke.setAdvanced`, `paint.editGradient`, `paint.setGradientGeom` and the `paint.freeform.*` commands +that edit points and lines: each other object edits the row or effect equal to it, and an object without one is left +as it is. When no object has one, `appearance.setItem` and `appearance.removeItem` leave the document as it is, as they +do for a row no object has, and the other commands are an error. The paint, stroke and gradient commands are also an +error when the art's row is not the kind of row they edit, and `paint.editGradient`, `paint.setGradientGeom` and the +`paint.freeform.*` commands without `stroke` edit the kind of the art's row. `appearance.moveItem`, `effect.move` and `appearance.duplicateItem` with `to` are an error when the art's stack differs from the other objects', and `appearance.duplicateItem` with `to` is also an error when two or more other objects are given, as it is without the art. To change the art, edit the design with `graph.design`. From 9578b61d286e34ce7c8cb73da5dfaba9aa69c970 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:27:38 -0800 Subject: [PATCH 03/11] Graphs: invert and complement remember the color of the first object they recolor With a graph design's art given first and an item without aligned, the art is left out, but paint.invert and paint.complement remembered the art's unchanged color as the last color. They now read the first object they recolor. --- crates/engine/src/cmd/graph/tests.rs | 6 ++++++ crates/engine/src/cmd/paint.rs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index cefadcda76..a48f012e40 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -890,6 +890,9 @@ fn aligned_paint_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_ob assert_eq!(now.items[0].paint(), &green); let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 1, "aligned": true})); assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the inverted color is the last color, not the art's"); + // Without `aligned`, the art is left out and the item is a row of the mark. + let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 0})); + assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the mark's inverted color is the last color, not the art's"); let now = fill(&mut s, "paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"})); let Paint::Gradient(g) = now.items[0].paint() else { panic!("{:?}", now.items[0].paint()) }; assert_eq!(&s.last_gradient, &**g, "the mark's new gradient is the last gradient"); @@ -926,6 +929,9 @@ fn aligned_paint_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_ob ("paint.setFill", json!({"ids": [art.0], "item": 1, "aligned": true, "color": "#00ff00"}), "no appearance item 1"), ("stroke.set", json!({"ids": [art.0], "item": 1, "aligned": true, "weight": 5}), "appearance item 1 is not a stroke"), ("paint.editGradient", json!({"ids": [art.0], "item": 1, "aligned": true, "kind": "linear"}), "no appearance item 1"), + // The weight steps take no row: they step each object's active or top stroke. + ("stroke.weightUp", json!({"ids": ids, "item": 2}), "unknown parameter `item`"), + ("stroke.weightDown", json!({"ids": ids, "aligned": true}), "unknown parameter `aligned`"), ] { let defaults = format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient)); let e = s.execute(cmd, &p).unwrap_err().to_string(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 91e1efdbe3..6e2071d7f8 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1025,7 +1025,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( ItemTarget::Item { index, .. } => Some((id, Some(index))), ItemTarget::Top => None, }), - None => ids.first().map(|id| (*id, Some(index))), + None => targets.first().map(|id| (*id, Some(index))), }; let mut changed = 0; edit_items(s, &targets, item, of, cmd, label, !stroke, |n, i| { From 771b4e54b5e526ea46cccf332dce2c6a5e23e127 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:14:22 -0800 Subject: [PATCH 04/11] Graphs: invert and complement remember the equal row they recolor; document aligned With a mixed selection and the Appearance panel's active row, paint.invert and paint.complement recolor each object's row equal to the active one, but remembered the color at the active row's index in the first object in paint order, which can be another row. They now remember the row they recolor there, as the gradient and freeform edits do. The params text of paint.setFill, paint.setStroke, paint.invert, paint.complement, paint.lastColor, paint.lastGradient, stroke.setAdvanced, paint.editGradient, paint.setGradientGeom and the paint.freeform edits now lists `aligned`. docs/mcp.md names paint.lastColor and paint.lastGradient, which take the same rows as paint.setFill, and docs/target-app-parity.md gets a line for the rows of a design's art. --- crates/engine/src/cmd/appearance.rs | 1 + crates/engine/src/cmd/freeform.rs | 10 ++++---- crates/engine/src/cmd/gradient.rs | 4 ++-- crates/engine/src/cmd/graph/tests.rs | 9 ++++++++ crates/engine/src/cmd/paint.rs | 27 ++++++++++------------ crates/engine/src/cmd/stroke.rs | 2 +- crates/engine/src/tests/proxyitems.rs | 33 +++++++++++++++++++++++++++ docs/mcp.md | 4 ++-- docs/target-app-parity.md | 1 + 9 files changed, 66 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index f969483876..e3814bee3d 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -617,6 +617,7 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { /// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not /// an edit, and when `f` leaves every target as it was, the document and its undo history stay as /// they are. +/// /// With `of` (see [`reference_of`]), an explicit aligned `item` is a row of the stack of `of`, which /// is not among `ids`: it must be there and of the edited kind, each target edits the row equal to /// it, a target without one is left as it is, and no target with one is an error. Returns the diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index d568a4e8bd..ad0164a62c 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", has_doc, set_point ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Delete Freeform Point", [], None, - "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", + "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", has_doc, delete_point ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Add Freeform Line", [], None, - "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", + "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", has_doc, add_line ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Split Freeform Line", [], None, - "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", + "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", has_doc, split_line ), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 4ff9c44805..97917a2469 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label", has_doc, edit_gradient ), @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label", has_doc, set_gradient_geom ), diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index d5d9f56c7f..f09e4142f5 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -890,12 +890,19 @@ fn aligned_paint_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_ob assert_eq!(now.items[0].paint(), &green); let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 1, "aligned": true})); assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the inverted color is the last color, not the art's"); + let now = fill(&mut s, "paint.lastColor", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false})); + assert_eq!(Some(s.last_solid), now.items[0].paint().color()); // Without `aligned`, the art is left out and the item is a row of the mark. let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 0})); assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the mark's inverted color is the last color, not the art's"); + s.last_solid = vectorcraft_color::Color::rgb(0.5, 0.5, 0.5); + let now = fill(&mut s, "paint.complement", json!({"ids": ids, "item": 0})); + assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the mark's complement is the last color, not the art's"); let now = fill(&mut s, "paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"})); let Paint::Gradient(g) = now.items[0].paint() else { panic!("{:?}", now.items[0].paint()) }; assert_eq!(&s.last_gradient, &**g, "the mark's new gradient is the last gradient"); + let now = fill(&mut s, "paint.lastGradient", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false})); + assert!(matches!(now.items[0].paint(), Paint::Gradient(_))); let stroke = |s: &mut Session, cmd: &str, p: serde_json::Value| { s.execute(cmd, &p).unwrap(); @@ -931,6 +938,8 @@ fn aligned_paint_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_ob ("paint.editGradient", json!({"ids": [art.0], "item": 1, "aligned": true, "kind": "linear"}), "no appearance item 1"), // The weight steps take no row: they step each object's active or top stroke. ("stroke.weightUp", json!({"ids": ids, "item": 2}), "unknown parameter `item`"), + ("stroke.weightUp", json!({"ids": ids, "aligned": true}), "unknown parameter `aligned`"), + ("stroke.weightDown", json!({"ids": ids, "item": 2}), "unknown parameter `item`"), ("stroke.weightDown", json!({"ids": ids, "aligned": true}), "unknown parameter `aligned`"), ] { let defaults = format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient)); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index fd5e9b4bf8..7bcc474bc3 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -105,7 +105,7 @@ pub fn proxy_specs() -> Vec { "Complement", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model()) ), @@ -114,7 +114,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Color", [], Some(","), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = Paint::solid(s.last_solid); @@ -126,7 +126,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Gradient", [], Some("."), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone()))); @@ -1080,17 +1080,14 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( } let item = item_target(s, p, cmd)?.of_kind(s, !stroke); let (r, shown_at) = match item { - ItemTarget::Item { index, .. } => { + ItemTarget::Item { .. } => { let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?); let of = super::appearance::reference_of(s, p, item, cmd)?; - // With design art first, the row shown is the one edited in the first object that has it. - let shown_at = match of { - Some(_) => super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it { - ItemTarget::Item { index, .. } => Some((id, Some(index))), - ItemTarget::Top => None, - }), - None => targets.first().map(|id| (*id, Some(index))), - }; + // The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row. + let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it { + ItemTarget::Item { index, .. } => Some((id, Some(index))), + ItemTarget::Top => None, + }); let mut changed = 0; edit_items(s, &targets, item, of, cmd, label, !stroke, |n, i| { let paint = diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index b338e6ae20..09ae0b8e41 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Stroke Options", [], None, - "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)", + "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)", has_doc, stroke_advanced ), diff --git a/crates/engine/src/tests/proxyitems.rs b/crates/engine/src/tests/proxyitems.rs index 22c4d0bcac..53ac25f1be 100644 --- a/crates/engine/src/tests/proxyitems.rs +++ b/crates/engine/src/tests/proxyitems.rs @@ -52,6 +52,39 @@ fn invert_and_complement_recolour_the_active_item() { assert_eq!((item_hex(&s, id, 0), item_hex(&s, id, 2)), ("#ff0000".into(), "#0000ff".into())); } +/// With a mixed selection, Invert on the Appearance panel's active row remembers the color of the row it recolors in the +/// first object, the row equal to the active one, which need not have the active row's index. +#[test] +fn invert_of_the_active_row_remembers_the_equal_row_it_recolors() { + let mut s = session(); + let rect = |s: &mut Session, x: f64| { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 50, "height": 50})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + }; + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 100.0)); + // `a` paints first: [red Fill, Stroke, blue Fill]. `b`, selected first: [green Fill, red Fill, Stroke]. + let look = Appearance::basic(Paint::solid(Color::from_hex("#ff0000").unwrap()), Paint::solid(Color::BLACK), 1.0); + let (mut a_look, mut b_look) = (look.clone(), look.clone()); + let (mut green, mut blue) = (look.items[0].clone(), look.items[0].clone()); + *green.paint_mut() = Paint::solid(Color::from_hex("#00ff00").unwrap()); + *blue.paint_mut() = Paint::solid(Color::from_hex("#0000ff").unwrap()); + b_look.items.insert(0, green); + a_look.items.push(blue); + s.edit("Looks", |d, _| { + d.node_mut(a).unwrap().appearance = vectorcraft_doc::Shared::new(a_look.clone()); + d.node_mut(b).unwrap().appearance = vectorcraft_doc::Shared::new(b_look.clone()); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 1})).unwrap(); + s.last_solid = Color::from_hex("#808080").unwrap(); + s.execute("paint.invert", &json!({})).unwrap(); + let hexes = (item_hex(&s, a, 0), item_hex(&s, a, 2), item_hex(&s, b, 0), item_hex(&s, b, 1)); + assert_eq!(hexes, ("#00ffff".into(), "#0000ff".into(), "#00ff00".into(), "#00ffff".into())); + assert_eq!(s.last_solid.to_hex(), "#00ffff", "the last color is the inverted red, not row 1 of the first object"); +} + #[test] fn the_mixed_proxy_compares_the_active_item() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index f6d7e35fb8..7f9a8866f2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -836,8 +836,8 @@ given), `threeD.mapGraphic`, do not use the Appearance panel's active row. When the first object given is design art, rows and effects given with `aligned: true` are rows of its stack in `appearance.setItem`, `appearance.removeItem`, `appearance.duplicateItem`, `transparency.set` with an `item`, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, -move or remove an effect, `paint.setFill`, `paint.setStroke`, `paint.invert` and `paint.complement` with an `item`, -`stroke.set`, `stroke.setAdvanced`, `paint.editGradient`, `paint.setGradientGeom` and the `paint.freeform.*` commands +move or remove an effect, `paint.setFill`, `paint.setStroke`, `paint.invert`, `paint.complement`, `paint.lastColor` and +`paint.lastGradient` with an `item`, `stroke.set`, `stroke.setAdvanced`, `paint.editGradient`, `paint.setGradientGeom` and the `paint.freeform.*` commands that edit points and lines: each other object edits the row or effect equal to it, and an object without one is left as it is. When no object has one, `appearance.setItem` and `appearance.removeItem` leave the document as it is, as they do for a row no object has, and the other commands are an error. The paint, stroke and gradient commands are also an diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f155a68510..b4ab312e48 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1157,6 +1157,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. The transparency, paint, stroke, gradient and overprint commands and Expand Appearance also leave the art of a column or marker design inside a series unchanged. The graph draws that art again from the design (`docs/mcp.md`). + When that art is given first with `aligned: true`, the paint, stroke and gradient commands read the `item` as a row of the art's stack, and each other object edits its equal row. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. While a drag rotates the view, a dial at the center of the canvas shows the angle. - **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation). From a3ac628576ba6a7da2f76f7f42f5469cd243d85e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:27:42 -0800 Subject: [PATCH 05/11] .ai import: symbol instances in older files are read, so art outside the artboard opens Files saved for versions 10 to 13 place each symbol instance with a TransformMatrix. On the page it takes the symbol's art to the canvas (y down); in a symbol's art, it takes the art to that symbol's space. The reader only knew the RTransformMatrix of newer files, so any such instance made the editing data unreadable, and the file opened from its PDF part alone, which holds only the art on the artboards. The reader now converts a TransformMatrix with the canvas point of art space's origin that the template box gives. A file whose symbol instances were the only part it could not read now opens from its layers, with the art outside its artboards. The symbols fuzz test also damages the same data in the older form. Docs: docs/target-app-parity.md, docs/file-format-parity.md. --- crates/engine/tests/import_fuzz.rs | 51 ++++++++++++++++ crates/eps/src/import/ai/read.rs | 6 +- crates/eps/src/import/ai/read/containers.rs | 15 +++-- crates/eps/src/import/ai/tests.rs | 65 +++++++++++++++++++++ crates/eps/src/import/tests_native.rs | 28 +++++++++ docs/file-format-parity.md | 3 +- docs/target-app-parity.md | 1 + 7 files changed, 161 insertions(+), 8 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index a768785abf..cdbc5fe845 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4504,6 +4504,10 @@ proptest! { let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + // The same symbols as files of versions 10 to 13 place them, by a `TransformMatrix`. + let older = mutate_text(&older_symbols_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&older)].concat(); + survive("mutated older .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; // A symbol library: the same symbols and list, no layers. let library = mutate_text(&symbol_library_text(), cut, &edits); let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&library)].concat(); @@ -4758,6 +4762,53 @@ fn the_symbols_fuzz_data_opens_live() { assert_eq!(instances, 3); } +/// [`symbols_text`] with its instances placed by a `TransformMatrix`, as files of versions 10 to +/// 13 write them. Art space's origin is at canvas (8091, 8242), from the template box: on the page +/// the matrix takes the symbol's art to the canvas (y down), and in S2's art to S2's space. +fn older_symbols_text() -> String { + let mut text = symbols_text(); + for (newer, older) in [ + ("1 0 0 -1 -8081 8237 /RTransformMatrix", "1 0 0 1 10 5 /TransformMatrix"), + ("1 0 0 -1 20 50 /RTransformMatrix", "1 0 0 1 8111 8192 /TransformMatrix"), + ("2 0 0 -2 100 50 /RTransformMatrix", "2 0 0 2 8191 8192 /TransformMatrix"), + ("1 0 0 -1 20 20 /RTransformMatrix", "1 0 0 1 8111 8222 /TransformMatrix"), + ] { + assert!(text.contains(newer), "{newer}"); + text = text.replace(newer, older); + } + text +} + +/// The older data [`ai_symbols_never_panic`] damages, as it is, opens with its instances live and +/// placed as [`symbols_text`] places them, on the page and in S2's art. +#[test] +fn the_older_symbols_fuzz_data_opens_live() { + use vectorcraft_doc::{Node, NodeKind}; + fn xfs(n: &Node, out: &mut Vec<[f64; 6]>) { + match &n.kind { + NodeKind::SymbolInstance { xf, .. } => out.push(xf.as_coeffs()), + _ => n.children().into_iter().flatten().for_each(|c| xfs(c, out)), + } + } + let open = |text: &str| { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat(); + let (doc, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let (mut page, mut nested) = (vec![], vec![]); + doc.layers.iter().for_each(|l| xfs(l, &mut page)); + let s2 = doc.symbols.iter().find(|s| s.name == "S2").expect("S2"); + xfs(&s2.art, &mut nested); + (page, nested) + }; + let text = older_symbols_text(); + assert!(!text.contains("/RTransformMatrix")); + let (older, newer) = (open(&text), open(&symbols_text())); + assert_eq!((older.0.len(), older.1.len()), (3, 1)); + let same = |a: &[[f64; 6]], b: &[[f64; 6]]| a.len() == b.len() && a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-9); + assert!(same(&older.0, &newer.0), "{older:?} {newer:?}"); + assert!(same(&older.1, &newer.1), "{older:?} {newer:?}"); +} + /// Symbols the reader must stop at: sections that don't end, references and matrices it can't /// use, definitions nested deeper than it reads, and symbols that hold each other. #[test] diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 0cf1c64a89..bc1b82c22d 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -102,8 +102,10 @@ //! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx //! ty /RTransformMatrix ;`, the matrix taking the symbol's art to art space; in a symbol's art, //! it takes it to art space about the canvas point of art space's origin, as a pattern's -//! gradients are. Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after -//! it. +//! gradients are. Files of versions 10 to 13 write `a b c d tx ty /TransformMatrix` instead, +//! the matrix taking the symbol's art to the canvas (y down, art space's origin at the canvas +//! point the template box gives); in a symbol's art, it takes the art to that symbol's space. +//! Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after it. //! //! Sections the reader doesn't need (styles, filters) are skipped; type, instances of symbols it //! can't read, fills with a pattern it can't read, placed files without a preview and operators diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 426416b754..8e670b3f72 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -636,17 +636,22 @@ impl<'a> Reader<'a> { /// A symbol instance (`/SymbolInstance`): the symbol its `SymbolRef` names, placed by its /// `RTransformMatrix`, hidden and locked as the state says. In a symbol's art the matrix is /// written about the canvas point of art space's origin, and the name is the file's until the - /// symbols are checked ([`Self::check_symbols`]). An instance of a symbol that wasn't read, one - /// whose appearance differs from its symbol's, or one placed only by a `Matrix` or `Transform`, - /// comes in as the page draws it, within the symbol's box placed by the matrix when the box is - /// known. + /// symbols are checked ([`Self::check_symbols`]). Files of versions 10 to 13 place an instance + /// by a `TransformMatrix` instead, which takes the symbol's art to the canvas (y down); in a + /// symbol's art, it takes the art to that symbol's space. The reader converts it with the canvas + /// point of art space's origin, from the template box. An instance of a symbol that wasn't + /// read, one whose appearance differs from its symbol's, or one placed only by a `Matrix` or + /// `Transform`, comes in as the page draws it, within the symbol's box placed by the matrix + /// when the box is known. fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> { let name = self.names.entry(o, "SymbolRef"); let affine = |n: &[f64]| match n { [a, b, c, d, e, f] if [a, b, c, d, e, f].iter().all(|v| v.is_finite()) => Some(super::Affine::new([*a, *b, *c, *d, *e, *f])), _ => None, }; - let live = affine(&o.nums("RTransformMatrix")); + // The canvas → art space: y turned up about the canvas point of art space's origin. + let from_canvas = self.canvas_origin().map(|o| super::Affine::new([1.0, 0.0, 0.0, -1.0, -o.x, o.y])); + let live = affine(&o.nums("RTransformMatrix")).or_else(|| Some(from_canvas? * affine(&o.nums("TransformMatrix"))?)); let boxed_only = live.is_none(); let matrix = live.or_else(|| { o.get("Matrix") diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index d160248a2d..8c438d6151 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5115,6 +5115,71 @@ fn an_instance_in_a_symbols_art_is_placed_from_the_canvas() { assert_eq!(instance_box(&doc, &a[0]), Rect::new(58.0, 53.0, 62.0, 57.0)); } +/// Files of versions 10 to 13 place an instance by a `TransformMatrix` that takes the symbol's art +/// to the canvas (y down): the instance stays live and lands where the `RTransformMatrix` of a +/// newer file puts it, on the page and in a symbol's art. +#[test] +fn an_instance_placed_on_the_canvas_by_an_older_file_stays_live() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). + let older = |name: &str, m: [f64; 6]| { + let [a, b, c, d, e, f] = m; + format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{a} {b} {c} {d} {e} {f} /TransformMatrix\n;\n") + }; + let page = older("Dot", [1.0, 0.0, 0.0, 1.0, 8111.0, 8192.0]) + &older("Dot", [2.0, 0.0, 0.0, 2.0, 8191.0, 8192.0]); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Dot", &dot(), 5)), layer(&page)); + let doc = read_ok(&body).doc; + let a = art(&doc); + assert_eq!(a.len(), 2); + assert!(a.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "{a:#?}"); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(18.0, 48.0, 22.0, 52.0)); + assert_eq!(instance_box(&doc, &a[1]), Rect::new(96.0, 46.0, 104.0, 54.0)); + // Turned and scaled, as the newer file writes the same instance: canvas x is art x + 8091 and + // canvas y is 8242 - art y, so the second row of the matrix changes sign. + let turned = [1.299, -0.4, 0.75, 0.6928, 8111.0, 8192.0]; + let newer = [1.299, 0.4, 0.75, -0.6928, 20.0, 50.0]; + let older_doc = + read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Dot", &dot(), 5)), layer(&older("Dot", turned)))).doc; + let newer_doc = + read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Dot", &dot(), 5)), layer(&instance("Dot", newer)))).doc; + let xf = |d: &Document| match &art(d)[0].kind { + NodeKind::SymbolInstance { xf, .. } => xf.as_coeffs(), + k => panic!("{k:?}"), + }; + let (o, n) = (xf(&older_doc), xf(&newer_doc)); + assert!(o.iter().zip(n).all(|(a, b)| (a - b).abs() < 1e-9), "{o:?} {n:?}"); + // In a symbol's art the matrix takes the art to the symbol's own space: Dot at (10, 5) in Pair's + // art, which the page instance puts at (50, 50). + let nested = older("Dot", [1.0, 0.0, 0.0, 1.0, 10.0, 5.0]); + let defs = symbols(&(symbol("Dot", &dot(), 5) + &symbol("Pair", &nested, 1))); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&older("Pair", [1.0, 0.0, 0.0, 1.0, 8141.0, 8192.0]))); + let doc = read_ok(&body).doc; + let a = art(&doc); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(58.0, 53.0, 62.0, 57.0)); + // One document saved in both forms: the template box's center is (100.5, 99.5), so art space's + // origin is at canvas (8091, 8291). Dot sits at (5, 2.5) in Pair's art, and the page instance + // puts Pair at (57, 145.5). Both instances get the newer file's matrices, coefficient by + // coefficient. + let saved = |inner: String, pair: String| { + let defs = symbols(&(symbol("Dot", &dot(), 5) + &symbol("Pair", &inner, 1))); + read_ok(&format!("%AI3_TemplateBox: 100.5 99.5 100.5 99.5\n{defs}{}", layer(&pair))).doc + }; + let older_doc = saved(older("Dot", [1.0, 0.0, 0.0, 1.0, 5.0, 2.5]), older("Pair", [1.0, 0.0, 0.0, 1.0, 8148.0, 8145.5])); + let newer_doc = saved(instance("Dot", [1.0, 0.0, 0.0, -1.0, -8086.0, 8288.5]), instance("Pair", [1.0, 0.0, 0.0, -1.0, 57.0, 145.5])); + fn first_xf(n: &Node) -> Option<[f64; 6]> { + match &n.kind { + NodeKind::SymbolInstance { xf, .. } => Some(xf.as_coeffs()), + _ => n.children()?.iter().find_map(|c| first_xf(c)), + } + } + let both = |d: &Document| (xf(d), first_xf(&d.symbols[1].art).expect("Dot's instance in Pair's art")); + let ((op, on), (np, nn)) = (both(&older_doc), both(&newer_doc)); + assert!(op.iter().zip(np).all(|(a, b)| (a - b).abs() < 1e-9), "{op:?} {np:?}"); + assert!(on.iter().zip(nn).all(|(a, b)| (a - b).abs() < 1e-9), "{on:?} {nn:?}"); + // Without a template box the canvas's place isn't known: the instance isn't read. + let e = read(stream(&layer(&older("Dot", [1.0, 0.0, 0.0, 1.0, 8111.0, 8192.0]))).as_bytes()); + assert!(e.is_err_and(|e| e.contains("symbols"))); +} + #[test] fn an_image_in_a_symbols_art_is_placed_from_the_canvas() { // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). The diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 738f02d857..4ecb414b91 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2197,6 +2197,34 @@ fn an_ai_file_gets_its_layers_and_the_art_outside_its_artboard() { assert!(!d.layers[2].visible); } +/// A `.ai` of versions 10 to 13, whose symbol instances are placed by a `TransformMatrix` on the +/// canvas, opens from its layers: the art outside its artboard, an instance among it, comes in, +/// rather than the PDF part alone, which has none of it. +#[test] +fn an_older_ai_files_symbols_keep_its_layers_and_the_art_outside_its_artboard() { + // The template box's center is (50.5, 50.5): art space's origin is at canvas (8141, 8242). The + // instance puts Box at (150, 50) in art space, right of the artboard (x 0 to 100). + let instance = "/SymbolInstance :\n(Box) /SymbolRef ,\n1 0 0 1 8291 8192 /TransformMatrix\n;\n9 () XW"; + let layers = format!( + "{}{}{}", + stroked_box_symbol(), + layer("Jig", true, &square(10, 10)), + layer("Parts", true, &format!("{}\n{instance}", square(30, 110))) + ); + let art = native(&layers).replacen("%AI5_NumLayers", "%AI3_TemplateBox: 50.5 50.5 50.5 50.5\n%AI5_NumLayers", 1); + let (d, warnings, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0); + assert!(read, "{warnings:?}"); + assert_eq!(names(&d), ["Jig", "Parts"], "{warnings:?}"); + let parts = d.layers[1].children().unwrap(); + let above = parts[0].visual_bounds().unwrap(); + assert!(above.y1 <= 1e-6, "the square above the artboard is kept, outside it: {above:?}"); + let NodeKind::SymbolInstance { symbol, .. } = &parts[1].kind else { panic!("an instance: {:?} {warnings:?}", parts[1].kind) }; + assert_eq!(symbol, "Box"); + let b = parts[1].visual_bounds_with(&d.symbol_boxes()).unwrap(); + let near = [b.x0 - 149.0, b.y0 - 49.5, b.x1 - 151.0, b.y1 - 50.5].iter().all(|v| v.abs() < 0.3); + assert!(near, "the instance right of the artboard: {b:?}"); +} + /// A `.ai` whose PDF part was read in points from a page of 10 points a unit (its `UserUnit`), and /// whose editing data has the page in those units: its layers come in at the page's size, ten /// times as large as the editing data has them, with stroke weights and dashes ten times as large. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bf52925f5c..acb5675aa8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -190,7 +190,8 @@ private editing data. VectorCraft: 14; #868: round trip with Illustrator 2018 loses layers and groups), some files 4× slower to open since the editing data is read whole (#758), live effects that are not read or have settings that are not read, and brushes come in as their drawn look (#637; pattern fills are read since #1025, and symbols and their instances - open live, as do the symbols of a symbol library without layers); legacy `.ai` without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868; guides + open live, those that files of versions 10 to 13 place with a `TransformMatrix` included, as do the symbols of a + symbol library without layers); legacy `.ai` without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868; guides open as ruler guides and guide paths since #5057 (#779), hidden, locked and named ruler guides with their state. Type under a Warp effect is compared with the art saved with it: type that draws as that art stays editable with the effect live, and type that draws differently, or that the file's limit of checks has no check left for, opens diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c6972468cc..87b49bb915 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1795,6 +1795,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A hidden (`1 Xw`) ruler guide path in `.ai` and EPS editing data opens as a hidden ruler guide rather than a guide path, and every ruler guide keeps its path's hide, lock and name, so its Layers row shows them (`hidden_locked_and_named_guide_paths_are_ruler_guides`). + `.ai` editing-data import reads symbol instances that files of versions 10 to 13 place with a `TransformMatrix` on the canvas, on the page and in a symbol's art, so such a file opens from its layers with the art outside its artboards instead of from its PDF part alone (`an_instance_placed_on_the_canvas_by_an_older_file_stays_live`, `an_older_ai_files_symbols_keep_its_layers_and_the_art_outside_its_artboard`). `.ai` and EPS editing-data import keeps each path's Attributes panel note (`%AI3_Note:`, `%%Note:`, more lines in `%AI5_NoteMore:`, up to 1,024 characters) and Show Center (`1 Ap`); a note or Show Center applies to every path after it until the next one, and a note before a group or compound path is not theirs (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_illustrator.rs`). `.ai` and EPS editing-data import reads object tags (`/identifier (string) XT`) on the object before them, whatever kind of object it is: `AdobeURL` becomes the object's URL, and every other tag is kept in the object's data in order, up to 64 per object; a tag longer than 64 KiB, and tags in a pattern's or brush's art, are ignored. A tag on art that shows no longer stops the editing data from being read, and brush art that holds tags is read (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_illustrator.rs`). A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). From 0ca231a31bf1bcf1c3ae58f5ccfb392796660f5b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:43:52 -0800 Subject: [PATCH 06/11] .ai import: the test of an older instance without a template box defines its symbol The last case of an_instance_placed_on_the_canvas_by_an_older_file_stays_live read an instance of a symbol the file did not define, so it failed for that reason as well as for the missing template box. It now defines Dot, so it fails only when the reader places an older instance without a template box. --- crates/eps/src/import/ai/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 8c438d6151..dd623c99c1 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5175,8 +5175,10 @@ fn an_instance_placed_on_the_canvas_by_an_older_file_stays_live() { let ((op, on), (np, nn)) = (both(&older_doc), both(&newer_doc)); assert!(op.iter().zip(np).all(|(a, b)| (a - b).abs() < 1e-9), "{op:?} {np:?}"); assert!(on.iter().zip(nn).all(|(a, b)| (a - b).abs() < 1e-9), "{on:?} {nn:?}"); - // Without a template box the canvas's place isn't known: the instance isn't read. - let e = read(stream(&layer(&older("Dot", [1.0, 0.0, 0.0, 1.0, 8111.0, 8192.0]))).as_bytes()); + // Without a template box the canvas's place isn't known: the instance isn't read, though Dot is + // defined and the same instance with a template box is read above. + let defs = symbols(&symbol("Dot", &dot(), 5)); + let e = read(stream(&format!("{defs}{}", layer(&older("Dot", [1.0, 0.0, 0.0, 1.0, 8111.0, 8192.0])))).as_bytes()); assert!(e.is_err_and(|e| e.contains("symbols"))); } From f05d48124778bd48dcfe3040209b7fb3ffb02410 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:30:33 -0800 Subject: [PATCH 07/11] Control bar: Select Similar Objects selects by the attribute its menu keeps With something selected, the Control bar shows a Select Similar Objects button and, beside it, the Select Similar Options menu. The button selects the objects like the first selected one by the attribute kept for the session; a menu item selects by its attribute and keeps it, and the kept item is checked. The items are All, Fill Color, Fill & Stroke, Stroke Color, Stroke Weight, Opacity, Blending Mode, Appearance, Graphic Style, Shape and Symbol Instance. - select.similar {by?} runs the select.same command of that name, or for "all" matches fill and stroke colors, stroke weight, opacity and blending mode together. An unknown by is an error that keeps the selection and the kept attribute. The journal records the attribute used, so a recorded action repeats it, and a failed script or plug-in call puts the kept attribute back. - The button and menu belong to the Object Options group and sit at the right end of the bar, after the X, Y, W and H fields. They take only the room the other controls leave, so the bar leaves them out before any other control. - The Paragraph tests' control_bar_node looks for a label before a value, so a link's text run listed first no longer stands in for the link. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/plugin_call.rs | 3 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/select.rs | 60 ++++++++ crates/engine/src/lib.rs | 3 + crates/engine/src/script/mod.rs | 6 +- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/menucmds.rs | 67 +++++++++ crates/engine/src/tests/script_run.rs | 5 + crates/ui-egui/src/chrome/control_bar.rs | 86 +++++++++-- crates/ui-egui/src/chrome/tests.rs | 133 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/panels/paragraph/tests.rs | 7 +- docs/mcp.md | 19 ++- docs/target-app-parity.md | 1 + 42 files changed, 436 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 99b8e1ecdd..313531bb99 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -828,6 +828,7 @@ pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; +pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 6d1ddbee43..6c23161a9d 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -540,6 +540,7 @@ struct Saved { recent_colors: Vec, recent_urls: Vec, global_edit_options: super::globaledit::Options, + select_similar: &'static str, envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>, } @@ -564,6 +565,7 @@ impl Saved { recent_colors: s.recent_colors.clone(), recent_urls: s.recent_urls.clone(), global_edit_options: s.global_edit_options.clone(), + select_similar: s.select_similar, envelope_defaults: s.envelope_defaults, } } @@ -587,6 +589,7 @@ impl Saved { s.recent_colors = self.recent_colors; s.recent_urls = self.recent_urls; s.global_edit_options = self.global_edit_options; + s.select_similar = self.select_similar; s.envelope_defaults = self.envelope_defaults; s.pending_paint = None; } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 03a931ba5d..2b1826328e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -536,6 +536,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.same.textStrokeColor", "select.segments", "select.set", + "select.similar", "select.storedPath", "select.toggle", "select.update", diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index ac9ca365f4..03bbd11ab6 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -225,9 +225,69 @@ pub fn specs() -> Vec { has_selection, same_attribute ), + cmd!( + "select.similar", + "Select Similar Objects", + [], + None, + "{by?: \"all\"|\"fillColor\"|\"fillAndStroke\"|\"strokeColor\"|\"strokeWeight\"|\"opacity\"|\"blendingMode\"|\"appearance\"|\"graphicStyle\"|\"shapeType\"|\"symbolInstance\"} the Control bar's Select Similar Objects button and its menu: selects the objects like the first selected object by `by`, running the select.same command of that name; `all` selects the objects with its fill and stroke colours, stroke weight, opacity and blending mode (tints, compound paths and Live Paint faces as select.same.fillColor). A `by` given is kept for the session once the selection is made; without it, the kept one (`all` until one is given). Any other `by` is an error that keeps the selection and the kept attribute → {count, by}", + has_selection, + similar + ), ] } +/// The attributes Select Similar Objects (`select.similar`) selects by, in its menu's order, each +/// with the Select › Same command it runs; `all` compares the fill and stroke colours, the stroke +/// weight, the opacity and the blending mode at once, with no command of its own. +pub const SIMILAR: [(&str, Option<&str>); 11] = [ + ("all", None), + ("fillColor", Some("select.same.fillColor")), + ("fillAndStroke", Some("select.same.fillAndStroke")), + ("strokeColor", Some("select.same.strokeColor")), + ("strokeWeight", Some("select.same.strokeWeight")), + ("opacity", Some("select.same.opacity")), + ("blendingMode", Some("select.same.blendingMode")), + ("appearance", Some("select.same.appearance")), + ("graphicStyle", Some("select.same.graphicStyle")), + ("shapeType", Some("select.same.shapeType")), + ("symbolInstance", Some("select.same.symbolInstance")), +]; + +fn similar(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.similar"; + let by = match text_param(p, "by", C)? { + Some(name) => *SIMILAR.iter().find(|(n, _)| *n == name).ok_or_else(|| { + let names: Vec<&str> = SIMILAR.iter().map(|(n, _)| *n).collect(); + bad(C, format!("unknown `by` \"{name}\": expected one of {}", names.join(", "))) + })?, + None => *SIMILAR.iter().find(|(n, _)| *n == s.select_similar).unwrap_or(&SIMILAR[0]), + }; + let mut r = match by.1 { + Some(same_cmd) => s.execute(same_cmd, &json!({}))?, + None => { + let tint = s.prefs.select_same_tint_percent; + let r = same_fill(s, C, |a, b| { + same_paint(&fill_of(a), &fill_of(b), tint) + && same_paint(&stroke_of(a).0, &stroke_of(b).0, tint) + && (stroke_weight(a) - stroke_weight(b)).abs() < 1e-9 + && (a.opacity - b.opacity).abs() < 1e-6 + && a.blend == b.blend + })?; + // Select › Reselect repeats `all`, whichever attribute is kept by then. + if let Some(last) = s.doc_mut()?.last_selection_cmd.as_mut() { + last.1 = json!({ "by": by.0 }); + } + r + } + }; + s.select_similar = by.0; + // A recorded action or the journal repeats the attribute used, not the one kept by then. + s.note_journal("by", json!(by.0)); + r["by"] = json!(by.0); + Ok(r) +} + /// Selectable objects: children of visible, unlocked layers (or of the isolation container). /// The objects Select All takes: those of the isolated container, else of every layer (looking /// through sublayers, which are not objects). In isolation mode there are none while the isolated diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4b47966463..890f8622f8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -344,6 +344,9 @@ pub struct Session { /// The Global Edit Options Start Global Edit matches with (`select.globalEditOptions`); not /// saved. pub global_edit_options: cmd::globaledit::Options, + /// The attribute Select Similar Objects selects by (`select.similar`), one of + /// [`cmd::SIMILAR`]; not saved. + pub select_similar: &'static str, /// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool /// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]). keyboard_text: bool, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 1b95b5fe2a..295c9ac795 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -429,7 +429,7 @@ struct World { } /// The choices outside the documents that a script's commands can change: the preferences, the -/// global edit options, the recent URLs, the chosen gradient stop, freeform point and appearance +/// global edit options, the Select Similar Objects attribute, the recent URLs, the chosen gradient stop, freeform point and appearance /// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state. #[derive(Clone)] struct Choices { @@ -437,6 +437,7 @@ struct Choices { caps_lock: bool, eyedropper_sample: Option>, global_edit_options: cmd::globaledit::Options, + select_similar: &'static str, recent_urls: Vec, gradient_stop: Option<(usize, cmd::gradient::StopOwner)>, freeform_point: Option<(usize, cmd::gradient::StopOwner)>, @@ -451,6 +452,7 @@ impl Choices { caps_lock: s.caps_lock, eyedropper_sample: s.eyedropper_sample.clone(), global_edit_options: s.global_edit_options.clone(), + select_similar: s.select_similar, recent_urls: s.recent_urls.clone(), gradient_stop: s.gradient_stop, freeform_point: s.freeform_point, @@ -464,6 +466,7 @@ impl Choices { s.caps_lock = self.caps_lock; s.eyedropper_sample = self.eyedropper_sample; s.global_edit_options = self.global_edit_options; + s.select_similar = self.select_similar; s.recent_urls = self.recent_urls; s.gradient_stop = self.gradient_stop; s.freeform_point = self.freeform_point; @@ -477,6 +480,7 @@ impl Choices { swap(&mut self.caps_lock, &mut s.caps_lock); swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample); swap(&mut self.global_edit_options, &mut s.global_edit_options); + swap(&mut self.select_similar, &mut s.select_similar); swap(&mut self.recent_urls, &mut s.recent_urls); swap(&mut self.gradient_stop, &mut s.gradient_stop); swap(&mut self.freeform_point, &mut s.freeform_point); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1244b77432..b54333206f 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -141,6 +141,7 @@ impl Session { link_stamps: Default::default(), link_scan: None, global_edit_options: Default::default(), + select_similar: crate::cmd::SIMILAR[0].0, keyboard_text: false, script_key: None, script_engines: crate::script::EnginesKey::new(), diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1151f83910..4afab29a91 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2789,6 +2789,73 @@ fn select_same_fill_keeps_live_paint_faces_to_their_group() { } } +/// Select Similar Objects (`select.similar`) runs the Select > Same command of the attribute it is +/// given and keeps that attribute for its next run without one; `all`, the attribute until one is +/// given, matches the fill and stroke colours, the stroke weight, the opacity and the blending mode +/// together. An unknown attribute is an error that keeps the selection and the kept attribute. +#[test] +fn select_similar_selects_by_the_kept_attribute() { + let mut s = session(); + let [a, b, faded, heavy, multiplied, blue] = [0.0, 20.0, 40.0, 60.0, 80.0, 100.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0)); + for id in [a, b, faded, heavy, multiplied] { + fill(&mut s, id, "#ff0000"); + } + fill(&mut s, blue, "#0000ff"); + s.execute("transparency.set", &json!({"ids": [faded.0], "opacity": 50, "item": null})).unwrap(); + s.execute("transparency.set", &json!({"ids": [multiplied.0], "blend": "multiply", "item": null})).unwrap(); + sel(&mut s, &[heavy]); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let similar = |s: &mut Session, p: Value| { + sel(s, &[a]); + let r = s.execute("select.similar", &p).unwrap(); + let mut v = selected(s); + v.sort(); + assert_eq!(r["count"], v.len(), "{p}"); + (r["by"].as_str().unwrap().to_string(), v) + }; + assert_eq!(s.select_similar, "all"); + assert_eq!(similar(&mut s, json!({})), ("all".into(), vec![a, b])); + assert_eq!(similar(&mut s, json!({"by": "fillColor"})), ("fillColor".into(), vec![a, b, faded, heavy, multiplied])); + assert_eq!(similar(&mut s, json!({})), ("fillColor".into(), vec![a, b, faded, heavy, multiplied])); + // The journal, and an action recorded around it, keep the attribute used. + let last = s.journal.last().unwrap(); + assert_eq!((last.0.as_str(), &last.1), ("select.similar", &json!({"by": "fillColor"}))); + assert_eq!(similar(&mut s, json!({"by": "opacity"})), ("opacity".into(), vec![a, b, heavy, multiplied, blue])); + assert_eq!(similar(&mut s, json!({"by": "blendingMode"})), ("blendingMode".into(), vec![a, b, faded, heavy, blue])); + assert_eq!(similar(&mut s, json!({"by": "strokeWeight"})), ("strokeWeight".into(), vec![a, b, faded, multiplied, blue])); + assert_eq!(similar(&mut s, json!({"by": "all"})).1, vec![a, b]); + // Select > Reselect repeats `all`, whichever attribute is kept by then. + s.select_similar = "fillColor"; + s.execute("select.reselect", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![a, b]); + // Every attribute names a command that runs. A path with no graphic style has none to match, + // which is an error that keeps the attribute as it was. + for (by, _) in crate::cmd::SIMILAR { + sel(&mut s, &[a]); + let was = s.select_similar; + let r = s.execute("select.similar", &json!({ "by": by })); + if by == "graphicStyle" { + assert!(r.is_err(), "{r:?}"); + assert_eq!(s.select_similar, was); + } else { + r.unwrap_or_else(|e| panic!("{by}: {e:?}")); + assert_eq!(s.select_similar, by); + } + } + // An unknown or malformed attribute changes nothing. + s.select_similar = "opacity"; + for bad in [json!("color"), json!(""), json!("FillColor"), json!(3), json!(true), json!(["all"])] { + sel(&mut s, &[a]); + let r = s.execute("select.similar", &json!({ "by": bad })); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert_eq!((selected(&s), s.select_similar), (vec![a], "opacity"), "{bad}"); + } + // With nothing selected it does not run, and keeps the attribute. + sel(&mut s, &[]); + assert!(s.execute("select.similar", &json!({"by": "fillColor"})).is_err()); + assert_eq!(s.select_similar, "opacity"); +} + /// Select by Color needs no object to start from: it matches fills and strokes as /// `document.inspect` reports them, `#rrggbb`. #[test] diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index d272fea167..94daa358bd 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -290,6 +290,11 @@ fn a_failed_run_puts_back_the_choices_its_commands_made() { run(&mut s, source).unwrap(); assert_eq!(s.global_edit_options, before, "the failed command's choice went back"); + let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); \ + if (vc.run('select.similar', {by: 'opacity'}).by !== 'opacity') throw new Error('not run'); throw new Error('x');"; + assert!(matches!(run(&mut s, source), Err(e) if !format!("{e:?}").contains("not run"))); + assert_eq!(s.select_similar, "all", "the Select Similar Objects attribute went back"); + assert!(!s.caps_lock); assert!(run(&mut s, "vc.run('view.capsLock', {on: true}); throw new Error('x');").is_err()); assert!(!s.caps_lock, "the Caps Lock state went back"); diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index fc06926247..8b6c2400e6 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -348,8 +348,11 @@ fn transform_reserve(app: &VectorcraftApp, ui: &Ui, selected: bool) -> f32 { /// Align To menu and, for two or more objects, the Distribute buttons (a single object keeps the bar /// as it was); each shows only while the end of the bar keeps its room. Groups the panel menu has /// off are left out, and take no room. Without `room` (the Character group had none), all of these -/// groups are left out, so the bar trims them from its right end before the Character group. -fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize, room: bool) -> bool { +/// groups are left out, so the bar trims them from its right end before the Character group. Also +/// returns whether the Character group and the Align group had their room: the Align buttons, the +/// Align To menu and the Distribute buttons the selection calls for all showed, or the group is +/// off. +fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize, room: bool) -> (bool, bool) { let nothing = objects == 0; let end = end_width(app, ui, nothing); if room && group_on(app, "paragraph") && crate::panels::paragraph::control_bar(app, ui, BUTTON, |ui| group_end_width(ui) + end) { @@ -374,24 +377,30 @@ fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize app.run("edit.preferences", json!({})).ok(); } } - return false; + return (false, false); } let transform = group_on(app, "transform"); let end = if transform { separator_width(ui) + end } else { 0.0 }; - if room && group_on(app, "alignDistribute") && ui.available_width() >= buttons_width(ui, 7) + end { + let align_on = group_on(app, "alignDistribute"); + // Whether the whole group showed: the Align buttons, the Align To menu and the Distribute + // buttons the selection calls for. + let mut whole = !align_on; + if room && align_on && ui.available_width() >= buttons_width(ui, 7) + end { crate::panels::align::align_buttons(app, ui, BUTTON); if ui.available_width() >= crate::panels::align::align_to_menu_width(BUTTON) + ui.spacing().item_spacing.x + end { crate::panels::align::align_to_menu(app, ui, BUTTON); + whole = objects < 2; if objects > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) + end { ui.add_space(GROUP_GAP); crate::panels::align::distribute_buttons(app, ui, BUTTON); + whole = true; } } if transform { boundary(ui, separator); } } - transform + (transform, room && whole) } /// Draws the Control bar's Align group after the artboard controls, with the Artboard tool in use: @@ -670,6 +679,59 @@ fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity: } } +/// The width of the chevron that opens the Select Similar Options menu. +const SELECT_SIMILAR_MENU_WIDTH: f32 = 16.0; + +/// The label of each attribute of [`vectorcraft_engine::cmd::SIMILAR`] in the Select Similar Options +/// menu, translated. +fn similar_label(by: &str) -> &'static str { + match by { + "all" => tl!("All"), + "fillColor" => tl!("Fill Color"), + "fillAndStroke" => tl!("Fill & Stroke"), + "strokeColor" => tl!("Stroke Color"), + "strokeWeight" => tl!("Stroke Weight"), + "opacity" => tl!("Opacity"), + "blendingMode" => tl!("Blending Mode"), + "appearance" => tl!("Appearance"), + "graphicStyle" => tl!("Graphic Style"), + "shapeType" => tl!("Shape"), + _ => tl!("Symbol Instance"), + } +} + +/// The Control bar's Select Similar Objects button and, beside it, the Select Similar Options menu +/// (). The +/// button runs `select.similar`, which selects the objects like the first selected one by the +/// attribute kept for the session; a menu item runs it by that item's attribute, which is kept from +/// then on, and the kept one is checked. Both are off while `select.similar` cannot run. They show +/// together at the right end of the bar, after a separator, while something is selected and the +/// panel menu has Object Options on, and only in the room every control ahead of them left +/// ([`contents`]): the bar leaves them out before any other control, and while `ahead_shown` is +/// false (a control ahead of them was left out for room). They show only while the room left is +/// also at least `keep`. +fn trailing_select_similar(app: &mut VectorcraftApp, ui: &mut Ui, ahead_shown: bool, keep: f32) { + let selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); + let width = separator_width(ui) + row_width(ui, &[BUTTON, SELECT_SIMILAR_MENU_WIDTH]); + if !ahead_shown || !selected || !group_on(app, "objectOptions") || ui.available_width() < width.max(keep) { + return; + } + boundary(ui, separator); + let enabled = crate::menus::enabled(app, "select.similar"); + if widgets::icon_button_enabled(ui, "copy", tl!("Select Similar Objects"), false, enabled, BUTTON).clicked() { + crate::menus::invoke(app, "select.similar", json!({})); + } + let options = widgets::icon_button_enabled(ui, "chevron-down", tl!("Select Similar Options"), false, enabled, SELECT_SIMILAR_MENU_WIDTH); + egui::Popup::menu(&options).show(|ui| { + ui.set_min_width(140.0); + for (by, _) in vectorcraft_engine::cmd::SIMILAR { + if widgets::menu_item(ui, similar_label(by), true, app.session.select_similar == by) { + crate::menus::invoke(app, "select.similar", json!({ "by": by })); + } + } + }); +} + /// The Control bar's gripper, at the left end of the bar `bar`. Dragging it shows where a release /// puts the bar ([`release_at`] in `dock_room`, the window below the menu bar): a band along the /// edge it docks to, or the outline of the bar floating under the pointer. The bar stays where it is @@ -861,7 +923,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, // The Character group shows whole, with the Transform link's room left after it, or not at // all; left out, it leaves out the groups between it and the link too. let room = !group_on(app, "character") || crate::panels::character::control_bar(app, ui, reserve); - if !groups_before_transform(app, ui, sel.len(), room) { + let (transform, groups_fit) = groups_before_transform(app, ui, sel.len(), room); + if !transform { + // With the Transform group off, the room its link and X/Y/W/H fields would take stays + // free too, as a group left out ahead takes less than that. + trailing_select_similar(app, ui, groups_fit, crate::panels::transform::link_width(ui) + inline_transform_width(ui, t)); erase_trailing(ui); return; } @@ -875,9 +941,9 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, } crate::panels::transform::link(app, ui); // The bounding box, rotated with rotated objects: its centre and its own sides. - if let Some(b) = app.selection_box() - && ui.available_width() >= inline_transform_width(ui, t) - { + let selection_box = app.selection_box(); + let fields_left_out = selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t); + if let Some(b) = selection_box.as_ref().filter(|_| !fields_left_out) { let c = b.center(); let origin = app.ruler_origin(); let link = crate::panels::transform::proportional(app, ui); @@ -906,6 +972,8 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); } } + // Select Similar Objects comes last: it takes only the room every control ahead of it left. + trailing_select_similar(app, ui, groups_fit && !fields_left_out, 0.0); erase_trailing(ui); }); // Controls that keep their size can still run into the button's room in a narrow window; diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index be37f10a29..fc0099a291 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3502,6 +3502,139 @@ fn the_control_bar_shows_the_global_edit_options() { assert!(seen, "a wide bar has room for it"); } +/// The Control bar's Select Similar Objects button selects the objects like the first selected one +/// by the attribute kept for the session (All at first), and the Select Similar Options menu beside +/// it selects by the item chosen, which is kept and checked from then on. Both show with something +/// selected while the Object Options group is on, and fit inside the bar or are left out. +#[test] +fn the_control_bar_selects_similar_objects() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64, color: &str| { + let id = app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap(); + id + }; + let a = rect(&mut app, 20.0, "#ff0000"); + let b = rect(&mut app, 100.0, "#ff0000"); + let c = rect(&mut app, 200.0, "#0000ff"); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2400.0, 300.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>; + let find = |nodes: &Nodes, name: &str| nodes.iter().find(|(_, n)| n.label() == Some(name) || n.value() == Some(name)).map(|(_, n)| n.clone()); + // A menu item's label carries its check mark or the room for it. + let item = |nodes: &Nodes, name: &str| { + nodes.iter().find(|(_, n)| n.label().or(n.value()).is_some_and(|t| t.trim_start_matches(['✓', ' ']) == name)).map(|(_, n)| n.clone()) + }; + let center = |n: &egui::accesskit::Node| { + let b = n.bounds().unwrap_or_else(|| panic!("{n:?}")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + let click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]); + frame(app, vec![]); + frame(app, vec![]) + }; + let selected = |app: &crate::VectorcraftApp| { + let mut ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|i| i.0).collect(); + ids.sort(); + ids + }; + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + assert!(find(&nodes, "Select Similar Objects").is_none() && find(&nodes, "Select Similar Options").is_none(), "nothing selected"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + let button = find(&nodes, "Select Similar Objects").unwrap_or_else(|| panic!("one rectangle: the button shows")); + click(&mut app, center(&button)); + assert_eq!(selected(&app), vec![a, b], "All: the red rectangles"); + // The menu selects by the item chosen and keeps it. + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + let options = find(&frame(&mut app, vec![]), "Select Similar Options").unwrap_or_else(|| panic!("the options menu shows")); + let nodes = click(&mut app, center(&options)); + for label in [ + "All", + "Fill Color", + "Fill & Stroke", + "Stroke Color", + "Stroke Weight", + "Opacity", + "Blending Mode", + "Appearance", + "Graphic Style", + "Shape", + "Symbol Instance", + ] { + assert!(item(&nodes, label).is_some(), "{label} in the menu"); + } + assert!(find(&nodes, "✓ All").is_some(), "All is checked at first"); + let stroke = item(&nodes, "Stroke Color").unwrap_or_else(|| panic!("Stroke Color")); + click(&mut app, center(&stroke)); + assert_eq!(app.session.select_similar, "strokeColor"); + assert_eq!(selected(&app), vec![a, b, c], "Stroke Color: all three share the default stroke"); + app.run("select.set", json!({"ids": [c]})).unwrap(); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + click(&mut app, center(&find(&nodes, "Select Similar Objects").unwrap_or_else(|| panic!("the button")))); + assert_eq!(selected(&app), vec![a, b, c], "the button keeps Stroke Color"); + let options = find(&frame(&mut app, vec![]), "Select Similar Options").unwrap_or_else(|| panic!("the options menu")); + let nodes = click(&mut app, center(&options)); + assert!(find(&nodes, "✓ Stroke Color").is_some(), "the kept item is checked"); + // The panel menu's Object Options group turns them off. + app.run("window.control.options", json!({"group": "objectOptions"})).unwrap(); + frame(&mut app, vec![]); + assert!(find(&frame(&mut app, vec![]), "Select Similar Objects").is_none(), "Object Options off"); + app.run("window.control.options", json!({"group": "objectOptions"})).unwrap(); + // At any width the button and its menu fit inside the bar together or are left out. They take + // only the room left at the end of the bar, so they show only while the Align buttons and the + // inline X field do too. A control ahead of them that appears in a wider bar (the Distribute + // buttons) can take that room again, so the widest bar is the one that must show them. + let mut seen = false; + for width in (600..=2400).step_by(10) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); + let mut nodes = Vec::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(&mut app, ui)); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + let shown = find(&nodes, "Select Similar Objects").and_then(|n| n.bounds()); + let menu = find(&nodes, "Select Similar Options").and_then(|n| n.bounds()); + assert_eq!(shown.is_some(), menu.is_some(), "{width}: the button and its menu show together"); + if let Some(b) = menu { + assert!(b.x1 <= f64::from(width), "{width}: {b:?}"); + assert!(find(&nodes, "Horizontal Align Left").is_some(), "{width}: shown without the Align buttons"); + let x = nodes.iter().find(|(_, n)| n.label() == Some("X:") || n.value() == Some("X:")).and_then(|(_, n)| n.bounds()); + assert!(x.is_some_and(|x| x.x1 <= b.x0), "{width}: shown without the X field ahead of it: {x:?}"); + } + seen = shown.is_some(); + } + assert!(seen, "the widest bar has room for it"); + // With the Transform group off they still show at the end of a wide bar, after the Align + // buttons. + app.run("window.control.options", json!({"group": "transform", "visible": false})).unwrap(); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + let (button, align) = (find(&nodes, "Select Similar Objects"), find(&nodes, "Horizontal Align Left")); + let (Some(b), Some(a)) = (button.and_then(|n| n.bounds()), align.and_then(|n| n.bounds())) else { + panic!("Transform off: the button and the Align buttons show") + }; + assert!(a.x1 <= b.x0, "after the Align buttons: {a:?} {b:?}"); +} + /// At any width the Control bar shows the inline X, Y, W and H fields whole inside its right margin, /// or leaves all four out and keeps the Transform link; a wider bar never leaves them out once a /// narrower one showed them. The Align buttons, and for two objects the Distribute buttons, are diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fb3080c8c2..0605145651 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6138,6 +6138,8 @@ axis Y Axis Y ос Create New Set Създаване на нов набор Stop Global Edit Край на глобалното редактиране Global Edit Options Опции за глобално редактиране + Select Similar Objects Избор на подобни обекти + Select Similar Options Опции за избор на подобни Leave Out of Global Edit Изключване от глобалното редактиране @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобалното редактиране работи с пътища, съставни пътища, екземпляри на символи и групи от тях Match Съвпадение diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 118609f801..06f7d13084 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6180,6 +6180,8 @@ axis Y Axis Y osa Create New Set Napravi novi skup Stop Global Edit Zaustavi globalno uređivanje Global Edit Options Opcije globalnog uređivanja + Select Similar Objects Odaberi slične objekte + Select Similar Options Opcije odabira sličnih Leave Out of Global Edit Isključi iz globalnog uređivanja Match Podudaranje On Artboards Na radnim pločama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ab50e14a58..8e43b2b181 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1853,6 +1853,8 @@ digits Malayalam Malaiàlam Global Adjust Ajust global Global Brush Dimensions Dimensions globals del pinzell Global Edit Options Opcions globals d’edició + Select Similar Objects Selecciona objectes similars + Select Similar Options Opcions de selecció de similars Leave Out of Global Edit Exclou de l’edició global Global Process Color Color de procés global Global Process Color, CMYK Color de procés global, CMYK diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3b9c300980..dc099defb7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6684,6 +6684,8 @@ axis Y Axis osa Y Create New Set Vytvořit novou sadu Stop Global Edit Ukončit globální úpravy Global Edit Options Možnosti globálních úprav + Select Similar Objects Vybrat podobné objekty + Select Similar Options Možnosti výběru podobných Leave Out of Global Edit Vyřadit z globálních úprav Match Shoda On Artboards Na pracovních plochách diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..616e6a2e3f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6764,6 +6764,8 @@ axis Y Axis Y-akse Create New Set Opret nyt sæt Stop Global Edit Stop global redigering Global Edit Options Indstillinger for global redigering + Select Similar Objects Vælg lignende objekter + Select Similar Options Indstillinger for valg af lignende Leave Out of Global Edit Udelad fra global redigering @msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering virker på stier, sammensatte stier, symbolforekomster og grupper af dem Match Match diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ddc01a8016..373b47b25b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6276,6 +6276,8 @@ axis Y Axis Y-Achse Create New Set Neuen Satz erstellen Stop Global Edit Globale Bearbeitung beenden Global Edit Options Optionen für globale Bearbeitung + Select Similar Objects Ähnliche Objekte auswählen + Select Similar Options Optionen für ähnliche Objekte Leave Out of Global Edit Von globaler Bearbeitung ausschließen Match Übereinstimmung On Artboards Auf Zeichenflächen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a89d3c72e4..7c476955bd 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6637,6 +6637,8 @@ axis Y Axis Άξονας Y Create New Set Δημιουργία νέου συνόλου Stop Global Edit Τερματισμός καθολικής επεξεργασίας Global Edit Options Επιλογές καθολικής επεξεργασίας + Select Similar Objects Επιλογή παρόμοιων αντικειμένων + Select Similar Options Επιλογές επιλογής παρόμοιων Leave Out of Global Edit Εξαίρεση από την καθολική επεξεργασία Match Αντιστοίχιση On Artboards Σε πίνακες σχεδίασης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4a912f8005..2de3b42bf1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6628,6 +6628,8 @@ axis Y Axis Eje Y Create New Set Crear nuevo conjunto Stop Global Edit Detener edición global Global Edit Options Opciones de edición global + Select Similar Objects Seleccionar objetos similares + Select Similar Options Opciones de selección de similares Leave Out of Global Edit Excluir de la edición global Match Coincidir On Artboards En mesas de trabajo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 06499d13ea..4c60f1aee1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6715,6 +6715,8 @@ axis Y Axis Y-akseli Create New Set Luo uusi sarja Stop Global Edit Lopeta yleismuokkaus Global Edit Options Yleismuokkauksen asetukset + Select Similar Objects Valitse samankaltaiset objektit + Select Similar Options Samankaltaisten valinnan asetukset Leave Out of Global Edit Jätä pois yleismuokkauksesta Match Vastaavuus On Artboards Piirtoalustoilla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 90882cf105..687baadeef 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6679,6 +6679,8 @@ axis Y Axis Axe Y Create New Set Créer un jeu Stop Global Edit Arrêter la modification globale Global Edit Options Options de modification globale + Select Similar Objects Sélectionner les objets similaires + Select Similar Options Options de sélection des objets similaires Leave Out of Global Edit Exclure de la modification globale Match Correspondance On Artboards Sur les plans de travail diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0e9ed1997e..9998610049 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1508,6 +1508,8 @@ Global ગ્લોબલ Global Brush Dimensions ગ્લોબલ બ્રશ પરિમાણો Global Edit Options ગ્લોબલ એડિટ વિકલ્પો + Select Similar Objects સમાન ઑબ્જેક્ટ પસંદ કરો + Select Similar Options સમાન પસંદગીના વિકલ્પો Global Process Color ગ્લોબલ પ્રોસેસ રંગ Glowing Edges… ગ્લોઇંગ એજિસ… Glyph Bounds ગ્લિફ બાઉન્ડ્સ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 671052e82b..d053ca01af 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2062,6 +2062,8 @@ antiAlias Sharp शार्प Global Adjust वैश्विक समायोजन Global Brush Dimensions ग्लोबल ब्रश आयाम Global Edit Options ग्लोबल एडिट ऑप्शन्स + Select Similar Objects समान ऑब्जेक्ट चुनें + Select Similar Options समान चयन विकल्प Global Process Color ग्लोबल प्रोसेस कलर Global Process Color, CMYK ग्लोबल प्रोसेस कलर, CMYK Glow Amount ग्लो मात्रा diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a218a2ce15..e540f5a3fb 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6667,6 +6667,8 @@ axis Y Axis Y tengely Create New Set Új készlet létrehozása Stop Global Edit Globális szerkesztés befejezése Global Edit Options Globális szerkesztés beállításai + Select Similar Objects Hasonló objektumok kijelölése + Select Similar Options Hasonlók kijelölésének beállításai Leave Out of Global Edit Kizárás a globális szerkesztésből Match Egyezés On Artboards Rajztáblákon diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index fdf06cc9ee..040f2bfd5a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6154,6 +6154,8 @@ axis Y Axis Sumbu Y Create New Set Buat set baru Stop Global Edit Hentikan edit global Global Edit Options Opsi edit global + Select Similar Objects Pilih objek serupa + Select Similar Options Opsi pilih serupa Leave Out of Global Edit Keluarkan dari edit global @msg Global Edit works on paths, compound paths, symbol instances and groups of them Edit global berfungsi pada jalur, jalur gabungan, instans simbol, dan grupnya Match Cocokkan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2b5a6bf3da..99e24d180d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6310,6 +6310,8 @@ axis Y Axis Asse Y Create New Set Crea nuovo set Stop Global Edit Interrompi modifica globale Global Edit Options Opzioni modifica globale + Select Similar Objects Seleziona oggetti simili + Select Similar Options Opzioni selezione oggetti simili Leave Out of Global Edit Escludi dalla modifica globale Match Corrispondenza On Artboards Sulle tavole da disegno diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 87ec6c8b05..952d811ccb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8181,6 +8181,8 @@ axis Y Axis Y 軸 Create New Set 新規セットを作成 Stop Global Edit グローバル編集を終了 Global Edit Options グローバル編集オプション + Select Similar Objects 類似オブジェクトを選択 + Select Similar Options 類似オブジェクトの選択オプション Leave Out of Global Edit グローバル編集から除外 Match 一致 On Artboards アートボード上 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8c42eafaf1..d5ea058337 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6636,6 +6636,8 @@ axis Y Axis Y ღერძი Create New Set ახალი ნაკრების შექმნა Stop Global Edit გლობალური რედაქტირების დასრულება Global Edit Options გლობალური რედაქტირების პარამეტრები + Select Similar Objects მსგავსი ობიექტების მონიშვნა + Select Similar Options მსგავსის მონიშვნის პარამეტრები Leave Out of Global Edit გლობალური რედაქტირებიდან გამორიცხვა Match დამთხვევა On Artboards სამუშაო დაფებზე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4fd8001ea7..6dbd010e41 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6271,6 +6271,8 @@ axis Y Axis Y축 Create New Set 새 세트 만들기 Stop Global Edit 전체 편집 중지 Global Edit Options 전체 편집 옵션 + Select Similar Objects 유사한 개체 선택 + Select Similar Options 유사 개체 선택 옵션 Leave Out of Global Edit 전체 편집에서 제외 Match 일치 On Artboards 아트보드에서 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 31872f060e..469712b7b4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8598,6 +8598,8 @@ axis Y Axis Y-as Create New Set Nieuwe set maken Stop Global Edit Globale bewerking stoppen Global Edit Options Opties voor globale bewerking + Select Similar Objects Vergelijkbare objecten selecteren + Select Similar Options Opties voor vergelijkbare objecten selecteren Leave Out of Global Edit Uitsluiten van globale bewerking @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale bewerking werkt op paden, samengestelde paden, symboolinstanties en groepen daarvan Match Overeenkomst diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 77b1425e5f..3b7c804fbe 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6539,6 +6539,8 @@ axis Y Axis Oś Y Create New Set Utwórz nowy zestaw Stop Global Edit Zakończ edycję globalną Global Edit Options Opcje edycji globalnej + Select Similar Objects Zaznacz podobne obiekty + Select Similar Options Opcje zaznaczania podobnych Leave Out of Global Edit Wyklucz z edycji globalnej Match Dopasowanie On Artboards Na obszarach kompozycji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index caed79af2a..5e0c001d25 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6599,6 +6599,8 @@ axis Y Axis Eixo Y Create New Set Criar Novo Conjunto Stop Global Edit Parar Edição Global Global Edit Options Opções de Edição Global + Select Similar Objects Selecionar Objetos Semelhantes + Select Similar Options Opções de Seleção de Semelhantes Leave Out of Global Edit Deixar Fora da Edição Global Match Corresponder On Artboards Nas Mesas de Trabalho diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 206b209ee2..9d49ebd6a7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6296,6 +6296,8 @@ axis Y Axis Ось Y Create New Set Создать новый набор Stop Global Edit Завершить глобальное редактирование Global Edit Options Параметры глобального редактирования + Select Similar Objects Выделить похожие объекты + Select Similar Options Параметры выделения похожих Leave Out of Global Edit Исключить из глобального редактирования Match Совпадение On Artboards На монтажных областях diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 82e63d1667..92ce3e0cef 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6664,6 +6664,8 @@ axis Y Axis Y-axel Create New Set Skapa ny uppsättning Stop Global Edit Avsluta global redigering Global Edit Options Alternativ för global redigering + Select Similar Objects Markera liknande objekt + Select Similar Options Alternativ för att markera liknande Leave Out of Global Edit Uteslut från global redigering Match Matcha On Artboards På ritytor diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 237694bff5..51df63e4f9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8561,6 +8561,8 @@ axis Y Axis Y ekseni Create New Set Yeni Set Oluştur Stop Global Edit Genel Düzenlemeyi Durdur Global Edit Options Genel Düzenleme Seçenekleri + Select Similar Objects Benzer Nesneleri Seç + Select Similar Options Benzer Seçimi Seçenekleri Leave Out of Global Edit Genel Düzenlemenin Dışında Bırak Match Eşleştir On Artboards Çalışma Yüzeylerinde diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a74a03529d..45e65cd644 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6290,6 +6290,8 @@ axis Y Axis Вісь Y Create New Set Створити новий набір Stop Global Edit Завершити глобальне редагування Global Edit Options Параметри глобального редагування + Select Similar Objects Виділити схожі об’єкти + Select Similar Options Параметри виділення схожих Leave Out of Global Edit Виключити з глобального редагування Match Збіг On Artboards На монтажних областях diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 16c613874c..db04b6ad0a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6292,6 +6292,8 @@ axis Y Axis Trục Y Create New Set Tạo bộ mới Stop Global Edit Dừng chỉnh sửa toàn cục Global Edit Options Tùy chọn chỉnh sửa toàn cục + Select Similar Objects Chọn các đối tượng tương tự + Select Similar Options Tùy chọn chọn đối tượng tương tự Leave Out of Global Edit Loại khỏi chỉnh sửa toàn cục Match Khớp On Artboards Trên các bảng vẽ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b83bee650f..65cb744c57 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6523,6 +6523,8 @@ axis Y Axis Y 轴 Create New Set 创建新组 Stop Global Edit 停止全局编辑 Global Edit Options 全局编辑选项 + Select Similar Objects 选择相似对象 + Select Similar Options 选择相似对象选项 Leave Out of Global Edit 从全局编辑中排除 Match 匹配 On Artboards 在画板上 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4637ecb811..14d1972d62 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6330,6 +6330,8 @@ axis Y Axis Y 軸 Create New Set 建立新組 Stop Global Edit 停止整體編輯 Global Edit Options 整體編輯選項 + Select Similar Objects 選取相似物件 + Select Similar Options 選取相似物件選項 Leave Out of Global Edit 從整體編輯中排除 Match 符合 On Artboards 在工作區域上 diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index f570beaeca..25c05ce3fc 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -792,9 +792,12 @@ fn control_bar_nodes(ctx: &egui::Context, app: &mut VectorcraftApp, width: f32, nodes } -/// The control named `name` (a button's or link's label, a label's text). +/// The control named `name`: a button's or link's label, else a label's text. A link's text run +/// carries the same text as its value, and the update lists the nodes in no set order, so the +/// label is looked for first. fn control_bar_node(nodes: &Nodes, name: &str) -> Option { - nodes.iter().find(|(_, n)| n.label() == Some(name) || n.value() == Some(name)).map(|(_, n)| n.clone()) + let labeled = nodes.iter().find(|(_, n)| n.label() == Some(name)); + labeled.or_else(|| nodes.iter().find(|(_, n)| n.value() == Some(name))).map(|(_, n)| n.clone()) } /// Where the control named `name` ends, if it shows. diff --git a/docs/mcp.md b/docs/mcp.md index 99b0bfef38..dee1116bfa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2776,6 +2776,22 @@ template layer, on a locked artboard while nothing is isolated, or outside the i such as a symbol instance just placed, is not passed over for being on a locked artboard while it stays selected. When the selection holds no other object, they return the error "nothing selected". +`select.similar {by?}` is the Control bar's Select Similar Objects button and the Select Similar Options menu beside it +([help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=165)). It selects the +objects like the first selected object by `by` and returns `{count, by}`. `by` is `fillColor`, `fillAndStroke`, +`strokeColor`, `strokeWeight`, `opacity`, `blendingMode`, `appearance`, `graphicStyle`, `shapeType` or +`symbolInstance`, which runs the `select.same.*` command of that name, or `all`, which selects the objects whose fill +and stroke colors, stroke weight, opacity and blending mode all match (tints, compound paths and Live Paint faces as +`select.same.fillColor`); Select › Reselect repeats `all` as `all`. The menu's items, their order and what `all` +compares are VectorCraft's own. A `by` given is kept for the session once the selection is made, and the menu checks +it; without `by` the command uses the kept one, `all` until one is given. Any other `by` is an error that keeps the +selection and the kept attribute, and an error of the `select.same.*` command it runs (for example "the selection has +no graphic style") keeps the kept attribute too. It needs a selection and records no undo step; the journal records the +attribute used, so a recorded action repeats it, and a script run that fails puts the kept attribute back. The button +and the menu show while something is selected and the +Object Options group is on, at the right end of the bar after the X, Y, W and H fields. They take only the room the +other controls leave, so the bar leaves them out, together, before any other control. + `select.object.allOnSameLayers` selects the objects on the layers and sublayers of the selected objects that can be selected. A selected object that is hidden or locked, inside a hidden or locked group or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group adds no layer. When the selection holds no @@ -6698,7 +6714,8 @@ where it is. `window.control.options {group, visible?}` (desktop app) turns a group of the Control bar's options on (`visible: true`), off (`false`) or toggles it (omitted), and returns `{group, visible}`. The groups are `snapping` (the Snapping menu), `anchors` (Convert and Anchors), `toolOptions` (the active tool's options), `objectOptions` (Isolate Selected -Object or Exit Isolation Mode, the envelope controls and the symbol instance controls), `imageOptions` (a selected +Object or Exit Isolation Mode, the envelope controls, the symbol instance controls and Select Similar Objects), +`imageOptions` (a selected image's or Image Trace object's controls), `fillStroke` (the fill and stroke chips, Stroke and its weight and width profile), `opacity`, `graphicStyle` (Style, Recolor Artwork and Global Edit Options), `character`, `paragraph`, `verticalAlignment` (area type's vertical alignment), `alignDistribute`, `transform` (the Transform link and the X/Y/W/H diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c6972468cc..9b66eaafec 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -648,6 +648,7 @@ since 2026-10-01. - **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit leaves out groups holding type or images:** Select › Start Global Edit on a group that holds type or an image, at any depth, refuses to start, and such a group is not taken as a match, as Global Edit does not take images or text ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test for a group holding type: `global_edit_needs_one_supported_object` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. +- **Select Similar Objects in the Control bar:** with something selected, the Control bar's Select Similar Objects button selects the objects like the first selected one, and the Select Similar Options menu beside it chooses what that is based on: All, Fill Color, Fill & Stroke, Stroke Color, Stroke Weight, Opacity, Blending Mode, Appearance, Graphic Style, Shape or Symbol Instance (`select.similar {by}`). The choice is kept for the session and checked in the menu ([archived help guide, select objects with the same attributes](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=165)). The list and what All compares are VectorCraft's own. Regression tests: `the_control_bar_selects_similar_objects` in `crates/ui-egui/src/chrome/tests.rs`, `select_similar_selects_by_the_kept_attribute` in `crates/engine/src/tests/menucmds.rs`. - **Global Edit's enabled check on large paths:** the check that decides whether Select › Start Global Edit can run on the selected path, compound path or symbol instance (which the Control bar makes every frame) measures the box of its anchors and handles instead of building and normalizing a copy of every anchor, with the same answer. On a 200,000-anchor path the check takes 0.7 ms instead of 2.2 to 3.0 ms. Regression tests: `support_*` in `crates/engine/src/cmd/globaledit.rs`. - **Start Global Edit is offered only for a group it can start on:** with a group selected, Select › Start Global Edit is disabled, and the Properties panel's Quick Actions and the Control bar do not offer it or its options, when the group holds type, an image or nothing, at any depth; the check walks the group's objects the same way, stopping at the first one Global Edit does not take. This is VectorCraft's own rule. Regression test: `start_global_edit_is_offered_only_for_a_group_of_supported_objects` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit takes rotated copies:** Select › Start Global Edit on an object or group also takes its rotated copies, with the highlights before the start and the options' Results count, and an edit reaches each copy turned by its angle, as copies of a group rotated around a point are edited at once ([Design a modern geometric logo](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html)). Under VectorCraft's own rules, a copy's angle is the one that lays the selected object's anchors and handles on the copy's in order, each within a millionth of the larger side of the copy's box; a reflected copy is not taken; and with Size, a rotated copy has the same size when it is the object rotated without scaling. Regression tests: `start_global_edit_takes_rotated_copies_*`, `a_rotated_copy_leads_*`, `size_takes_a_rotated_copy_*`, `a_square_whose_anchors_were_turned_*`, `rotated_groups_are_like_the_group_*` and `a_rotated_symbol_instance_*` in `crates/engine/src/tests/globaledit.rs`. From f198a45b3172807a5f2c395273d69d631d6d9393 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:32:16 -0800 Subject: [PATCH 08/11] Control bar: Select Similar Objects takes no room for groups that are off With the Transform group off, the bar no longer reserves room for its link and X/Y/W/H fields before showing Select Similar Objects. Every control ahead that is left out for room is now noted, and the button shows only when nothing ahead was left out. The test sweeps bar widths with Transform off. --- crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/chrome/control_bar.rs | 135 +++++++++++++++-------- crates/ui-egui/src/chrome/tests.rs | 23 ++++ crates/ui-egui/src/panels/paragraph.rs | 5 +- 4 files changed, 114 insertions(+), 51 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index fc0234885b..a6b7b11714 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -18,13 +18,13 @@ mod hints; mod status_bar; mod tabs; -pub(crate) use control_bar::group_separator; pub use control_bar::{ AnchorControls, CONTROL_BAR_EDGES, CONTROL_BAR_GROUPS, anchor_buttons, anchor_controls, control_bar, control_bar_moving, control_bar_placement, read_hidden_groups, }; #[cfg(test)] use control_bar::{CONTROL_BAR_FLOAT_AT, ISOLATION_BUTTON}; +pub(crate) use control_bar::{group_separator, left_out}; #[cfg(test)] use hints::hint_segments; pub use hints::{hint_bar, hint_strings}; diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 8b6c2400e6..12821d70a8 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -61,6 +61,7 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon for (label, buttons) in groups.into_iter().take(shown) { let text = egui::RichText::new(label).size(12.0).color(t.text); if in_row && ui.available_width() < row_width(ui, &[widgets::text_width(ui, text.clone())]) + buttons_width(ui, buttons.len()) { + left_out(ui); break; } ui.horizontal(|ui| { @@ -164,9 +165,13 @@ const GLOBAL_EDIT_OPTIONS_WIDTH: f32 = 24.0; /// It opens the Properties panel's Global Edit Options, which set the same session options, and is /// off and closed while Global Edit is on, as that panel's dropdown is. It sits after Recolor /// Artwork, ahead of the X/Y/W/H fields that the bar leaves out when it runs short of room, and is -/// left out when the room left, less `reserve` ([`transform_reserve`]), cannot hold it. +/// left out when the room left, less `reserve` ([`transform_reserve`]), cannot hold it ([`left_out`]). fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { - if !crate::menus::enabled(app, "select.globalEdit") || ui.available_width() < row_width(ui, &[GLOBAL_EDIT_OPTIONS_WIDTH]) + reserve { + if !crate::menus::enabled(app, "select.globalEdit") { + return; + } + if ui.available_width() < row_width(ui, &[GLOBAL_EDIT_OPTIONS_WIDTH]) + reserve { + left_out(ui); return; } let on = app.session.active().is_some_and(|d| d.global_edit.is_some()); @@ -287,6 +292,24 @@ fn boundary(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { ui.data_mut(|d| d.insert_temp(key, b)); } +/// The key of the pass in which a control of the row `ui` was last left out for room. +fn left_out_key(ui: &Ui) -> egui::Id { + ui.unique_id().with("cb-left-out") +} + +/// Notes that a control of the Control bar's row `ui` was left out in this pass for want of room, +/// so the controls the bar leaves out first stay out too ([`any_left_out`]). +pub(crate) fn left_out(ui: &mut Ui) { + let (key, pass) = (left_out_key(ui), ui.ctx().cumulative_pass_nr()); + ui.data_mut(|d| d.insert_temp(key, pass)); +} + +/// Whether a control of the row `ui` was left out in this pass for want of room ([`left_out`]). +fn any_left_out(ui: &Ui) -> bool { + let (key, pass) = (left_out_key(ui), ui.ctx().cumulative_pass_nr()); + ui.data(|d| d.get_temp::(key)) == Some(pass) +} + /// The separator that ends a group of the Control bar's controls, drawn as `ui.separator()` draws /// one, and left out when no control follows it ([`boundary`]) or the row has no room left for it. pub(crate) fn group_separator(ui: &mut Ui) { @@ -348,23 +371,26 @@ fn transform_reserve(app: &VectorcraftApp, ui: &Ui, selected: bool) -> f32 { /// Align To menu and, for two or more objects, the Distribute buttons (a single object keeps the bar /// as it was); each shows only while the end of the bar keeps its room. Groups the panel menu has /// off are left out, and take no room. Without `room` (the Character group had none), all of these -/// groups are left out, so the bar trims them from its right end before the Character group. Also -/// returns whether the Character group and the Align group had their room: the Align buttons, the -/// Align To menu and the Distribute buttons the selection calls for all showed, or the group is -/// off. -fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize, room: bool) -> (bool, bool) { +/// groups are left out, so the bar trims them from its right end before the Character group. The +/// Character group without its room, and a control left out for room here, are noted with +/// [`left_out`]. +fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize, room: bool) -> bool { + if !room { + left_out(ui); + } let nothing = objects == 0; let end = end_width(app, ui, nothing); if room && group_on(app, "paragraph") && crate::panels::paragraph::control_bar(app, ui, BUTTON, |ui| group_end_width(ui) + end) { group_end(ui); } - if room - && group_on(app, "verticalAlignment") - && crate::panels::properties::vertical_align::shown(app).is_some() - && ui.available_width() >= buttons_width(ui, 4) + group_end_width(ui) + end - && crate::panels::properties::vertical_align::buttons(app, ui, BUTTON) - { - group_end(ui); + if room && group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some() { + if ui.available_width() >= buttons_width(ui, 4) + group_end_width(ui) + end { + if crate::panels::properties::vertical_align::buttons(app, ui, BUTTON) { + group_end(ui); + } + } else { + left_out(ui); + } } if nothing { // Each button shows only while the bar has room left for it, so Preferences can show @@ -377,30 +403,34 @@ fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize app.run("edit.preferences", json!({})).ok(); } } - return (false, false); + return false; } let transform = group_on(app, "transform"); let end = if transform { separator_width(ui) + end } else { 0.0 }; - let align_on = group_on(app, "alignDistribute"); - // Whether the whole group showed: the Align buttons, the Align To menu and the Distribute - // buttons the selection calls for. - let mut whole = !align_on; - if room && align_on && ui.available_width() >= buttons_width(ui, 7) + end { + if room && group_on(app, "alignDistribute") { + if ui.available_width() < buttons_width(ui, 7) + end { + left_out(ui); + return transform; + } crate::panels::align::align_buttons(app, ui, BUTTON); if ui.available_width() >= crate::panels::align::align_to_menu_width(BUTTON) + ui.spacing().item_spacing.x + end { crate::panels::align::align_to_menu(app, ui, BUTTON); - whole = objects < 2; - if objects > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) + end { - ui.add_space(GROUP_GAP); - crate::panels::align::distribute_buttons(app, ui, BUTTON); - whole = true; + if objects > 1 { + if ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) + end { + ui.add_space(GROUP_GAP); + crate::panels::align::distribute_buttons(app, ui, BUTTON); + } else { + left_out(ui); + } } + } else { + left_out(ui); } if transform { boundary(ui, separator); } } - (transform, room && whole) + transform } /// Draws the Control bar's Align group after the artboard controls, with the Artboard tool in use: @@ -603,9 +633,10 @@ fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { /// and the width profile, and the separator after them while a control follows ([`group_separator`]). /// Short of room, the bar leaves out the width profile first, then the Stroke link with the weight, /// then the two chips; each shows only while the bar has room for all of it and `reserve` after it -/// ([`transform_reserve`]). +/// ([`transform_reserve`]), and a control left out is noted with [`left_out`]. fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { if ui.available_width() < row_width(ui, &[CHIP_WIDTH, CHIP_WIDTH]) + reserve { + left_out(ui); return; } let shown_stroke = crate::panels::current_stroke(app); @@ -619,11 +650,13 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { if ui.available_width() >= row_width(ui, &[link, WEIGHT_FIELD_WIDTH]) + reserve { stroke_panel::link(app, ui, tl!("Stroke:")); stroke_panel::weight_field(app, ui, "cb-stroke", weight, WEIGHT_FIELD_WIDTH); - if ui.available_width() >= row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve - && let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) - { + if ui.available_width() < row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve { + left_out(ui); + } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) { app.run("stroke.set", json!({"profile": id})).ok(); } + } else { + left_out(ui); } group_end(ui); } @@ -634,7 +667,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { /// the bar leaves out Global Edit Options first, then Recolor Artwork, then the Style link with its /// chip. The Opacity link with its field and the Style link with its chip each show only while the /// bar has room for all of it and `reserve` after it ([`transform_reserve`]), so the narrower Style -/// part can show without the Opacity part. +/// part can show without the Opacity part. A control left out is noted with [`left_out`]. fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity: f32, selected: bool, reserve: f32) { let (opacity_on, style_on) = (group_on(app, "opacity"), group_on(app, "graphicStyle") && selected); let mut drawn = false; @@ -651,10 +684,15 @@ fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity: app.run("transparency.set", json!({"opacity": o.clamp(0.0, 100.0)})).ok(); } drawn = true; + } else { + left_out(ui); } } let text = egui::RichText::new(tl!("Style:")).size(12.0).color(t.text).underline(); - if style_on && ui.available_width() >= GROUP_GAP + row_width(ui, &[widgets::text_width(ui, text.clone()), CHIP_WIDTH]) + reserve { + let style_room = GROUP_GAP + row_width(ui, &[widgets::text_width(ui, text.clone()), CHIP_WIDTH]) + reserve; + if style_on && ui.available_width() < style_room { + left_out(ui); + } else if style_on { // Style picker: the selection's graphic style; its menu applies another. ui.add_space(GROUP_GAP); if ui.link(text).clicked() { @@ -665,10 +703,9 @@ fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity: egui::Popup::menu(&resp).show(|ui| crate::panels::graphic_styles::picker(app, ui)); // Recolor Artwork, when the selection has colours to recolour. let colored = app.session.active().is_some_and(|st| crate::canvas::has_colors(&st.doc, &st.selection.objects)); - if colored - && ui.available_width() >= buttons_width(ui, 1) + reserve - && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, BUTTON).clicked() - { + if colored && ui.available_width() < buttons_width(ui, 1) + reserve { + left_out(ui); + } else if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, BUTTON).clicked() { crate::menus::invoke(app, "ui.recolorDialog", json!({})); } global_edit_options(app, ui, reserve); @@ -707,13 +744,12 @@ fn similar_label(by: &str) -> &'static str { /// then on, and the kept one is checked. Both are off while `select.similar` cannot run. They show /// together at the right end of the bar, after a separator, while something is selected and the /// panel menu has Object Options on, and only in the room every control ahead of them left -/// ([`contents`]): the bar leaves them out before any other control, and while `ahead_shown` is -/// false (a control ahead of them was left out for room). They show only while the room left is -/// also at least `keep`. -fn trailing_select_similar(app: &mut VectorcraftApp, ui: &mut Ui, ahead_shown: bool, keep: f32) { +/// ([`contents`]): the bar leaves them out before any other control, and while a control ahead of +/// them was left out for room ([`any_left_out`]). Groups the panel menu has off take no room. +fn trailing_select_similar(app: &mut VectorcraftApp, ui: &mut Ui) { let selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); let width = separator_width(ui) + row_width(ui, &[BUTTON, SELECT_SIMILAR_MENU_WIDTH]); - if !ahead_shown || !selected || !group_on(app, "objectOptions") || ui.available_width() < width.max(keep) { + if any_left_out(ui) || !selected || !group_on(app, "objectOptions") || ui.available_width() < width { return; } boundary(ui, separator); @@ -881,6 +917,8 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, let label = egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text); if ui.available_width() >= widgets::text_width(ui, label.clone()) { ui.label(label); + } else { + left_out(ui); } // With the Artboard tool in use, the bar shows the active artboard's controls in place // of the object controls. @@ -923,11 +961,9 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, // The Character group shows whole, with the Transform link's room left after it, or not at // all; left out, it leaves out the groups between it and the link too. let room = !group_on(app, "character") || crate::panels::character::control_bar(app, ui, reserve); - let (transform, groups_fit) = groups_before_transform(app, ui, sel.len(), room); - if !transform { - // With the Transform group off, the room its link and X/Y/W/H fields would take stays - // free too, as a group left out ahead takes less than that. - trailing_select_similar(app, ui, groups_fit, crate::panels::transform::link_width(ui) + inline_transform_width(ui, t)); + if !groups_before_transform(app, ui, sel.len(), room) { + // With the Transform group off, its link and X/Y/W/H fields take no room. + trailing_select_similar(app, ui); erase_trailing(ui); return; } @@ -942,8 +978,9 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, crate::panels::transform::link(app, ui); // The bounding box, rotated with rotated objects: its centre and its own sides. let selection_box = app.selection_box(); - let fields_left_out = selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t); - if let Some(b) = selection_box.as_ref().filter(|_| !fields_left_out) { + if selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t) { + left_out(ui); + } else if let Some(b) = selection_box { let c = b.center(); let origin = app.ruler_origin(); let link = crate::panels::transform::proportional(app, ui); @@ -973,7 +1010,7 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, } } // Select Similar Objects comes last: it takes only the room every control ahead of it left. - trailing_select_similar(app, ui, groups_fit && !fields_left_out, 0.0); + trailing_select_similar(app, ui); erase_trailing(ui); }); // Controls that keep their size can still run into the button's room in a narrow window; diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index fc0099a291..dc71c3f3dc 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3633,6 +3633,29 @@ fn the_control_bar_selects_similar_objects() { panic!("Transform off: the button and the Align buttons show") }; assert!(a.x1 <= b.x0, "after the Align buttons: {a:?} {b:?}"); + // With the Transform group off, its link and X/Y/W/H fields take no room: the button and its + // menu show in the narrowest bar that holds them after every control ahead of them, and never + // while a control ahead of them is left out. + let mut first = None; + for width in (600..=2400).step_by(10) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); + let mut nodes = Vec::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(&mut app, ui)); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + let Some(b) = find(&nodes, "Select Similar Options").and_then(|n| n.bounds()) else { + continue; + }; + for name in ["Stroke:", "Opacity:", "Horizontal Align Left", "Recolor Artwork"] { + assert!(find(&nodes, name).is_some(), "{width}: shown without {name} ahead of it"); + } + first.get_or_insert((width, b.x1)); + } + let Some((width, end)) = first else { panic!("Transform off: a wide bar has room for them") }; + let free = f64::from(width) - end; + assert!(free < 120.0, "Transform off: the narrowest bar that shows them, {width} pt wide, leaves {free} pt after them"); } /// At any width the Control bar shows the inline X, Y, W and H fields whole inside its right margin, diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index e594052f60..100540cbd0 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -399,7 +399,7 @@ fn control_bar_link_text(ui: &Ui) -> egui::RichText { /// Character controls: the Paragraph link, which opens the Paragraph panel in a popover under it, /// and the Align left, Align center and Align right buttons, `size` points square as the bar's others. `reserve` gives the room the controls /// after them keep, asked only when type is selected: short of room, the buttons are left out, -/// then the link too. Returns whether the link shows. +/// then the link too, each noted with [`crate::chrome::left_out`]. Returns whether the link shows. pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, size: f32, reserve: impl FnOnce(&Ui) -> f32) -> bool { let Some((_, para)) = text_style(app) else { return false }; let text = control_bar_link_text(ui); @@ -407,6 +407,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, size: f32, rese let room = ui.available_width() - reserve(ui); let link_room = link_width + ui.spacing().item_spacing.x; if room < link_room { + crate::chrome::left_out(ui); return false; } let link = ui.link(text).on_hover_text(tl!("Paragraph options")); @@ -419,6 +420,8 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, size: f32, rese ui.spacing_mut().item_spacing.x = CONTROL_BAR_BUTTON_SPACING; first_alignment_buttons(app, ui, ¶, size, CONTROL_BAR_ALIGNMENTS); ui.spacing_mut().item_spacing.x = spacing; + } else { + crate::chrome::left_out(ui); } true } From d0f6f6cf9ba860fbd43eb2f22051cb1f74f4411f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:49:56 -0800 Subject: [PATCH 09/11] Swatch Conflict: OK pastes nothing after another document became active An immediate paste that asks about swatch conflicts now records the document it asked in. When another document is active at OK, the dialog closes as Cancel does and pastes nothing, as Delete Brush does (dialogs/brush_delete.rs). A deferred paste still goes back to the document it was given in. --- crates/ui-egui/src/dialogs/swatch_conflict.rs | 16 +++++++++++++--- crates/ui-egui/src/tests/clipboard.rs | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index 490646e852..fb8b528b01 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -5,7 +5,8 @@ //! //! Fields: `conflicts` (as `clipboard.conflicts` lists them: `[{name, document, clipboard, spot}]`), //! `index` (the one asked about), `choice` (`merge` or `add`), `applyToAll`, `choices` (the -//! answers so far, by swatch name), `__command` and `__params` (the paste to run). +//! answers so far, by swatch name), `__command` and `__params` (the paste to run), and `__doc` +//! (the uid of the document it asks about). use egui::vec2; use serde_json::{Map, Value, json}; @@ -39,7 +40,7 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option Option &[Value] { d.fields.get("conflicts").and_then(Value::as_array).map_or(&[], Vec::as_slice) } @@ -102,8 +106,14 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// Record the answer; ask about the next conflict, or paste once every one is answered. +/// Record the answer; ask about the next conflict, or paste once every one is answered. When +/// another document has become the active one since an immediate paste asked, it closes as Cancel +/// does and pastes nothing (a deferred paste goes back to its own document). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + if d.fields.get("__deferredPaste").is_none() && d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } let choice = d.str("choice"); if !matches!(choice.as_str(), "merge" | "add") { return Err(format!("choice must be \"merge\" or \"add\", not `{choice}`")); diff --git a/crates/ui-egui/src/tests/clipboard.rs b/crates/ui-egui/src/tests/clipboard.rs index d3b0c25a65..1892df67be 100644 --- a/crates/ui-egui/src/tests/clipboard.rs +++ b/crates/ui-egui/src/tests/clipboard.rs @@ -104,6 +104,22 @@ fn apply_to_all_answers_the_rest_and_cancel_pastes_nothing() { assert!(app.ui.dialog.is_none()); } +#[test] +fn ok_pastes_nothing_after_another_document_became_active() { + let mut app = conflicting(); + run(&mut app, "edit.paste", json!({})); + set(&mut app, "applyToAll", json!(true)); + app.run("document.activate", json!({"index": 0})).unwrap(); + let before = objects(&app); + let undo = app.session.active().unwrap().history.undo.len(); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "it closes as Cancel does"); + assert_eq!(objects(&app), before, "the document made active pastes nothing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert!(objects(&app).is_empty(), "the document it asked in pastes nothing"); +} + #[test] fn paste_goes_to_the_centre_of_the_view() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); From 8767cf847f40260eb7ccb713b6c69b76702d1f8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:48:56 -0800 Subject: [PATCH 10/11] .ai save: check a split top object's sides at every point they have The writer compared the top object's patch with the one the reader makes of the written grid on an even 9 x 9 grid of places. A split side can change how the reader samples a short curve that falls between those places, so a top object could be written live although the reader would map the contents differently there. Coons::places gives the places in u and v where the patch's sides have points. Each side runs straight between them, so the writer now compares the four sides of both patches at every one of those places, within a third of the tolerance; a point inside a patch blends its sides and corners, so the patches then lie within the tolerance everywhere. --- crates/doc/src/live.rs | 28 +++++++++++++++++++ crates/doc/src/live/mesh.rs | 25 +++++++++++++++++ crates/eps/src/ai_editing/tests.rs | 19 +++++++++++++ crates/eps/src/ai_editing/writer/envelopes.rs | 17 +++++++++-- 4 files changed, 86 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 20d0623d4d..6b16973cf1 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -358,6 +358,34 @@ mod tests { assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 25.0).abs() < 1e-6, "{p:?}"); } + #[test] + fn coons_places_are_where_the_patch_bends() { + // A rectangle's sides have 65 evenly spaced points. + let [u, v] = Coons::rect(Rect::new(0.0, 0.0, 100.0, 50.0)).places(); + assert_eq!((u.len(), v.len()), (65, 65)); + assert!(u.iter().enumerate().all(|(i, x)| (x - i as f64 / 64.0).abs() < 1e-12), "{u:?}"); + // A top object with a curved top: between two places next to each other the patch is + // straight, in `u` and in `v`. + let mut path = kurbo::BezPath::new(); + path.move_to((0.0, 0.0)); + path.curve_to((30.0, -20.0), (70.0, 10.0), (100.0, 0.0)); + path.line_to((100.0, 50.0)); + path.line_to((40.0, 50.0)); + path.line_to((0.0, 50.0)); + path.close_path(); + let c = Coons::from_top_object(&PathData::from_bezpath(&path), Some([0, 1, 2, 4])).unwrap(); + let [u, v] = c.places(); + assert!(u.first() == Some(&0.0) && u.last() == Some(&1.0) && u.windows(2).all(|w| w[0] < w[1]), "{u:?}"); + assert!(v.first() == Some(&0.0) && v.last() == Some(&1.0) && v.windows(2).all(|w| w[0] < w[1]), "{v:?}"); + for w in u.windows(2) { + for y in [0.0, 0.3, 1.0] { + let mid = c.eval((w[0] + w[1]) / 2.0, y); + let half = c.eval(w[0], y).midpoint(c.eval(w[1], y)); + assert!(mid.distance(half) < 1e-9, "{w:?} {y}: {mid:?} {half:?}"); + } + } + } + #[test] fn maps_go_on_past_the_content_box() { // A stroke outline reaches past the box: a flat mesh and a rectangle stay the identity there. diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index b6d5bbc88d..ef0a9a908d 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -338,6 +338,31 @@ impl Coons { let end = |side: &[Point]| side.last().copied().unwrap_or_default(); [self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]] } + + /// The places in `u` where the top or bottom side has a point, and the places in `v` where the + /// left or right side has one, rising from 0 to 1. Between two places next to each other, each + /// side runs straight, so [`Self::eval`] changes linearly in `u` and in `v` inside each cell of + /// the grid they make. + pub fn places(&self) -> [Vec; 2] { + let sides = [&self.top, &self.right, &self.bottom, &self.left]; + let at = |which: usize| -> Vec { + match self.knots.as_deref().and_then(|k| k.get(which)) { + Some(knots) => knots.clone(), + None => { + let last = sides[which].len().saturating_sub(1).max(1); + (0..=last).map(|i| i as f64 / last as f64).collect() + } + } + }; + let merge = |a: usize, b: usize| { + let mut v = at(a); + v.extend(at(b)); + v.sort_by(f64::total_cmp); + v.dedup(); + v + }; + [merge(0, 2), merge(1, 3)] + } } /// The most points one side of [`Coons::from_top_object`] holds while it adds points between its diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index be833e258b..4a37a65152 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -10633,6 +10633,25 @@ fn a_top_object_whose_split_side_would_map_another_way_is_written_as_its_art() { assert!(matches!(back.kind, NodeKind::Group { .. }), "{back:#?}"); } +/// A top object whose split side would map the content another way only between the places of an +/// even grid of eighths is written as its art too: a bottom side of a long straight segment, which is +/// split, and a short curve in its last eighth, which the reader then samples at fewer points. +#[test] +fn a_top_object_whose_split_side_differs_between_eighths_is_written_as_its_art() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut path = uneven_top_object(3); + path.truncate(5); + path.curve_to((168.0, 85.0), (164.0, 85.0), (162.0, 90.0)); + path.line_to((30.0, 90.0)); + path.close_path(); + let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&path), corners: None }; + let doc = envelope_doc(kind, 50.0, false, EnvelopeOptions::NEW); + assert!(!program(&doc).contains("AIDeformOptionsKey")); + let (back, warnings, _) = envelope_back(&doc); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + assert!(matches!(back.kind, NodeKind::Group { .. }), "{back:#?}"); +} + /// An envelope with its contents in an opacity mask's art is written as its art there, and an /// envelope in a group stays live. #[test] diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 1e1f16996b..cae8993827 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -328,9 +328,20 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, let read = Coons::from_top_object(&outline, Some(corners))?; let [tl, tr, br, bl] = coons.corners(); let reach = tl.distance(br).max(tr.distance(bl)).max(1.0) * TOP_OBJECT_TOLERANCE; - const STEPS: usize = 8; - let at = |i: usize| i as f64 / STEPS as f64; - let same = (0..=STEPS).all(|j| (0..=STEPS).all(|i| coons.eval(at(i), at(j)).distance(read.eval(at(i), at(j))) <= reach)); + // Each side of both patches runs straight between the places the sides have points + // ([`Coons::places`]), so two matching sides lie furthest apart at one of those places. A point + // inside a patch blends its four sides and corners, so where every side lies within a third of + // `reach` of the other patch's, the patches lie within `reach` of each other everywhere. + let merge = |a: Vec, b: Vec| { + let mut v = [a, b].concat(); + v.sort_by(f64::total_cmp); + v.dedup(); + v + }; + let ([cu, cv], [ru, rv]) = (coons.places(), read.places()); + let (us, vs) = (merge(cu, ru), merge(cv, rv)); + let near = |u: f64, v: f64| coons.eval(u, v).distance(read.eval(u, v)) <= reach / 3.0; + let same = us.iter().all(|&u| near(u, 0.0) && near(u, 1.0)) && vs.iter().all(|&v| near(0.0, v) && near(1.0, v)); same.then_some((rows, cols, pts)) } From 13fa65cf77d4367d1f2d91faae40daf9e52cbdb1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:35:10 -0800 Subject: [PATCH 11/11] SVG import: :not() rules test only the rules indexed for the element set_by_not_rules tested every rule with a :not() against every element, while matched_bytes, which charges the import's selector budget, counts only the rules Index::candidates gives for the element. A style sheet of many class-keyed :not() rules made the pre-pass test rules x elements selectors that the budget never saw. It now loops over the same candidates, which hold every rule that can match the element, so the properties it returns are unchanged. --- crates/svg/src/import/css.rs | 4 +++- crates/svg/src/import/css/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/import/css.rs b/crates/svg/src/import/css.rs index b5f1d80320..7bf440cc73 100644 --- a/crates/svg/src/import/css.rs +++ b/crates/svg/src/import/css.rs @@ -556,10 +556,12 @@ impl Styles { } /// The properties rules with a `:not()` set on `n`, each with its value after the cascade. + /// Only the rules [`Index::candidates`] gives for `n` are tested, as in [`Styles::matched_bytes`]. pub(super) fn set_by_not_rules(&self, n: XNode) -> Vec<(String, String)> { let declared = self.declared(n); let mut out: Vec<(String, String)> = Vec::new(); - for r in self.rules.iter().filter(|r| r.selector.has_not() && r.selector.matches(n)) { + let rules = self.index.candidates(n).into_iter().filter_map(|i| self.rules.get(i)); + for r in rules.filter(|r| r.selector.has_not() && r.selector.matches(n)) { for (k, ..) in r.decls.iter() { if !out.iter().any(|(o, _)| o == k) && let Some(v) = declared.get(k) diff --git a/crates/svg/src/import/css/tests.rs b/crates/svg/src/import/css/tests.rs index 2e78c4da98..5c9e305c27 100644 --- a/crates/svg/src/import/css/tests.rs +++ b/crates/svg/src/import/css/tests.rs @@ -334,6 +334,26 @@ fn not_selectors() { ); } +/// The `:not()` rules filed under classes an element lacks are not tested against it, so +/// [`Styles::set_by_not_rules`] tests no more rules than [`Styles::matched_bytes`] counts. +#[test] +fn not_rules_test_only_the_indexed_candidates() { + const N: usize = 2_000; + let rules: String = (0..N).map(|i| format!(".c{i}:not(.skip) {{ fill: #{i:06x} }}\n")).collect(); + let rects: String = (0..N).map(|i| format!(r#""#)).collect(); + let svg = format!(r#"{rects}"#); + with_doc(&svg, |doc, st| { + let before = selector_tests(); + for i in 0..N { + assert_eq!(st.set_by_not_rules(by_id(doc, &format!("r{i}"))), [("fill".to_string(), format!("#{i:06x}"))]); + } + assert!(st.set_by_not_rules(by_id(doc, "skip")).is_empty()); + // Testing every `:not()` rule against every element would test N × N selectors. + let tests = selector_tests() - before; + assert!(tests <= 3 * N as u64, "finding the :not() rules of {N} elements tested {tests} selectors"); + }); +} + #[test] fn decl_comments_are_stripped() { let d = |k: &str, v: &str| (k.to_string(), v.to_string(), false);