diff --git a/ROADMAP.md b/ROADMAP.md index dabed3eb94..0ed5bbd6b9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -130,6 +130,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c286492236..9e31f8e6c4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -158,7 +158,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, parse_number}; +pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 234513df1d..052830ef0f 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -308,6 +308,36 @@ fn percent(s: &str) -> Option { } } +/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). +pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } +} + +/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three +/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it +/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are +/// decimals). +fn thousands(text: &str) -> bool { + let number = text.trim().trim_start_matches('-'); + let Some((whole, rest)) = number.split_once(',') else { return false }; + let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); + (1..=3).contains(&whole.len()) + && whole.bytes().all(|b| b.is_ascii_digit()) + && !whole.starts_with('0') + && part.len() == 3 + && unit.trim().chars().all(char::is_alphabetic) +} + +/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length +/// near the largest number in points is too large in Q and Ha. +pub fn finite_in_every_unit(pt: f64) -> bool { + pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite()) +} + /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as /// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. pub fn parse_number(s: &str) -> Option { diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 66c67651a3..e1e31ebdfb 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -13,6 +13,7 @@ mod pen; mod select; mod shapes; mod typetools; +mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; @@ -32,5 +33,6 @@ pub fn specs() -> Vec { v.extend(select::specs()); v.extend(shapes::specs()); v.extend(typetools::specs()); + v.extend(units::specs()); v } diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs new file mode 100644 index 0000000000..5d362a0acb --- /dev/null +++ b/crates/engine/src/cmd/addons/units.rs @@ -0,0 +1,124 @@ +//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. +//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and +//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). +//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform +//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the +//! UI's; the panel applies a length to the selection with `object.setBounds`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit}; +use vectorcraft_render::effects; + +use super::super::{CommandSpec, always, bad, cmd, has_selection}; +use crate::{Result, Session}; + +const CONVERT: &str = "addon.units.convert"; +const SELECTION_SIZE: &str = "addon.units.selectionSize"; +/// The most characters of a refused value an error message shows. +const SHOWN_CHARS: usize = 64; +/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes. +const MAX_TEXT_LEN: usize = 1024; +/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one +/// level of recursion per sign. +const MAX_OPERATORS: usize = 128; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "addon.units.convert", + "Convert Units", + [], + None, + "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + always, + convert + ), + cmd!( + query "addon.units.selectionSize", + "Selection Size in Units", + [], + None, + "{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}", + has_selection, + selection_size + ), + ] +} + +/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit, +/// label, number, text}]}`. +pub fn in_every_unit(pt: f64) -> Value { + let units: Vec = + Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect(); + json!({ "points": pt, "units": units }) +} + +/// The unit `p` gives for a number without a suffix (points when left out). +fn unit_param(p: &Value) -> Result { + let Some(given) = p.get("unit").filter(|u| !u.is_null()) else { return Ok(Unit::Points) }; + let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian); + named.ok_or_else(|| { + let u = match given { + Value::String(s) => clipped(s).escape_debug().to_string(), + other => shown(other), + }; + bad(CONVERT, format!("unknown units `{u}`")) + }) +} + +fn convert(_: &mut Session, p: &Value) -> Result { + let unit = unit_param(p)?; + let Some(v) = p.get("value").filter(|v| !v.is_null()) else { + return Err(bad(CONVERT, "missing `value`")); + }; + let pt = match v { + Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), + _ => None, + }; + let pt = pt.filter(|&pt| finite_in_every_unit(pt)); + pt.map(in_every_unit).ok_or_else(|| { + let v = shown(v); + bad(CONVERT, format!("`value` must be a number, not {v}")) + }) +} + +/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` +/// signs? +fn readable(s: &str) -> bool { + s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS +} + +/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON, +/// an array as `[…]` and an object as `{…}`. +fn shown(v: &Value) -> String { + match v { + Value::String(s) => Value::String(clipped(s)).to_string(), + Value::Array(_) => "[…]".into(), + Value::Object(_) => "{…}".into(), + other => other.to_string(), + } +} + +/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer. +fn clipped(s: &str) -> String { + match s.char_indices().nth(SHOWN_CHARS) { + Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()), + None => s.to_string(), + } +} + +fn selection_size(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let measure = s.bounds_measure(); + let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) { + Some(r) => Some(OrientedBox::aligned(r)), + None => s.transform_box(&st.selection.objects), + }; + let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?; + Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) })) +} diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs new file mode 100644 index 0000000000..2b572c3d11 --- /dev/null +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -0,0 +1,200 @@ +//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's +//! size as the Transform panel measures it, bad params refused, and nothing in the document changed. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn convert(s: &mut Session, p: Value) -> Value { + s.execute("addon.units.convert", &p).unwrap() +} + +/// The row of `r` for the unit with key `key`. +fn row<'a>(r: &'a Value, key: &str) -> &'a Value { + r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}")) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_length_comes_back_in_every_unit_in_order() { + let mut s = session(); + let r = convert(&mut s, json!({"value": "10mm"})); + assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4)); + let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect(); + assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key)); + assert_eq!(row(&r, "millimeters")["number"], "10"); + assert_eq!(row(&r, "millimeters")["text"], "10 mm"); + assert_eq!(row(&r, "centimeters")["text"], "1 cm"); + assert_eq!(row(&r, "inches")["text"], "0.3937 in"); + assert_eq!(row(&r, "points")["text"], "28.346 pt"); + assert_eq!(row(&r, "q")["text"], "40 Q"); + assert_eq!(row(&r, "ha")["text"], "40 H"); + assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points"); + assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches"); + // Each row is what a field of that unit shows for the length. + for u in Unit::EAST_ASIAN { + let pt = 720.0 / 25.4; + assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}"); + assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}"); + } +} + +#[test] +fn values_read_as_number_fields_read_them() { + let mut s = session(); + let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); + assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0)); + assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0)); + assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6)); + // A number without a unit is in `unit`, points by default. + assert!(near(pt(&mut s, json!({"value": 12})), 12.0)); + assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6)); + assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0)); + // A suffix wins over `unit`. + assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0)); + // A decimal comma reads as a point, as in the number fields. + assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); + // A sum of 128 signs still reads. + assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); +} + +#[test] +fn keys_the_commands_do_not_take_are_refused() { + let s = session(); + s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap(); + s.check_params("addon.units.selectionSize", &json!({})).unwrap(); + for (id, p) in [ + ("addon.units.convert", json!({"value": 1, "units": "mm"})), + ("addon.units.convert", json!({"value": 1, "ids": [1]})), + ("addon.units.selectionSize", json!({"ids": [1]})), + ("addon.units.selectionSize", json!({"value": 1})), + ] { + match s.check_params(id, &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"), + other => panic!("{id} {p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_follows_preview_bounds_and_selected_anchors() { + let mut s = session(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap(); + let wh = |s: &mut Session| { + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) + }; + assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds"); + // Use Preview Bounds: the stroke's outer half on every side. + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let (w, h) = wh(&mut s); + assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}"); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap(); + // Two neighboring anchors selected (Direct Selection): the box around them, one edge of the + // rectangle. + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let (w, h) = wh(&mut s); + assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}"); +} + +#[test] +fn it_needs_no_document_and_changes_nothing() { + let mut s = Session::new(); + assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0)); + let mut s = session(); + let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + convert(&mut s, json!({"value": "5mm"})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn bad_values_and_units_are_refused() { + let mut s = session(); + for p in [ + json!({}), + json!({"value": null}), + json!({"value": "abc"}), + json!({"value": "10 furlongs"}), + json!({"value": "1in/0"}), + json!({"value": "1e400"}), + // Finite in points, too large in Q and Ha. + json!({"value": 1.5e308}), + json!({"value": "1.5e308"}), + // A thousands comma is refused, as the number fields refuse it. + json!({"value": "1,000 mm"}), + json!({"value": "1,000.5"}), + // A long expression is refused instead of exhausting the stack. + json!({"value": format!("1{}", "+1".repeat(200_000))}), + json!({"value": format!("1{}", "+1".repeat(129))}), + json!({"value": true}), + json!({"value": [1]}), + json!({"value": 1, "unit": "furlongs"}), + json!({"value": 1, "unit": 5}), + json!({"value": 1, "unit": ["mm"]}), + ] { + match s.execute("addon.units.convert", &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"), + other => panic!("{p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn a_long_value_or_unit_is_refused_with_a_short_message() { + let mut s = session(); + let long = "9".repeat(100_000); + for (p, says) in [ + (json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))), + (json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()), + (json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))), + (json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()), + (json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()), + ] { + match s.execute("addon.units.convert", &p) { + Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"), + other => panic!("expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_is_the_transform_panels() { + let mut s = session(); + assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected"); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(row(&r["width"], "inches")["text"], "1 in"); + assert_eq!(row(&r["height"], "picas")["text"], "3 p"); + // A turned object keeps its own sides, as the Transform panel's W and H show them. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width())); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step"); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..71c0e1a011 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -77,6 +77,8 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.shapes.star", "addon.type.releasePath", "addon.type.textTweaker", + "addon.units.convert", + "addon.units.selectionSize", "appearance.addEffect", "appearance.addFill", "appearance.addStroke", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 797ca39f52..0ea1350d78 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -925,6 +925,12 @@ fn structured_junk() { ("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})), ("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})), ("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})), + // Unit Converter add-on. + ("addon.units.convert", json!({"value": f64::MAX, "unit": "yards"})), + ("addon.units.convert", json!({"value": "1e308m*1e308", "unit": "q"})), + ("addon.units.convert", json!({"value": "-2p6/0", "unit": ["mm"]})), + ("addon.units.convert", json!({"value": [1], "unit": 5})), + ("addon.units.selectionSize", json!({"ids": [u64::MAX]})), // Cutting Tools add-on: Stencil Bridges. ("addon.cutting.bridges", json!({"width": 0.01, "count": 16, "direction": "shortest", "keepOriginal": true})), ("addon.cutting.bridges", json!({"width": 1000, "count": 1, "direction": "horizontal", "keepOriginal": false})), diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 522f82bd2b..3d706881c1 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -14,6 +14,7 @@ pub mod pen; pub mod select; pub mod shapes; pub mod typetools; +pub mod units; use crate::menus::Item; @@ -34,6 +35,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sub("Type Tools", typetools::menu()), + Item::Sub("Unit Converter", units::menu()), Item::Sep, ] } diff --git a/crates/ui-egui/src/addons/units.rs b/crates/ui-egui/src/addons/units.rs new file mode 100644 index 0000000000..2e2801a2ca --- /dev/null +++ b/crates/ui-egui/src/addons/units.rs @@ -0,0 +1,194 @@ +//! Unit Converter in the interface: its submenu (Object › Plug-ins › Unit Converter), which opens +//! the panel, and the panel. The panel shows one length in every unit of +//! [`Unit::EAST_ASIAN`], one number field each. A value typed in any field (units and arithmetic, +//! as every number field reads them) updates the others as it is typed; text that does not read +//! leaves them as they were. From Selection reads the selection's width and height +//! (`addon.units.selectionSize`), and Width or Height picks which of the two the fields show; the +//! size read is dropped when the document, its selection or the bounds measure changes. Apply gives the selection that +//! width or height through `object.setBounds` as the Transform panel's W or H field does (its +//! reference point, Constrain Width and Height Proportions and Transform Object Only, Pattern +//! Only or Both), as one undo step. Each field's copy button puts its value on the clipboard, with +//! its unit when Copy with Units is on. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{Unit, finite_in_every_unit}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::transform; +use crate::panels::{pstate, set_pstate}; +use crate::widgets; + +/// The panel's id (`window.panel {panel: "unitConverter"}`). +pub const ID: &str = "unitConverter"; +/// The command that measures the selection. +pub const SELECTION_SIZE: &str = "addon.units.selectionSize"; + +/// Where the panel keeps its length and choices (panel state). +const STATE: &str = "unit-converter"; +/// A row (label, field, copy button and two gaps) is 214 pt wide, inside the 240 pt body of the +/// default 260 pt floating panel with room for its scroll bar. +const LABEL_W: f32 = 90.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Unit Converter. +pub fn menu() -> Vec { + vec![Item::Cmd("Unit Converter Panel", "window.panel", json!({ "panel": ID }))] +} + +/// The selection's side the fields show and Apply sets. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +pub(crate) enum Side { + #[default] + Width, + Height, +} + +impl Side { + /// `object.setBounds`'s param for this side. + fn key(self) -> &'static str { + match self { + Side::Width => "width", + Side::Height => "height", + } + } +} + +/// The panel's length and choices. +#[derive(Clone, Default, Debug, PartialEq)] +pub(crate) struct Converter { + /// The length (points), none until one is typed or read from the selection. + pub points: Option, + /// The selection's width and height (points) From Selection last read. + pub size: Option<(f64, f64)>, + /// The active document's uid and revision, and the bounds measure (Use Preview Bounds, + /// glyph bounds), when [`Converter::size`] was read. + pub read_at: Option, + /// Which of them the fields show, and the side Apply sets. + pub side: Side, + /// Copy puts the unit after the number. + pub with_units: bool, +} + +impl Converter { + /// Show `side`: the fields take that side of the size From Selection read, if any. + pub fn pick(&mut self, side: Side) { + self.side = side; + if let Some((w, h)) = self.size { + self.points = Some(if side == Side::Width { w } else { h }); + } + } + + /// A length typed in a field: after From Selection it replaces the side shown, so picking the + /// other side and back keeps it. + pub fn set(&mut self, pt: f64) { + self.points = Some(pt); + if let Some((w, h)) = &mut self.size { + *(if self.side == Side::Width { w } else { h }) = pt; + } + } + + /// Drop the size From Selection read when the active document is no longer the one it was + /// read from or is measured another way (`now`: its uid and revision, which a change to the + /// selection also moves, and the bounds measure). The length the fields show stays. + pub fn follow(&mut self, now: Option) { + if self.size.is_some() && self.read_at != now { + self.size = None; + self.read_at = None; + } + } + + /// What the copy button of the field in `unit` puts on the clipboard. + pub fn copied(&self, unit: Unit) -> Option { + self.points.map(|pt| if self.with_units { unit.format(pt) } else { unit.number(pt) }) + } +} + +/// A document's uid and revision, and the bounds measure. +pub(crate) type ReadAt = (u64, u64, vectorcraft_effects::preview::Measure); + +/// The active document's uid and revision, and the bounds measure. +pub(crate) fn document_now(app: &VectorcraftApp) -> Option { + app.session.active().map(|st| (st.uid, st.revision, app.session.bounds_measure())) +} + +/// From Selection: read the selection's width and height into `st`, and show the side picked. +pub(crate) fn from_selection(app: &mut VectorcraftApp, st: &mut Converter) -> Result<(), String> { + let r = app.run(SELECTION_SIZE, json!({}))?; + if let (Some(w), Some(h)) = (r["width"]["points"].as_f64(), r["height"]["points"].as_f64()) { + st.size = Some((w, h)); + st.read_at = document_now(app); + st.pick(st.side); + } + Ok(()) +} + +/// Apply: give the selection the length as its width or height, as the Transform panel's W or H +/// field does: from its reference point (a symbol instance's registration point with Use +/// Registration Point for Symbol on), with the other side following under Constrain Width and +/// Height Proportions, and with the panel menu's Transform Object Only, Pattern Only or Both. +/// Without a length it does nothing. +pub(crate) fn apply(app: &mut VectorcraftApp, ui: &Ui, st: &Converter) -> Result<(), String> { + let Some(pt) = st.points else { return Ok(()) }; + let reference = app.selection_box().map_or_else(|| transform::reference_index(ui), |b| transform::panel_reference(app, ui, &b).index); + let params = json!({ st.side.key(): pt, "reference": reference, "proportional": transform::proportional(app, ui) }); + let params = transform::with_pattern_switches(app, params); + app.run("object.setBounds", params)?; + Ok(()) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let mut st: Converter = pstate(ui.ctx(), STATE); + st.follow(document_now(app)); + for unit in Unit::EAST_ASIAN { + widgets::label_row(ui, unit.label(), LABEL_W, |ui| { + // A length too large to show in one of the units (near the largest number, in Q and + // Ha) leaves the others as they were, as text that does not read does. + if let Some(pt) = widgets::num_field_live(ui, ("unit-converter", unit.key()), st.points, unit, FIELD_W) + && finite_in_every_unit(pt) + { + st.set(pt); + } + // The button's name and tip carry the row's unit ("Copy Millimeters"). + let tip = format!("{} {}", tl!("Copy"), tl!(unit.label())); + let copy = widgets::icon_button_enabled(ui, "copy", &tip, false, st.points.is_some(), 22.0); + if copy.clicked() + && let Some(text) = st.copied(unit) + { + ui.ctx().copy_text(text); + } + }); + } + if widgets::check(ui, "Copy with Units", st.with_units, true) { + st.with_units = !st.with_units; + } + ui.add_space(6.0); + widgets::subheader(ui, tl!("Selection")); + let selected = app.session.active().is_some_and(|d| !d.selection.is_empty()); + ui.horizontal(|ui| { + for (side, label) in [(Side::Width, "Width"), (Side::Height, "Height")] { + if widgets::radio(ui, label, st.side == side, true) { + st.pick(side); + } + } + }); + ui.horizontal(|ui| { + let read = ui.add_enabled_ui(selected, |ui| widgets::flat_button(ui, tl!("From Selection"), 110.0)).inner; + if read.clicked() + && let Err(e) = from_selection(app, &mut st) + { + app.status(e); + } + let set = ui.add_enabled_ui(selected && st.points.is_some(), |ui| widgets::flat_button(ui, tl!("Apply"), 70.0)).inner; + if set.clicked() + && let Err(e) = apply(app, ui, &st) + { + app.status(e); + } + }); + set_pstate(ui.ctx(), STATE, st); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/units/tests.rs b/crates/ui-egui/src/addons/units/tests.rs new file mode 100644 index 0000000000..63d35f8b8d --- /dev/null +++ b/crates/ui-egui/src/addons/units/tests.rs @@ -0,0 +1,301 @@ +//! Unit Converter's submenu and panel: one field per unit, typing in one updates the others and +//! text that does not read leaves them alone, From Selection reads the selection's size, Apply +//! sets the side picked as one undo step and adds none when nothing changes, and Copy writes the +//! value with or without its unit. + +use egui::{Event, Key, Modifiers, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::Unit; +use vectorcraft_engine::Session; + +use super::{Converter, ID, STATE, Side, apply, document_now, from_selection, show}; +use crate::panels::{pstate, set_pstate}; +use crate::tests_labels::{painted_text, shapes_text}; +use crate::{VectorcraftApp, menus}; + +/// An app with a selected 72 × 36 pt rectangle. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap(); + app +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// The selection's width and height. +fn size(app: &mut VectorcraftApp) -> (f64, f64) { + let r = app.run("addon.units.selectionSize", json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) +} + +#[test] +fn the_submenu_opens_the_panel() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Unit Converter"] && e.label == "Unit Converter Panel").expect("listed"); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); +} + +#[test] +fn the_panel_has_a_field_for_every_unit_and_its_buttons() { + let mut app = app(); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, Converter { points: Some(720.0 / 25.4), ..Converter::default() }); + show(app, ui); + }); + for u in Unit::EAST_ASIAN { + assert!(text.lines().any(|l| l == u.label()), "{} in {text}", u.label()); + } + for s in ["10 mm", "1 cm", "0.3937 in", "28.346 pt", "40 Q", "40 H"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + for s in ["Copy with Units", "Selection", "Width", "Height", "From Selection", "Apply"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } +} + +#[test] +fn typing_in_a_field_updates_the_others_and_text_that_does_not_read_leaves_them() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + (pstate::(&ctx, STATE), shapes_text(&out)) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the first field, Points, which selects its text so typing replaces it. + frame(&mut app, vec![tab]); + frame(&mut app, vec![]); + let (st, _) = frame(&mut app, vec![Event::Text("1in/2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 36.0)), "{st:?}"); + let (st, text) = frame(&mut app, vec![]); + assert!(near(st.points.unwrap(), 36.0)); + for s in ["0.5 in", "3 p", "12.7 mm", "1.27 cm"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + // Text that does not read keeps the length the other fields show. + let (st, text) = frame(&mut app, vec![Event::Text("x".into())]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); + assert!(text.lines().any(|l| l == "12.7 mm"), "{text}"); + // So does a length too large to show in Q and Ha. + let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }; + frame(&mut app, vec![select_all]); + // 1.7e308 pt: finite in points. + let (st, _) = frame(&mut app, vec![Event::Text(format!("17{}", "0".repeat(307)))]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); +} + +#[test] +fn picking_a_side_shows_that_side_of_the_size_read() { + let mut st = Converter { size: Some((72.0, 36.0)), ..Converter::default() }; + st.pick(Side::Height); + assert_eq!((st.side, st.points), (Side::Height, Some(36.0))); + st.pick(Side::Width); + assert_eq!(st.points, Some(72.0)); + // A length typed after From Selection replaces the side shown, and picking the other side and + // back keeps it. + st.set(100.0); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + st.pick(Side::Width); + assert_eq!((st.points, st.size), (Some(100.0), Some((100.0, 36.0)))); + // Before From Selection a side keeps the length typed. + let mut st = Converter::default(); + st.set(5.0); + st.pick(Side::Height); + assert_eq!((st.points, st.size), (Some(5.0), None)); +} + +#[test] +fn copy_writes_the_value_with_or_without_its_unit() { + let mut st = Converter { points: Some(72.0), ..Converter::default() }; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1")); + st.with_units = true; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1 in")); + assert_eq!(st.copied(Unit::Millimeters), Some(Unit::Millimeters.format(72.0))); + assert_eq!(Converter::default().copied(Unit::Points), None, "nothing to copy before a length"); +} + +/// Apply `st` in a frame whose shared reference point (the Transform panel's) is `reference`. +fn apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) { + try_apply_at(app, st, reference).unwrap(); +} + +/// [`apply_at`], with its result. +fn try_apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) -> Result<(), String> { + let ctx = egui::Context::default(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), reference)); + let mut result = Ok(()); + ctx.run_ui(Default::default(), |ui| result = apply(app, ui, st)).textures_delta.clear(); + result +} + +/// The selection's bounding box. +fn bounds(app: &mut VectorcraftApp) -> vectorcraft_geom::Rect { + app.selection_box().unwrap().rect +} + +#[test] +fn from_selection_reads_the_size_and_apply_sets_the_side_picked() { + let mut app = app(); + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + assert_eq!((st.size, st.points), (Some((72.0, 36.0)), Some(72.0))); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + // Apply: 1 in high, from the centre, as one undo step. + let steps = undo_steps(&app); + st.points = Some(72.0); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 72.0) && near(h, 72.0), "{w} × {h}"); + assert_eq!(undo_steps(&app), steps + 1); + // The same length again changes nothing and adds no step. + apply_at(&mut app, &st, 4); + assert_eq!(undo_steps(&app), steps + 1); + // Without a length Apply does nothing. + apply_at(&mut app, &Converter::default(), 4); + assert_eq!(undo_steps(&app), steps + 1); + // Width, kept at the left edge (reference 3). + let x0 = bounds(&mut app).x0; + let st = Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }; + apply_at(&mut app, &st, 3); + let b = bounds(&mut app); + assert!(near(b.width(), 144.0) && near(b.x0, x0), "{b:?}"); + assert_eq!(undo_steps(&app), steps + 2); +} + +/// Apply follows the Transform panel's W and H fields: Constrain Width and Height Proportions +/// scales the other side too, and Transform Pattern Only leaves the object's size alone. +#[test] +fn apply_follows_the_transform_panels_proportions_and_pattern_choice() { + let mut app = app(); + app.run("prefs.set", json!({"key": "constrainProportions", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "{w} × {h}"); + app.run("prefs.set", json!({"key": "constrainProportions", "value": false})).unwrap(); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "pattern"})).unwrap(); + // The object has no pattern to transform: whether the command reports that or not, the + // object keeps its size. + let _ = try_apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "the object keeps its size: {w} × {h}"); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "both"})).unwrap(); + apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + assert!(near(size(&mut app).0, 10.0)); +} + +/// With Use Registration Point for Symbol on and one symbol instance selected, Apply keeps the +/// symbol's registration point (here its top-left corner) in place, as the Transform panel does, +/// instead of the shared reference point (the centre). +#[test] +fn apply_keeps_a_symbol_instances_registration_point() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); + let id = app.run("symbol.new", json!({"name": "Corner", "registration": 0})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("prefs.set", json!({"key": "useRegistrationPointForSymbol", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(160.0), side: Side::Width, ..Converter::default() }, 4); + assert_eq!(bounds(&mut app), vectorcraft_geom::Rect::new(100.0, 50.0, 260.0, 90.0)); +} + +/// The size From Selection read belongs to the selection it was read from: after the selection +/// changes, picking a side keeps the length shown instead of showing the old object's side, and +/// Apply sets that length. +#[test] +fn a_size_read_from_another_selection_is_dropped() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| { + ctx.run_ui(Default::default(), |ui| show(app, ui)).textures_delta.clear(); + pstate::(&ctx, STATE) + }; + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + set_pstate(&ctx, STATE, st); + // Drawing the panel again with nothing changed keeps it. + assert_eq!(frame(&mut app).size, Some((72.0, 36.0))); + // Another object selected. + app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 20, "height": 50})).unwrap(); + let mut st = frame(&mut app); + assert_eq!((st.size, st.points), (None, Some(72.0)), "{st:?}"); + st.pick(Side::Height); + assert_eq!(st.points, Some(72.0), "not the first object's height"); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 20.0) && near(h, 72.0), "{w} × {h}"); + // So does a change to the document. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); + // And a change to how the selection is measured (Use Preview Bounds), which leaves the + // document as it is. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + st.follow(document_now(&app)); + assert!(st.size.is_some()); + app.run("prefs.set", json!({"key": "usePreviewBounds", "value": true})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); +} + +/// Each row's copy button reads as copying that row's unit, so a screen reader tells the twelve +/// apart, and the fields are named by their rows. +#[test] +fn each_copy_button_and_field_is_named_with_its_unit() { + let mut app = app(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, STATE, Converter { points: Some(72.0), ..Converter::default() }); + ctx.run_ui(Default::default(), |ui| show(&mut app, ui)).textures_delta.clear(); + let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A label node carries its text as its value. + let label_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + let buttons: Vec = + nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + for u in Unit::EAST_ASIAN { + let name = format!("Copy {}", u.label()); + assert_eq!(buttons.iter().filter(|b| **b == name).count(), 1, "{name} in {buttons:?}"); + // The row fits the 240 pt body of the default 260 pt floating panel, with 10 pt left for + // its scroll bar. + let button = nodes.iter().find(|(_, n)| n.label() == Some(name.as_str())).and_then(|(_, n)| n.bounds()).unwrap(); + assert!(button.x1 <= 230.0, "{name} ends at {}", button.x1); + // The field of the row is labeled by the row's label. + let field = nodes + .iter() + .find(|(_, n)| n.role() != egui::accesskit::Role::Button && n.labelled_by().iter().any(|l| label_of(*l).as_deref() == Some(u.label()))); + assert!(field.is_some(), "a field labeled {}", u.label()); + } +} + +#[test] +fn from_selection_with_nothing_selected_reports_it_and_keeps_the_length() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let mut st = Converter { points: Some(10.0), ..Converter::default() }; + assert!(from_selection(&mut app, &mut st).is_err()); + assert_eq!((st.points, st.size), (Some(10.0), None)); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 28944173dd..2528cb6731 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6426,6 +6426,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` трябва да е "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` трябва да е [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Преобразувател на мерни единици + Unit Converter Panel Панел „Преобразувател на мерни единици“ + Copy with Units Копиране с мерните единици + From Selection От селекцията + # Color Effects add-on: Select by Color Kind. Select by Color Kind Избиране по вид цвят Objects with Spot Colors Обекти с плакатни цветове diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 01b90e5148..c5dbf362ef 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6767,6 +6767,11 @@ shape Open Otvoren Create Swatch Legend… Kreiraj legendu uzoraka boja… HEX HEX Help Bar Traka pomoći +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pretvarač jedinica + Unit Converter Panel Panel Pretvarač jedinica + Copy with Units Kopiraj s jedinicama + From Selection Iz odabira # Type Tools add-on (Object › Plug-ins › Type Tools). Type Tools Alati za tekst Text Tweaker… Podešavanje teksta… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4ddd1d5605..25a4b4ae51 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6960,6 +6960,12 @@ anchor Points: Punts: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` ha de ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` ha de ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertidor d’unitats + Unit Converter Panel Tauler Convertidor d’unitats + Copy with Units Copia amb les unitats + From Selection De la selecció + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecciona per tipus de color Objects with Spot Colors Objectes amb colors directes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 211982f086..fa3f76a611 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6991,6 +6991,12 @@ anchor Points: Body: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musí být "free", "keepAngles" nebo "symmetric" @msg `{key}` must be [x, y] `{key}` musí být [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Převodník jednotek + Unit Converter Panel Panel Převodník jednotek + Copy with Units Kopírovat s jednotkami + From Selection Z výběru + # Color Effects add-on: Select by Color Kind. Select by Color Kind Vybrat podle druhu barvy Objects with Spot Colors Objekty s přímými barvami diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b3de0ae89a..ca2070c486 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6442,6 +6442,12 @@ anchor Points: Punkter: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` skal være "free", "keepAngles" eller "symmetric" @msg `{key}` must be [x, y] `{key}` skal være [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhedsomregner + Unit Converter Panel Panelet Enhedsomregner + Copy with Units Kopiér med enheder + From Selection Fra markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markér efter farvetype Objects with Spot Colors Objekter med spotfarver diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d0610144ef..6f585c66fe 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6586,6 +6586,12 @@ anchor Points: Punkte: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` muss "free", "keepAngles" oder "symmetric" sein @msg `{key}` must be [x, y] `{key}` muss [x, y] sein +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Einheitenumrechner + Unit Converter Panel Einheitenumrechner-Bedienfeld + Copy with Units Mit Einheiten kopieren + From Selection Aus Auswahl + # Color Effects add-on: Select by Color Kind. Select by Color Kind Nach Farbart auswählen Objects with Spot Colors Objekte mit Volltonfarben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d03f8c6958..f13e494831 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6943,6 +6943,12 @@ anchor Points: Σημεία: @msg `mode` must be "free", "keepAngles" or "symmetric" Το `mode` πρέπει να είναι "free", "keepAngles" ή "symmetric" @msg `{key}` must be [x, y] Το `{key}` πρέπει να είναι [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Μετατροπέας μονάδων + Unit Converter Panel Πλαίσιο Μετατροπέας μονάδων + Copy with Units Αντιγραφή με μονάδες + From Selection Από την επιλογή + # Color Effects add-on: Select by Color Kind. Select by Color Kind Επιλογή κατά είδος χρώματος Objects with Spot Colors Αντικείμενα με χρώματα spot diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3e8bd23752..cab3dd8174 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6935,6 +6935,12 @@ anchor Points: Puntos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` debe ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` debe ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Panel Conversor de unidades + Copy with Units Copiar con unidades + From Selection Desde la selección + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleccionar por tipo de color Objects with Spot Colors Objetos con tintas planas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d408220f47..2917f064d7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7021,6 +7021,12 @@ anchor Points: Pisteet: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` on oltava "free", "keepAngles" tai "symmetric" @msg `{key}` must be [x, y] `{key}` on oltava [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Yksikkömuunnin + Unit Converter Panel Yksikkömuunnin-paneeli + Copy with Units Kopioi yksiköineen + From Selection Valinnasta + # Color Effects add-on: Select by Color Kind. Select by Color Kind Valitse värityypin mukaan Objects with Spot Colors Objektit, joissa on spottivärejä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 318bbbeb44..72803f301d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6986,6 +6986,12 @@ anchor Points: Points : @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` doit être "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` doit être [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertisseur d’unités + Unit Converter Panel Panneau Convertisseur d’unités + Copy with Units Copier avec les unités + From Selection Depuis la sélection + # Color Effects add-on: Select by Color Kind. Select by Color Kind Sélectionner par type de couleur Objects with Spot Colors Objets avec tons directs diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 716d851655..63e2119daa 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -752,6 +752,7 @@ Copy into the document's folder દસ્તાવેજના ફોલ્ડરમાં નકલ કરો Copy only fonts you own or are licensed to install. ફક્ત તમારી માલિકીના અથવા ઇન્સ્ટોલ કરવાના લાઇસન્સવાળા ફોન્ટ્સની નકલ કરો. Copy to User Defined વપરાશકર્તા-વ્યાખ્યાયિતમાં નકલ કરો + Copy with Units એકમો સાથે નકલ કરો Copyright કૉપીરાઇટ Copyright Info URL: કૉપીરાઇટ માહિતી URL: Copyright Notice: કૉપીરાઇટ સૂચના: @@ -1468,6 +1469,7 @@ Frequencies and angles are the output device's to apply. ફ્રિક્વન્સી અને એંગલ આઉટપુટ ડિવાઇસ લાગુ કરશે. Frequency ફ્રિક્વન્સી Fresco… ફ્રેસ્કો… + From Selection પસંદગીમાંથી From: થી: Front આગળ Full Document સંપૂર્ણ દસ્તાવેજ @@ -3969,6 +3971,8 @@ Uniform યુનિફોર્મ Uniformly Scaled સમાન રીતે સ્કેલ કરેલ Unite યુનાઇટ + Unit Converter એકમ રૂપાંતરક + Unit Converter Panel એકમ રૂપાંતરક પેનલ Units એકમો Units: એકમો: Units: {units} એકમો: {units} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 78c0a9a7eb..ba33f1ce0a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1067,6 +1067,7 @@ antiAlias Sharp शार्प Copy Selected Style सिलेक्टेड स्टाइल को कॉपी करें Copy to User Defined उपयोगकर्ता परिभाषित करने के लिए कॉपी करें Copy Width Point कॉपी चौड़ाई पॉइंट + Copy with Units इकाइयों के साथ कॉपी करें Copyright कॉपीराइट Copyright and Contact Info कॉपीराइट और संपर्क जानकारी Copyright Info URL: कॉपीराइट जानकारी URL: @@ -2008,6 +2009,7 @@ antiAlias Sharp शार्प Fresco… फ़्रेस्को… from the format's public description फ़ॉर्मैट के सार्वजनिक विवरण से from your earlier imports अपने पहले आयात से + From Selection सिलेक्शन से From: से: Front सामने Frosted फ़्रॉस्टेड @@ -5308,6 +5310,8 @@ antiAlias Sharp शार्प Unique अनोखा Unite मिलाएँ Unite and Simplify एकजुट और सरलीकरण + Unit Converter इकाई कनवर्टर + Unit Converter Panel इकाई कनवर्टर पैनल Units इकाइयाँ Units & Scale इकाइयों और स्केल Units: इकाइयाँ: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a1f6100b2f..215ee1c9c1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6975,6 +6975,12 @@ anchor Points: Pontok: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`: "free", "keepAngles" vagy "symmetric" kell @msg `{key}` must be [x, y] `{key}`: [x, y] kell +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Mértékegység-átváltó + Unit Converter Panel Mértékegység-átváltó panel + Copy with Units Másolás mértékegységgel + From Selection A kijelölésből + # Color Effects add-on: Select by Color Kind. Select by Color Kind Kijelölés színtípus szerint Objects with Spot Colors Direkt színeket használó objektumok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c7c6b956db..f518b286b7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6442,6 +6442,12 @@ anchor Points: Titik: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` harus "free", "keepAngles" atau "symmetric" @msg `{key}` must be [x, y] `{key}` harus [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pengonversi Satuan + Unit Converter Panel Panel Pengonversi Satuan + Copy with Units Salin dengan Satuan + From Selection Dari Seleksi + # Color Effects add-on: Select by Color Kind. Select by Color Kind Pilih menurut Jenis Warna Objects with Spot Colors Objek dengan Warna Spot diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6743704785..c198db8963 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6620,6 +6620,12 @@ anchor Points: Punti: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve essere "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` deve essere [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertitore di unità + Unit Converter Panel Pannello Convertitore di unità + Copy with Units Copia con le unità + From Selection Dalla selezione + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleziona per tipo di colore Objects with Spot Colors Oggetti con colori spot diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c9cdb8fcbe..2be853ffdb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8490,6 +8490,12 @@ anchor Points: ポイント: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` には "free"、"keepAngles" または "symmetric" を指定してください @msg `{key}` must be [x, y] `{key}` には [x, y] を指定してください +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 単位換算 + Unit Converter Panel 単位換算パネル + Copy with Units 単位付きでコピー + From Selection 選択範囲から + # Color Effects add-on: Select by Color Kind. Select by Color Kind カラーの種類で選択 Objects with Spot Colors 特色を使用したオブジェクト diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 55f726dc38..7087f2841d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7017,6 +7017,12 @@ anchor Points: წერტილები: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` უნდა იყოს "free", "keepAngles" ან "symmetric" @msg `{key}` must be [x, y] `{key}` უნდა იყოს [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter ერთეულების გადამყვანი + Unit Converter Panel ერთეულების გადამყვანის პანელი + Copy with Units ერთეულებით კოპირება + From Selection მონიშნულიდან + # Color Effects add-on: Select by Color Kind. Select by Color Kind ფერის სახეობით არჩევა Objects with Spot Colors ობიექტები სპოტ-ფერებით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index abe2b4bc28..f0196f0316 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6581,6 +6581,12 @@ anchor Points: 포인트: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`는 "free", "keepAngles" 또는 "symmetric"이어야 합니다 @msg `{key}` must be [x, y] `{key}`은(는) [x, y]여야 합니다 +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 단위 변환기 + Unit Converter Panel 단위 변환기 패널 + Copy with Units 단위 포함 복사 + From Selection 선택 영역에서 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 색상 종류로 선택 Objects with Spot Colors 별색을 사용한 개체 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ed281382a4..29d23b1d3e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8885,6 +8885,12 @@ anchor Points: Punten: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` moet "free", "keepAngles" of "symmetric" zijn @msg `{key}` must be [x, y] `{key}` moet [x, y] zijn +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Eenhedenomrekenaar + Unit Converter Panel Deelvenster Eenhedenomrekenaar + Copy with Units Kopiëren met eenheden + From Selection Uit selectie + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecteren op kleursoort Objects with Spot Colors Objecten met steunkleuren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 08e96e6a35..d9882c7efb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6847,6 +6847,12 @@ anchor Points: Punkty: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musi mieć wartość "free", "keepAngles" lub "symmetric" @msg `{key}` must be [x, y] `{key}` musi mieć postać [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Konwerter jednostek + Unit Converter Panel Panel Konwerter jednostek + Copy with Units Kopiuj z jednostkami + From Selection Z zaznaczenia + # Color Effects add-on: Select by Color Kind. Select by Color Kind Zaznacz według rodzaju koloru Objects with Spot Colors Obiekty z kolorami dodatkowymi diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 79c4d9dc8e..1856771d1d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6907,6 +6907,12 @@ anchor Points: Pontos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve ser "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` deve ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Painel Conversor de unidades + Copy with Units Copiar com unidades + From Selection Da seleção + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecionar por tipo de cor Objects with Spot Colors Objetos com cores spot diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9f608618e7..fdde9d31d0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6968,6 +6968,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` должно быть "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` должно быть [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер единиц + Unit Converter Panel Панель «Конвертер единиц» + Copy with Units Копировать с единицами + From Selection Из выделения + # Color Effects add-on: Select by Color Kind. Select by Color Kind Выделить по типу цвета Objects with Spot Colors Объекты с плашечными цветами diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6156ca23d5..813134bc5c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7000,6 +7000,12 @@ anchor Points: Punkter: @msg not an RTF file: it doesn't start with {{\\rtf inte en RTF-fil: den börjar inte med {{\\rtf shape Open Öppen +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhetsomvandlare + Unit Converter Panel Panelen Enhetsomvandlare + Copy with Units Kopiera med enheter + From Selection Från markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markera efter färgtyp Objects with Spot Colors Objekt med dekorfärger diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7120d44707..d77f2d945e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7064,6 +7064,12 @@ anchor Points: Noktalar: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` "free", "keepAngles" veya "symmetric" olmalıdır @msg `{key}` must be [x, y] `{key}` [x, y] olmalıdır +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Birim Dönüştürücü + Unit Converter Panel Birim Dönüştürücü Paneli + Copy with Units Birimlerle Kopyala + From Selection Seçimden + # Color Effects add-on: Select by Color Kind. Select by Color Kind Renk Türüne Göre Seç Objects with Spot Colors Spot Renkli Nesneler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 84f296b0a6..c160fe6bbb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6600,6 +6600,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` має бути "free", "keepAngles" або "symmetric" @msg `{key}` must be [x, y] `{key}` має бути [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер одиниць + Unit Converter Panel Панель «Конвертер одиниць» + Copy with Units Копіювати з одиницями + From Selection З виділення + # Color Effects add-on: Select by Color Kind. Select by Color Kind Виділити за типом кольору Objects with Spot Colors Об’єкти з плашковими кольорами diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e8b9e5758f..64f5118b70 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6601,6 +6601,12 @@ anchor Points: Điểm: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` phải là "free", "keepAngles" hoặc "symmetric" @msg `{key}` must be [x, y] `{key}` phải là [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Bộ chuyển đổi đơn vị + Unit Converter Panel Bảng Bộ chuyển đổi đơn vị + Copy with Units Sao chép kèm đơn vị + From Selection Từ vùng chọn + # Color Effects add-on: Select by Color Kind. Select by Color Kind Chọn theo loại màu Objects with Spot Colors Đối tượng có màu pha diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 719968086f..d22e6e9344 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6833,6 +6833,12 @@ anchor Points: 点: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必须是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必须是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 单位换算器 + Unit Converter Panel 单位换算器面板 + Copy with Units 复制时包含单位 + From Selection 从所选对象 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 按颜色类型选择 Objects with Spot Colors 使用专色的对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 121a8b8c02..5d7b0e02e5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6640,6 +6640,12 @@ anchor Points: 點: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必須是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必須是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 單位換算器 + Unit Converter Panel 單位換算器面板 + Copy with Units 複製時包含單位 + From Selection 從選取範圍 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 依顏色類型選取 Objects with Spot Colors 使用特別色的物件 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index bbe91da5a6..10f1bf3694 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -193,6 +193,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), + crate::addons::units::ID => crate::addons::units::show(app, ui), id if library_panel::parse(id).is_some() => library_panel::show(app, ui, id), _ => { dim_label(ui, tl!("This panel is on the roadmap (see the parity plan).")); diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index b759a2df7b..8e782df357 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -125,7 +125,13 @@ const PATTERN_MODES: [(&str, &str); 3] = [("object", "Transform Object Only"), ( /// Only (the pattern tiles alone) or Transform Both. Until one is chosen (`default`, or any other /// value) neither is passed: patterns follow General › Transform Pattern Tiles. Errors are /// dropped, as the panels' fields have always done. -pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json::Value) { +pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, params: serde_json::Value) { + let params = with_pattern_switches(app, params); + app.run(cmd, params).ok(); +} + +/// `params` with the `objects` and `patterns` switches [`run_transform`] adds. +pub fn with_pattern_switches(app: &VectorcraftApp, mut params: serde_json::Value) -> serde_json::Value { let switches = match app.session.prefs.transform_panel_patterns.as_str() { "object" => Some((true, false)), "pattern" => Some((false, true)), @@ -136,7 +142,7 @@ pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json params["objects"] = json!(objects); params["patterns"] = json!(patterns); } - app.run(cmd, params).ok(); + params } /// The panel menu's checked choice of [`PATTERN_MODES`]: the one chosen, else (`default`) what diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 80a87b4563..bf34a5195f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -230,6 +230,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), + (crate::addons::units::ID, "Unit Converter", "ruler"), ]; /// Groups of icon panels separated by dividers in the collapsed column. diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 89ce8d70d5..5627fe774c 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -22,29 +22,7 @@ pub(crate) fn typed_unit(ctx: &egui::Context, unit: Unit) -> Unit { if bare_points && unit == Unit::Picas { Unit::Points } else { unit } } -/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` -/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed -/// after the value the field shows) is 100 mm (#5684). A number written with both separators has -/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a -/// number that reads as thousands ([`thousands`]). -pub(super) fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { - if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } -} - -/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three -/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it -/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are -/// decimals). -fn thousands(text: &str) -> bool { - let number = text.trim().trim_start_matches('-'); - let Some((whole, rest)) = number.split_once(',') else { return false }; - let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); - (1..=3).contains(&whole.len()) - && whole.bytes().all(|b| b.is_ascii_digit()) - && !whole.starts_with('0') - && part.len() == 3 - && unit.trim().chars().all(char::is_alphabetic) -} +pub(super) use vectorcraft_doc::decimal_point; /// A recessed numeric field showing `value` (points) in `unit`. Returns the new value (points) /// when the user commits (Enter / focus loss / Shift+Enter, which keeps the focus outside dialogs). diff --git a/docs/mcp.md b/docs/mcp.md index 2e43c14d0e..af50622f56 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11855,6 +11855,45 @@ Path Options' Preview does (#5360). {"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} ``` +## Unit Converter add-on + +Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are +`addon.units.convert` and `addon.units.selectionSize`, and in the desktop app it lives in Object › Plug-ins › Unit +Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither command changes the document. + +`addon.units.convert {value, unit?}` reads `value` as a number field reads it: a number, or text with a unit suffix and +`+ - * /` arithmetic (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`, `"3cm*50%"`, `"13q"`), a decimal comma read as a point +(`"0,5 mm"`) and a single number with a thousands comma (`"1,000 mm"`) refused, in at most 1024 bytes with at most 128 `+ - * /` signs. A +number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`, +`centimeters`, `pixels`, `feetInches`, `meters`, `yards`, `feet`, `q`, `ha`; default `points`); a suffix in the text +takes precedence over `unit`. It works without an open document. The command fails when `value` is missing, does not +read, or is not finite in every unit, and when `unit` is not a unit. Result: `{points, units: [{unit, label, number, +text}]}`: the length in points, then one row per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, +px, ft & in, m, yd, ft, Q, Ha) in that order, with the unit's key, its label, the number without its suffix and the +text with it, rounded as the number fields round them (3 decimals in pt, px, picas, Q and Ha, 4 in the others). Pixels +are points. + +`addon.units.selectionSize {}` gives the selection's width and height as the Transform panel shows them: the bounding +box (rotated with rotated objects), the visual bounds with Use Preview Bounds, or the box around the selected anchor +points with Direct Selection. It fails with nothing selected. Result: `{width, height}`, each as +`addon.units.convert` gives a length. + +The panel has one field per unit. A value typed in any field updates the others as it is typed, and text that does not +read leaves them as they were. Each field's copy button puts its value on the clipboard, with the unit when Copy with +Units is on. From Selection reads the selection's size (`addon.units.selectionSize`), and Width or Height picks which +of the two the fields show; the size read is dropped when the document, its selection, Use Preview Bounds or Measure +Type by Glyph Bounds changes, and the fields keep the length they show. Apply sets that side of the selection to the length with `object.setBounds`, as the Transform +panel's W or H field does: from its reference point (a symbol instance's registration point with Use Registration Point +for Symbol on), with the other side scaled too under Constrain Width and Height Proportions, and with the panel menu's +Transform Object Only, Transform Pattern Only or Transform Both. It is one undo step, and none when the size is already +that length. + +```json +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":"10mm"}}} +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":2.5,"unit":"in"}}} +{"name":"run_command","arguments":{"command":"addon.units.selectionSize","params":{}}} +``` + ## Save location errors A save refused by the filesystem with PermissionDenied or ReadOnlyFilesystem returns diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c6375f3aa3..54a6a27828 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2297,6 +2297,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. +## Unit Converter add-on (2026-11-14) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. + ## Cutting Tools add-on: Stencil Bridges (2026-11-12) A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges.