From eb1407217f2e3c72fe66587ba21bbc1f0a019505 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:05:55 +0000 Subject: [PATCH 1/7] feat: Object > Step and Repeat for print-and-cut sheets Grid or fill-sheet layout with per-axis gaps measured on a chosen cut path, optional 180-degree alternation of columns or rows, scriptable as object.stepAndRepeat. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/stepandrepeat.rs | 214 ++++++++++++++++++ crates/engine/src/cmd/stepandrepeat/tests.rs | 132 +++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs/object_dialogs.rs | 6 +- .../src/dialogs/rearrange_artboards.rs | 2 +- crates/ui-egui/src/dialogs/step_repeat.rs | 147 ++++++++++++ crates/ui-egui/src/menus/tree.rs | 1 + 9 files changed, 504 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/stepandrepeat.rs create mode 100644 crates/engine/src/cmd/stepandrepeat/tests.rs create mode 100644 crates/ui-egui/src/dialogs/step_repeat.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 009fc4efd8..17132f9b5a 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -109,6 +109,7 @@ mod textedit; pub use textedit::effective_kerning; mod retype; +mod stepandrepeat; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; @@ -325,6 +326,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(layerpanel::specs()); v.extend(draw2::specs()); v.extend(xform::specs()); + v.extend(stepandrepeat::specs()); v.extend(effectcmd::specs()); v.extend(bevels::specs()); v.extend(wireframe::specs()); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 612cf436b7..b4ffedbd77 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -415,6 +415,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.textWrap.release", "object.transform", "object.transformAgain", + "object.stepAndRepeat", "object.transformEach", "object.ungroup", "object.unlockAll", diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs new file mode 100644 index 0000000000..cc66e04a69 --- /dev/null +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -0,0 +1,214 @@ +//! Object › Step and Repeat: lays out copies of the selection on a grid or fills a sheet, for +//! print-and-cut work (stickers, labels). + +use serde_json::{Value, json}; +use vectorcraft_geom::{Rect, Vec2, rotate_deg}; + +use super::edit::{copy_above, selected_roots}; +use super::object::group_nodes; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or}; +use crate::EngineError; +use vectorcraft_doc::Scaling; + +const CMD: &str = "object.stepAndRepeat"; +const MAX_CELLS: usize = 10_000; +const EPS: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "object.stepAndRepeat", + "Step and Repeat…", + ["Object", "Transform"], + None, + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + has_selection, + step_and_repeat + )] +} + +/// Which cells of the grid are turned by 180°. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Alternate { + None, + Columns, + Rows, +} + +/// One cell of a layout: its place in the grid, the offset of its top-left corner from the first +/// cell's, and whether its copy is turned by 180° about the cell's center. +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct Cell { + pub row: usize, + pub col: usize, + pub dx: f64, + pub dy: f64, + pub turned: bool, +} + +/// How many items of `size` with `gap` between them fit in `room` (all at least 0). +pub fn fit_count(room: f64, size: f64, gap: f64) -> usize { + if !(room.is_finite() && size.is_finite() && gap.is_finite()) || size <= 0.0 || room < size - EPS { + return 0; + } + (((room + gap) / (size + gap)) + EPS).floor().max(0.0) as usize +} + +/// The `(rows, columns)` of items `w` × `h` with gaps `gx`, `gy` that fit a sheet `sw` × `sh` +/// inside `margin` on every side. +pub fn fill_counts(sw: f64, sh: f64, margin: f64, w: f64, h: f64, gx: f64, gy: f64) -> (usize, usize) { + let m = margin.max(0.0); + (fit_count(sh - 2.0 * m, h, gy), fit_count(sw - 2.0 * m, w, gx)) +} + +/// The cells of a `rows` × `cols` grid of items `w` × `h` with gaps `gx` between columns and `gy` +/// between rows, in reading order. +pub fn layout(w: f64, h: f64, gx: f64, gy: f64, rows: usize, cols: usize, alt: Alternate) -> Vec { + (0..rows) + .flat_map(|row| (0..cols).map(move |col| (row, col))) + .map(|(row, col)| Cell { + row, + col, + dx: col as f64 * (w + gx), + dy: row as f64 * (h + gy), + turned: match alt { + Alternate::None => false, + Alternate::Columns => col % 2 == 1, + Alternate::Rows => row % 2 == 1, + }, + }) + .collect() +} + +fn count_param(p: &Value, key: &str) -> Result { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(1), + Some(v) => v + .as_u64() + .filter(|n| (1..=MAX_CELLS as u64).contains(n)) + .map(|n| n as usize) + .ok_or_else(|| bad(CMD, format!("`{key}` must be a whole number from 1 to {MAX_CELLS}"))), + } +} + +fn sheet_param(p: &Value) -> Result> { + let Some(v) = p.get("sheet").filter(|v| !v.is_null()) else { return Ok(None) }; + let n = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(CMD, format!("`sheet.{k}` must be a number"))); + let (x, y, w, h) = (n("x")?, n("y")?, n("width")?, n("height")?); + if w <= 0.0 || h <= 0.0 { + return Err(bad(CMD, "`sheet` needs a positive width and height")); + } + Ok(Some(Rect::new(x, y, x + w, y + h))) +} + +fn step_and_repeat(s: &mut Session, p: &Value) -> Result { + check_numbers(p, &["gap", "gapX", "gapY", "margin"], CMD)?; + check_switches(p, &["patterns"], CMD)?; + let fill = switch_or(p, "fill", false, CMD)?; + let alt = match p.get("rotate").filter(|v| !v.is_null()) { + None => Alternate::None, + Some(v) => match v.as_str() { + Some("none") => Alternate::None, + Some("columns") => Alternate::Columns, + Some("rows") => Alternate::Rows, + _ => return Err(bad(CMD, "`rotate` must be \"none\", \"columns\" or \"rows\"")), + }, + }; + let gap = super::f64_or(p, "gap", 0.0); + let (gx, gy) = (super::f64_or(p, "gapX", gap), super::f64_or(p, "gapY", gap)); + let margin = super::f64_or(p, "margin", 0.0); + if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) { + return Err(bad(CMD, "gaps and margin must be finite")); + } + let (rows, cols) = (count_param(p, "rows")?, count_param(p, "columns")?); + let sheet = sheet_param(p)?; + let mut roots = selected_roots(s)?; + if roots.is_empty() { + return Err(EngineError::Other("nothing selected".into())); + } + let d = &s.doc()?.doc; + let cut = match p.get("cutPath").filter(|v| !v.is_null()) { + None => None, + Some(v) => { + let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutPath` must be an object id"))?); + let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| { + let mut found = false; + n.walk(&mut |c| found |= c.id == id); + found + }); + if !held { + return Err(bad(CMD, "`cutPath` must be part of the selection")); + } + Some(id) + } + }; + let measured = cut.map_or_else(|| roots.clone(), |id| vec![id]); + let b = d.bounds_of(&measured, false); + let b = b.ok_or_else(|| EngineError::Other("the selection has no bounds".into()))?; + let (w, h) = (b.width(), b.height()); + if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(EngineError::Other("the selection has no area to repeat".into())); + } + let anchor = if fill { + let sheet = sheet.or_else(|| { + let c = b.center(); + d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect) + }); + let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?; + Some((sheet, margin.max(0.0))) + } else { + None + }; + let (rows, cols) = match anchor { + Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy), + None => (rows, cols), + }; + if rows == 0 || cols == 0 { + return Err(EngineError::Other("the selection does not fit the sheet".into())); + } + if rows.saturating_mul(cols) > MAX_CELLS { + return Err(bad(CMD, format!("more than {MAX_CELLS} copies"))); + } + let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); + let cells = layout(w, h, gx, gy, rows, cols, alt); + let center = b.center().to_vec2(); + let place = |c: &Cell| -> Affine { + let t = Affine::translate(origin + Vec2::new(c.dx, c.dy)); + if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t } + }; + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; + let ids = s.edit("Step and Repeat", |d, sel| { + if roots.len() > 1 { + roots = vec![group_nodes(d, &roots)?]; + } + let mut copied: Vec = vec![]; + let mut first = Affine::IDENTITY; + for c in &cells { + let m = place(c); + if c.row == 0 && c.col == 0 { + first = m; + continue; + } + let copies = copy_above(d, &roots, |_, _, n| { + n.transform(m, sc); + super::object::keep_pixel_aligned(n, sc); + })?; + copied.extend(copies); + } + if first != Affine::IDENTITY { + for id in &roots { + if let Some(n) = d.node_mut(*id) { + n.transform(first, sc); + super::object::keep_pixel_aligned(n, sc); + } + } + } + let mut out: Vec = roots.clone(); + out.extend(copied); + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "rows": rows, "columns": cols, "count": ids.len() })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs new file mode 100644 index 0000000000..e2addab74b --- /dev/null +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -0,0 +1,132 @@ +use serde_json::json; + +use super::*; + +const A4: (f64, f64) = (210.0, 297.0); + +#[test] +fn fills_a4_with_50_by_30_items_and_3_gap() { + assert_eq!(fill_counts(A4.0, A4.1, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 4)); + assert_eq!(fill_counts(A4.0, A4.1, 5.0, 50.0, 30.0, 3.0, 3.0), (8, 3)); + assert_eq!(fill_counts(40.0, 297.0, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 0)); +} + +#[test] +fn layout_places_cells_at_the_pitch_and_alternates_rotation() { + let c = layout(50.0, 30.0, 3.0, 3.0, 9, 4, Alternate::Columns); + assert_eq!(c.len(), 36); + let at = |r: usize, k: usize| c[r * 4 + k]; + assert_eq!((at(0, 0).dx, at(0, 0).dy), (0.0, 0.0)); + assert_eq!((at(2, 3).dx, at(2, 3).dy), (159.0, 66.0)); + assert_eq!(c.iter().filter(|c| c.turned).count(), 18); + assert!(at(4, 1).turned && at(4, 3).turned && !at(4, 0).turned && !at(4, 2).turned); + let rows = layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::Rows); + assert_eq!(rows.iter().map(|c| c.turned).collect::>(), [false, false, true, true, false, false]); + assert!(layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::None).iter().all(|c| !c.turned)); +} + +fn setup() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + (s, id) +} + +fn bounds(s: &Session, id: u64) -> (f64, f64, f64, f64) { + let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0, b.x1, b.y1) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() { + let (mut s, _) = setup(); + let (before, steps) = (s.doc().unwrap().doc.clone(), undo_steps(&s)); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gap": 3})).unwrap(); + assert_eq!((r["count"].clone(), r["rows"].clone(), r["columns"].clone()), (json!(6), json!(2), json!(3))); + assert_eq!(undo_steps(&s), steps + 1); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!(bounds(&s, ids[0]), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(bounds(&s, ids[4]), (53.0, 33.0, 103.0, 63.0)); + assert_eq!(bounds(&s, ids[5]), (106.0, 33.0, 156.0, 63.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let d = &s.doc().unwrap().doc; + assert_eq!(d.artboards.len(), before.artboards.len()); + assert!(d.node(NodeId(ids[0])).is_some()); + assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none())); +} + +#[test] +fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() { + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 0})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(9), json!(4), json!(36))); + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5})).unwrap(); + assert_eq!(r["count"], json!(24)); + let first = r["ids"][0].as_u64().unwrap(); + assert_eq!(bounds(&s, first), (5.0, 5.0, 55.0, 35.0)); +} + +#[test] +fn fill_places_every_cell_from_the_original_when_it_starts_away_from_the_margin() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 40, "width": 50, "height": 30})).unwrap(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5, "rotate": "columns"})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(8), json!(3))); + assert_eq!(bounds(&s, ids[0]), (5.0, 5.0, 55.0, 35.0)); + assert_eq!(bounds(&s, ids[1]), (58.0, 5.0, 108.0, 35.0)); + assert_eq!(bounds(&s, ids[2]), (111.0, 5.0, 161.0, 35.0)); + assert_eq!(bounds(&s, ids[3]), (5.0, 38.0, 55.0, 68.0)); +} + +#[test] +fn alternate_columns_turn_by_180_degrees_about_the_cell_center() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let id = s.execute("shape.polygon", &json!({"cx": 25, "cy": 15, "radius": 10, "sides": 3})).unwrap()["id"].as_u64().unwrap(); + let b0 = bounds(&s, id); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gap": 4, "rotate": "columns"})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let (w, b1) = (b0.2 - b0.0, bounds(&s, ids[1])); + assert!((b1.0 - (b0.0 + w + 4.0)).abs() < 1e-6 && ((b1.2 - b1.0) - w).abs() < 1e-6); + assert!((b1.1 - b0.1).abs() < 1e-6 && (b1.3 - b0.3).abs() < 1e-6); + let tri = |s: &Session, id: u64| format!("{:?}", s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind); + assert_ne!(tri(&s, ids[0]), tri(&s, ids[1])); +} + +#[test] +fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() { + let (mut s, art) = setup(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutPath": cut})).unwrap(); + assert_eq!(r["count"], json!(3)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let n = d.node(NodeId(id.as_u64().unwrap())).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. })); + let mut paths = 0; + n.walk(&mut |c| paths += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert_eq!(paths, 2); + } +} + +#[test] +fn rejects_bad_params_and_a_selection_that_does_not_fit() { + let (mut s, _) = setup(); + assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err()); + assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err()); + assert!(s.execute(CMD, &json!({"cutPath": 999999})).is_err()); + assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err()); + let mut e = Session::new(); + e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert!(e.execute(CMD, &json!({})).is_err()); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0e5e2100ba..8046049528 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -146,6 +146,7 @@ pub mod shortcut_import; pub(crate) mod simplify_slider; pub mod slices; pub mod smart_punctuation; +pub mod step_repeat; pub(crate) mod smooth_slider; pub mod spot_colors; pub mod svg_filter; diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index df0c1be3ed..ee26844185 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -4,7 +4,7 @@ use super::path_ops::PathOp; use super::simplify_slider::StripKind; use super::{ blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form, - path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, transform, transform_each, + path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, step_repeat, transform, transform_each, width_point, }; use crate::VectorcraftApp; @@ -16,6 +16,8 @@ pub(crate) struct ObjectDialogs { pub transform: Option, /// The open Transform Each dialog's preview record. pub each: Option, + /// The open Step and Repeat dialog's preview record. + pub step: Option, /// The open Average, Average & Join, Offset Path and Simplify dialogs' preview records. pub path: Vec, /// The open Split Into Grid dialog's record. @@ -47,6 +49,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { sync(app); transform::pump(app, ctx); transform_each::pump(app, ctx); + step_repeat::pump(app, ctx); path_ops::pump(app, ctx); shapes::pump(app, ctx); flare_options::pump(app, ctx); @@ -75,6 +78,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> bool { } match id { "object.transformEach" => transform_each::open(app), + step_repeat::CMD => step_repeat::open(app), "path.average" => path_ops::open(app, PathOp::Average), "path.averageJoin" => path_ops::open(app, PathOp::AverageJoin), "object.path.offsetPath" => path_ops::open(app, PathOp::OffsetPath), diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index 3926501a05..d567dd3363 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -110,7 +110,7 @@ impl RearrangeValues { } /// The length unit a document unit shows as. -fn length_kind(unit: Unit) -> UnitKind { +pub(super) fn length_kind(unit: Unit) -> UnitKind { match unit { Unit::Picas => UnitKind::Picas, Unit::Inches => UnitKind::Inches, diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs new file mode 100644 index 0000000000..442c25da18 --- /dev/null +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -0,0 +1,147 @@ +//! Object → Step and Repeat: copies of the selection on a grid or filling a sheet, with the gaps +//! between the cut paths, every other column or row turned by 180° (`object.stepAndRepeat`), +//! previewed live on the canvas. +//! +//! Fields: `rows`, `columns`, `gapX`, `gapY` (pt), `margin` (pt), `fill` (as many as fit the +//! artboard), `rotate` (`none`, `columns` or `rows`), `cutPath` (an object of the selection, or +//! empty for the selection itself). + +use craft::ui::contract::Bind; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; +use serde_json::{Map, Value, json}; + +use super::host::{HeldOptions, open_held_with}; +use super::preview::LivePreview; +use crate::VectorcraftApp; + +pub(crate) const CMD: &str = "object.stepAndRepeat"; + +pub(crate) struct Open { + pub id: DialogId, + pub preview: LivePreview, +} + +fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { + let mut out = vec![(String::new(), Label::from(tl!("Selection")))]; + let Some(st) = app.session.active() else { return out }; + let single = st.selection.objects.len() == 1; + for id in &st.selection.objects { + let Some(n) = st.doc.node(*id) else { continue }; + out.push((id.0.to_string(), Label::from(n.display_name()))); + if single { + for c in &n.children { + out.push((c.id.0.to_string(), Label::from(c.display_name()))); + } + } + } + out +} + +fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec { + let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths.clone()); + vec![ + Param::new("rows", tl!("Rows"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), + Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), + len("gapX", tl!("Horizontal Gap")), + len("gapY", tl!("Vertical Gap")), + Param::new("cutPath", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))), + Param::new("fill", tl!("Fill the Artboard"), ParamKind::bool(false)), + len("margin", tl!("Margin")).enabled_when("fill", true), + Param::new( + "rotate", + tl!("Rotate 180°"), + ParamKind::choice( + vec![ + ("none".into(), Label::from(tl!("None"))), + ("columns".into(), Label::from(tl!("Every Other Column"))), + ("rows".into(), Label::from(tl!("Every Other Row"))), + ], + Some("none".into()), + ), + ), + ] +} + +pub fn fields() -> DialogFields { + DialogFields::from_pairs([ + ("rows", FieldValue::Int(2)), + ("columns", FieldValue::Int(2)), + ("gapX", FieldValue::Number(12.0)), + ("gapY", FieldValue::Number(12.0)), + ("margin", FieldValue::Number(0.0)), + ("fill", FieldValue::Bool(false)), + ("cutPath", FieldValue::Text(String::new())), + ("rotate", FieldValue::Text("none".into())), + ]) +} + +fn count(f: &DialogFields, key: &str) -> u64 { + f.int(key).or_else(|| f.number(key).map(|n| n as i64)).unwrap_or(1).max(1) as u64 +} + +fn params(f: &DialogFields) -> Value { + let mut p = Map::new(); + p.insert("rows".into(), json!(count(f, "rows"))); + p.insert("columns".into(), json!(count(f, "columns"))); + for k in ["gapX", "gapY", "margin"] { + p.insert(k.into(), json!(f.number(k).unwrap_or(0.0))); + } + p.insert("fill".into(), json!(f.bool("fill").unwrap_or(false))); + p.insert("rotate".into(), json!(f.text("rotate").unwrap_or("none"))); + if let Some(id) = f.text("cutPath").and_then(|t| t.parse::().ok()) { + p.insert("cutPath".into(), json!(id)); + } + Value::Object(p) +} + +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let ctx = app.ui_ctx.clone().ok_or("no window")?; + let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0); + let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); + let cuts = cut_options(app); + let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| { + ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths.clone(), cuts.clone())).previews(true).values(Bind::bound(fields)) + }); + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; + let done = std::mem::take(&mut open.preview).commit(app, CMD, params(&result.fields)); + if done.is_err() { + app.object_dialogs.step = Some(open); + } + done.map(|_| ()) + }; + let cancel: Box = Box::new(|app| { + if let Some(open) = app.object_dialogs.step.take() { + open.preview.cancel(app); + } + }); + let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; + app.object_dialogs.step = Some(Open { id, preview: LivePreview::default() }); + Ok(Value::Null) +} + +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(mut open) = app.object_dialogs.step.take() else { return }; + let shown = app.dialogs().and_then(|host| { + host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields())))) + }); + if let Some((on, p)) = shown { + let _ = open.preview.run(app, on, "Step and Repeat", CMD, &p); + } + app.object_dialogs.step = Some(open); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cut_path_is_sent_only_when_one_is_chosen() { + let mut f = fields(); + assert!(params(&f).get("cutPath").is_none()); + f.set("cutPath", FieldValue::Text("42".into())); + assert_eq!(params(&f)["cutPath"], json!(42)); + } +} diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index b2757b3cbd..c8f67c81d7 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -847,6 +847,7 @@ pub(super) fn transform_items() -> Vec { c("Shear…", "object.shear"), Sep, c("Transform Each…", "object.transformEach"), + c("Step and Repeat…", "object.stepAndRepeat"), Sep, c("Reset Bounding Box", "object.resetBoundingBox"), cp("Rotate Bounding Box…", "object.rotateBoundingBox", json!({"angle": 0})), From 9ddc0aef3aa42c553a61c57755ee2c5cbcb6dc79 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:36:42 +0000 Subject: [PATCH 2/7] fix: step and repeat dialog on the hosted form, cut path choice, sorted review list --- crates/engine/src/cmd/plugin_call/reviewed.rs | 2 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/object_dialogs.rs | 4 ++-- crates/ui-egui/src/dialogs/step_repeat.rs | 17 ++++++++++------- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index b4ffedbd77..cd7d1db8ae 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -405,6 +405,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.stepAndRepeat", "object.tag.add", "object.tag.remove", "object.tag.removeAll", @@ -415,7 +416,6 @@ pub(super) const ALLOWED: &[&str] = &[ "object.textWrap.release", "object.transform", "object.transformAgain", - "object.stepAndRepeat", "object.transformEach", "object.ungroup", "object.unlockAll", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8046049528..eee24e9a47 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -146,9 +146,9 @@ pub mod shortcut_import; pub(crate) mod simplify_slider; pub mod slices; pub mod smart_punctuation; -pub mod step_repeat; pub(crate) mod smooth_slider; pub mod spot_colors; +pub mod step_repeat; pub mod svg_filter; pub(crate) mod svg_options; pub mod swatch_conflict; diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index ee26844185..4ef12e9828 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -4,8 +4,8 @@ use super::path_ops::PathOp; use super::simplify_slider::StripKind; use super::{ blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form, - path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, step_repeat, transform, transform_each, - width_point, + path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, step_repeat, transform, + transform_each, width_point, }; use crate::VectorcraftApp; diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 442c25da18..8828f2e172 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -31,7 +31,7 @@ fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { let Some(n) = st.doc.node(*id) else { continue }; out.push((id.0.to_string(), Label::from(n.display_name()))); if single { - for c in &n.children { + for c in n.children().into_iter().flatten() { out.push((c.id.0.to_string(), Label::from(c.display_name()))); } } @@ -40,7 +40,7 @@ fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { } fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec { - let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths.clone()); + let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths); vec![ Param::new("rows", tl!("Rows"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), @@ -96,13 +96,17 @@ fn params(f: &DialogFields) -> Value { Value::Object(p) } -pub(crate) fn open(app: &mut VectorcraftApp) -> Result { +pub(crate) fn open(app: &mut VectorcraftApp) { + let _ = try_open(app); +} + +fn try_open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0); let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); let cuts = cut_options(app); let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| { - ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths.clone(), cuts.clone())).previews(true).values(Bind::bound(fields)) + ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields)) }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; @@ -124,9 +128,8 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.object_dialogs.step.take() else { return }; - let shown = app.dialogs().and_then(|host| { - host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields())))) - }); + let shown = + app.dialogs().and_then(|host| host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields()))))); if let Some((on, p)) = shown { let _ = open.preview.run(app, on, "Step and Repeat", CMD, &p); } From 8074d6fbc0cad89db688107aaebb94ea42cde631 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:31:58 +0000 Subject: [PATCH 3/7] fix: say which way Step and Repeat rotate turns --- crates/engine/src/cmd/stepandrepeat.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index cc66e04a69..7109d6a766 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] From e5cb0d8dcaec63230fe2d50e528e8600612eea97 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:09:38 +0000 Subject: [PATCH 4/7] fix: name the Step and Repeat cut object param cutId --- crates/engine/src/cmd/stepandrepeat.rs | 8 ++++---- crates/engine/src/cmd/stepandrepeat/tests.rs | 4 ++-- crates/ui-egui/src/dialogs/step_repeat.rs | 16 ++++++++-------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 7109d6a766..b83ebbb28a 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -126,17 +126,17 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("nothing selected".into())); } let d = &s.doc()?.doc; - let cut = match p.get("cutPath").filter(|v| !v.is_null()) { + let cut = match p.get("cutId").filter(|v| !v.is_null()) { None => None, Some(v) => { - let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutPath` must be an object id"))?); + let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutId` must be an object id"))?); let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| { let mut found = false; n.walk(&mut |c| found |= c.id == id); found }); if !held { - return Err(bad(CMD, "`cutPath` must be part of the selection")); + return Err(bad(CMD, "`cutId` must be part of the selection")); } Some(id) } diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index e2addab74b..73948bd664 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -106,7 +106,7 @@ fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() { let (mut s, art) = setup(); let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); - let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutPath": cut})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutId": cut})).unwrap(); assert_eq!(r["count"], json!(3)); let d = &s.doc().unwrap().doc; for id in r["ids"].as_array().unwrap() { @@ -124,7 +124,7 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err()); assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err()); - assert!(s.execute(CMD, &json!({"cutPath": 999999})).is_err()); + assert!(s.execute(CMD, &json!({"cutId": 999999})).is_err()); assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err()); let mut e = Session::new(); e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 8828f2e172..b057d1b320 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -3,7 +3,7 @@ //! previewed live on the canvas. //! //! Fields: `rows`, `columns`, `gapX`, `gapY` (pt), `margin` (pt), `fill` (as many as fit the -//! artboard), `rotate` (`none`, `columns` or `rows`), `cutPath` (an object of the selection, or +//! artboard), `rotate` (`none`, `columns` or `rows`), `cutId` (an object of the selection, or //! empty for the selection itself). use craft::ui::contract::Bind; @@ -46,7 +46,7 @@ fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec { Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), len("gapX", tl!("Horizontal Gap")), len("gapY", tl!("Vertical Gap")), - Param::new("cutPath", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))), + Param::new("cutId", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))), Param::new("fill", tl!("Fill the Artboard"), ParamKind::bool(false)), len("margin", tl!("Margin")).enabled_when("fill", true), Param::new( @@ -72,7 +72,7 @@ pub fn fields() -> DialogFields { ("gapY", FieldValue::Number(12.0)), ("margin", FieldValue::Number(0.0)), ("fill", FieldValue::Bool(false)), - ("cutPath", FieldValue::Text(String::new())), + ("cutId", FieldValue::Text(String::new())), ("rotate", FieldValue::Text("none".into())), ]) } @@ -90,8 +90,8 @@ fn params(f: &DialogFields) -> Value { } p.insert("fill".into(), json!(f.bool("fill").unwrap_or(false))); p.insert("rotate".into(), json!(f.text("rotate").unwrap_or("none"))); - if let Some(id) = f.text("cutPath").and_then(|t| t.parse::().ok()) { - p.insert("cutPath".into(), json!(id)); + if let Some(id) = f.text("cutId").and_then(|t| t.parse::().ok()) { + p.insert("cutId".into(), json!(id)); } Value::Object(p) } @@ -143,8 +143,8 @@ mod tests { #[test] fn cut_path_is_sent_only_when_one_is_chosen() { let mut f = fields(); - assert!(params(&f).get("cutPath").is_none()); - f.set("cutPath", FieldValue::Text("42".into())); - assert_eq!(params(&f)["cutPath"], json!(42)); + assert!(params(&f).get("cutId").is_none()); + f.set("cutId", FieldValue::Text("42".into())); + assert_eq!(params(&f)["cutId"], json!(42)); } } From 7583602d8fae63e99e714ceb256ba6c25267d106 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:12:39 +0000 Subject: [PATCH 5/7] fix: step and repeat ignores counts when filling, keeps exact spacing, lists nested cut objects --- crates/engine/src/cmd/stepandrepeat.rs | 6 ++-- crates/engine/src/cmd/stepandrepeat/tests.rs | 18 ++++++++++ crates/ui-egui/src/dialogs/step_repeat.rs | 38 ++++++++++++++------ 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index b83ebbb28a..27ee3504c9 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); spacing is exact: copies are not snapped to the pixel grid; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -119,7 +119,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) { return Err(bad(CMD, "gaps and margin must be finite")); } - let (rows, cols) = (count_param(p, "rows")?, count_param(p, "columns")?); + let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) }; let sheet = sheet_param(p)?; let mut roots = selected_roots(s)?; if roots.is_empty() { @@ -190,7 +190,6 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } let copies = copy_above(d, &roots, |_, _, n| { n.transform(m, sc); - super::object::keep_pixel_aligned(n, sc); })?; copied.extend(copies); } @@ -198,7 +197,6 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { for id in &roots { if let Some(n) = d.node_mut(*id) { n.transform(first, sc); - super::object::keep_pixel_aligned(n, sc); } } } diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 73948bd664..dcf5009ca5 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -130,3 +130,21 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); assert!(e.execute(CMD, &json!({})).is_err()); } + +#[test] +fn fill_ignores_explicit_counts() { + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "rows": 0, "columns": 0, "gap": 3})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(9), json!(4))); + assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); +} + +#[test] +fn a_pixel_aligned_copy_keeps_the_requested_fractional_gap() { + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": 0.5})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!(bounds(&s, ids[1]).0, 50.5); + assert_eq!(bounds(&s, ids[2]).0, 101.0); +} diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index b057d1b320..927b344d8d 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -23,18 +23,20 @@ pub(crate) struct Open { pub preview: LivePreview, } +fn cut_ids(doc: &vectorcraft_doc::Document, selected: &[vectorcraft_doc::NodeId]) -> Vec<(u64, String)> { + let mut out = vec![]; + for id in selected { + if let Some(n) = doc.node(*id) { + n.walk(&mut |c| out.push((c.id.0, c.display_name()))); + } + } + out +} + fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { let mut out = vec![(String::new(), Label::from(tl!("Selection")))]; - let Some(st) = app.session.active() else { return out }; - let single = st.selection.objects.len() == 1; - for id in &st.selection.objects { - let Some(n) = st.doc.node(*id) else { continue }; - out.push((id.0.to_string(), Label::from(n.display_name()))); - if single { - for c in n.children().into_iter().flatten() { - out.push((c.id.0.to_string(), Label::from(c.display_name()))); - } - } + if let Some(st) = app.session.active() { + out.extend(cut_ids(&st.doc, &st.selection.objects).into_iter().map(|(id, name)| (id.to_string(), Label::from(name)))); } out } @@ -147,4 +149,20 @@ mod tests { f.set("cutId", FieldValue::Text("42".into())); assert_eq!(params(&f)["cutId"], json!(42)); } + + #[test] + fn cut_choices_reach_objects_nested_in_groups() { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [inner, c]})).unwrap(); + let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let ids: Vec = cut_ids(doc, &[vectorcraft_doc::NodeId(outer)]).into_iter().map(|(i, _)| i).collect(); + assert!([outer, inner, a, b, c].iter().all(|i| ids.contains(i))); + } } From 7f821d39de46511df638852f1c089963d8e076eb Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:00:33 +0000 Subject: [PATCH 6/7] test: cover fractional gaps with pixel-aligned objects, document the contract --- crates/engine/src/cmd/stepandrepeat.rs | 4 +++- crates/engine/src/cmd/stepandrepeat/tests.rs | 21 +++++++++++++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 27ee3504c9..620f64a9a7 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); spacing is exact: copies are not snapped to the pixel grid; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -190,6 +190,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } let copies = copy_above(d, &roots, |_, _, n| { n.transform(m, sc); + super::object::keep_pixel_aligned(n, sc); })?; copied.extend(copies); } @@ -197,6 +198,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { for id in &roots { if let Some(n) = d.node_mut(*id) { n.transform(first, sc); + super::object::keep_pixel_aligned(n, sc); } } } diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index dcf5009ca5..c25953d598 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -140,11 +140,18 @@ fn fill_ignores_explicit_counts() { } #[test] -fn a_pixel_aligned_copy_keeps_the_requested_fractional_gap() { - let (mut s, id) = setup(); - s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); - let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": 0.5})).unwrap(); - let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); - assert_eq!(bounds(&s, ids[1]).0, 50.5); - assert_eq!(bounds(&s, ids[2]).0, 101.0); +fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_grid() { + let gap = |aligned: bool| { + let (mut s, id) = setup(); + if aligned { + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + } + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": 0.5})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let (a, c) = (bounds(&s, ids[0]), bounds(&s, ids[1])); + (c.0 - a.2, c.0 - a.0) + }; + assert!((gap(false).0 - 0.5).abs() < 1e-9); + let pitch = gap(true).1; + assert!((pitch - pitch.round()).abs() < 1e-9); } From 07b4332dfc601de36b57d683ff7e5617660d80e4 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:42:16 +0000 Subject: [PATCH 7/7] fix: Step and Repeat fill picks the artboard from the whole selection; rustfmt --- crates/engine/src/cmd/stepandrepeat.rs | 2 +- crates/engine/src/cmd/stepandrepeat/tests.rs | 21 ++++++++++++++++++++ crates/ui-egui/src/dialogs/object_dialogs.rs | 4 ++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 620f64a9a7..9ba4666598 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -150,7 +150,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } let anchor = if fill { let sheet = sheet.or_else(|| { - let c = b.center(); + let c = d.bounds_of(&roots, false).unwrap_or(b).center(); d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect) }); let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index c25953d598..991800d964 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -155,3 +155,24 @@ fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_ let pitch = gap(true).1; assert!((pitch - pitch.round()).abs() < 1e-9); } + +#[test] +fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() { + let first_x = |sheet: Option| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 105, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); + let mut p = json!({"fill": true, "cutId": cut}); + if let Some(sh) = sheet { + p["sheet"] = sh; + } + let r = s.execute(CMD, &p).unwrap(); + bounds(&s, r["ids"][0].as_u64().unwrap()).0 + }; + let default = first_x(None); + let explicit = first_x(Some(json!({"x": 100, "y": 0, "width": 100, "height": 100}))); + assert!((explicit - default - 100.0).abs() < 1e-9); +} diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index 3f3b69da54..ee0867d0dd 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -4,8 +4,8 @@ use super::path_ops::PathOp; use super::simplify_slider::StripKind; use super::{ blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form, - path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, step_repeat, transform, - transform_each, width_point, + path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, step_repeat, transform, transform_each, + width_point, }; use crate::VectorcraftApp;