mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
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.
This commit is contained in:
1 parent
82ea216abc
commit
eb1407217f
9 files changed
+504
-2
No files matched your search
@@ -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());
|
||||
|
||||
@@ -415,6 +415,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.textWrap.release",
|
||||
"object.transform",
|
||||
"object.transformAgain",
|
||||
"object.stepAndRepeat",
|
||||
"object.transformEach",
|
||||
"object.ungroup",
|
||||
"object.unlockAll",
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Cell> {
|
||||
(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<usize> {
|
||||
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<Option<Rect>> {
|
||||
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<Value> {
|
||||
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<NodeId> = 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<NodeId> = roots.clone();
|
||||
out.extend(copied);
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "rows": rows, "columns": cols, "count": ids.len() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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::<Vec<_>>(), [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<u64> = 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<u64> = 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<u64> = 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());
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<transform::Open>,
|
||||
/// The open Transform Each dialog's preview record.
|
||||
pub each: Option<transform_each::Open>,
|
||||
/// The open Step and Repeat dialog's preview record.
|
||||
pub step: Option<step_repeat::Open>,
|
||||
/// The open Average, Average & Join, Offset Path and Simplify dialogs' preview records.
|
||||
pub path: Vec<path_ops::Open>,
|
||||
/// 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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Param> {
|
||||
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::<u64>().ok()) {
|
||||
p.insert("cutPath".into(), json!(id));
|
||||
}
|
||||
Value::Object(p)
|
||||
}
|
||||
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
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<dyn FnOnce(&mut VectorcraftApp)> = 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::<HostedParamDialog>(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));
|
||||
}
|
||||
}
|
||||
@@ -847,6 +847,7 @@ pub(super) fn transform_items() -> Vec<Node> {
|
||||
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})),
|
||||
|
||||
Reference in new issue
Block a user