From 2b21c1248f974c27a8ba4b497843d12642c2318d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:23:40 -0800 Subject: [PATCH 1/2] Fields: number fields outside the shared widgets read field arithmetic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Contour bar's distance, Graph Data's Number of Decimals and Column Width, Map Art's surface number, the Keyboard Shortcuts dialog's Hold Shortcut Delay, the unitless values of the 3D effect dialogs and the number fields of Character Style Options read typed text with their own readers, so `4x3` or `1+2` were not read in most of them. They now read it with the shared field arithmetic. The Contour bar's distance and Character Style Options' length fields also read a unit (`2 mm`). Warichu Settings' Lines and Scale read text given through `ui.dialog.set` the same way. These fields take `%` and `°` only where they show them, and none of them reads an exponent (`1e3`) or a space inside a number (`1 000`). In the shared unitless fields, a unit suffix, `%` or `°` between two digits is now refused: `1%2` read as 12. The Stroke panel's Limit reads `2x3` as 6 instead of 23. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/ui-egui/src/canvas/contour_bar.rs | 6 +- crates/ui-egui/src/canvas/tests.rs | 40 +++++++++++++ .../ui-egui/src/dialogs/char_style_options.rs | 31 +++++++++- crates/ui-egui/src/dialogs/graph_data.rs | 59 ++++++++++++++++++- crates/ui-egui/src/dialogs/revolve.rs | 16 +++-- crates/ui-egui/src/dialogs/revolve/tests.rs | 13 ++++ .../ui-egui/src/dialogs/tests_track_cube.rs | 37 ++++++++++++ crates/ui-egui/src/dialogs/three_d_classic.rs | 3 +- crates/ui-egui/src/dialogs/warichu.rs | 31 ++++++++-- crates/ui-egui/src/shortcut_editor.rs | 42 ++++++++++++- crates/ui-egui/src/widgets.rs | 43 +++++++++++++- crates/ui-egui/src/widgets/numeric.rs | 46 ++++++++++++++- docs/mcp.md | 8 ++- docs/target-app-parity.md | 1 + 14 files changed, 353 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/canvas/contour_bar.rs b/crates/ui-egui/src/canvas/contour_bar.rs index 4b560eeba6..f01a916738 100644 --- a/crates/ui-egui/src/canvas/contour_bar.rs +++ b/crates/ui-egui/src/canvas/contour_bar.rs @@ -88,10 +88,12 @@ pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; ui.label(egui::RichText::new(tl!("Contour")).color(t.text_strong)); - // The distance: a drag or typed value is applied when it ends, as one step. + // The distance: a drag or typed value is applied when it ends, as one step. Typed + // text reads as a length field's does (`4x3`, `2 mm`). let key = egui::Id::unique("contour-bar-offset"); let mut v = ui.data(|d| d.get_temp::(key)).unwrap_or(shown); - let resp = ui.add(egui::DragValue::new(&mut v).speed(0.5).range(-1e5..=1e5).suffix(" pt")); + let resp = + ui.add(egui::DragValue::new(&mut v).speed(0.5).range(-1e5..=1e5).suffix(" pt").custom_parser(crate::widgets::typed_points)); if resp.dragged() || resp.has_focus() { ui.data_mut(|d| d.insert_temp(key, v)); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..cb85ce653e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -14332,6 +14332,46 @@ fn the_contour_bar_sets_corners_and_bakes() { assert!(offsets(&app).is_empty(), "baked"); } +/// The Contour bar's distance reads typed text as a length field does: `4x3` is 12 pt, `2 mm` is +/// 2 mm and `−3` (a minus sign) is -3 pt, applied when Enter ends the typing. +#[test] +fn the_contour_bar_distance_takes_field_arithmetic() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + app.select_tool("contour"); + app.session.execute("addon.contour.set", &json!({"offset": 8, "corners": "round"})).unwrap(); + let ctx = egui::Context::default(); + let offset = |app: &VectorcraftApp| { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let Some(e) = n.appearance.effects.iter().find(|e| e.id == "path.offsetPath") { + found.push(e.params["offset"].as_f64().unwrap_or(f64::NAN)); + } + }); + found + }; + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + // Text that does not read (`2 qq`) leaves the distance as it was. + let mm = 2.0 * 72.0 / 25.4; + for (typed, want) in [(&["4x3"][..], 12.0), (&["2 mm"], mm), (&["\u{2212}3"], -3.0), (&["2 qq"], -3.0)] { + contour_bar_labels(&mut app, &ctx, vec![]); + let labels = contour_bar_labels(&mut app, &ctx, vec![]); + let at = labels.iter().find(|(t, _)| t.ends_with(" pt")).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no distance in {labels:?}")); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + contour_bar_labels(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + contour_bar_labels(&mut app, &ctx, vec![button(true), button(false)]); + contour_bar_labels(&mut app, &ctx, vec![]); + for part in typed { + contour_bar_labels(&mut app, &ctx, vec![egui::Event::Text((*part).into())]); + } + contour_bar_labels(&mut app, &ctx, vec![enter.clone()]); + contour_bar_labels(&mut app, &ctx, vec![]); + let got = offset(&app); + assert!(got.len() == 1 && (got[0] - want).abs() < 1e-6, "{typed:?}: {got:?}"); + } +} + /// A frame the render worker finished for `job`: white pixels of the job's size. fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done { let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] }; diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index c07f7af647..cf47c85156 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -309,6 +309,18 @@ fn case_from_attrs(attrs: &Map) -> Option<&'static str> { } } +/// The number text typed into number field `key` reads as, with the field arithmetic: a length in +/// points (`2 mm`) for the length fields, `%` only in the percent fields and `°` only in Character +/// Rotation. +fn typed_number(key: &str, text: &str) -> Option { + match key { + "size" | "leading" | "baseline_shift" | "tcyUpDown" | "tcyLeftRight" | "stroke_width" => crate::widgets::typed_points(text), + "h_scale" | "v_scale" | "fill_tint" | "stroke_tint" => crate::widgets::typed_number_with(text, "%"), + "rotation" => crate::widgets::typed_number_with(text, "°"), + _ => crate::widgets::typed_number(text), + } +} + fn optional_number(d: &Dialog, key: &str) -> Result, String> { let label = match key { "size" => tl!("Size"), @@ -338,7 +350,7 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { Some(v) => { let n = v .as_f64() - .or_else(|| v.as_str().and_then(|s| s.trim().parse::().ok())) + .or_else(|| v.as_str().and_then(|s| typed_number(key, s))) .filter(|n| n.is_finite()) .ok_or_else(|| format!("{label} must be a number"))?; // Character Style fields use the Character panel's visible ranges. @@ -1472,6 +1484,23 @@ mod tests { } assert!(same > 0, "General draws its content again: {back:?}"); } + + /// The number fields read typed text as other number fields do: `6x2`, `10+4`, `200/2`, `45°`, + /// and a length with its unit. `%` and `°` only where the field takes them, and an exponent + /// is not read. + #[test] + fn number_fields_take_field_arithmetic() { + let fields = json!({"size": "6x2", "tracking": "10+4", "h_scale": "200/2%", "rotation": "45°", "fill_tint": "25*2", "leading": "1 in"}); + let d = Dialog { kind: KIND.into(), fields: fields.as_object().unwrap().clone() }; + for (key, want) in [("size", 12.0), ("tracking", 14.0), ("h_scale", 100.0), ("rotation", 45.0), ("fill_tint", 50.0), ("leading", 72.0)] { + assert_eq!(optional_number(&d, key), Ok(Some(json!(want))), "{key}"); + } + for (key, text) in [("size", "12°"), ("leading", "50%"), ("tracking", "10%"), ("rotation", "45%"), ("h_scale", "1%2"), ("size", "1e3")] { + let d = Dialog { kind: KIND.into(), fields: json!({ key: text }).as_object().unwrap().clone() }; + assert!(optional_number(&d, key).is_err(), "{key} {text}"); + } + } + #[test] fn unchanged_basic_fields_preserve_original_keys() { for attrs in [ diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ab46dbd82c..e1a2071108 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -379,14 +379,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { dec = on.then_some(2); } let mut n = dec.unwrap_or(2); - if ui.add_enabled(on, egui::DragValue::new(&mut n).range(0..=MAX_DECIMALS)).changed() { + let field = egui::DragValue::new(&mut n).range(0..=MAX_DECIMALS).custom_parser(widgets::typed_number); + if ui.add_enabled(on, field).changed() { dec = Some(n); } d.fields.insert("decimals".into(), json!(dec)); ui.add_space(12.0); widgets::dim_label(ui, tl!("Column Width:")); let mut w = d.fields.get("width").and_then(Value::as_u64).unwrap_or(7); - let r = ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)); + let r = ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH).custom_parser(widgets::typed_number)); // A value entered with Enter sets every column, also when it is the width shown. Leaving the // field without a new value keeps the columns' own widths. if r.changed() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) { @@ -901,6 +902,60 @@ mod tests { assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (7, 7, 7), "Column Width sets every column"); } + /// Cell Style's Number of Decimals and Column Width read typed text as other number fields do: + /// `1+2` is 3 decimals and `4x3` is 12 digits. + #[test] + fn cell_style_fields_take_field_arithmetic() { + let (mut app, _) = app_with("a,b\n1,2", "column"); + open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("decimals".into(), json!(2)); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + for _ in 0..3 { + frame(&mut app, vec![]); + } + // The spin button right of the label `name`. + let field_after = |app: &mut VectorcraftApp, name: &str| { + let nodes = frame(app, vec![]); + let label = nodes + .iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::Label && n.value() == Some(name)) + .and_then(|(_, n)| n.bounds()) + .unwrap_or_else(|| panic!("the {name} label is drawn")); + let field = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::SpinButton) + .filter_map(|(_, n)| n.bounds()) + .filter(|b| b.x0 >= label.x1 && b.y0 < label.y1 && b.y1 > label.y0) + .min_by(|a, b| a.x0.total_cmp(&b.x0)) + .unwrap_or_else(|| panic!("the {name} field is drawn")); + egui::pos2(((field.x0 + field.x1) / 2.0) as f32, ((field.y0 + field.y1) / 2.0) as f32) + }; + for (name, typed) in [("Number of Decimals:", "1+2"), ("Column Width:", "4x3")] { + let at = field_after(&mut app, name); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]); + frame(&mut app, vec![button(at, false)]); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text(typed.into())]); + frame(&mut app, vec![enter.clone()]); + frame(&mut app, vec![]); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields.get("decimals"), Some(&json!(3)), "1+2 decimals"); + assert_eq!((col_digits(d, 0), col_digits(d, 1)), (12, 12), "4x3 digits for every column"); + } + #[test] fn a_column_width_in_points_maps_to_whole_digits() { for n in 0..=MAX_WIDTH { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 568acdb121..eed2c1d33a 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -739,6 +739,15 @@ fn rail_width(ui: &egui::Ui) -> f32 { (ui.available_width() - VALUE_W - 24.0 - 18.0).clamp(40.0, 134.0) } +/// The value text typed into a [`number`] field showing `suffix` reads as: a length in `unit` (read +/// in the `typed` unit when one is given), otherwise a number with the field arithmetic. +fn typed_value(text: &str, suffix: &str, unit: Option, typed: Option) -> Option { + match unit { + Some(u) => typed.unwrap_or(u).parse(text).map(|v| u.from_pt(v)), + None => widgets::typed_number_with(text, suffix), + } +} + /// A value can be typed, dragged, scrubbed by its label, or moved on its slider. #[allow(clippy::too_many_arguments)] pub(super) fn number(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, range: (f64, f64), suffix: &str, decimals: usize, unit: Option) { @@ -770,12 +779,7 @@ pub(super) fn number(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, r .max_decimals(decimals) .suffix(&suffix) .update_while_editing(false) - .custom_parser(|s| { - unit.map_or_else( - || vectorcraft_doc::parse_number(&s.replace(['°', '%'], "")), - |u| typed.unwrap_or(u).parse(s).map(|v| u.from_pt(v)), - ) - }), + .custom_parser(|s| typed_value(s, &suffix, unit, typed)), ) }) .inner; diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index dd5f05ad5d..23a6e852b1 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -903,3 +903,16 @@ fn lighting_presets_cancel_restores_an_existing_custom_light_rig() { dialogs::cancel(&mut h.app); assert_eq!(h.app.session.doc().unwrap().doc, before); } + +/// Unitless values read typed text as other number fields do; the field's `°` or `%` only after an +/// operand, never between two digits. +#[test] +fn typed_values_take_field_arithmetic() { + for (text, suffix, want) in [("45*2", "°", 90.0), ("45x2°", "°", 90.0), ("12,5", "", 12.5), ("50%", "%", 50.0), ("\u{2212}30", "°", -30.0)] { + assert_eq!(typed_value(text, suffix, None, None), Some(want), "{text}"); + } + for (text, suffix) in [("1%2", "%"), ("4°5", "°"), ("8%", ""), ("30%", "°")] { + assert_eq!(typed_value(text, suffix, None, None), None, "{text}"); + } + assert_eq!(typed_value("1 in", " pt", Some(Unit::Points), None), Some(72.0)); +} diff --git a/crates/ui-egui/src/dialogs/tests_track_cube.rs b/crates/ui-egui/src/dialogs/tests_track_cube.rs index 9e36fb89f0..d1cd116c47 100644 --- a/crates/ui-egui/src/dialogs/tests_track_cube.rs +++ b/crates/ui-egui/src/dialogs/tests_track_cube.rs @@ -216,3 +216,40 @@ fn map_art_surfaces_follow_the_active_document() { assert_ne!(first, second, "the two objects' solids differ in size"); assert_eq!(Some(first.as_ref()), own.as_ref(), "the first document's surfaces"); } + +/// Map Art's surface number reads typed text as other number fields do: `1+2` shows surface 3. +#[test] +fn the_map_art_surface_field_takes_field_arithmetic() { + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + app.run("path.create", json!({"d": "M50 50L150 50L150 150L50 150Z"})).unwrap(); + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + assert!(surfaces(&app, &ctx, &d).unwrap().len() >= 3, "the extruded square has at least 3 surfaces"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let frame = |d: &mut Dialog, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| map_art_controls(&app, ui, d)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + frame(&mut d, vec![]); + let nodes = frame(&mut d, vec![]); + let field = nodes + .iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::SpinButton && n.label() == Some("Surface")) + .and_then(|(_, n)| n.bounds()) + .expect("the Surface field is drawn"); + let at = pos2(((field.x0 + field.x1) / 2.0) as f32, ((field.y0 + field.y1) / 2.0) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut d, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut d, vec![button(false)]); + frame(&mut d, vec![]); + frame(&mut d, vec![egui::Event::Text("1+2".into())]); + frame(&mut d, vec![enter]); + frame(&mut d, vec![]); + assert_eq!(shown_surface(&d, 99), 3, "1+2 shows surface 3"); +} diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index f25251f574..d6049ee230 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -128,7 +128,8 @@ pub(super) fn map_art_controls(app: &crate::VectorcraftApp, ui: &mut egui::Ui, d next = Some(current - 1); } let mut typed = current; - let field = ui.add_sized([44.0, 24.0], egui::DragValue::new(&mut typed).range(1..=count).speed(0.1)); + let field = egui::DragValue::new(&mut typed).range(1..=count).speed(0.1).custom_parser(crate::widgets::typed_number); + let field = ui.add_sized([44.0, 24.0], field); field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, true, tl!("Surface"))); if field.changed() { next = Some(typed); diff --git a/crates/ui-egui/src/dialogs/warichu.rs b/crates/ui-egui/src/dialogs/warichu.rs index 156d10e596..c9893caff2 100644 --- a/crates/ui-egui/src/dialogs/warichu.rs +++ b/crates/ui-egui/src/dialogs/warichu.rs @@ -111,14 +111,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// A number field's value: a number, or a string that reads as one (`"3"`, `"40%"`); `None` for a -/// blank field. `Err` names the field when it holds anything else. -fn number(d: &Dialog, key: &str, name: &str) -> Result, String> { +/// A number field's value: a number, or a string that reads as one (`"3"`, `"20*2"`, and `"40%"` +/// when `suffix` is `%`); `None` for a blank field. `Err` names the field when it holds anything else. +fn number(d: &Dialog, key: &str, name: &str, suffix: &str) -> Result, String> { let v = match d.fields.get(key) { None | Some(Value::Null) => return Ok(None), Some(Value::String(s)) if s.trim().is_empty() => return Ok(None), Some(Value::Number(n)) => n.as_f64(), - Some(Value::String(s)) => s.trim().trim_end_matches('%').trim().parse::().ok(), + Some(Value::String(s)) => crate::widgets::typed_number_with(s, suffix), Some(_) => None, }; v.filter(|v| v.is_finite()).map(Some).ok_or_else(|| format!("{name} must be a number")) @@ -135,7 +135,7 @@ fn params(d: &Dialog) -> Result, String> { let unchanged = |key: &str, v: &Value| initial.and_then(|m| m.get(key)) == Some(v); let opened_with = |key: &str, v: f64| initial.and_then(|m| m.get(key)).and_then(Value::as_f64) == Some(v); let mut p = Map::new(); - if let Some(n) = number(d, "warichuLines", "Lines")?.filter(|&n| !opened_with("warichuLines", n)) { + if let Some(n) = number(d, "warichuLines", "Lines", "")?.filter(|&n| !opened_with("warichuLines", n)) { let n = n.round().clamp(f64::from(*WARICHU_LINES.start()), f64::from(*WARICHU_LINES.end())); // Within 1..6 after the clamp, so the cast keeps the value. let v = json!(n as u8); @@ -155,7 +155,7 @@ fn params(d: &Dialog) -> Result, String> { { p.insert("warichuGap".into(), json!(v)); } - if let Some(n) = number(d, "warichuScale", "Scale")?.filter(|&n| !opened_with("warichuScale", n)) { + if let Some(n) = number(d, "warichuScale", "Scale", "%")?.filter(|&n| !opened_with("warichuScale", n)) { let v = n.clamp(*WARICHU_SCALE.start(), *WARICHU_SCALE.end()); if !opened_with("warichuScale", v) { p.insert("warichuScale".into(), json!(v)); @@ -257,6 +257,25 @@ mod tests { assert_eq!(params(&d).unwrap().get("warichuGap"), Some(&json!(MAX_WARICHU_GAP))); } + /// Lines and Scale given as text read as other number fields read it: `1+2` lines and `30x2%`. + #[test] + fn warichu_settings_dialog_reads_field_arithmetic() { + let opened = json!({"warichuLines": 2, "warichuGap": 0.0, "warichuScale": 50.0}); + let mut fields = opened.clone(); + fields[INITIAL] = opened; + let mut d = Dialog::new(KIND, fields); + d.fields.insert("warichuLines".into(), json!("1+2")); + d.fields.insert("warichuScale".into(), json!("30x2%")); + let p = params(&d).unwrap(); + assert_eq!((p.get("warichuLines"), p.get("warichuScale")), (Some(&json!(3)), Some(&json!(60.0)))); + // `%` only in Scale, and neither field reads an exponent or a mark between two digits. + for (key, text) in [("warichuLines", "3%"), ("warichuLines", "1e0"), ("warichuScale", "1%2"), ("warichuScale", "2e1")] { + let mut d = d.clone(); + d.fields.insert(key.into(), json!(text)); + assert!(params(&d).is_err(), "{key} {text}"); + } + } + /// Characters that differ open a blank field; OK leaves that value alone and sets the others. #[test] fn warichu_settings_dialog_leaves_mixed_values_blank() { diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a9d7b022a7..39cfa6e806 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -2320,7 +2320,8 @@ fn hold_row(ui: &mut egui::Ui, t: &Tokens, d: &mut Dialog) { ui.label(egui::RichText::new(tl!("Hold Shortcut Delay")).color(t.text_dim)); let (min, max) = vectorcraft_engine::KEY_HOLD_DELAY_RANGE; let mut delay = dialog_hold_delay(d); - if ui.add(egui::DragValue::new(&mut delay).range(min..=max).speed(0.01).fixed_decimals(2).suffix(" s")).changed() { + let field = egui::DragValue::new(&mut delay).range(min..=max).speed(0.01).fixed_decimals(2).suffix(" s"); + if ui.add(field.custom_parser(|s| crate::widgets::typed_number_with(s, "s"))).changed() { d.fields.insert("keyHoldDelay".into(), json!(delay)); } } @@ -3881,6 +3882,45 @@ mod tests { assert_eq!(app.ui.engine_prefs["keyHoldDelay"], json!(0.5)); } + /// The Hold Shortcut Delay reads typed text as other number fields do, its `s` after any operand: + /// `0.25 s x 2` is half a second. + #[test] + fn the_hold_shortcut_delay_takes_field_arithmetic() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + open(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("holdShortcuts".into(), json!(true)); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + out.shapes + .into_iter() + .filter_map(|c| match c.shape { + egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())), + _ => None, + }) + .collect::>() + }; + frame(&mut app, vec![]); + let texts = frame(&mut app, vec![]); + let shown = format!("{:.2}", dialog_hold_delay(app.ui.dialog.as_ref().unwrap())); + let at = texts.iter().find(|(t, _)| *t == shown).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{shown}` in {texts:?}")); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut app, vec![button(false)]); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text("0.25 s x 2".into())]); + frame(&mut app, vec![enter]); + frame(&mut app, vec![]); + // Enter may also end the dialog with OK, which writes the delay to the preferences. + let delay = app.ui.dialog.as_ref().map_or(app.session.prefs.key_hold_delay, dialog_hold_delay); + assert_eq!(delay, 0.5, "0.25 s x 2"); + } + /// The info button shows how hold shortcuts work. #[test] fn the_info_button_explains_hold_shortcuts() { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b67df13c7f..a17d9b0e85 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -62,7 +62,7 @@ pub use dropdowns::{ pub(crate) use dropdowns::{menu_floor, menu_room_either}; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; -pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; +pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_number, typed_number_with, typed_points, typed_unit}; pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, num_field_within_empty, opt_field, opt_field_named, plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped, @@ -657,6 +657,47 @@ mod field_number_tests { assert_eq!(field_number("50% / 2", "%", false), Some(25.0)); } + /// A field that is not a numeric field widget (a drag value's text, a dialog's text field) reads + /// what a plain field reads: arithmetic, `x` as a multiplication sign and a decimal comma, with + /// `%` and `°` only when the field shows them. + #[test] + fn typed_numbers_take_field_arithmetic() { + for (text, want) in [("45*2", 90.0), ("4x3", 12.0), (" 10 + 5 ", 15.0), ("100/4", 25.0), ("12,5", 12.5), ("7", 7.0)] { + assert_eq!(super::typed_number(text), Some(want), "{text}"); + } + for text in ["", "abc", "1,000", "(12)", "3%", "2°", "1e3", "1 000"] { + assert_eq!(super::typed_number(text), None, "{text}"); + } + assert_eq!(super::typed_number_with("12,5%", "%"), Some(12.5)); + assert_eq!(super::typed_number_with("45°", "°"), Some(45.0)); + assert_eq!(super::typed_number_with("45%", "°"), None, "a mark the field does not show"); + assert_eq!(super::typed_points("4x3"), Some(12.0)); + assert_eq!(super::typed_points("1 in"), Some(72.0)); + assert_eq!(super::typed_points("\u{2212}2"), Some(-2.0)); + assert_eq!(super::typed_number("\u{2212}5"), Some(-5.0), "a minus sign"); + assert_eq!(super::typed_number_with("0.25 s x 2", "s"), Some(0.5), "the field's suffix"); + assert_eq!(super::typed_number("0.25 s"), None, "a suffix the field does not show"); + // The suffix, `%` and `°` only follow an operand; between two digits they are refused. + for (text, suffix) in [("1%2", "%"), ("4°5", "°"), ("0.2s5", "s"), ("%5", "%"), ("2 % 3", "%")] { + assert_eq!(super::typed_number_with(text, suffix), None, "{text}"); + } + assert_eq!(field_number("1%2", "%", false), None, "a numeric field's own suffix"); + assert_eq!(field_number("1%2", "", false), None, "`%` in any field"); + assert_eq!(field_number("50%-2", "%", false), Some(48.0), "subtraction after the suffix"); + assert_eq!(super::typed_number_with("45°\u{2212}15", "°"), Some(30.0), "a minus sign after the suffix"); + assert_eq!(super::typed_number_with("25% + 5%", "%"), Some(30.0)); + } + + /// A field whose suffix is a multiplication sign (the Stroke panel's Limit, `4 x`) reads `x` + /// inside the text as multiplication and only a final one as its suffix. + #[test] + fn a_multiplication_sign_suffix_still_multiplies() { + for (text, want) in [("2x3", 6.0), ("4 x", 4.0), ("2 x 3 x", 6.0), ("5", 5.0), ("10x", 10.0)] { + assert_eq!(field_number(text, " x", false), Some(want), "{text}"); + } + assert_eq!(field_number("x4", " x", false), None); + } + /// A resolution field reads the unit it shows: "200 ppp" in a French interface. #[test] fn a_resolution_field_reads_its_translated_unit() { diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index a9d4020ab3..a3c0ca6a35 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -947,9 +947,16 @@ fn bounded_field_reading( /// automatic value as `(12)`), one pair of parentheses around the whole text is dropped first, so /// `(12)` reads as 12. Any other parentheses are refused: `(10+5)*2` reads as nothing, not as /// `10+5*2`. A decimal comma is read ([`decimal_point`]) after the suffix, `%`, `°` and that pair -/// are dropped, so `(1,000)` and `1,000%` are refused as thousands rather than read as 1. +/// are dropped, so `(1,000)` and `1,000%` are refused as thousands rather than read as 1. The +/// suffix, `%` or `°` between two digits is refused: `1%2` reads as nothing, not as 12. A suffix +/// that is a multiplication sign (the Stroke panel's Limit, `4 x`) is the suffix only at the end of +/// the text, so `2x3` reads as 6. pub(super) fn field_number(buf: &str, suffix: &str, parentheses: bool) -> Option { let suffix = suffix.trim(); + let (buf, suffix) = if matches!(suffix, "x" | "X" | "×") { (buf.trim_end().strip_suffix(suffix).unwrap_or(buf), "") } else { (buf, suffix) }; + if !marks_follow_operands(buf, suffix) { + return None; + } let bare = if suffix.is_empty() { buf.to_string() } else { buf.replace(suffix, "") }; let bare = bare.replace(['%', '°'], ""); let bare = bare.trim(); @@ -957,6 +964,43 @@ pub(super) fn field_number(buf: &str, suffix: &str, parentheses: bool) -> Option vectorcraft_doc::parse_number(&decimal_point(bare)) } +/// Whether each `suffix`, `%` and `°` in `buf` comes right after an operand (a digit, a decimal +/// point or comma, or `)`) and is followed only by an operator, `)` or the end of the text. +fn marks_follow_operands(buf: &str, suffix: &str) -> bool { + [suffix, "%", "°"].into_iter().filter(|m| !m.is_empty()).all(|mark| { + buf.match_indices(mark).all(|(at, m)| { + let before = buf.get(..at).and_then(|s| s.trim_end().chars().next_back()); + let after = buf.get(at + m.len()..).and_then(|s| s.trim_start().chars().next()); + before.is_some_and(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | ')')) + && after.is_none_or(|c| matches!(c, '+' | '-' | '*' | '/' | 'x' | 'X' | '×' | ')' | '%' | '°')) + }) + }) +} + +/// A unitless number typed into a field that is not a [`bounded_field`] (an `egui::DragValue`'s +/// parser, a dialog's text field): the same `+ - * /` and `x` arithmetic and decimal comma as +/// [`field_number`], so `45*2`, `4x3` and `12,5` read as 90, 12 and 12.5. `%` and `°` are refused. +pub(crate) fn typed_number(text: &str) -> Option { + typed_number_with(text, "") +} + +/// [`typed_number`] for a field showing `suffix` after its value (`s`, `%` or `°`), which may +/// follow any operand as in [`field_number`]. `%` and `°` are refused unless they are the suffix. +/// A minus sign (U+2212) reads as `-`, as `egui::DragValue`'s own parser reads it. +pub(crate) fn typed_number_with(text: &str, suffix: &str) -> Option { + let suffix = suffix.trim(); + if ['%', '°'].into_iter().any(|mark| text.contains(mark) && !suffix.contains(mark)) { + return None; + } + field_number(&text.replace('\u{2212}', "-"), suffix, false) +} + +/// A length typed into a field that is not a length field widget, in points: a bare number is in +/// points, and a unit, arithmetic and a decimal comma read as in a length field (`4x3`, `2 mm`). +pub(crate) fn typed_points(text: &str) -> Option { + vectorcraft_doc::Unit::Points.parse(&decimal_point(&text.replace('\u{2212}', "-"))) +} + /// The text [`plain_field`] shows for `value`: at most `decimals` places, without trailing zeros, /// then `suffix`. pub(super) fn field_text(value: f64, suffix: &str, decimals: usize) -> String { diff --git a/docs/mcp.md b/docs/mcp.md index 5a2c7eeb7d..6bcdc37895 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11924,7 +11924,8 @@ outside its range is refused with `` `warichuLines` must be a whole number from `` `warichuScale` must be from 10 to 100 ``, naming the key, and an unknown alignment with the list of the values. One undo step; a `text.setFormat` call that changes nothing records none. `ui.warichuSettings` opens the Warichu Settings dialog on the values the selected characters share, a blank field where they differ; OK sends the values that changed and leaves a -blank field's value alone. OK with a field that is not a number returns `Lines must be a number`, +blank field's value alone. Lines and Scale given as text take the arithmetic of the app's number fields (`"1+2"`, +`"30x2%"`); `%` is read only in Scale. OK with a field that is not a number returns `Lines must be a number`, `Line Gap must be a number` or `Scale must be a number` and keeps the dialog open. ```json @@ -12928,7 +12929,10 @@ dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning` `tcyLeftRight`, `rotation`, `akiLeft`, `akiRight`, `tsume`, `diacriticHorizontal`, `diacriticVertical`, `language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, `ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, `ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its -attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. +attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. A number field +given as text takes the arithmetic of the app's number fields (`"6x2"`, `"10+4"`); `size`, `leading`, `baseline_shift`, +`tcyUpDown`, `tcyLeftRight` and `stroke_width` also read a unit (`"1 in"`), `%` is read only in `h_scale`, `v_scale`, +`fill_tint` and `stroke_tint`, and `°` only in `rotation`. Advanced Character Formats holds `h_scale` and `v_scale` (percent, 1 to 10000), `baseline_shift` (points, -1296 to 1296), the Tate-chu-yoko Settings `tcyUpDown` and `tcyLeftRight` (points, -1296 to 1296, as `text.setRangeStyle` takes them; an explicit 0 stays distinct from unset), `rotation` (degrees, stored from -180 to 180), Insert Aki Left and Right `akiLeft` and `akiRight` (thousandths of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 125b9f2019..4edb10df12 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1075,6 +1075,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Numeric fields keep the pointer's pressed character as the text-drag start when movement exceeds the click threshold (#1326); a completed focus click selects the unit too. Pixel/point, plain and optional fields are regression-tested in both directions, before/after focus, with replacement text; keyboard focus, double-click, arrows and wheel keep their prior behavior. Native egui input confirms partial replacement gives 17 px instead of 700 px, one Undo/Redo, window captures and an exact saved-document read in a separate CLI process. A focus click released more than 1 pt from its press keeps the caret, and a tap within 1 pt still selects all (#6659; short-drag and jitter-tap regressions in `tests/numfields.rs`). - Unit fields and length strings take `%` in arithmetic: `3cm*50%` reads as 1.5 cm, and `50pt+25%` reads as 62.5 pt. - Value fields and length strings read `x` as a multiplication sign, as they read `*` (#8435; the help's "Calculate values in a panel or dialog box" lists `x` for multiplication: [help PDF, archived](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). `X` and `×` also multiply; that is VectorCraft's own choice. `10x2` reads as 20 and `2x3 mm` as 6 mm. A lowercase `x` right after a `p` stays the `px` unit (`2px x 3` is 6 px, and `2px3` is not read). Tests: `x_is_a_multiplication_sign` in `crates/doc/src/tests/units.rs`. + - The number fields drawn without the shared field widgets read typed text with the same arithmetic: the Contour bar's distance (`4x3` is 12 pt, `2 mm` is 2 mm), Graph Data's Number of Decimals and Column Width, Map Art's surface number, the Keyboard Shortcuts dialog's Hold Shortcut Delay, the unitless values of the 3D effect dialogs and the number fields of Character Style Options, whose length fields also read a unit (`1 in` is 72 pt). Warichu Settings' Lines and Scale read text given through `ui.dialog.set` (MCP `answer_dialog`) the same way. These fields take `%` and `°` only where they show them. An exponent (`1e3`) and a space inside a number (`1 000`) are not read in these fields, though several of them read both before. In the shared unitless fields a unit suffix, `%` or `°` between two digits is refused (`1%2` was read as 12), and the Stroke panel's Limit reads `2x3` as 6 (it read 23). Tests: the `vectorcraft-ui-egui` tests whose names end in `take_field_arithmetic`, `warichu_settings_dialog_reads_field_arithmetic` and `a_multiplication_sign_suffix_still_multiplies`. - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools, the Type tools, the basic shape tools, the Smooth tool and the Artboard tool show it). - A click on another object moves the contextual task bar under it without hiding it for the press; it gives way only to a drag (#4681). - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. From c3c2b0294ed28ca7d0ae3773dd2938ef70c03f9e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 16:41:48 -0800 Subject: [PATCH 2/2] Fields: Tsume reads a percent sign like the other percent fields The Tsume field in Advanced Character Formats shows a % beside it but read its text as a unitless number, so 25% and 50%/2 were rejected with "Tsume must be a number". It now takes the percent field dispatch; the 0 to 100 clamp still applies. --- crates/ui-egui/src/dialogs/char_style_options.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index cf47c85156..f5174d1231 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -315,7 +315,7 @@ fn case_from_attrs(attrs: &Map) -> Option<&'static str> { fn typed_number(key: &str, text: &str) -> Option { match key { "size" | "leading" | "baseline_shift" | "tcyUpDown" | "tcyLeftRight" | "stroke_width" => crate::widgets::typed_points(text), - "h_scale" | "v_scale" | "fill_tint" | "stroke_tint" => crate::widgets::typed_number_with(text, "%"), + "h_scale" | "v_scale" | "tsume" | "fill_tint" | "stroke_tint" => crate::widgets::typed_number_with(text, "%"), "rotation" => crate::widgets::typed_number_with(text, "°"), _ => crate::widgets::typed_number(text), } @@ -2017,7 +2017,7 @@ mod tests { assert_eq!(d.fields["tsume"], json!("")); let mut d = dialog_for(json!({"tsume": 50.0})); assert_eq!(d.fields["tsume"], json!(50.0)); - for (typed, kept) in [("0", 0.0), ("25.5", 25.5), ("150", 100.0), ("-5", 0.0)] { + for (typed, kept) in [("0", 0.0), ("25.5", 25.5), ("25%", 25.0), ("50%/2", 25.0), ("150", 100.0), ("-5", 0.0)] { d.fields.insert("tsume".into(), json!(typed)); assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"tsume": kept})), "{typed}"); }