diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 9ba4666598..bf15cc340e 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -4,11 +4,11 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Rect, Vec2, rotate_deg}; -use super::edit::{copy_above, selected_roots}; +use super::edit::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; +use vectorcraft_doc::{Node, Scaling}; const CMD: &str = "object.stepAndRepeat"; const MAX_CELLS: usize = 10_000; @@ -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); 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}", + "{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, not negative), 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; a negative gap overlaps neighbors and must be smaller than the width or height it is between), 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 )] @@ -119,6 +119,9 @@ 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")); } + if margin < 0.0 { + return Err(bad(CMD, "`margin` must be 0 or more")); + } 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)?; @@ -148,6 +151,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { 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())); } + if w + gx <= EPS || h + gy <= EPS { + return Err(bad(CMD, "a negative gap must be smaller than the width or height it is between")); + } let anchor = if fill { let sheet = sheet.or_else(|| { let c = d.bounds_of(&roots, false).unwrap_or(b).center(); @@ -180,6 +186,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if roots.len() > 1 { roots = vec![group_nodes(d, &roots)?]; } + // Every copy is made first, and all of them go in with one insertion. + let originals: Vec<(NodeId, Node)> = roots.iter().filter_map(|id| d.node(*id).map(|n| (*id, n.clone()))).collect(); + let mut lists: Vec<(NodeId, Vec)> = originals.iter().map(|(id, _)| (*id, Vec::with_capacity(cells.len()))).collect(); let mut copied: Vec = vec![]; let mut first = Affine::IDENTITY; for c in &cells { @@ -188,11 +197,21 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { first = m; continue; } - let copies = copy_above(d, &roots, |_, _, n| { + for ((_, original), (_, list)) in originals.iter().zip(lists.iter_mut()) { + let mut n = d.reid(original); n.transform(m, sc); - super::object::keep_pixel_aligned(n, sc); - })?; - copied.extend(copies); + super::object::keep_pixel_aligned(&mut n, sc); + copied.push(n.id); + list.push(n); + } + } + if !copied.is_empty() { + // The copy of the last cell goes directly above its original and the first cell's on top. + for (_, list) in &mut lists { + list.reverse(); + } + d.insert_beside(lists, false)?; + super::typecmd::refresh_bounds_of(d, &copied); } if first != Affine::IDENTITY { for id in &roots { diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 991800d964..4d807f7d8d 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -131,6 +131,46 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { assert!(e.execute(CMD, &json!({})).is_err()); } +#[test] +fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() { + let (mut s, _) = setup(); + let steps = undo_steps(&s); + assert!(s.execute(CMD, &json!({"fill": true, "margin": -5})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": -50})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 3, "columns": 1, "gapY": -40})).is_err()); + assert!(s.execute(CMD, &json!({"fill": true, "gap": -50})).is_err()); + assert_eq!(undo_steps(&s), steps, "a refusal records no undo step"); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": -10})).unwrap(); + assert_eq!(bounds(&s, r["ids"][1].as_u64().unwrap()), (40.0, 0.0, 90.0, 30.0), "a gap above minus the width overlaps neighbors"); +} + +#[test] +fn copies_go_in_with_one_walk_of_the_document_whatever_the_count() { + let walks = |columns: u64| { + let (mut s, _) = setup(); + for i in 0..50 { + s.execute("shape.rectangle", &json!({"x": 0, "y": 100 + i, "width": 5, "height": 5})).unwrap(); + } + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let before = vectorcraft_doc::tree_walks(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": columns, "gap": 1})).unwrap(); + assert_eq!(r["count"], json!(columns)); + vectorcraft_doc::tree_walks() - before + }; + assert_eq!(walks(40), walks(2), "the walks of the document do not grow with the number of copies"); +} + +#[test] +fn the_last_cells_copy_sits_directly_above_the_original() { + let (mut s, id) = setup(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 1})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let d = &s.doc().unwrap().doc; + let order: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(order, [id, ids[2], ids[1]]); +} + #[test] fn fill_ignores_explicit_counts() { let (mut s, _) = setup(); diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 927b344d8d..4a14fe4d2a 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -21,6 +21,40 @@ pub(crate) const CMD: &str = "object.stepAndRepeat"; pub(crate) struct Open { pub id: DialogId, pub preview: LivePreview, + /// The opening document's uid and revert count. + document: (u64, u64), +} + +impl Open { + fn in_source(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|doc| (doc.uid, doc.reverts) == self.document) + } + + /// Why OK is refused while the opening document is not the active one, after a revert too. + fn away(&self, app: &mut VectorcraftApp) -> Option { + if self.in_source(app) { + return None; + } + let (uid, _) = self.document; + if app.session.active().is_some_and(|doc| doc.uid == uid) { + let reason = tl!("The document was reverted. Reopen this dialog to continue."); + app.status(reason); + Some(reason.into()) + } else if app.session.documents().iter().any(|doc| doc.uid == uid) { + Some("switch back to the document where Step and Repeat was opened".into()) + } else { + Some("the document where Step and Repeat was opened has closed".into()) + } + } +} + +/// Rolls back the preview of an open dialog and drops its record. +fn cancel_open(app: &mut VectorcraftApp) { + if let Some(open) = app.object_dialogs.step.take() + && open.in_source(app) + { + open.preview.cancel(app); + } } fn cut_ids(doc: &vectorcraft_doc::Document, selected: &[vectorcraft_doc::NodeId]) -> Vec<(u64, String)> { @@ -104,6 +138,9 @@ pub(crate) fn open(app: &mut VectorcraftApp) { fn try_open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; + // Rolls back the preview of a dialog this one replaces, before the cut paths are listed. + cancel_open(app); + let document = app.session.active().map(|doc| (doc.uid, doc.reverts)).ok_or("no document")?; 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); @@ -112,23 +149,28 @@ fn try_open(app: &mut VectorcraftApp) -> Result { }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; + if let Some(reason) = open.away(app) { + app.object_dialogs.step = Some(open); + return Err(reason); + } 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 cancel: Box = Box::new(cancel_open); 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() }); + app.object_dialogs.step = Some(Open { id, preview: LivePreview::default(), document }); Ok(Value::Null) } +/// Each frame: previews the dialog's values on the opening document while Preview is on. Another +/// document, or the opening one after a revert, gets no preview. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + if !app.object_dialogs.step.as_ref().is_some_and(|open| open.in_source(app)) { + return; + } 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()))))); @@ -165,4 +207,100 @@ mod tests { 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))); } + + type Harness = egui_kittest::Harness<'static, VectorcraftApp>; + + /// An app with two documents, each with one selected square, the first one active. + fn two_documents() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + for x in [20, 70] { + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + app + } + + /// A harness that shows the dialog host and runs this module's pump each frame. + fn start(app: VectorcraftApp) -> Harness { + let mut ready = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut ready, true) { + crate::testing::install(ui.ctx()); + app.adopt_context(ui.ctx()); + return; + } + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + pump(app, ui.ctx()); + crate::dialogs::host::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h + } + + fn id(h: &Harness) -> DialogId { + h.state().object_dialogs.step.as_ref().expect("Step and Repeat is open").id + } + + fn set(h: &mut Harness, key: &str, value: Value) { + let (ctx, id) = (h.ctx.clone(), id(h)); + h.state().dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, key, value)).unwrap(); + h.run_steps(2); + } + + fn confirm(h: &mut Harness) { + let (ctx, id) = (h.ctx.clone(), id(h)); + assert!(h.state().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)) || h.state().object_dialogs.step.is_some()); + h.run_steps(3); + } + + fn objects(h: &Harness) -> usize { + h.state().session.doc().unwrap().doc.layers[0].children().unwrap().len() + } + + #[test] + fn preview_and_ok_stay_on_the_opening_document() { + let mut h = start(two_documents()); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "columns", json!(3)); + assert_eq!(objects(&h), 6, "the opening document previews 2 × 3"); + + h.state_mut().run("document.activate", json!({"index": 1})).unwrap(); + let other = h.state().session.doc().unwrap().doc.clone(); + set(&mut h, "columns", json!(4)); + assert_eq!(h.state().session.doc().unwrap().doc, other, "Preview must leave the other document unchanged"); + confirm(&mut h); + assert_eq!(h.state().session.doc().unwrap().doc, other, "OK must leave the other document unchanged"); + assert!(h.state().object_dialogs.step.is_some(), "the dialog stays open"); + + h.state_mut().run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut h); + assert!(h.state().object_dialogs.step.is_none(), "OK applies on the opening document"); + assert_eq!(objects(&h), 8); + } + + #[test] + fn reopening_rolls_back_the_earlier_preview() { + let mut h = start(two_documents()); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "columns", json!(3)); + assert_eq!(objects(&h), 6); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "preview", json!(false)); + assert_eq!(objects(&h), 1, "the first dialog's preview is rolled back"); + assert!(!h.state().session.in_interaction()); + set(&mut h, "columns", json!(3)); + confirm(&mut h); + assert!(h.state().object_dialogs.step.is_none(), "OK of the reopened dialog applies"); + assert_eq!(objects(&h), 6); + } }