From a7c8d287772aadbfe0282ad5196ef32eb584115b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:25:01 -0800 Subject: [PATCH 01/12] Object Mosaic: Create Object Mosaic opens a dialog with its size, ratio and percentage options Object > Create Object Mosaic... opens its own dialog on the selected image: Current Size, New Size, Tile Spacing, Number of Tiles, Constrain Ratio (Width or Height), Result (Color or Grayscale), Resize Using Percentages, Delete Raster and Use Ratio. It replaces the generic parameter dialog, which showed only the counts, the spacing and the two switches. object.createObjectMosaic takes percentages, constrain and useRatio. Use Ratio keeps the count on the kept side and picks the other count whose tiles, spacing taken off, come closest to square, measured along the image's own sides. A new width or height outside 0.1 to 1000000 is refused, and the result gives the columns and rows used. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd.rs | 3 + crates/engine/src/cmd/menucmds.rs | 137 +++++- crates/engine/src/tests.rs | 108 +++++ crates/ui-egui/src/dialogs.rs | 7 + crates/ui-egui/src/dialogs/object_mosaic.rs | 468 ++++++++++++++++++++ crates/ui-egui/src/dialogs/tests.rs | 8 +- crates/ui-egui/src/i18n/bg.tsv | 10 + crates/ui-egui/src/i18n/bs.tsv | 10 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 9 + crates/ui-egui/src/i18n/hi.tsv | 9 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/menus/run.rs | 4 + docs/mcp.md | 30 +- docs/target-app-parity.md | 1 + 37 files changed, 1022 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/object_mosaic.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index a2d0316913..4abdbf1556 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -885,6 +885,9 @@ pub(crate) use buildcmds::TracePresetChanges; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them). +pub use menucmds::mosaic_counts; + /// The gaps View › Show Live Paint Gaps shows on a Live Paint group. pub use buildcmds::live_paint_gaps; diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 1ab0e0b670..41fc1cf2fe 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Create Object Mosaic…", ["Object"], None, - "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt; default the image's), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles}", + "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles, columns, rows}", has_image, object_mosaic ), @@ -891,7 +891,23 @@ pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> { } } -fn object_mosaic(s: &mut Session, p: &Value) -> Result { +/// What `object.createObjectMosaic` makes from its params: the image, the tile counts, the tiles' +/// placement, their size and spacing in image pixels, and the options. +struct MosaicPlan { + id: NodeId, + im: ImageObject, + cols: u32, + rows: u32, + xf: Affine, + tile: (f64, f64), + gap: (f64, f64), + gray: bool, + delete: bool, +} + +/// The mosaic `object.createObjectMosaic` would make from `p`, worked out without decoding the +/// image or changing the document. +fn mosaic_plan(s: &Session, p: &Value) -> Result { const C: &str = "object.createObjectMosaic"; let st = s.doc()?; let id = st @@ -901,28 +917,92 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { .copied() .find(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))) .ok_or_else(|| bad(C, "select an image"))?; - let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; - let blob = st.doc.images.get(&im.key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; - let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; - let cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; - let rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; + if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) { + return Err(bad(C, "the image has no embedded pixels")); + } + let mut cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; + let mut rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; let gray = switch_or(p, "gray", false, C)?; - let colors = vectorcraft_trace::mosaic(&raster, cols, rows); + let percentages = switch_or(p, "percentages", false, C)?; + // A side named "width" (true) or "height" (false), as `constrain` and `useRatio` take it. + let side = |key: &str, v: &Value, also: &str| match v.as_str() { + Some("width") => Ok(true), + Some("height") => Ok(false), + _ => Err(bad(C, format!("`{key}` must be one of {}", format_args!("\"width\", \"height\"{also} or null")))), + }; + let constrain = match p.get("constrain") { + None | Some(Value::Null) => None, + Some(v) => Some(side("constrain", v, "")?), + }; + // Use Ratio's kept side: true keeps Constrain Ratio's side (the width when it is left out). + let use_ratio = match p.get("useRatio") { + None | Some(Value::Null | Value::Bool(false)) => None, + Some(Value::Bool(true)) => Some(constrain.unwrap_or(true)), + Some(v) => Some(side("useRatio", v, ", true, false")?), + }; // Tiles in image space, placed by the image transform (scaled to a new size if asked). let b = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; check_numbers(p, &["width", "height", "spacingX", "spacingY"], C)?; - let (nw, nh) = (f64_or(p, "width", b.width()).max(0.1), f64_or(p, "height", b.height()).max(0.1)); - let resize = Affine::translate(b.origin().to_vec2()) - * Affine::scale_non_uniform(nw / b.width().max(1e-9), nh / b.height().max(1e-9)) - * Affine::translate(-b.origin().to_vec2()); + let (bw, bh) = (b.width().max(1e-9), b.height().max(1e-9)); + // A size given (pt, or % of the image's) is from 0.1 to 1,000,000; one left out is the image's. + let size = |key: &str, base: f64| -> Result { + let Some(x) = p.get(key).and_then(Value::as_f64) else { return Ok(base) }; + let (min, max) = (0.1, 1_000_000.0); + if !(min..=max).contains(&x) { + return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + Ok(if percentages { base * x / 100.0 } else { x }) + }; + let (mut nw, mut nh) = (size("width", bw)?, size("height", bh)?); + // Constrain Ratio keeps the image's proportions: the named side leads and the other follows. + match constrain { + Some(true) => nh = nw * bh / bw, + Some(false) => nw = nh * bw / bh, + None => {} + } + // A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. + let (nw, nh) = match constrain { + Some(_) => { + let k = (0.1 / nw.min(nh)).max(1.0); + (nw * k, nh * k) + } + None => (nw.max(0.1), nh.max(0.1)), + }; + let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2()); let xf = resize * im.xf; - let (tw, th) = (im.width as f64 / cols as f64, im.height as f64 / rows as f64); - // Spacing is in points; convert to image pixels along each axis. + // Points per image pixel along each of the image's axes (the image may be turned). let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9); let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9); - let (gx, gy) = ((f64_or(p, "spacingX", 0.0).max(0.0) / ppx).min(tw * 0.9), (f64_or(p, "spacingY", 0.0).max(0.0) / ppy).min(th * 0.9)); + let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0)); + let (iw, ih) = (im.width as f64, im.height as f64); + // Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side, + // measured along the image's axes. + match use_ratio { + Some(true) => rows = mosaic_square_count(cols, iw * ppx, ih * ppy, sx, sy), + Some(false) => cols = mosaic_square_count(rows, ih * ppy, iw * ppx, sy, sx), + None => {} + } + let (tw, th) = (iw / cols as f64, ih / rows as f64); + // Spacing is in points; convert to image pixels along each axis. + let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9)); let delete = switch_or(p, "deleteRaster", false, C)?; + Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete }) +} + +/// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio +/// included, without making the mosaic (the dialog's Use Ratio button shows them). +pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> { + mosaic_plan(s, p).map(|m| (m.cols, m.rows)) +} + +fn object_mosaic(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.createObjectMosaic"; + let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?; + let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; + let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; + let colors = vectorcraft_trace::mosaic(&raster, cols, rows); let (gid, n) = s.edit("Create Object Mosaic", |d, sel| { let mut tiles = vec![]; for r in 0..rows { @@ -960,7 +1040,32 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { sel.set([gid]); Ok((gid, n)) })?; - Ok(json!({ "id": gid.0, "tiles": n })) + Ok(json!({ "id": gid.0, "tiles": n, "columns": cols, "rows": rows })) +} + +/// The tile count along one side of an Object Mosaic whose tiles, as drawn, come closest to square +/// (Use Ratio): `kept` tiles span `kept_len` on the other side, and this side is `other_len` long. +/// Each tile is its cell less the gap on its side (`kept_gap`, `other_gap`), and a gap takes at +/// most 90% of a cell, as the tiles are drawn. Within 1..1000, the smaller count on a tie; all +/// lengths in points. +pub(crate) fn mosaic_square_count(kept: u32, kept_len: f64, other_len: f64, kept_gap: f64, other_gap: f64) -> u32 { + let drawn = |len: f64, n: u32, gap: f64| { + let cell = len / n.max(1) as f64; + cell - gap.max(0.0).min(cell * 0.9) + }; + let side = drawn(kept_len, kept, kept_gap); + if !(side.is_finite() && side > 0.0 && other_len.is_finite() && other_len > 0.0) { + return 1; + } + // A tile on this side shrinks as the count grows: find the first count whose tile is no wider + // than `side`, then take it or the count before it, whichever is closer. + let (mut lo, mut hi) = (1u32, 1000u32); + while lo < hi { + let mid = (lo + hi) / 2; + if drawn(other_len, mid, other_gap) > side { lo = mid + 1 } else { hi = mid } + } + let off = |n: u32| (drawn(other_len, n, other_gap) - side).abs(); + if lo > 1 && off(lo - 1) <= off(lo) { lo - 1 } else { lo } } fn polygon_path(pts: &[Point]) -> PathData { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 57445a36be..8f7cf46950 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4035,6 +4035,114 @@ fn object_mosaic_refuses_a_boolean_given_as_text() { assert_eq!((r["tiles"].clone(), images(&s)), (json!(2), 1)); } +/// The size of the mosaic a call makes from the 100 × 50 pt image selected in `s`, with its column and row counts. +fn mosaic_size(s: &mut Session, p: serde_json::Value) -> (f64, f64, serde_json::Value, serde_json::Value) { + let image = s.doc().unwrap().selection.objects.clone(); + let r = s.execute("object.createObjectMosaic", &p).unwrap(); + let b = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + ((b.width() * 1e6).round() / 1e6, (b.height() * 1e6).round() / 1e6, r["columns"].clone(), r["rows"].clone()) +} + +/// Resize Using Percentages reads the new width and height as percentages of the image's size; Constrain Ratio keeps +/// the image's proportions, the named side leading; Use Ratio makes the tiles square from the count on the +/// constrained side (columns by default), and the call answers the counts it used. +#[test] +fn object_mosaic_resizes_by_percentages_constrains_the_ratio_and_squares_the_tiles() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + assert_eq!(mosaic_size(&mut s, json!({"columns": 2, "rows": 1})), (100.0, 50.0, json!(2), json!(1))); + assert_eq!(mosaic_size(&mut s, json!({"width": 50, "height": 200, "percentages": true})), (50.0, 100.0, json!(10), json!(10))); + // A side left out is 100% of the image's. + assert_eq!(mosaic_size(&mut s, json!({"width": 150, "percentages": true})).0, 150.0); + assert_eq!(mosaic_size(&mut s, json!({"width": 200, "height": 10, "constrain": "width"})), (200.0, 100.0, json!(10), json!(10))); + assert_eq!(mosaic_size(&mut s, json!({"width": 10, "height": 25, "constrain": "height"})), (50.0, 25.0, json!(10), json!(10))); + assert_eq!(mosaic_size(&mut s, json!({"width": 50, "constrain": "width", "percentages": true})), (50.0, 25.0, json!(10), json!(10))); + // Square tiles: 10 columns of 10 pt over 50 pt are 5 rows; 4 rows of 12.5 pt over 100 pt are 8 columns. + assert_eq!(mosaic_size(&mut s, json!({"columns": 10, "rows": 3, "useRatio": true})), (100.0, 50.0, json!(10), json!(5))); + assert_eq!(mosaic_size(&mut s, json!({"columns": 3, "rows": 4, "useRatio": true, "constrain": "height"})), (100.0, 50.0, json!(8), json!(4))); + // A side named for Use Ratio is kept without Constrain Ratio: the size stays as given. + assert_eq!(mosaic_size(&mut s, json!({"rows": 4, "height": 100, "useRatio": "height"})), (100.0, 100.0, json!(4), json!(4))); + // On a new size: 30 columns over 300 × 50 pt are 5 rows. + assert_eq!(mosaic_size(&mut s, json!({"columns": 30, "width": 300, "useRatio": true})), (300.0, 50.0, json!(30), json!(5))); + // The count is kept within 1..1000. + assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 1, "height": 5000, "useRatio": true})).3, json!(1000)); + assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 5000, "height": 1, "useRatio": true})).3, json!(1)); + // A size under 0.1 pt grows in proportion while Constrain Ratio keeps it. + let (w, h, ..) = mosaic_size(&mut s, json!({"width": 0.1, "constrain": "width"})); + assert!((w - 0.2).abs() < 1e-6 && (h - 0.1).abs() < 1e-6, "{w} × {h}"); +} + +/// Use Ratio squares the tiles as drawn: with 4 pt between columns, 10 columns of 10 pt cells draw 6 pt wide, so the +/// rows are 6 pt plus their own 4 pt apart (5 rows down 50 pt); on an image turned 90°, the tiles are measured along +/// its own axes. +#[test] +fn object_mosaic_use_ratio_takes_spacing_and_turned_images_into_account() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let image = s.doc().unwrap().selection.objects.clone(); + let counts = |s: &Session, p: serde_json::Value| crate::cmd::mosaic_counts(s, &p).unwrap(); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4, "spacingY": 4})), (10, 5)); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4})), (10, 8)); + assert_eq!(counts(&s, json!({"columns": 10, "rows": 7})), (10, 7), "without Use Ratio the counts are kept"); + let r = s.execute("object.createObjectMosaic", &json!({"columns": 10, "useRatio": true, "spacingX": 4})).unwrap(); + let g = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone(); + let t = g.children().unwrap()[0].geometric_bounds().unwrap(); + assert!((t.width() - 6.0).abs() < 1e-6 && (t.height() - 6.25).abs() < 1e-6, "{t:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + // Turned 90°, the image's 100 pt side runs down the page; 10 columns along it are still 5 rows across its 50. + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true})), (10, 5)); +} + +#[test] +fn object_mosaic_square_count_is_the_nearest_whole_count() { + use crate::cmd::menucmds::mosaic_square_count; + assert_eq!(mosaic_square_count(10, 100.0, 50.0, 0.0, 0.0), 5); + assert_eq!(mosaic_square_count(3, 100.0, 50.0, 0.0, 0.0), 2); + assert_eq!(mosaic_square_count(0, 100.0, 50.0, 0.0, 0.0), 1); + assert_eq!(mosaic_square_count(10, 0.0, 50.0, 0.0, 0.0), 1); + assert_eq!(mosaic_square_count(1000, 1.0, 1000.0, 0.0, 0.0), 1000); + // Spacing wider than a cell leaves 10% of it, on either side. + assert_eq!(mosaic_square_count(10, 100.0, 50.0, 50.0, 0.0), 50); + // 10 columns of 1 pt tiles (9 pt gaps) over 100 pt; rows 100 pt apart are capped too, so 10 rows draw 1 pt. + assert_eq!(mosaic_square_count(10, 100.0, 100.0, 9.0, 100.0), 10); + // 15 pt tiles over 50 pt: 3 rows draw 16.7 pt and 4 rows 12.5 pt, so 3. + assert_eq!(mosaic_square_count(1, 15.0, 50.0, 0.0, 0.0), 3); +} + +/// A Constrain Ratio side that is not "width" or "height", a new size of 0 or less, and Use Ratio or Resize Using +/// Percentages given as text are errors naming the key; no mosaic is made. +#[test] +fn object_mosaic_refuses_a_bad_ratio_side_size_or_switch() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + for (p, msg) in [ + (json!({"constrain": "both"}), "`constrain` must be one of \"width\", \"height\" or null"), + (json!({"constrain": 1}), "`constrain` must be one of \"width\", \"height\" or null"), + (json!({"width": 0}), "`width` must be between 0.1 and 1000000 (got 0)"), + (json!({"height": -5, "percentages": true}), "`height` must be between 0.1 and 1000000 (got -5)"), + (json!({"width": 2e6, "percentages": true}), "`width` must be between 0.1 and 1000000 (got 2000000)"), + (json!({"useRatio": "true"}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), + (json!({"useRatio": 1}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), + (json!({"percentages": 1}), "`percentages` must be true or false"), + ] { + let r = s.execute("object.createObjectMosaic", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{p}: {r:?}"); + assert_eq!(undo(&s), before, "{p}"); + } + let r = s.execute("object.createObjectMosaic", &json!({"constrain": null, "useRatio": null, "percentages": null})).unwrap(); + assert_eq!(r["tiles"], json!(100)); +} + #[test] fn snap_to_pixel_rounds_drawing_and_moves() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5afad21b0d..e05da0a333 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -78,6 +78,7 @@ pub mod new_color_group; mod new_document; pub mod new_swatch; pub mod new_text_style; +pub mod object_mosaic; pub mod objects_on_path_options; pub mod office_export; pub mod package; @@ -428,6 +429,7 @@ registry! { ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, + ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC, @@ -593,6 +595,11 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &value); } + // Create Object Mosaic's Resize Using Percentages shows the new size the other way, as its checkbox does. + if d.kind == object_mosaic::KIND && field == "percentages" { + object_mosaic::set_percentages(d, &value); + return; + } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs new file mode 100644 index 0000000000..ed8b060a92 --- /dev/null +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -0,0 +1,468 @@ +//! Object → Create Object Mosaic: the selected image's Current Size, the mosaic's New Size, Tile +//! Spacing and Number of Tiles, Constrain Ratio (Width or Height), Result (Color or Grayscale), +//! Resize Using Percentages, Delete Raster and Use Ratio. OK runs `object.createObjectMosaic` as one +//! undo step. +//! +//! Fields: `width`, `height` (pt, or percentages of the image's size with `percentages`), +//! `spacingX`, `spacingY` (pt), `columns`, `rows`, `lock` (Constrain Ratio on), `constrain` +//! (`width` | `height`: the side Constrain Ratio and Use Ratio keep), `gray`, `percentages` and +//! `deleteRaster`. `__imageW` and `__imageH` hold the image's size (pt). + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; + +use super::{DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Create Object Mosaic. +pub const KIND: &str = "objectMosaic"; + +/// The command the dialog runs. +pub const COMMAND: &str = "object.createObjectMosaic"; + +/// Width of the label column. +const LABEL_W: f32 = 112.0; + +/// Width of a size or count field. +const FIELD_W: f32 = 76.0; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Create Object Mosaic").into(), body, confirm, min_width: 360.0, ..DialogSpec::FORM }; + +/// The size (pt) of the first selected image, which the mosaic is made from. +fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> { + let st = app.session.active()?; + let node = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).find(|n| matches!(n.kind, NodeKind::Image(_)))?; + let b = node.geometric_bounds()?; + Some((b.width(), b.height())) +} + +/// Open the dialog on the selected image, with the values `given` holds (the menu item's params, or +/// a caller's `object.createObjectMosaic` params, its Use Ratio applied to the counts) and the +/// command's defaults for the rest. With no image selected, or with params the command refuses, +/// nothing opens and the error says why. +pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { + let Some((w, h)) = image_size(app) else { return Err("select an image".into()) }; + let none = json!({}); + let given = if given.is_null() { &none } else { given }; + app.session.check_params(COMMAND, given).map_err(|e| e.to_string())?; + let (cols, rows) = vectorcraft_engine::cmd::mosaic_counts(&app.session, given).map_err(|e| e.to_string())?; + let n = |key: &str, d: f64| given.get(key).and_then(Value::as_f64).unwrap_or(d); + let b = |key: &str| given.get(key).and_then(Value::as_bool).unwrap_or(false); + let pct = b("percentages"); + // The new size starts at the image's, within the sizes the command takes (0.1 to 1,000,000 pt). + let (base_w, base_h) = if pct { (100.0, 100.0) } else { (w.clamp(0.1, 1.0e6), h.clamp(0.1, 1.0e6)) }; + let named = |key: &str| given.get(key).and_then(Value::as_str).filter(|s| matches!(*s, "width" | "height")); + let constrain = named("constrain"); + // The side the dialog keeps: Constrain Ratio's, else the one Use Ratio names. + let side = constrain.or(named("useRatio")).unwrap_or("width"); + let fields = json!({ + "width": n("width", base_w), "height": n("height", base_h), "spacingX": n("spacingX", 0.0), "spacingY": n("spacingY", 0.0), + "columns": cols, "rows": rows, + "lock": constrain.is_some(), "constrain": side, "gray": b("gray"), "percentages": pct, + "deleteRaster": b("deleteRaster"), "__imageW": w, "__imageH": h, + }); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(json!({ "dialog": KIND })) +} + +/// The image's size (pt) the dialog holds. +fn image(d: &Dialog) -> (f64, f64) { + (d.f64("__imageW", 1.0).max(1e-9), d.f64("__imageH", 1.0).max(1e-9)) +} + +/// Whether Constrain Ratio and Use Ratio keep the width (else the height). +fn keeps_width(d: &Dialog) -> bool { + d.str("constrain") != "height" +} + +/// With Constrain Ratio on, the side that follows set from the side that leads, in the image's +/// proportions. +fn follow_ratio(d: &mut Dialog) { + if !d.bool("lock") { + return; + } + let (iw, ih) = image(d); + let pct = d.bool("percentages"); + if keeps_width(d) { + let w = d.f64("width", 0.0); + d.fields.insert("height".into(), json!(if pct { w } else { w * ih / iw })); + } else { + let h = d.f64("height", 0.0); + d.fields.insert("width".into(), json!(if pct { h } else { h * iw / ih })); + } +} + +/// Resize Using Percentages turned on or off: the new size shown the other way, so it stays the +/// same size. +fn switch_percentages(d: &mut Dialog, on: bool) { + let (iw, ih) = image(d); + let (w, h) = (d.f64("width", iw), d.f64("height", ih)); + let (w, h) = if on { (w / iw * 100.0, h / ih * 100.0) } else { (iw * w / 100.0, ih * h / 100.0) }; + d.fields.insert("width".into(), json!(w)); + d.fields.insert("height".into(), json!(h)); + d.fields.insert("percentages".into(), json!(on)); +} + +/// `ui.dialog.set` of `percentages`: true or false switches the new size as the checkbox does; +/// another value is kept as it is, and the command refuses it on OK. +pub(super) fn set_percentages(d: &mut Dialog, value: &Value) { + match value.as_bool() { + Some(on) if on != d.bool("percentages") => switch_percentages(d, on), + Some(_) => {} + None => { + d.fields.insert("percentages".into(), value.clone()); + } + } +} + +/// Use Ratio: the count on the kept side stays and the other makes the tiles square, as the +/// command counts them for the fields as they are (Constrain Ratio's side, the new size and the +/// spacing). +fn use_ratio(app: &VectorcraftApp, d: &mut Dialog) { + let mut p = params(d); + p["useRatio"] = json!(if keeps_width(d) { "width" } else { "height" }); + match vectorcraft_engine::cmd::mosaic_counts(&app.session, &p) { + Ok((cols, rows)) => { + d.fields.insert("columns".into(), json!(cols)); + d.fields.insert("rows".into(), json!(rows)); + } + Err(e) => form::note_refusal(d, &e), + } +} + +/// Field `key` as `object.createObjectMosaic` takes it: a number (text with a unit, as +/// `ui.dialog.set` may give it, read in points), `default` when the field is missing, and any other +/// value as it is, for the command to refuse. +fn number(d: &Dialog, key: &str, default: f64) -> Value { + match d.fields.get(key) { + None => json!(default), + Some(Value::String(s)) => vectorcraft_doc::Unit::Points.parse(s).map_or_else(|| json!(s), |v| json!(v)), + Some(v) => v.clone(), + } +} + +/// Field `key` as the command takes an on/off value: false when the field is missing, and any +/// other value as it is, for the command to refuse one that is not true or false. +fn switch(d: &Dialog, key: &str) -> Value { + d.fields.get(key).cloned().unwrap_or(json!(false)) +} + +/// `object.createObjectMosaic` parameters from the fields. +fn params(d: &Dialog) -> Value { + json!({ + "columns": number(d, "columns", 10.0), "rows": number(d, "rows", 10.0), + "width": number(d, "width", 100.0), "height": number(d, "height", 100.0), "percentages": switch(d, "percentages"), + "constrain": if d.bool("lock") { json!(if keeps_width(d) { "width" } else { "height" }) } else { Value::Null }, + "spacingX": number(d, "spacingX", 0.0), "spacingY": number(d, "spacingY", 0.0), + "gray": switch(d, "gray"), "deleteRaster": switch(d, "deleteRaster"), + }) +} + +/// A Width and a Height field for `keys`: lengths in `unit` of at least `least` points, or +/// percentages with `pct`. With `follows`, the field of that key is grayed (Constrain Ratio sets it). +fn pair(ui: &mut egui::Ui, d: &mut Dialog, keys: [&str; 2], unit: vectorcraft_doc::Unit, (pct, least): (bool, f64), follows: Option<&str>) { + for (key, label) in keys.into_iter().zip([tl!("Width:"), tl!("Height:")]) { + widgets::dim_label(ui, label); + ui.add_enabled_ui(follows != Some(key), |ui| { + if pct { + if let Some(v) = widgets::spin_plain(ui, ("mosaic", key), d.f64(key, 100.0), "%", 2, FIELD_W, 1.0, 0.1, &[]) { + d.fields.insert(key.into(), json!(v)); + } + } else { + form::length_within(ui, d, key, unit, FIELD_W, Some(least..=1.0e6)); + } + }); + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + let (iw, ih) = image(d); + widgets::label_row(ui, tl!("Current Size:"), LABEL_W, |ui| { + widgets::dim_label(ui, tl!("Width:")); + widgets::dim_name(ui, &unit.format(iw)); + widgets::dim_label(ui, tl!("Height:")); + widgets::dim_name(ui, &unit.format(ih)); + }); + ui.add_space(4.0); + let follows = d.bool("lock").then(|| if keeps_width(d) { "height" } else { "width" }); + let pct = d.bool("percentages"); + widgets::label_row(ui, tl!("New Size:"), LABEL_W, |ui| pair(ui, d, ["width", "height"], unit, (pct, 0.1), follows)); + follow_ratio(d); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Tile Spacing:"), LABEL_W, |ui| pair(ui, d, ["spacingX", "spacingY"], unit, (false, 0.0), None)); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Number of Tiles:"), LABEL_W, |ui| { + for (key, label) in [("columns", tl!("Width:")), ("rows", tl!("Height:"))] { + widgets::dim_label(ui, label); + if let Some(v) = widgets::spin_plain(ui, ("mosaic", key), d.f64(key, 10.0), "", 0, FIELD_W, 1.0, 1.0, &[]) { + d.fields.insert(key.into(), json!(v.round().clamp(1.0, 1000.0))); + } + } + }); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Constrain Ratio:"), LABEL_W, |ui| { + form::check(ui, d, "lock", tl!("Constrain Width and Height Proportions")); + let width = keeps_width(d); + if widgets::radio(ui, tl!("Width"), width, true) { + d.fields.insert("constrain".into(), json!("width")); + } + if widgets::radio(ui, tl!("Height"), !width, true) { + d.fields.insert("constrain".into(), json!("height")); + } + }); + follow_ratio(d); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Result:"), LABEL_W, |ui| { + let gray = d.bool("gray"); + if widgets::radio(ui, tl!("Color"), !gray, true) { + d.fields.insert("gray".into(), json!(false)); + } + if widgets::radio(ui, tl!("Grayscale"), gray, true) { + d.fields.insert("gray".into(), json!(true)); + } + }); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Options:"), LABEL_W, |ui| { + ui.vertical(|ui| { + if widgets::check(ui, tl!("Resize Using Percentages"), pct, true) { + switch_percentages(d, !pct); + } + form::check(ui, d, "deleteRaster", tl!("Delete Raster")); + }); + }); + ui.add_space(6.0); + if widgets::flat_button(ui, tl!("Use Ratio"), 96.0).clicked() { + use_ratio(app, d); + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + run_and_close(app, COMMAND, params(d)) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// A frame of the open dialog → the texts painted. The dialog measures itself on its first + /// frame, so a fresh context needs two. + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.shapes.iter().filter_map(|s| if let egui::epaint::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect() + } + + fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + } + + /// A tile count the dialog holds. + fn count(d: &Dialog, key: &str) -> u32 { + d.f64(key, 0.0) as u32 + } + + /// An app with a 100 × 50 pt embedded image selected. + fn app_with_image() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("object.rasterize", json!({"ppi": 72})).unwrap(); + app + } + + /// The mosaic group's size and tile count. + fn mosaic(app: &VectorcraftApp) -> Option<(f64, f64, usize)> { + let mut found = None; + app.session.active()?.doc.walk(|n| { + if n.name.as_deref() == Some("Object Mosaic") { + let b = n.geometric_bounds().unwrap(); + found = Some(((b.width() * 1e6).round() / 1e6, (b.height() * 1e6).round() / 1e6, n.children().map_or(0, |c| c.len()))); + } + }); + found + } + + fn open_from_menu(app: &mut VectorcraftApp) { + let entry = crate::menus::menu_entries(app).into_iter().find(|e| e.label == "Create Object Mosaic…").expect("menu item"); + let (cmd, params) = crate::menus::click_target(&entry.label, entry.command.as_deref().unwrap(), &entry.params); + crate::menus::invoke(app, &cmd, params); + } + + /// The menu item opens this dialog, not the generic one, on the image's size, with every documented row; OK + /// makes the mosaic as one undo step. + #[test] + fn the_menu_item_opens_the_dialog_with_its_rows() { + let mut app = app_with_image(); + open_from_menu(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog"); + assert_eq!(d.kind, KIND); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.f64("columns", 0.0), d.f64("rows", 0.0)), (100.0, 50.0, 10.0, 10.0)); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + for want in [ + "Create Object Mosaic", + "Current Size:", + "New Size:", + "Tile Spacing:", + "Number of Tiles:", + "Constrain Ratio:", + "Constrain Width and Height Proportions", + "Result:", + "Color", + "Grayscale", + "Resize Using Percentages", + "Delete Raster", + "Use Ratio", + "100 pt", + "50 pt", + ] { + assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}"); + } + let undo = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 100))); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + } + + /// An image narrower than 0.1 pt opens with a new width of 0.1 pt, which OK makes. + #[test] + fn a_tiny_image_opens_with_a_size_the_command_takes() { + let mut app = app_with_image(); + app.run("object.scale", json!({"sx": 0.05, "sy": 100})).unwrap(); + open(&mut app, &json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 0.1); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| m.0), Some(0.1)); + } + + /// With no image selected the dialog does not open and the error says why. + #[test] + fn without_an_image_nothing_opens() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + let e = open(&mut app, &json!({})).unwrap_err(); + assert!(app.ui.dialog.is_none()); + assert!(e.contains("select an image"), "{e}"); + } + + /// Constrain Ratio keeps the new size in the image's proportions from the side it names; Resize Using + /// Percentages shows the same size as percentages; Use Ratio makes the tiles square from the kept side's count. + #[test] + fn constrain_ratio_percentages_and_use_ratio_set_the_fields() { + let mut app = app_with_image(); + open(&mut app, &json!({"columns": 10, "rows": 10})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lock".into(), json!(true)); + d.fields.insert("width".into(), json!(300)); + frame(&mut app, &ctx); + let mut d = app.ui.dialog.take().unwrap(); + assert_eq!(d.f64("height", 0.0), 150.0, "height follows the width"); + // Percentages: 300 × 150 pt of a 100 × 50 pt image is 300%. + switch_percentages(&mut d, true); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (300.0, 300.0)); + // Use Ratio: 10 columns across 300 pt are 30 pt tiles, so 5 rows down 150 pt. + use_ratio(&app, &mut d); + assert_eq!((count(&d, "columns"), count(&d, "rows")), (10, 5)); + // Kept by height: 4 rows of 37.5 pt over 300 pt are 8 columns. + d.fields.insert("constrain".into(), json!("height")); + d.fields.insert("rows".into(), json!(4)); + use_ratio(&app, &mut d); + assert_eq!((count(&d, "columns"), count(&d, "rows")), (8, 4)); + switch_percentages(&mut d, false); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (300.0, 150.0)); + d.fields.insert("gray".into(), json!(true)); + app.ui.dialog = Some(d); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app), Some((300.0, 150.0, 32))); + } + + /// A caller's params open the dialog with their values, and OK makes the mosaic they ask for. + #[test] + fn a_callers_params_open_the_dialog_with_their_values() { + let mut app = app_with_image(); + let params = json!({"columns": 4, "rows": 2, "width": 200, "percentages": true, "constrain": "width", "gray": true}); + app.run("ui.paramDialog", json!({"command": COMMAND, "label": "Create Object Mosaic", "params": params})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.kind, KIND); + assert_eq!( + (d.f64("width", 0.0), d.bool("percentages"), d.bool("lock"), d.str("constrain"), d.bool("gray")), + (200.0, true, true, "width".into(), true) + ); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app), Some((200.0, 100.0, 8))); + // Use Ratio given applies to the counts shown: 10 columns over 100 × 50 pt are 5 rows. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + let params = json!({"columns": 10, "rows": 3, "useRatio": true}); + app.run("ui.paramDialog", json!({"command": COMMAND, "params": params})).unwrap(); + assert_eq!(count(app.ui.dialog.as_ref().unwrap(), "rows"), 5); + // A side Use Ratio names is the side the dialog keeps: 4 rows over 100 × 50 pt are 8 columns. + let params = json!({"columns": 3, "rows": 4, "useRatio": "height"}); + app.run("ui.paramDialog", json!({"command": COMMAND, "params": params})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((count(d, "columns"), count(d, "rows"), d.str("constrain"), d.bool("lock")), (8, 4, "height".into(), false)); + app.ui.dialog = None; + // Params the command refuses open nothing and say why. + for (bad, key) in [(json!({"width": "abc"}), "width"), (json!({"constrain": "both"}), "constrain"), (json!({"widht": 200}), "widht")] { + let e = app.run("ui.paramDialog", json!({"command": COMMAND, "params": bad})).unwrap_err(); + assert!(app.ui.dialog.is_none(), "{e}"); + assert!(e.contains(key), "{e}"); + } + } + + /// `ui.dialog.set` of Resize Using Percentages shows the new size the other way, as the checkbox + /// does, so OK makes the same mosaic. Values the command refuses, set that way, are refused on OK + /// and make no mosaic. + #[test] + fn setting_fields_from_outside_keeps_the_size_or_is_refused() { + let mut app = app_with_image(); + open(&mut app, &json!({"width": 200, "height": 100})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (200.0, 200.0, true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((200.0, 100.0))); + app.run("edit.undo", json!({})).unwrap(); + for (field, value) in [("percentages", json!("yes")), ("width", json!("abc")), ("gray", json!(1))] { + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), field.into(), value); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains(field), "{field}: {e}"); + assert_eq!(mosaic(&app), None, "{field}"); + } + } + + /// The id of the image in the document. + fn image_id(app: &VectorcraftApp) -> u64 { + let mut id = None; + app.session.active().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + id = Some(n.id.0); + } + }); + id.unwrap() + } + + /// #1000: the count the dialog holds reaches the command, so a count of 3.0 makes three columns. + #[test] + fn a_count_reaches_the_command() { + let mut app = app_with_image(); + open_from_menu(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("columns".into(), json!(3.0)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| m.2), Some(30)); + } +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 3ce5455437..d50b08f97f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1128,8 +1128,8 @@ fn a_hex_code_pasted_into_the_hex_field_replaces_its_digits() { } } -/// #1000: a count typed in Object › Create Object Mosaic… reaches the command (a whole number typed -/// in a command's dialog is an integer), so the mosaic has that many columns, not the 10 × 10 grid. +/// #1000: a count set in Object › Create Object Mosaic… reaches the command, so the mosaic has that +/// many columns, not the 10 × 10 grid; Enter confirms the dialog. #[test] fn object_mosaic_makes_the_grid_typed_in_its_dialog() { let mut app = app(); @@ -1145,9 +1145,9 @@ fn object_mosaic_makes_the_grid_typed_in_its_dialog() { let entry = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Create Object Mosaic…").expect("menu item"); let (cmd, params) = crate::menus::click_target(&entry.label, entry.command.as_deref().unwrap(), &entry.params); crate::menus::invoke(&mut app, &cmd, params); - // Its first field, Columns, is focused: type 3 over it and press Enter. frame(&mut app, vec![]); - frame(&mut app, vec![egui::Event::Text("3".into())]); + app.ui.dialog.as_mut().expect("the mosaic dialog").fields.insert("columns".into(), json!(3.0)); + frame(&mut app, vec![]); let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; frame(&mut app, vec![enter]); assert!(app.ui.dialog.is_none()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 28944173dd..da7fdcc70a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -668,6 +668,16 @@ font-technology Variable Променливи Create New Swatch… Създаване на нов образец… Create New {kind} Style Създаване на нов стил за {kind} Create Object Mosaic… Създаване на обектова мозайка… + Create Object Mosaic Създаване на обектова мозайка + Current Size: Текущ размер: + New Size: Нов размер: + Tile Spacing: Разстояние между плочките: + Number of Tiles: Брой плочки: + Constrain Ratio: Ограничаване на съотношението: + Result: Резултат: + Resize Using Percentages Преоразмеряване с проценти + Delete Raster Изтриване на растерното изображение + Use Ratio Използване на съотношението Create Outlines Създаване на контур Create Path Създаване на път Create PDF layers from layers and sublayers Създаване на PDF слоеве от слоеве и подслоеве diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 01b90e5148..88530380fb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -219,6 +219,16 @@ Rasterize… Rasteriziraj… Create Gradient Mesh… Kreiraj gradijentnu mrežu… Create Object Mosaic… Kreiraj mozaik objekata… + Create Object Mosaic Kreiraj mozaik objekata + Current Size: Trenutna veličina: + New Size: Nova veličina: + Tile Spacing: Razmak između pločica: + Number of Tiles: Broj pločica: + Constrain Ratio: Ograniči omjer: + Result: Rezultat: + Resize Using Percentages Promijeni veličinu u postocima + Delete Raster Izbriši rastersku sliku + Use Ratio Koristi omjer Vector Halftone… Vektorski polutonovi… Create Trim Marks Kreiraj oznake za obrezivanje Flatten Transparency… Spljošti prozirnost… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4ddd1d5605..120a525639 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -979,6 +979,16 @@ antiAlias Sharp Nítid Create New Swatch… Crea una mostra nova… Create New {kind} Style Crea un estil de {kind} nou Create Object Mosaic… Crea un mosaic d’objectes… + Create Object Mosaic Crea un mosaic d’objectes + Current Size: Mida actual: + New Size: Mida nova: + Tile Spacing: Espaiat de les tessel·les: + Number of Tiles: Nombre de tessel·les: + Constrain Ratio: Restringeix la proporció: + Result: Resultat: + Resize Using Percentages Canvia la mida amb percentatges + Delete Raster Suprimeix la imatge ràster + Use Ratio Usa la proporció Create Outlines Crea contorns Create Path Crea un traçat Create PDF layers from layers and sublayers Crea capes de PDF a partir de capes i subcapes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 211982f086..328b60a247 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -225,6 +225,16 @@ Rasterize… Rastrovat… Create Gradient Mesh… Vytvořit přechodovou síť… Create Object Mosaic… Vytvořit mozaiku objektů… + Create Object Mosaic Vytvořit mozaiku objektů + Current Size: Aktuální velikost: + New Size: Nová velikost: + Tile Spacing: Rozestupy dlaždic: + Number of Tiles: Počet dlaždic: + Constrain Ratio: Zachovat poměr: + Result: Výsledek: + Resize Using Percentages Změnit velikost v procentech + Delete Raster Odstranit rastrový obraz + Use Ratio Použít poměr Vector Halftone… Vektorový polotón… Create Trim Marks Vytvořit značky ořezu Flatten Transparency… Sloučit průhlednost… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b3de0ae89a..65d141c988 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -212,6 +212,16 @@ Rasterize… Rasterisér… Create Gradient Mesh… Opret gradientnet… Create Object Mosaic… Opret objektmosaik… + Create Object Mosaic Opret objektmosaik + Current Size: Aktuel størrelse: + New Size: Ny størrelse: + Tile Spacing: Mellemrum mellem fliser: + Number of Tiles: Antal fliser: + Constrain Ratio: Begræns forhold: + Result: Resultat: + Resize Using Percentages Tilpas størrelse med procenter + Delete Raster Slet rasterbillede + Use Ratio Brug forhold Vector Halftone… Vektorhalvtone… Create Trim Marks Opret beskæringsmærker Flatten Transparency… Udjævn gennemsigtighed… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d0610144ef..d64a3ec160 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -661,6 +661,16 @@ font-technology Variable Variabel Create New Swatch… Neues Farbfeld erstellen… Create New {kind} Style Neues {kind}format erstellen Create Object Mosaic… Objektmosaik erstellen… + Create Object Mosaic Objektmosaik erstellen + Current Size: Aktuelle Größe: + New Size: Neue Größe: + Tile Spacing: Kachelabstand: + Number of Tiles: Anzahl der Kacheln: + Constrain Ratio: Proportionen beschränken: + Result: Ergebnis: + Resize Using Percentages Größe in Prozent ändern + Delete Raster Pixelbild löschen + Use Ratio Verhältnis verwenden Create Outlines In Pfade umwandeln Create Path Pfad erstellen Create PDF layers from layers and sublayers PDF-Ebenen aus Ebenen und Unterebenen erstellen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d03f8c6958..b2b525911b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -642,6 +642,16 @@ font-technology Variable Μεταβλητές Create New Swatch… Δημιουργία νέου δείγματος χρώματος… Create New {kind} Style Δημιουργία νέου στυλ {kind} Create Object Mosaic… Δημιουργία μωσαϊκού αντικειμένων… + Create Object Mosaic Δημιουργία μωσαϊκού αντικειμένων + Current Size: Τρέχον μέγεθος: + New Size: Νέο μέγεθος: + Tile Spacing: Απόσταση πλακιδίων: + Number of Tiles: Αριθμός πλακιδίων: + Constrain Ratio: Περιορισμός αναλογίας: + Result: Αποτέλεσμα: + Resize Using Percentages Αλλαγή μεγέθους με ποσοστά + Delete Raster Διαγραφή εικόνας εικονοστοιχείων + Use Ratio Χρήση αναλογίας Create Outlines Δημιουργία περιγραμμάτων Create Path Δημιουργία διαδρομής Create PDF layers from layers and sublayers Δημιουργία επιπέδων PDF από επίπεδα και υποεπίπεδα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3e8bd23752..df7bf676a7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -683,6 +683,16 @@ font-technology Variable Variables Create New Swatch… Crear muestra nueva… Create New {kind} Style Crear estilo de {kind} nuevo Create Object Mosaic… Crear mosaico de objetos… + Create Object Mosaic Crear mosaico de objetos + Current Size: Tamaño actual: + New Size: Tamaño nuevo: + Tile Spacing: Espaciado de teselas: + Number of Tiles: Número de teselas: + Constrain Ratio: Limitar proporción: + Result: Resultado: + Resize Using Percentages Cambiar tamaño con porcentajes + Delete Raster Eliminar imagen rasterizada + Use Ratio Usar proporción Create Outlines Crear contornos Create Path Crear trazado Create PDF layers from layers and sublayers Crear capas PDF a partir de las capas y subcapas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d408220f47..97cb15c00e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -232,6 +232,16 @@ Rasterize… Rasteroi… Create Gradient Mesh… Luo liukuväriverkko… Create Object Mosaic… Luo objektimosaiikki… + Create Object Mosaic Luo objektimosaiikki + Current Size: Nykyinen koko: + New Size: Uusi koko: + Tile Spacing: Laattojen välistys: + Number of Tiles: Laattojen määrä: + Constrain Ratio: Rajoita suhdetta: + Result: Tulos: + Resize Using Percentages Muuta kokoa prosentteina + Delete Raster Poista rasterikuva + Use Ratio Käytä suhdetta Vector Halftone… Vektorirasterointi… Create Trim Marks Luo leikkuumerkit Flatten Transparency… Litistä läpinäkyvyys… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 318bbbeb44..0c88b39ea4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -684,6 +684,16 @@ font-technology Variable Variables Create New Swatch… Créer une nuance… Create New {kind} Style Créer un style de {kind} Create Object Mosaic… Créer une mosaïque d’objets… + Create Object Mosaic Créer une mosaïque d’objets + Current Size: Taille actuelle : + New Size: Nouvelle taille : + Tile Spacing: Espacement des carreaux : + Number of Tiles: Nombre de carreaux : + Constrain Ratio: Conserver les proportions : + Result: Résultat : + Resize Using Percentages Redimensionner en pourcentage + Delete Raster Supprimer l’image pixellisée + Use Ratio Utiliser le rapport Create Outlines Vectoriser Create Path Créer un tracé Create PDF layers from layers and sublayers Créer des calques PDF à partir des calques et sous-calques diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 716d851655..672077c95d 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -783,6 +783,15 @@ Create New Swatch… નવો સ્વેચ બનાવો… Create Object Mosaic ઑબ્જેક્ટ મોઝેઇક બનાવો Create Object Mosaic… ઑબ્જેક્ટ મોઝેઇક બનાવો… + Current Size: વર્તમાન કદ: + New Size: નવું કદ: + Tile Spacing: ટાઇલ વચ્ચે અંતર: + Number of Tiles: ટાઇલની સંખ્યા: + Constrain Ratio: ગુણોત્તર જાળવો: + Result: પરિણામ: + Resize Using Percentages ટકાવારીથી કદ બદલો + Delete Raster રાસ્ટર છબી કાઢી નાખો + Use Ratio ગુણોત્તર વાપરો Create Outlines આઉટલાઇન બનાવો Create PDF layers from layers and sublayers લેયર અને સબલેયરમાંથી PDF લેયર બનાવો Create PDF-Compatible File PDF-સુસંગત ફાઇલ બનાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 78c0a9a7eb..26eebd7628 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1117,6 +1117,15 @@ antiAlias Sharp शार्प Create New Swatch… नया स्वॉच बनाएँ… Create Object Mosaic ऑब्जेक्ट मोज़ेक बनाएँ Create Object Mosaic… ऑब्जेक्ट मोज़ेक बनाएँ… + Current Size: वर्तमान साइज़: + New Size: नया साइज़: + Tile Spacing: टाइल स्पेसिंग: + Number of Tiles: टाइलों की संख्या: + Constrain Ratio: अनुपात सीमित करें: + Result: परिणाम: + Resize Using Percentages प्रतिशत से साइज़ बदलें + Delete Raster रास्टर इमेज हटाएँ + Use Ratio अनुपात इस्तेमाल करें Create Outlines आउटलाइन बनाएँ Create Path पाथ बनाएँ Create PDF layers from layers and sublayers लेयर्स और सबलेयरों से PDF लेयरें बनाएं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a1f6100b2f..8ae9f8db91 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -881,6 +881,16 @@ font-technology Variable Változó Create New Swatch… Új színminta létrehozása… Create New {kind} Style Új stílus létrehozása: {kind} Create Object Mosaic… Objektummozaik létrehozása… + Create Object Mosaic Objektummozaik létrehozása + Current Size: Jelenlegi méret: + New Size: Új méret: + Tile Spacing: Csempék térköze: + Number of Tiles: Csempék száma: + Constrain Ratio: Arány rögzítése: + Result: Eredmény: + Resize Using Percentages Átméretezés százalékban + Delete Raster Raszterkép törlése + Use Ratio Arány használata Create Outlines Átalakítás útvonallá Create Path Útvonal létrehozása Create PDF layers from layers and sublayers PDF-rétegek létrehozása a rétegekből és alrétegekből diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c7c6b956db..af0cdf56d3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -212,6 +212,16 @@ Rasterize… Rasterisasi… Create Gradient Mesh… Buat mesh gradien… Create Object Mosaic… Buat mozaik objek… + Create Object Mosaic Buat mozaik objek + Current Size: Ukuran saat ini: + New Size: Ukuran baru: + Tile Spacing: Spasi ubin: + Number of Tiles: Jumlah ubin: + Constrain Ratio: Batasi rasio: + Result: Hasil: + Resize Using Percentages Ubah ukuran dengan persentase + Delete Raster Hapus gambar raster + Use Ratio Gunakan rasio Vector Halftone… Halftone vektor… Create Trim Marks Buat tanda potong Flatten Transparency… Ratakan transparansi… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6743704785..3a0c6aba8b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -683,6 +683,16 @@ font-technology Variable Variabili Create New Swatch… Crea nuovo campione… Create New {kind} Style Crea nuovo stile {kind} Create Object Mosaic… Crea mosaico di oggetti… + Create Object Mosaic Crea mosaico di oggetti + Current Size: Dimensione attuale: + New Size: Nuova dimensione: + Tile Spacing: Spaziatura tessere: + Number of Tiles: Numero di tessere: + Constrain Ratio: Vincola proporzioni: + Result: Risultato: + Resize Using Percentages Ridimensiona in percentuale + Delete Raster Elimina immagine raster + Use Ratio Usa proporzioni Create Outlines Crea contorni Create Path Crea tracciato Create PDF layers from layers and sublayers Crea livelli PDF dai livelli e sottolivelli diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c9cdb8fcbe..6ea5212bf5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -261,6 +261,16 @@ digits Malayalam マラヤーラム数字 Rasterize… ラスタライズ… Create Gradient Mesh… グラデーションメッシュを作成… Create Object Mosaic… モザイクオブジェクトを作成… + Create Object Mosaic モザイクオブジェクトを作成 + Current Size: 現在のサイズ: + New Size: 新しいサイズ: + Tile Spacing: タイルの間隔: + Number of Tiles: タイル数: + Constrain Ratio: 比率を固定: + Result: 結果: + Resize Using Percentages パーセントでサイズを変更 + Delete Raster ラスター画像を削除 + Use Ratio 比率を使用 Vector Halftone… ベクターハーフトーン… Create Trim Marks トリムマークを作成 Flatten Transparency… 透明部分を分割・統合… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 55f726dc38..dd799eccd4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -183,6 +183,16 @@ Rasterize… რასტრირება… Create Gradient Mesh… გრადიენტული ბადის შექმნა… Create Object Mosaic… ობიექტების მოზაიკის შექმნა… + Create Object Mosaic ობიექტების მოზაიკის შექმნა + Current Size: მიმდინარე ზომა: + New Size: ახალი ზომა: + Tile Spacing: ფილებს შორის ინტერვალი: + Number of Tiles: ფილების რაოდენობა: + Constrain Ratio: პროპორციის შეზღუდვა: + Result: შედეგი: + Resize Using Percentages ზომის შეცვლა პროცენტებით + Delete Raster რასტრული გამოსახულების წაშლა + Use Ratio პროპორციის გამოყენება Vector Halftone… ვექტორული ნახევარტონი… Create Trim Marks ჭრის ნიშნების შექმნა Flatten Transparency… გამჭვირვალობის გაბრტყელება… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index abe2b4bc28..d7aff86dba 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -254,6 +254,16 @@ digits Malayalam 말라얄람어 Rasterize… 래스터화… Create Gradient Mesh… 그레이디언트 메시 만들기… Create Object Mosaic… 개체 모자이크 만들기… + Create Object Mosaic 개체 모자이크 만들기 + Current Size: 현재 크기: + New Size: 새 크기: + Tile Spacing: 타일 간격: + Number of Tiles: 타일 수: + Constrain Ratio: 비율 제한: + Result: 결과: + Resize Using Percentages 백분율로 크기 조정 + Delete Raster 래스터 이미지 삭제 + Use Ratio 비율 사용 Vector Halftone… 벡터 하프톤… Create Trim Marks 트림 마크 만들기 Flatten Transparency… 투명도 병합… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ed281382a4..8737dbfb32 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -730,6 +730,16 @@ Rasterize… Rasteriseren… Create Gradient Mesh… Verloopmesh maken… Create Object Mosaic… Objectmozaïek maken… + Create Object Mosaic Objectmozaïek maken + Current Size: Huidige grootte: + New Size: Nieuwe grootte: + Tile Spacing: Tussenruimte tegels: + Number of Tiles: Aantal tegels: + Constrain Ratio: Verhouding beperken: + Result: Resultaat: + Resize Using Percentages Grootte wijzigen met percentages + Delete Raster Rasterafbeelding verwijderen + Use Ratio Verhouding gebruiken Vector Halftone… Vectorhalftoon… Create Trim Marks Afsnijtekens maken Flatten Transparency… Transparantie afvlakken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 08e96e6a35..736f3931fe 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -189,6 +189,16 @@ Rasterize… Rasteryzuj… Create Gradient Mesh… Utwórz siatkę gradientową… Create Object Mosaic… Utwórz mozaikę obiektów… + Create Object Mosaic Utwórz mozaikę obiektów + Current Size: Bieżący rozmiar: + New Size: Nowy rozmiar: + Tile Spacing: Odstęp między kafelkami: + Number of Tiles: Liczba kafelków: + Constrain Ratio: Ogranicz proporcje: + Result: Wynik: + Resize Using Percentages Zmień rozmiar w procentach + Delete Raster Usuń obraz rastrowy + Use Ratio Użyj proporcji Vector Halftone… Półton wektorowy… Create Trim Marks Utwórz znaczniki przycięcia Flatten Transparency… Spłaszcz przezroczystość… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 79c4d9dc8e..ef6b2ffd91 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -608,6 +608,16 @@ antiAlias Sharp Nítido Create New Swatch… Criar Nova Amostra… Create New {kind} Style Criar Novo Estilo de {kind} Create Object Mosaic… Criar Mosaico de Objetos… + Create Object Mosaic Criar Mosaico de Objetos + Current Size: Tamanho atual: + New Size: Novo tamanho: + Tile Spacing: Espaçamento dos ladrilhos: + Number of Tiles: Número de ladrilhos: + Constrain Ratio: Restringir proporção: + Result: Resultado: + Resize Using Percentages Redimensionar usando porcentagens + Delete Raster Excluir imagem rasterizada + Use Ratio Usar proporção Create Outlines Criar Contornos Create PDF layers from layers and sublayers Criar camadas de PDF a partir das camadas e subcamadas Create PDF-Compatible File Criar Arquivo Compatível com PDF diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9f608618e7..00ba36c68f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -681,6 +681,16 @@ font-technology Variable Вариативные Create New Swatch… Создать новый образец… Create New {kind} Style Создать новый стиль {kind} Create Object Mosaic… Создать мозаику объектов… + Create Object Mosaic Создать мозаику объектов + Current Size: Текущий размер: + New Size: Новый размер: + Tile Spacing: Интервал между плитками: + Number of Tiles: Количество плиток: + Constrain Ratio: Сохранять пропорции: + Result: Результат: + Resize Using Percentages Изменить размер в процентах + Delete Raster Удалить растровое изображение + Use Ratio Использовать пропорции Create Outlines Создать контуры Create Path Создать контур Create PDF layers from layers and sublayers Создавать слои PDF из слоёв и подслоёв diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6156ca23d5..64f32f05d7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -670,6 +670,16 @@ font-technology Variable Variabla Create New Swatch… Skapa ny färgruta… Create New {kind} Style Skapa ny stil ({kind}) Create Object Mosaic… Skapa objektmosaik… + Create Object Mosaic Skapa objektmosaik + Current Size: Aktuell storlek: + New Size: Ny storlek: + Tile Spacing: Avstånd mellan plattor: + Number of Tiles: Antal plattor: + Constrain Ratio: Begränsa förhållande: + Result: Resultat: + Resize Using Percentages Ändra storlek med procent + Delete Raster Ta bort rasterbild + Use Ratio Använd förhållande Create Outlines Skapa konturbanor Create Path Skapa bana Create PDF layers from layers and sublayers Skapa PDF-lager från lager och underlager diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7120d44707..089c4caa82 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -662,6 +662,16 @@ font-technology Variable Değişken Create New Swatch… Yeni Renk Örneği Oluştur… Create New {kind} Style Yeni {kind} Stili Oluşturun Create Object Mosaic… Nesne Mozaiği Oluştur… + Create Object Mosaic Nesne Mozaiği Oluştur + Current Size: Geçerli Boyut: + New Size: Yeni Boyut: + Tile Spacing: Döşeme Aralığı: + Number of Tiles: Döşeme Sayısı: + Constrain Ratio: Oranı Sınırla: + Result: Sonuç: + Resize Using Percentages Yüzdelerle Yeniden Boyutlandır + Delete Raster Raster Görüntüyü Sil + Use Ratio Oranı Kullan Create Outlines Anahatlar Oluştur Create Path Yol Oluştur Create PDF layers from layers and sublayers Katmanlardan ve alt katmanlardan PDF katmanları oluşturun diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 84f296b0a6..a50cb47980 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -677,6 +677,16 @@ font-technology Variable Варіативні Create New Swatch… Створити новий зразок… Create New {kind} Style Створити новий стиль {kind} Create Object Mosaic… Створити мозаїку об’єктів… + Create Object Mosaic Створити мозаїку об’єктів + Current Size: Поточний розмір: + New Size: Новий розмір: + Tile Spacing: Інтервал між плитками: + Number of Tiles: Кількість плиток: + Constrain Ratio: Зберігати пропорції: + Result: Результат: + Resize Using Percentages Змінити розмір у відсотках + Delete Raster Видалити растрове зображення + Use Ratio Використати пропорції Create Outlines Створити контури Create Path Створити контур Create PDF layers from layers and sublayers Створювати шари PDF із шарів та підшарів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e8b9e5758f..eabdc31ae6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -782,6 +782,16 @@ font-technology Variable Biến thiên Create New Swatch… Tạo mẫu màu mới… Create New {kind} Style Tạo kiểu {kind} mới Create Object Mosaic… Tạo khảm đối tượng… + Create Object Mosaic Tạo khảm đối tượng + Current Size: Kích thước hiện tại: + New Size: Kích thước mới: + Tile Spacing: Khoảng cách ô: + Number of Tiles: Số ô: + Constrain Ratio: Ràng buộc tỷ lệ: + Result: Kết quả: + Resize Using Percentages Đổi kích thước theo phần trăm + Delete Raster Xóa ảnh raster + Use Ratio Dùng tỷ lệ Create Outlines Tạo đường bao Create Path Tạo đường dẫn Create PDF layers from layers and sublayers Tạo lớp PDF từ các lớp và lớp con diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 719968086f..b5f17c7d9d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -628,6 +628,16 @@ antiAlias Sharp 锐利 Create New Swatch… 新建色板… Create New {kind} Style 创建新的{kind}样式 Create Object Mosaic… 创建对象马赛克… + Create Object Mosaic 创建对象马赛克 + Current Size: 当前尺寸: + New Size: 新尺寸: + Tile Spacing: 拼贴间距: + Number of Tiles: 拼贴数量: + Constrain Ratio: 约束比例: + Result: 结果: + Resize Using Percentages 使用百分比调整大小 + Delete Raster 删除栅格图像 + Use Ratio 使用比例 Create Outlines 创建轮廓 Create Path 创建路径 Create PDF layers from layers and sublayers 从图层和子图层创建 PDF 图层 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 121a8b8c02..3f1dd675b0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -646,6 +646,16 @@ font-technology Variable 可變 Create New Swatch… 建立新色票… Create New {kind} Style 建立新的{kind}樣式 Create Object Mosaic… 建立物件馬賽克… + Create Object Mosaic 建立物件馬賽克 + Current Size: 目前大小: + New Size: 新大小: + Tile Spacing: 拼貼間距: + Number of Tiles: 拼貼數量: + Constrain Ratio: 限制比例: + Result: 結果: + Resize Using Percentages 使用百分比調整大小 + Delete Raster 刪除點陣圖 + Use Ratio 使用比例 Create Outlines 建立外框 Create Path 建立路徑 Create PDF layers from layers and sublayers 從圖層和子圖層建立 PDF 圖層 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7b7f7a6b21..ed5c94fbba 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -702,6 +702,10 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { + crate::dialogs::object_mosaic::open(app, p.get("params").unwrap_or(&Value::Null)) + } "ui.paramDialog" => { let cmd = s("command").unwrap_or_default(); let mut fields = p.get("params").and_then(Value::as_object).cloned().unwrap_or_default(); diff --git a/docs/mcp.md b/docs/mcp.md index 2e43c14d0e..d760baa267 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1815,12 +1815,38 @@ nothing. These Object menu commands refuse a string, a number or another value that is not true or false with `` `copy` must be true or false ``, naming the key, and change nothing: `reflectX`, `reflectY`, `random`, `copy`, -`relative`, `strokes`, `corners`, `objects` and `patterns` in `object.transformEach`; `gray` and `deleteRaster` in -`object.createObjectMosaic`; `trim` in `object.cropImage`; `allArtboards` in `object.createTrimMarks`; and `byColumn`, +`relative`, `strokes`, `corners`, `objects` and `patterns` in `object.transformEach`; `gray`, `deleteRaster` +and `percentages` in `object.createObjectMosaic`; `trim` in `object.cropImage`; `allArtboards` in `object.createTrimMarks`; and `byColumn`, `moveArtwork`, `patterns` and `lockedAndHidden` in `artboard.rearrange`. A null is read as a key left out. `object.createTrimMarks` refuses a `style` that is not a string, such as `5`, with `` `style` must be roman or japanese ``, the message it gives for a string that names no style. +Object › Create Object Mosaic… opens a dialog on the selected image +([Create a mosaic from a bitmap image](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-mosaic-from-bitmap-image.html)): +Current Size, New Size, Tile Spacing, Number of Tiles, Constrain Ratio (Width or Height), Result (Color or +Grayscale), Resize Using Percentages, Delete Raster and Use Ratio. With no image selected it does not open. OK runs +`object.createObjectMosaic` as one undo step. The command takes: + +- `percentages: true`: `width` and `height` are percentages of the image's size (a side left out is 100). +- `constrain: "width"` or `"height"`: the mosaic keeps the image's proportions. The named side's size is used and the + other side's is worked out from it, so a `height` given with `constrain: "width"` is not used. +- `useRatio: "width"` or `"height"`: the tiles are square as drawn, with the spacing taken off. The count on the named + side (`columns` for `"width"`) stays, and the other count, within 1 to 1000, is the one whose tiles come closest to + square, measured along the image's own sides when it is turned. `useRatio: true` keeps the `constrain` side, or the + width when `constrain` is left out. This rounding is VectorCraft's own rule. The dialog's Use Ratio button sets the + counts the same way. + +A `width` or `height` outside 0.1 to 1000000 (points, or percent with `percentages`) is refused with +`` `width` must be between 0.1 and 1000000 (got 0) ``. A `constrain` other than `"width"`, `"height"` or null is +refused with `` `constrain` must be one of "width", "height" or null ``, and a `useRatio` other than those, true or +false with `` `useRatio` must be one of "width", "height", true, false or null ``; the command then changes nothing. A +side that `constrain` works out as under 0.1 pt grows to 0.1 pt, and the other side grows with it. The result also gives the `columns` and `rows` the mosaic was made with, here for a 100 × 50 pt image: + +```json +{"columns": 10, "rows": 3, "useRatio": true} +→ {"id": 42, "tiles": 50, "columns": 10, "rows": 5} +``` + A whole number that is larger than the build's `usize` can hold (4294967295 on a 32-bit build, such as the `wasm32-unknown-unknown` web build) counts as larger than any index, place, byte offset or count. An index, such as a `subpath`, `anchor`, `segment`, document `index`, `artboard`, appearance `item` or `index`, gradient `stop` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c6375f3aa3..eb5428f4e2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1319,6 +1319,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Cap is on by default with continuous curved vector rims; shading uses vector gradients automatically, with sharp profile corners, uniform caps and round seam joins. The Lights list, Add Light and Delete Light manage one to ten independent colored lights; ambient is shared and visibility remains approximate ([revolve.md](revolve.md)). - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). Zig Zag spaces its ridges evenly along each segment, so lines and curves get a regular wave in Corner and Smooth (#1558). Warp › Arc (the effect and Envelope › Make with Warp) bends in the object's real proportions: a circular arc with concentric edges and no fold-over at 100%, so Arc on art that isn't square draws differently from before (#1581, fixes #1578). `effect.apply` and `effect.setParams` give an error for a misspelt or wrongly typed effect parameter instead of running the effect with its default (#1623, #1592). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). - Scribble (Effect › Stylize › Scribble…) has a Variation for each of Path Overlap, Curviness and Spacing ([Scribble options](https://helpx.adobe.com/illustrator/using/creating-sketches-mosaics.html)) (`overlapVariation`, `curvinessVariation`, `spacingVariation`), shown in its dialog and in the Appearance panel. A Scribble saved with the earlier single `variation` reads it as the Path Overlap and Spacing variations and draws as before. The angle is stored above -180° and up to 180°, so 270° is stored as -90°. + - Object › Create Object Mosaic… opens its own dialog on the selected image ([Create a mosaic from a bitmap image](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-mosaic-from-bitmap-image.html)): Current Size, New Size, Tile Spacing, Number of Tiles, Constrain Ratio (Width or Height), Result (Color or Grayscale), Resize Using Percentages, Delete Raster and Use Ratio. `object.createObjectMosaic` takes `percentages`, `constrain` and `useRatio`; Use Ratio keeps the constrained side's count and picks the other count whose tiles, spacing taken off, come closest to square, VectorCraft's own rule (`dialogs::object_mosaic::tests`, `tests::object_mosaic_resizes_by_percentages_constrains_the_ratio_and_squares_the_tiles`). - **Simplify feedback and component selection (#1272):** the existing tolerance dialog previews from the original interaction snapshot and shows original/new anchor counts. Preview off and Cancel restore the document and selection; OK is one Undo. A refit or Add Anchor Points clears component indexes only on paths whose geometry changes, keeping their objects selected whole and unchanged paths' components intact. Engine and real-egui frame regressions cover document/selection restoration and grouped paths. Public references: [Simplify benefits](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/simplify-path-benefits.html) and [advanced options](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/simplify-paths-advanced-options-overview.html). Nearly unchanged appearance is expected when reducing points. The checklist is partial, without raising scores. From 95a237e57599f0b9aefa200553822c1955826933 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:14:51 -0800 Subject: [PATCH 02/12] Object Mosaic: a constrained size under the minimum grows in proportion With Constrain Ratio on, OK leaves out the side it sets while that side holds the size Constrain Ratio gave it, so the command works it out from the kept side and grows both in proportion to its 0.1 pt minimum. A kept width of 0.1 pt over a 100 x 50 pt image now makes a 0.2 x 0.1 pt mosaic instead of refusing the 0.05 pt height. Another value set on that side is still passed on for the command to check. Resize Using Percentages keeps the fields and the mode as they are when the size would fall outside 0.1 to 1000000 the other way, and the dialog shows the limit. The dialog also shows why Use Ratio was refused. Docs: docs/target-app-parity.md (image tools row). --- crates/ui-egui/src/dialogs/object_mosaic.rs | 112 +++++++++++++++++--- docs/target-app-parity.md | 2 +- 2 files changed, 97 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index ed8b060a92..ca699569be 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -13,6 +13,7 @@ use vectorcraft_doc::NodeKind; use super::{DialogSpec, form, run_and_close}; use crate::state::Dialog; +use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; /// The dialog kind of Create Object Mosaic. @@ -77,29 +78,51 @@ fn keeps_width(d: &Dialog) -> bool { d.str("constrain") != "height" } +/// With Constrain Ratio on, the size field that follows the kept side. +fn follower(d: &Dialog) -> Option<&'static str> { + d.bool("lock").then(|| if keeps_width(d) { "height" } else { "width" }) +} + +/// The new sizes the command takes, in points or percentages (`object.createObjectMosaic`). +const SIZE_RANGE: std::ops::RangeInclusive = 0.1..=1.0e6; + /// With Constrain Ratio on, the side that follows set from the side that leads, in the image's /// proportions. fn follow_ratio(d: &mut Dialog) { - if !d.bool("lock") { - return; - } - let (iw, ih) = image(d); - let pct = d.bool("percentages"); - if keeps_width(d) { - let w = d.f64("width", 0.0); - d.fields.insert("height".into(), json!(if pct { w } else { w * ih / iw })); - } else { - let h = d.f64("height", 0.0); - d.fields.insert("width".into(), json!(if pct { h } else { h * iw / ih })); + if let Some((key, v)) = derived(d) { + d.fields.insert(key.into(), json!(v)); } } +/// With Constrain Ratio on, the side that follows and the size it gets from the side that leads. +fn derived(d: &Dialog) -> Option<(&'static str, f64)> { + let key = follower(d)?; + let (iw, ih) = image(d); + let pct = d.bool("percentages"); + Some(if key == "height" { + let w = d.f64("width", 0.0); + (key, if pct { w } else { w * ih / iw }) + } else { + let h = d.f64("height", 0.0); + (key, if pct { h } else { h * iw / ih }) + }) +} + /// Resize Using Percentages turned on or off: the new size shown the other way, so it stays the -/// same size. +/// same size. When a size the command takes (all but the side Constrain Ratio sets) falls outside +/// what the command accepts the other way, the fields and the mode stay as they are and the dialog +/// shows the limit. fn switch_percentages(d: &mut Dialog, on: bool) { let (iw, ih) = image(d); let (w, h) = (d.f64("width", iw), d.f64("height", ih)); let (w, h) = if on { (w / iw * 100.0, h / ih * 100.0) } else { (iw * w / 100.0, ih * h / 100.0) }; + let skip = follower(d); + if let Some((key, v)) = [("width", w), ("height", h)].into_iter().find(|(k, v)| skip != Some(*k) && !SIZE_RANGE.contains(v)) { + let why = format!("`{key}` must be between {} and {} (got {v})", SIZE_RANGE.start(), SIZE_RANGE.end()); + d.fields.insert(form::REFUSED.into(), json!(why)); + return; + } + d.fields.remove(form::REFUSED); d.fields.insert("width".into(), json!(w)); d.fields.insert("height".into(), json!(h)); d.fields.insert("percentages".into(), json!(on)); @@ -125,6 +148,7 @@ fn use_ratio(app: &VectorcraftApp, d: &mut Dialog) { p["useRatio"] = json!(if keeps_width(d) { "width" } else { "height" }); match vectorcraft_engine::cmd::mosaic_counts(&app.session, &p) { Ok((cols, rows)) => { + d.fields.remove(form::REFUSED); d.fields.insert("columns".into(), json!(cols)); d.fields.insert("rows".into(), json!(rows)); } @@ -149,15 +173,24 @@ fn switch(d: &Dialog, key: &str) -> Value { d.fields.get(key).cloned().unwrap_or(json!(false)) } -/// `object.createObjectMosaic` parameters from the fields. +/// `object.createObjectMosaic` parameters from the fields. With Constrain Ratio on, the side it +/// sets is left out while it holds the size Constrain Ratio gives it: the command works it out from +/// the kept side and grows both in proportion to its 0.1 pt minimum. Any other value set on that +/// side is passed on for the command to check. fn params(d: &Dialog) -> Value { - json!({ + let mut p = json!({ "columns": number(d, "columns", 10.0), "rows": number(d, "rows", 10.0), "width": number(d, "width", 100.0), "height": number(d, "height", 100.0), "percentages": switch(d, "percentages"), "constrain": if d.bool("lock") { json!(if keeps_width(d) { "width" } else { "height" }) } else { Value::Null }, "spacingX": number(d, "spacingX", 0.0), "spacingY": number(d, "spacingY", 0.0), "gray": switch(d, "gray"), "deleteRaster": switch(d, "deleteRaster"), - }) + }); + if let (Some((key, v)), Some(o)) = (derived(d), p.as_object_mut()) + && o.get(key).and_then(Value::as_f64).is_some_and(|x| x == v) + { + o.remove(key); + } + p } /// A Width and a Height field for `keys`: lengths in `unit` of at least `least` points, or @@ -187,7 +220,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::dim_name(ui, &unit.format(ih)); }); ui.add_space(4.0); - let follows = d.bool("lock").then(|| if keeps_width(d) { "height" } else { "width" }); + let follows = follower(d); let pct = d.bool("percentages"); widgets::label_row(ui, tl!("New Size:"), LABEL_W, |ui| pair(ui, d, ["width", "height"], unit, (pct, 0.1), follows)); follow_ratio(d); @@ -233,6 +266,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "deleteRaster", tl!("Delete Raster")); }); }); + if let Some(why) = d.fields.get(form::REFUSED).and_then(Value::as_str) { + ui.add_space(4.0); + ui.add(egui::Label::new(egui::RichText::new(why).color(Tokens::get(ui.ctx()).warning)).wrap()); + } ui.add_space(6.0); if widgets::flat_button(ui, tl!("Use Ratio"), 96.0).clicked() { use_ratio(app, d); @@ -389,6 +426,23 @@ mod tests { assert_eq!(mosaic(&app), Some((300.0, 150.0, 32))); } + /// With Constrain Ratio on, a kept width of 0.1 pt over a 100 × 50 pt image sets a height of + /// 0.05 pt, under the command's minimum: OK makes the 0.2 × 0.1 pt mosaic the command grows it to. + #[test] + fn a_constrained_size_under_the_minimum_grows_in_proportion() { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lock".into(), json!(true)); + d.fields.insert("width".into(), json!(0.1)); + frame(&mut app, &ctx); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("height", 0.0), 0.05, "height follows the width"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((0.2, 0.1))); + } + /// A caller's params open the dialog with their values, and OK makes the mosaic they ask for. #[test] fn a_callers_params_open_the_dialog_with_their_values() { @@ -435,6 +489,23 @@ mod tests { crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((200.0, 100.0))); app.run("edit.undo", json!({})).unwrap(); + // 0.1 × 0.1 pt of a 1000 × 500 pt image are 0.01% × 0.02%, under the command's 0.1%: the + // points stay, with the limit shown, and OK makes that size. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + app.run("object.scale", json!({"sx": 1000, "sy": 1000})).unwrap(); + open(&mut app, &json!({"width": 0.1, "height": 0.1})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (0.1, 0.1, false)); + assert!(d.str(form::REFUSED).contains("`width` must be between 0.1"), "{}", d.str(form::REFUSED)); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|t| t.contains("must be between")), "the limit is shown: {texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((0.1, 0.1))); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); for (field, value) in [("percentages", json!("yes")), ("width", json!("abc")), ("gray", json!(1))] { app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); open(&mut app, &json!({})).unwrap(); @@ -443,6 +514,15 @@ mod tests { assert!(e.contains(field), "{field}: {e}"); assert_eq!(mosaic(&app), None, "{field}"); } + // With Constrain Ratio on, a value the command refuses, set on the side it sets, is refused too. + for value in [json!("abc"), json!(0)] { + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "height".into(), value.clone()); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{value}: {e}"); + assert_eq!(mosaic(&app), None, "{value}"); + } } /// The id of the image in the document. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eb5428f4e2..60ea6baab7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -246,7 +246,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | +| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354); materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | From 3183d77489a619e4ececebe32c5768267fbe88a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:12:06 -0800 Subject: [PATCH 03/12] Object Mosaic: a refused size set on the constrained side stays for OK to report A new width or height that ui.dialog.set gives and the command refuses (not a number, or outside 0.1 to 1000000) now stays in its field, also on the side Constrain Ratio sets, until a size the command takes replaces it. Before, the next frame replaced it with the size worked out from the kept side, so OK made a mosaic instead of reporting it. --- crates/ui-egui/src/dialogs.rs | 4 ++ crates/ui-egui/src/dialogs/object_mosaic.rs | 59 +++++++++++++++++++-- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e05da0a333..ee57b8010a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -601,10 +601,14 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { return; } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); + let mosaic = (d.kind == object_mosaic::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { dxf_options::note_set(d, &field); } + if let Some(field) = mosaic { + object_mosaic::note_set(d, &field); + } } /// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index ca699569be..1ab1262952 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -87,10 +87,41 @@ fn follower(d: &Dialog) -> Option<&'static str> { const SIZE_RANGE: std::ops::RangeInclusive = 0.1..=1.0e6; /// With Constrain Ratio on, the side that follows set from the side that leads, in the image's -/// proportions. +/// proportions. A size `ui.dialog.set` gave the following side that the command refuses stays, +/// for OK to report. fn follow_ratio(d: &mut Dialog) { - if let Some((key, v)) = derived(d) { - d.fields.insert(key.into(), json!(v)); + let Some((key, v)) = derived(d) else { return }; + if d.bool(&kept(key)) { + if !takes(d, key) { + return; + } + d.fields.remove(&kept(key)); + } + d.fields.insert(key.into(), json!(v)); +} + +/// The field that is true while size field `key` holds a value `ui.dialog.set` gave and the +/// command refuses. +fn kept(key: &str) -> String { + format!("__kept.{key}") +} + +/// Whether the command takes size field `key` as it is: a number from 0.1 to 1,000,000. +fn takes(d: &Dialog, key: &str) -> bool { + number(d, key, 0.0).as_f64().is_some_and(|x| SIZE_RANGE.contains(&x)) +} + +/// `ui.dialog.set` of `field`: a new size the command refuses (not a number, or outside 0.1 to +/// 1,000,000) stays in its field while it is refused, also on the side Constrain Ratio sets, instead +/// of being replaced by the size worked out from the kept side. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if !matches!(field, "width" | "height") { + return; + } + if takes(d, field) { + d.fields.remove(&kept(field)); + } else { + d.fields.insert(kept(field), json!(true)); } } @@ -514,15 +545,35 @@ mod tests { assert!(e.contains(field), "{field}: {e}"); assert_eq!(mosaic(&app), None, "{field}"); } - // With Constrain Ratio on, a value the command refuses, set on the side it sets, is refused too. + // With Constrain Ratio on, a value the command refuses, set on the side it sets, is refused + // too, also after a frame. for value in [json!("abc"), json!(0)] { app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); open(&mut app, &json!({"constrain": "width"})).unwrap(); crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "height".into(), value.clone()); + frame(&mut app, &ctx); let e = crate::dialogs::confirm(&mut app).unwrap_err(); assert!(e.contains("height"), "{value}: {e}"); assert_eq!(mosaic(&app), None, "{value}"); } + // Once that side holds a size the command takes, Constrain Ratio sets it again. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for (field, value) in [("height", json!(0)), ("lock", json!(false)), ("height", json!(80)), ("lock", json!(true))] { + crate::dialogs::set_field(d, field.into(), value); + } + frame(&mut app, &ctx); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("height", 0.0), 50.0); + // A refused height stays while a refused width is set and then corrected. + let d = app.ui.dialog.as_mut().unwrap(); + for (field, value) in [("height", json!(0)), ("width", json!(0)), ("width", json!(100))] { + crate::dialogs::set_field(d, field.into(), value); + } + frame(&mut app, &ctx); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{e}"); + assert_eq!(mosaic(&app), None); } /// The id of the image in the document. From 2242af85f7a8f40e01578f24c028e046f0e5f73f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:57:19 -0800 Subject: [PATCH 04/12] Object Mosaic: a size that is not a number, or a refused height, stays for OK to report Resize Using Percentages no longer replaces a width or height that is not a number with one converted from the image's size: the fields and the mode stay and the dialog shows why. With Constrain Ratio on, a refused size set on the constrained side is passed to the command even when it equals the size worked out from the kept side, so OK reports it. --- crates/ui-egui/src/dialogs/object_mosaic.rs | 49 ++++++++++++++++++--- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 1ab1262952..680ebd4d95 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -140,12 +140,19 @@ fn derived(d: &Dialog) -> Option<(&'static str, f64)> { } /// Resize Using Percentages turned on or off: the new size shown the other way, so it stays the -/// same size. When a size the command takes (all but the side Constrain Ratio sets) falls outside -/// what the command accepts the other way, the fields and the mode stay as they are and the dialog -/// shows the limit. +/// same size. When a size field does not hold a number, or a size the command takes (all but the +/// side Constrain Ratio sets) falls outside what the command accepts the other way, the fields and +/// the mode stay as they are and the dialog shows why. fn switch_percentages(d: &mut Dialog, on: bool) { let (iw, ih) = image(d); - let (w, h) = (d.f64("width", iw), d.f64("height", ih)); + let size = |key: &str| number(d, key, 100.0).as_f64().ok_or_else(|| format!("`{key}` must be a number (got {})", d.str(key))); + let (w, h) = match (size("width"), size("height")) { + (Ok(w), Ok(h)) => (w, h), + (Err(why), _) | (_, Err(why)) => { + d.fields.insert(form::REFUSED.into(), json!(why)); + return; + } + }; let (w, h) = if on { (w / iw * 100.0, h / ih * 100.0) } else { (iw * w / 100.0, ih * h / 100.0) }; let skip = follower(d); if let Some((key, v)) = [("width", w), ("height", h)].into_iter().find(|(k, v)| skip != Some(*k) && !SIZE_RANGE.contains(v)) { @@ -207,7 +214,8 @@ fn switch(d: &Dialog, key: &str) -> Value { /// `object.createObjectMosaic` parameters from the fields. With Constrain Ratio on, the side it /// sets is left out while it holds the size Constrain Ratio gives it: the command works it out from /// the kept side and grows both in proportion to its 0.1 pt minimum. Any other value set on that -/// side is passed on for the command to check. +/// side, and a refused value `ui.dialog.set` gave it even when it equals that size, is passed on for +/// the command to check. fn params(d: &Dialog) -> Value { let mut p = json!({ "columns": number(d, "columns", 10.0), "rows": number(d, "rows", 10.0), @@ -217,6 +225,7 @@ fn params(d: &Dialog) -> Value { "gray": switch(d, "gray"), "deleteRaster": switch(d, "deleteRaster"), }); if let (Some((key, v)), Some(o)) = (derived(d), p.as_object_mut()) + && !d.bool(&kept(key)) && o.get(key).and_then(Value::as_f64).is_some_and(|x| x == v) { o.remove(key); @@ -576,6 +585,36 @@ mod tests { assert_eq!(mosaic(&app), None); } + /// A width `ui.dialog.set` gave that is not a number stays when Resize Using Percentages is set, + /// with the mode unchanged and the reason shown, and OK refuses it. + #[test] + fn a_size_that_is_not_a_number_stays_when_percentages_switch() { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!("abc")); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.str("width"), d.bool("percentages")), ("abc".into(), false)); + assert!(d.str(form::REFUSED).contains("`width` must be a number"), "{}", d.str(form::REFUSED)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("width"), "{e}"); + assert_eq!(mosaic(&app), None); + } + + /// With Constrain Ratio on, a refused height `ui.dialog.set` gave is refused on OK even when it + /// equals the size Constrain Ratio works out from the width (0.05 pt from 0.1 pt over 100 × 50 pt). + #[test] + fn a_refused_height_equal_to_the_constrained_size_is_refused() { + let mut app = app_with_image(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!(0.1)); + crate::dialogs::set_field(d, "height".into(), json!(0.05)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{e}"); + assert_eq!(mosaic(&app), None); + } + /// The id of the image in the document. fn image_id(app: &VectorcraftApp) -> u64 { let mut id = None; From 69410d99d7a6b1e46923029b53e40dc0c4d2727c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:31:45 -0800 Subject: [PATCH 05/12] Object Mosaic: a constrained size above 1000000 pt shrinks in proportion - With Constrain Ratio on, a side worked out above 1000000 pt shrinks to 1000000 pt and the other side shrinks with it, as a side under 0.1 pt grows. An image more than 10000000 times wider than tall (or taller than wide) leaves no such size, and the call is refused with an error. - A percentage typed in New Size is kept at 1000000, the most the command takes. - The #1000 test types the count into Number of Tiles again. - docs/mcp.md says a size given for the side Constrain Ratio works out is still checked, and the new lines are wrapped like the paragraph. --- crates/engine/src/cmd/menucmds.rs | 11 +++-- crates/engine/src/tests.rs | 10 +++++ crates/ui-egui/src/dialogs/object_mosaic.rs | 45 +++++++++++++++++++-- crates/ui-egui/src/dialogs/tests.rs | 26 ++++++++++-- docs/mcp.md | 15 +++++-- 5 files changed, 94 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 41fc1cf2fe..606cd28618 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Create Object Mosaic…", ["Object"], None, - "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles, columns, rows}", + "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}", has_image, object_mosaic ), @@ -962,10 +962,15 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result { Some(false) => nw = nh * bw / bh, None => {} } - // A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. + // A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. A side + // Constrain Ratio works out above 1,000,000 pt shrinks to 1,000,000 pt, the other with it. let (nw, nh) = match constrain { Some(_) => { - let k = (0.1 / nw.min(nh)).max(1.0); + let k = (0.1 / nw.min(nh)).max(1.0).min(1_000_000.0 / nw.max(nh)); + // Proportions over 10,000,000 to 1 leave no size with both sides within the range. + if nw.min(nh) * k < 0.1 * (1.0 - 1e-9) { + return Err(bad(C, "the image's proportions leave no size with both sides between 0.1 and 1000000 pt")); + } (nw * k, nh * k) } None => (nw.max(0.1), nh.max(0.1)), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index df9fea654d..15023df3ab 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4079,6 +4079,14 @@ fn object_mosaic_resizes_by_percentages_constrains_the_ratio_and_squares_the_til // A size under 0.1 pt grows in proportion while Constrain Ratio keeps it. let (w, h, ..) = mosaic_size(&mut s, json!({"width": 0.1, "constrain": "width"})); assert!((w - 0.2).abs() < 1e-6 && (h - 0.1).abs() < 1e-6, "{w} × {h}"); + // A side Constrain Ratio works out above 1,000,000 pt shrinks to it, in proportion: a height of + // 1,000,000 pt over the 100 × 50 pt image would need a width of 2,000,000 pt. + assert_eq!(mosaic_size(&mut s, json!({"height": 1e6, "constrain": "height"})), (1e6, 5e5, json!(10), json!(10))); + // An image 20,000,000 times wider than it is tall has no such size: the call is refused. + s.execute("object.scale", &json!({"sx": 1, "sy": 1e-7})).unwrap(); + let r = s.execute("object.createObjectMosaic", &json!({"width": 1e6, "constrain": "width"})); + let msg = "the image's proportions leave no size with both sides between 0.1 and 1000000 pt"; + assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{r:?}"); } /// Use Ratio squares the tiles as drawn: with 4 pt between columns, 10 columns of 10 pt cells draw 6 pt wide, so the @@ -4137,6 +4145,8 @@ fn object_mosaic_refuses_a_bad_ratio_side_size_or_switch() { (json!({"width": 0}), "`width` must be between 0.1 and 1000000 (got 0)"), (json!({"height": -5, "percentages": true}), "`height` must be between 0.1 and 1000000 (got -5)"), (json!({"width": 2e6, "percentages": true}), "`width` must be between 0.1 and 1000000 (got 2000000)"), + // A side Constrain Ratio works out is not used, but a size given for it is still checked. + (json!({"width": 200, "height": 0, "constrain": "width"}), "`height` must be between 0.1 and 1000000 (got 0)"), (json!({"useRatio": "true"}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), (json!({"useRatio": 1}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), (json!({"percentages": 1}), "`percentages` must be true or false"), diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 680ebd4d95..313751320a 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -1,4 +1,4 @@ -//! Object → Create Object Mosaic: the selected image's Current Size, the mosaic's New Size, Tile +//! Object › Create Object Mosaic…: the selected image's Current Size, the mosaic's New Size, Tile //! Spacing and Number of Tiles, Constrain Ratio (Width or Height), Result (Color or Grayscale), //! Resize Using Percentages, Delete Raster and Use Ratio. OK runs `object.createObjectMosaic` as one //! undo step. @@ -234,14 +234,14 @@ fn params(d: &Dialog) -> Value { } /// A Width and a Height field for `keys`: lengths in `unit` of at least `least` points, or -/// percentages with `pct`. With `follows`, the field of that key is grayed (Constrain Ratio sets it). +/// percentages with `pct`, up to 1,000,000. With `follows`, the field of that key is grayed (Constrain Ratio sets it). fn pair(ui: &mut egui::Ui, d: &mut Dialog, keys: [&str; 2], unit: vectorcraft_doc::Unit, (pct, least): (bool, f64), follows: Option<&str>) { for (key, label) in keys.into_iter().zip([tl!("Width:"), tl!("Height:")]) { widgets::dim_label(ui, label); ui.add_enabled_ui(follows != Some(key), |ui| { if pct { if let Some(v) = widgets::spin_plain(ui, ("mosaic", key), d.f64(key, 100.0), "%", 2, FIELD_W, 1.0, 0.1, &[]) { - d.fields.insert(key.into(), json!(v)); + d.fields.insert(key.into(), json!(v.min(*SIZE_RANGE.end()))); } } else { form::length_within(ui, d, key, unit, FIELD_W, Some(least..=1.0e6)); @@ -615,6 +615,45 @@ mod tests { assert_eq!(mosaic(&app), None); } + /// A percentage typed in New Size above 1,000,000 is kept at 1,000,000, the most the command + /// takes, so Enter makes the mosaic: 1,000,000% of the 100 pt width is 1,000,000 pt. + #[test] + fn a_typed_percentage_stays_within_what_the_command_takes() { + let mut app = app_with_image(); + open(&mut app, &json!({"percentages": true})).unwrap(); + let ctx = context(); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|s| { + if let egui::epaint::Shape::Text(t) = &s.shape { + Some((t.galley.text().to_string(), t.visual_bounding_rect().center())) + } else { + None + } + }) + .collect::>() + }; + run(&mut app, vec![]); + let texts = run(&mut app, vec![]); + // New Size's Width field comes right after the row's Width caption. + let row = texts.iter().position(|(t, _)| t == "New Size:").expect("the New Size row"); + let width = texts[row..].iter().position(|(t, _)| t == "Width:").and_then(|i| texts.get(row + i + 1)); + assert_eq!(width.map(|(t, _)| t.as_str()), Some("100%"), "{texts:?}"); + let at = width.map(|(_, p)| *p).unwrap(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); + run(&mut app, vec![press(false)]); + run(&mut app, vec![]); + run(&mut app, vec![egui::Event::Text("2000000".into())]); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + run(&mut app, vec![enter]); + assert!(app.ui.dialog.is_none(), "Enter makes the mosaic: {:?}", app.ui.dialog.as_ref().map(|d| d.str(form::REFUSED))); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((1e6, 50.0))); + } + /// The id of the image in the document. fn image_id(app: &VectorcraftApp) -> u64 { let mut id = None; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index d50b08f97f..85f6a14baa 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1128,8 +1128,8 @@ fn a_hex_code_pasted_into_the_hex_field_replaces_its_digits() { } } -/// #1000: a count set in Object › Create Object Mosaic… reaches the command, so the mosaic has that -/// many columns, not the 10 × 10 grid; Enter confirms the dialog. +/// #1000: a count typed in Object › Create Object Mosaic…'s Number of Tiles reaches the command, so +/// the mosaic has that many columns, not the 10 × 10 grid; Enter confirms the dialog. #[test] fn object_mosaic_makes_the_grid_typed_in_its_dialog() { let mut app = app(); @@ -1138,16 +1138,36 @@ fn object_mosaic_makes_the_grid_typed_in_its_dialog() { let ctx = egui::Context::default(); theme::install_fonts(&ctx); theme::apply(&ctx, Default::default()); + // A frame → the texts painted, with their centers. let frame = |app: &mut VectorcraftApp, events: Vec| { let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx())); out.textures_delta.clear(); + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect().center())), + _ => {} + } + } + let mut texts = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + texts }; let entry = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Create Object Mosaic…").expect("menu item"); let (cmd, params) = crate::menus::click_target(&entry.label, entry.command.as_deref().unwrap(), &entry.params); crate::menus::invoke(&mut app, &cmd, params); frame(&mut app, vec![]); - app.ui.dialog.as_mut().expect("the mosaic dialog").fields.insert("columns".into(), json!(3.0)); + let texts = frame(&mut app, vec![]); + // Number of Tiles' Width field comes right after the row's Width caption. + let row = texts.iter().position(|(t, _)| t == "Number of Tiles:").expect("the Number of Tiles row"); + let columns = texts[row..].iter().position(|(t, _)| t == "Width:").and_then(|i| texts.get(row + i + 1)); + assert_eq!(columns.map(|(t, _)| t.as_str()), Some("10"), "{texts:?}"); + let at = columns.map(|(_, p)| *p).unwrap(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(&mut app, vec![press(false)]); frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text("3".into())]); let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; frame(&mut app, vec![enter]); assert!(app.ui.dialog.is_none()); diff --git a/docs/mcp.md b/docs/mcp.md index 32acf6084a..7c00e1ca06 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1882,8 +1882,9 @@ nothing. These Object menu commands refuse a string, a number or another value that is not true or false with `` `copy` must be true or false ``, naming the key, and change nothing: `reflectX`, `reflectY`, `random`, `copy`, -`relative`, `strokes`, `corners`, `objects` and `patterns` in `object.transformEach`; `gray`, `deleteRaster` -and `percentages` in `object.createObjectMosaic`; `trim` in `object.cropImage`; `allArtboards` in `object.createTrimMarks`; and `byColumn`, +`relative`, `strokes`, `corners`, `objects` and `patterns` in `object.transformEach`; `gray`, `deleteRaster` and +`percentages` in `object.createObjectMosaic`; `trim` in `object.cropImage`; `allArtboards` in +`object.createTrimMarks`; and `byColumn`, `moveArtwork`, `patterns` and `lockedAndHidden` in `artboard.rearrange`. A null is read as a key left out. `object.createTrimMarks` refuses a `style` that is not a string, such as `5`, with `` `style` must be roman or japanese ``, the message it gives for a string that names no style. @@ -1896,7 +1897,8 @@ Grayscale), Resize Using Percentages, Delete Raster and Use Ratio. With no image - `percentages: true`: `width` and `height` are percentages of the image's size (a side left out is 100). - `constrain: "width"` or `"height"`: the mosaic keeps the image's proportions. The named side's size is used and the - other side's is worked out from it, so a `height` given with `constrain: "width"` is not used. + other side's is worked out from it, so a `height` given with `constrain: "width"` is not used. It is still checked + against the range below. - `useRatio: "width"` or `"height"`: the tiles are square as drawn, with the spacing taken off. The count on the named side (`columns` for `"width"`) stays, and the other count, within 1 to 1000, is the one whose tiles come closest to square, measured along the image's own sides when it is turned. `useRatio: true` keeps the `constrain` side, or the @@ -1907,7 +1909,12 @@ A `width` or `height` outside 0.1 to 1000000 (points, or percent with `percentag `` `width` must be between 0.1 and 1000000 (got 0) ``. A `constrain` other than `"width"`, `"height"` or null is refused with `` `constrain` must be one of "width", "height" or null ``, and a `useRatio` other than those, true or false with `` `useRatio` must be one of "width", "height", true, false or null ``; the command then changes nothing. A -side that `constrain` works out as under 0.1 pt grows to 0.1 pt, and the other side grows with it. The result also gives the `columns` and `rows` the mosaic was made with, here for a 100 × 50 pt image: +side that `constrain` works out as under 0.1 pt grows to 0.1 pt, and the other side grows with it. A side that +`constrain` works out as over 1000000 pt shrinks to 1000000 pt, and the other side shrinks with it. With `constrain` +on an image more than 10000000 times wider than tall (or taller than wide), no size keeps both sides in the range, and +the call is refused with `` the image's proportions leave no size with both sides between 0.1 and 1000000 pt ``. + +The result also gives the `columns` and `rows` the mosaic was made with, here for a 100 × 50 pt image: ```json {"columns": 10, "rows": 3, "useRatio": true} From 176db2d09cabbc7600025d8f52c32982880575b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 05:10:33 -0800 Subject: [PATCH 06/12] Object Mosaic: true or false replaces a refused percentages value After ui.dialog.set gave Resize Using Percentages a value that is not true or false, setting false (or setting true while the sizes were already in percentages) left the refused value in place, so OK kept failing. The dialog now remembers the mode the sizes were in while such a value is set: the same mode stores the boolean and keeps the sizes, and the other mode shows the sizes the other way, as the checkbox does. Null is read as false, as the command reads it, so percentage sizes are converted to points. --- crates/ui-egui/src/dialogs/object_mosaic.rs | 57 ++++++++++++++++++--- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 313751320a..bc7ebdbbfe 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -129,7 +129,7 @@ pub(super) fn note_set(d: &mut Dialog, field: &str) { fn derived(d: &Dialog) -> Option<(&'static str, f64)> { let key = follower(d)?; let (iw, ih) = image(d); - let pct = d.bool("percentages"); + let pct = in_percentages(d); Some(if key == "height" { let w = d.f64("width", 0.0); (key, if pct { w } else { w * ih / iw }) @@ -161,18 +161,36 @@ fn switch_percentages(d: &mut Dialog, on: bool) { return; } d.fields.remove(form::REFUSED); + d.fields.remove(&kept("percentages")); d.fields.insert("width".into(), json!(w)); d.fields.insert("height".into(), json!(h)); d.fields.insert("percentages".into(), json!(on)); } -/// `ui.dialog.set` of `percentages`: true or false switches the new size as the checkbox does; -/// another value is kept as it is, and the command refuses it on OK. +/// Whether the new size fields hold percentages: Resize Using Percentages, or while that field holds +/// a value that is not true or false, the mode it held before that value was set. +fn in_percentages(d: &Dialog) -> bool { + match d.fields.get("percentages") { + Some(Value::Bool(on)) => *on, + Some(_) => d.bool(&kept("percentages")), + None => false, + } +} + +/// `ui.dialog.set` of `percentages`: true or false switches the new size as the checkbox does, and +/// replaces a value that is not true or false; null is false. Another value is kept as it is, and +/// the command refuses it on OK. pub(super) fn set_percentages(d: &mut Dialog, value: &Value) { - match value.as_bool() { - Some(on) if on != d.bool("percentages") => switch_percentages(d, on), - Some(_) => {} + let mode = in_percentages(d); + // The command reads null as the field left out, which is off. + match if value.is_null() { Some(false) } else { value.as_bool() } { + Some(on) if on != mode => switch_percentages(d, on), + Some(on) => { + d.fields.remove(&kept("percentages")); + d.fields.insert("percentages".into(), json!(on)); + } None => { + d.fields.insert(kept("percentages"), json!(mode)); d.fields.insert("percentages".into(), value.clone()); } } @@ -261,7 +279,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); ui.add_space(4.0); let follows = follower(d); - let pct = d.bool("percentages"); + let pct = in_percentages(d); widgets::label_row(ui, tl!("New Size:"), LABEL_W, |ui| pair(ui, d, ["width", "height"], unit, (pct, 0.1), follows)); follow_ratio(d); ui.add_space(4.0); @@ -601,6 +619,31 @@ mod tests { assert_eq!(mosaic(&app), None); } + /// True or false set after a Resize Using Percentages value the command refuses replaces it: the + /// same mode as before keeps the sizes, and the other mode shows them the other way. Null is + /// false, as the command reads it. OK then makes the mosaic. + #[test] + fn true_or_false_replaces_a_refused_percentages_value() { + let pct = json!({"percentages": true, "width": 50, "height": 50}); + for (given, sets, size) in [ + (json!({}), vec![json!("yes"), json!(false)], (100.0, 50.0)), + (pct.clone(), vec![json!("yes"), json!(false)], (50.0, 25.0)), + (pct.clone(), vec![Value::Null], (50.0, 25.0)), + (pct, vec![json!("yes"), Value::Null], (50.0, 25.0)), + ] { + let mut app = app_with_image(); + open(&mut app, &given).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for value in sets { + crate::dialogs::set_field(d, "percentages".into(), value); + } + assert_eq!(d.fields.get("percentages"), Some(&json!(false)), "{given}"); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), size, "{given}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some(size), "{given}"); + } + } + /// With Constrain Ratio on, a refused height `ui.dialog.set` gave is refused on OK even when it /// equals the size Constrain Ratio works out from the width (0.05 pt from 0.1 pt over 100 × 50 pt). #[test] From e91116e0bfba872eb69e03116edd81aefaea0545 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 06:00:08 -0800 Subject: [PATCH 07/12] Object Mosaic: percentages convert against the image's current size The dialog reads the selected image's size again each frame, before ui.dialog.set sets fields, and on OK. An image scaled while the dialog is open shows its new Current Size, and Resize Using Percentages converts New Size against it, so OK makes the size shown. With no image selected, switching Resize Using Percentages leaves the fields as they are and the dialog asks for an image. --- crates/ui-egui/src/control.rs | 2 + crates/ui-egui/src/dialogs/object_mosaic.rs | 97 ++++++++++++++++++++- 2 files changed, 96 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a2c29fadc4..3ce5846e65 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1607,6 +1607,8 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) let names = crate::dialogs::field_names(d).join(", "); return err(format!("the `{}` dialog has no field `{f}`; its fields: {names}", d.kind)); } + // Create Object Mosaic converts New Size against the selected image's size as it is now. + crate::dialogs::object_mosaic::refresh(app); // In order: a field that sets others (an export preset) goes before the fields after it. // A field that fails leaves the dialog as it was before the request. let before = app.ui.dialog.clone(); diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index bc7ebdbbfe..cab5371d93 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -6,7 +6,9 @@ //! Fields: `width`, `height` (pt, or percentages of the image's size with `percentages`), //! `spacingX`, `spacingY` (pt), `columns`, `rows`, `lock` (Constrain Ratio on), `constrain` //! (`width` | `height`: the side Constrain Ratio and Use Ratio keep), `gray`, `percentages` and -//! `deleteRaster`. `__imageW` and `__imageH` hold the image's size (pt). +//! `deleteRaster`. `__imageW` and `__imageH` hold the image's size (pt), read again from the +//! selected image each frame, before `ui.dialog.set` sets fields and on OK; `__noImage` is true +//! while no image is selected. use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; @@ -68,6 +70,36 @@ pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { Ok(json!({ "dialog": KIND })) } +/// The field that is true while no image is selected. +const NO_IMAGE: &str = "__noImage"; + +/// What the dialog shows when Resize Using Percentages is switched with no image selected. +const NO_IMAGE_WHY: &str = "select an image"; + +/// The selected image's size `size` (from [`image_size`]) read into the dialog, so New Size is +/// converted and constrained against the image as it is now, also after it was scaled while the +/// dialog was open. With no image selected the last size read stays and `__noImage` is set. +fn read_image(size: Option<(f64, f64)>, d: &mut Dialog) { + let Some((w, h)) = size else { + d.fields.insert(NO_IMAGE.into(), json!(true)); + return; + }; + if d.fields.remove(NO_IMAGE).is_some() && d.str(form::REFUSED) == NO_IMAGE_WHY { + d.fields.remove(form::REFUSED); + } + d.fields.insert("__imageW".into(), json!(w)); + d.fields.insert("__imageH".into(), json!(h)); +} + +/// [`read_image`] on the open dialog when it is this one. `ui.dialog.set` runs it before it sets +/// any field. +pub(crate) fn refresh(app: &mut VectorcraftApp) { + let size = image_size(app); + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == KIND) { + read_image(size, d); + } +} + /// The image's size (pt) the dialog holds. fn image(d: &Dialog) -> (f64, f64) { (d.f64("__imageW", 1.0).max(1e-9), d.f64("__imageH", 1.0).max(1e-9)) @@ -142,8 +174,13 @@ fn derived(d: &Dialog) -> Option<(&'static str, f64)> { /// Resize Using Percentages turned on or off: the new size shown the other way, so it stays the /// same size. When a size field does not hold a number, or a size the command takes (all but the /// side Constrain Ratio sets) falls outside what the command accepts the other way, the fields and -/// the mode stay as they are and the dialog shows why. +/// the mode stay as they are and the dialog shows why. With no image selected, nothing changes and +/// the dialog asks for one. fn switch_percentages(d: &mut Dialog, on: bool) { + if d.bool(NO_IMAGE) { + d.fields.insert(form::REFUSED.into(), json!(NO_IMAGE_WHY)); + return; + } let (iw, ih) = image(d); let size = |key: &str| number(d, key, 100.0).as_f64().ok_or_else(|| format!("`{key}` must be a number (got {})", d.str(key))); let (w, h) = match (size("width"), size("height")) { @@ -270,6 +307,7 @@ fn pair(ui: &mut egui::Ui, d: &mut Dialog, keys: [&str; 2], unit: vectorcraft_do fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let unit = app.session.general_unit(); + read_image(image_size(app), d); let (iw, ih) = image(d); widgets::label_row(ui, tl!("Current Size:"), LABEL_W, |ui| { widgets::dim_label(ui, tl!("Width:")); @@ -335,8 +373,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// OK: the new size worked out against the image's size as it is now, as a frame would show it. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - run_and_close(app, COMMAND, params(d)) + let mut d = d.clone(); + read_image(image_size(app), &mut d); + follow_ratio(&mut d); + run_and_close(app, COMMAND, params(&d)) } #[cfg(test)] @@ -619,6 +661,55 @@ mod tests { assert_eq!(mosaic(&app), None); } + /// The image scaled from 100 × 50 pt to 200 × 100 pt while the dialog is open: Current Size shows + /// the new size, and Resize Using Percentages, by `ui.dialog.set` or by its checkbox, converts + /// New Size against it, so OK makes the size shown. With no image selected, switching is refused. + #[test] + fn percentages_convert_against_the_image_scaled_while_the_dialog_is_open() { + let set = |app: &mut VectorcraftApp, field: &str, value: Value| { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value})); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &egui::Context::default(), &req) else { + panic!("expected an immediate reply") + }; + r + }; + let mut app = app_with_image(); + open(&mut app, &json!({"width": 200, "height": 100})).unwrap(); + app.run("object.scale", json!({"sx": 200, "sy": 200})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|t| t == "200 pt"), "Current Size shows the scaled image: {texts:?}"); + let r = set(&mut app, "percentages", json!(true)); + assert_eq!(r["ok"], json!(true), "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (100.0, 100.0, true)); + app.run("object.scale", json!({"sx": 50, "sy": 50})).unwrap(); + // The checkbox, after the image went back to 100 × 50 pt: 100% of it is 100 × 50 pt. + let size = image_size(&app); + let d = app.ui.dialog.as_mut().unwrap(); + read_image(size, d); + switch_percentages(d, false); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (100.0, 50.0)); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + app.run("object.scale", json!({"sx": 200, "sy": 200})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((200.0, 100.0)), "100% of the image as it is on OK"); + app.run("edit.undo", json!({})).unwrap(); + // No image selected: the mode and sizes stay and the dialog asks for an image. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + set(&mut app, "percentages", json!(true)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.bool("percentages")), (200.0, false)); + assert_eq!(d.str(form::REFUSED), NO_IMAGE_WHY); + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + set(&mut app, "percentages", json!(true)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.bool("percentages"), d.str(form::REFUSED)), (100.0, true, String::new())); + } + /// True or false set after a Resize Using Percentages value the command refuses replaces it: the /// same mode as before keeps the sizes, and the other mode shows them the other way. Null is /// false, as the command reads it. OK then makes the mosaic. From c8d16e66ae28d7275c4f5648cb4301c818fed2ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 06:11:27 -0800 Subject: [PATCH 08/12] Object Mosaic: OK refuses a Constrain Ratio value the command refuses A Constrain Ratio side other than width or height, set through ui.dialog.set, is passed to object.createObjectMosaic, which refuses it, instead of being read as the width. A Constrain Ratio (lock) that is not true or false is refused on OK, and the dialog stays open. --- crates/ui-egui/src/dialogs/object_mosaic.rs | 36 ++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index cab5371d93..08497fb3c0 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -266,6 +266,18 @@ fn switch(d: &Dialog, key: &str) -> Value { d.fields.get(key).cloned().unwrap_or(json!(false)) } +/// `constrain` as the command takes it: null with Constrain Ratio off, else the side the field +/// holds (the width when it holds none), and any other value as it is, for the command to refuse. +fn constrained_side(d: &Dialog) -> Value { + if !d.bool("lock") { + return Value::Null; + } + match d.fields.get("constrain") { + None | Some(Value::Null) => json!("width"), + Some(v) => v.clone(), + } +} + /// `object.createObjectMosaic` parameters from the fields. With Constrain Ratio on, the side it /// sets is left out while it holds the size Constrain Ratio gives it: the command works it out from /// the kept side and grows both in proportion to its 0.1 pt minimum. Any other value set on that @@ -275,7 +287,7 @@ fn params(d: &Dialog) -> Value { let mut p = json!({ "columns": number(d, "columns", 10.0), "rows": number(d, "rows", 10.0), "width": number(d, "width", 100.0), "height": number(d, "height", 100.0), "percentages": switch(d, "percentages"), - "constrain": if d.bool("lock") { json!(if keeps_width(d) { "width" } else { "height" }) } else { Value::Null }, + "constrain": constrained_side(d), "spacingX": number(d, "spacingX", 0.0), "spacingY": number(d, "spacingY", 0.0), "gray": switch(d, "gray"), "deleteRaster": switch(d, "deleteRaster"), }); @@ -374,7 +386,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } /// OK: the new size worked out against the image's size as it is now, as a frame would show it. +/// A Constrain Ratio (`lock`) that is not true or false is refused, and the dialog stays open. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get("lock").is_some_and(|v| !v.is_boolean() && !v.is_null()) { + return Err("`lock` must be true or false".into()); + } let mut d = d.clone(); read_image(image_size(app), &mut d); follow_ratio(&mut d); @@ -710,6 +726,24 @@ mod tests { assert_eq!((d.f64("width", 0.0), d.bool("percentages"), d.str(form::REFUSED)), (100.0, true, String::new())); } + /// A Constrain Ratio side other than width or height, or a Constrain Ratio that is not true or + /// false, set by `ui.dialog.set`, is refused on OK and makes no mosaic. + #[test] + fn a_constrain_ratio_value_the_command_refuses_is_refused() { + for (field, value, also) in [("constrain", json!("both"), Some(("lock", json!(true)))), ("lock", json!("yes"), None)] { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + if let Some((k, v)) = also { + crate::dialogs::set_field(d, k.into(), v); + } + crate::dialogs::set_field(d, field.into(), value.clone()); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains(field), "{value}: {e}"); + assert_eq!(mosaic(&app), None, "{value}"); + } + } + /// True or false set after a Resize Using Percentages value the command refuses replaces it: the /// same mode as before keeps the sizes, and the other mode shows them the other way. Null is /// false, as the command reads it. OK then makes the mosaic. From 0586232cbf22d88c54d4823b5a9eafaca3f593ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 07:53:39 -0800 Subject: [PATCH 09/12] i18n: French Object Mosaic labels use a no-break space before colons The six Object Mosaic dialog labels that end in a colon now put U+00A0 before it, as the other colon rows in fr.tsv do, so french_catalog_uses_nonbreaking_prose_punctuation passes. --- crates/ui-egui/src/i18n/fr.tsv | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 99dd69b285..53527e3afe 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -700,12 +700,12 @@ font-technology Variable Variables Create New {kind} Style Créer un style de {kind} Create Object Mosaic… Créer une mosaïque d’objets… Create Object Mosaic Créer une mosaïque d’objets - Current Size: Taille actuelle : - New Size: Nouvelle taille : - Tile Spacing: Espacement des carreaux : - Number of Tiles: Nombre de carreaux : - Constrain Ratio: Conserver les proportions : - Result: Résultat : + Current Size: Taille actuelle : + New Size: Nouvelle taille : + Tile Spacing: Espacement des carreaux : + Number of Tiles: Nombre de carreaux : + Constrain Ratio: Conserver les proportions : + Result: Résultat : Resize Using Percentages Redimensionner en pourcentage Delete Raster Supprimer l’image pixellisée Use Ratio Utiliser le rapport From 0a212624c10fbc5d90f37b95f9c2fc21985c0626 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 08:09:58 -0800 Subject: [PATCH 10/12] Object Mosaic: OK keeps the dialog open when the command refuses its fields OK closed the dialog whether or not object.createObjectMosaic succeeded, so a field the command refused, set through ui.dialog.set, was lost. The dialog now closes only when the command succeeds, as form::commit_preview does. --- crates/ui-egui/src/dialogs/object_mosaic.rs | 30 ++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 08497fb3c0..eac36e9095 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -386,7 +386,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } /// OK: the new size worked out against the image's size as it is now, as a frame would show it. -/// A Constrain Ratio (`lock`) that is not true or false is refused, and the dialog stays open. +/// A Constrain Ratio (`lock`) that is not true or false is refused, and the dialog stays open. The +/// dialog also stays open with its fields when the command refuses them, as [`form::commit_preview`] +/// does. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if d.fields.get("lock").is_some_and(|v| !v.is_boolean() && !v.is_null()) { return Err("`lock` must be true or false".into()); @@ -394,7 +396,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); read_image(image_size(app), &mut d); follow_ratio(&mut d); - run_and_close(app, COMMAND, params(&d)) + let r = app.run(COMMAND, params(&d)); + if r.is_ok() { + app.ui.dialog = None; + } + r } #[cfg(test)] @@ -744,6 +750,24 @@ mod tests { } } + /// When the command refuses the dialog's fields, OK leaves the dialog open with them, so they can + /// be corrected; OK then makes the mosaic and closes it. + #[test] + fn a_refused_field_keeps_the_dialog_open() { + let mut app = app_with_image(); + open(&mut app, &json!({"width": 80})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "gray".into(), json!(1)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("gray"), "{e}"); + assert_eq!(mosaic(&app), None); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + assert_eq!((d.f64("width", 0.0), d.fields.get("gray")), (80.0, Some(&json!(1)))); + crate::dialogs::set_field(d, "gray".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(mosaic(&app).map(|m| m.0), Some(80.0)); + } + /// True or false set after a Resize Using Percentages value the command refuses replaces it: the /// same mode as before keeps the sizes, and the other mode shows them the other way. Null is /// false, as the command reads it. OK then makes the mosaic. From 8842a9d6eac3a4b34bc7ea7cf2c3703d2700eb18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:30:43 -0800 Subject: [PATCH 11/12] Rerun CI From b4afcadc5ce4ec1176e491176f6bc43295d78b60 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 01:32:12 -0800 Subject: [PATCH 12/12] Object Mosaic: a size out of range stays when percentages switch Resize Using Percentages now checks the new size as it is before converting it. A width or height the command refuses (outside 0.1 to 1,000,000) stays, with the mode unchanged and the reason shown, even when the converted value would be in range, for example 0.05 pt of a 10 pt wide image, which is 0.5%. --- crates/ui-egui/src/dialogs/object_mosaic.rs | 37 ++++++++++++++++++--- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index eac36e9095..0ee49a194a 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -173,8 +173,8 @@ fn derived(d: &Dialog) -> Option<(&'static str, f64)> { /// Resize Using Percentages turned on or off: the new size shown the other way, so it stays the /// same size. When a size field does not hold a number, or a size the command takes (all but the -/// side Constrain Ratio sets) falls outside what the command accepts the other way, the fields and -/// the mode stay as they are and the dialog shows why. With no image selected, nothing changes and +/// side Constrain Ratio sets) falls outside what the command accepts either as it is or the other +/// way, the fields and the mode stay as they are and the dialog shows why. With no image selected, nothing changes and /// the dialog asks for one. fn switch_percentages(d: &mut Dialog, on: bool) { if d.bool(NO_IMAGE) { @@ -190,13 +190,19 @@ fn switch_percentages(d: &mut Dialog, on: bool) { return; } }; - let (w, h) = if on { (w / iw * 100.0, h / ih * 100.0) } else { (iw * w / 100.0, ih * h / 100.0) }; let skip = follower(d); - if let Some((key, v)) = [("width", w), ("height", h)].into_iter().find(|(k, v)| skip != Some(*k) && !SIZE_RANGE.contains(v)) { - let why = format!("`{key}` must be between {} and {} (got {v})", SIZE_RANGE.start(), SIZE_RANGE.end()); + let checked = |key: &str| skip != Some(key) || d.bool(&kept(key)); + let refused = |w: f64, h: f64| { + let (key, v) = [("width", w), ("height", h)].into_iter().find(|(k, v)| checked(k) && !SIZE_RANGE.contains(v))?; + Some(format!("`{key}` must be between {} and {} (got {v})", SIZE_RANGE.start(), SIZE_RANGE.end())) + }; + // A size the command refuses as it is stays refused, even when it falls in range the other way. + let converted = if on { (w / iw * 100.0, h / ih * 100.0) } else { (iw * w / 100.0, ih * h / 100.0) }; + if let Some(why) = refused(w, h).or_else(|| refused(converted.0, converted.1)) { d.fields.insert(form::REFUSED.into(), json!(why)); return; } + let (w, h) = converted; d.fields.remove(form::REFUSED); d.fields.remove(&kept("percentages")); d.fields.insert("width".into(), json!(w)); @@ -683,6 +689,27 @@ mod tests { assert_eq!(mosaic(&app), None); } + /// A size `ui.dialog.set` gave that the command refuses stays when Resize Using Percentages + /// switches, even when it is in range the other way (0.05 pt of a 10 pt wide image is 0.5%, and + /// 0.05% of a 1,000 pt wide image is 0.5 pt), with the mode unchanged and the reason shown, and + /// OK refuses it. + #[test] + fn a_size_out_of_range_stays_when_percentages_switch() { + for (scale, given, on) in [(10, json!({}), true), (1000, json!({"percentages": true}), false)] { + let mut app = app_with_image(); + app.run("object.scale", json!({"sx": scale, "sy": scale})).unwrap(); + open(&mut app, &given).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!(0.05)); + crate::dialogs::set_field(d, "percentages".into(), json!(on)); + assert_eq!((d.f64("width", 0.0), d.bool("percentages")), (0.05, !on), "{given}"); + assert!(d.str(form::REFUSED).contains("`width` must be between 0.1"), "{given}: {}", d.str(form::REFUSED)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("width"), "{given}: {e}"); + assert_eq!(mosaic(&app), None, "{given}"); + } + } + /// The image scaled from 100 × 50 pt to 200 × 100 pt while the dialog is open: Current Size shows /// the new size, and Resize Using Percentages, by `ui.dialog.set` or by its checkbox, converts /// New Size against it, so OK makes the size shown. With no image selected, switching is refused.