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.
This commit is contained in:
dotCooCoo
2026-11-15 07:31:45 -08:00
parent a639a0b640
commit 69410d99d7
5 changed files with 94 additions and 13 deletions
+8 -3
View File
@@ -124,7 +124,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<MosaicPlan> {
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)),
+10
View File
@@ -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"),
+42 -3
View File
@@ -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<egui::Event>| {
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::<Vec<_>>()
};
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;
+23 -3
View File
@@ -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<egui::Event>| {
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());
+11 -4
View File
@@ -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}