From a49698ee3dbac75967585cc236df7b97bc316ed4 Mon Sep 17 00:00:00 2001 From: Ahmad Khan Date: Sun, 25 Oct 2026 05:34:03 +0000 Subject: [PATCH] Value fields step with the arrow keys and the mouse wheel (#2320) (#2608) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #2320 * Value fields step with the arrow keys and the mouse wheel (#2320) Up/Down in a focused value field step a plain number by 1 in the unit it is written in ("20 mm" -> "21 mm", "2,5 mm" -> "3,5 mm"), 10 with Shift and 0.1 with Alt; the wheel over the focused field does the same, a step a notch, instead of scrolling the panel under it. Expressions such as `width / 2` are left as typed, and an open completion list keeps the arrows. Every expression field gets this through `params_dialog::complete`: the value box beside the geometry in every dialog, the dialog rows, sketch dimensions, the dimension editor, Drive Joint and the Parameters window. * The value box beside the geometry stays under the pointer The box rides on the arrow's tip, so each wheel notch that stepped its value moved it, and after a notch or two the box slid out from under the pointer and the wheel zoomed the view instead. While the pointer is over it the box now keeps its place, and it goes back to the tip when the pointer leaves. * Value stepping is a preference, off by default Preferences › General › "Step values with the arrow keys and the wheel" (`step_values`, also through `ui.prefs`) turns on Up/Down and wheel stepping in value fields, and the value box staying under the pointer while the wheel steps it. Off, as by default, value fields behave as before: Up/Down move the text cursor, the wheel scrolls, and the box beside the geometry follows its arrow. * Value stepping test: Bend Radius is under Advanced now * Value stepping test: the preference is on the Design page * Value stepping test: draw the field straight into the test's frame (#2320) The shared outer-host rule now covers tests too; the field needs no panel around it. --- assets/locales/en.json | 2 + assets/locales/ja.json | 2 + assets/locales/zh.json | 2 + crates/ui-egui/src/canvas.rs | 13 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/navigation.rs | 9 + crates/ui-egui/src/params_dialog.rs | 7 +- crates/ui-egui/src/prefs.rs | 3 + crates/ui-egui/src/prefs/design.rs | 3 + crates/ui-egui/src/value_step.rs | 189 +++++++++++++ crates/ui-egui/src/value_step_tests.rs | 368 +++++++++++++++++++++++++ docs/book/src/guide/parameters.md | 7 + docs/book/src/guide/shortcuts.md | 4 +- docs/control-protocol.md | 2 +- 14 files changed, 607 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/value_step.rs create mode 100644 crates/ui-egui/src/value_step_tests.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index d8d58e629..0874e1e3c 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -3003,6 +3003,8 @@ "ui.start": "Start", "ui.start_over": "Start over", "ui.start_page": "Start page", + "ui.step_values": "Step values with the arrow keys and the wheel", + "ui.step_values_tip": "In a value field you are typing in, Up/Down change a plain number by 1 (Shift: 10, Alt: 0.1), and so does the mouse wheel over the field. Expressions are left as typed.", "ui.stretch": "Stretch", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Only when the view is still", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index fcd6770d3..66bb90114 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -3003,6 +3003,8 @@ "ui.start": "開始", "ui.start_over": "最初からやり直す", "ui.start_page": "スタートページ", + "ui.step_values": "矢印キーとホイールで数値を増減", + "ui.step_values_tip": "入力中の値フィールドでは、上下矢印キーとフィールド上のマウスホイールで数値を 1 ずつ増減します(Shift: 10、Alt: 0.1)。式はそのまま残ります。", "ui.stretch": "伸縮", "ui.supersampling": "スーパーサンプリング (SSAA)", "ui.supersampling_adaptive": "ビューが静止しているときのみ", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 27f76b63b..7364e0c27 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -3003,6 +3003,8 @@ "ui.start": "开始", "ui.start_over": "重新开始", "ui.start_page": "起始页", + "ui.step_values": "使用方向键和滚轮调整数值", + "ui.step_values_tip": "在正在输入的数值框中,上下方向键和框上的鼠标滚轮可将数字增减 1(Shift:10,Alt:0.1)。表达式保持不变。", "ui.stretch": "伸展", "ui.supersampling": "超级采样 (SSAA)", "ui.supersampling_adaptive": "仅在视图静止时", diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fe65e4b6f..c4438c5bd 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -617,7 +617,10 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, /// top-left corner. `select_all` re-selects the whole field, both right after a pick and on every /// frame a drag is changing the value underneath it: without the latter, a drag that grows the /// text (e.g. "4 mm" -> "15 mm") would leave the stale, shorter selection from the pick in place, -/// covering only part of the new text. +/// covering only part of the new text. With value stepping on, the box stays where it is while +/// the pointer is over it: the wheel steps its value (`value_step`), which moves the arrow tip +/// the box follows, and a box sliding out from under the pointer would hand the next notch to +/// the camera. fn value_box(ui: &mut egui::Ui, label: &str, value: &mut String, at: Pos2, select_all: bool) { value_box_with(ui, label, value, at, select_all, false); } @@ -661,6 +664,14 @@ fn value_box_full( note: Option<&str>, ) -> Option { let t = Tokens::get(); + // Held in place while the pointer is over it and value stepping is on (see `value_box`): by + // its pivot, the point of the box that sits at `at`, which is not always its top-left corner. + let pointer = ui.ctx().pointer_hover_pos(); + let at = ui + .ctx() + .memory(|m| m.area_rect(area)) + .filter(|r| crate::value_step::enabled(ui.ctx()) && pointer.is_some_and(|p| r.contains(p))) + .map_or(at, |r| pivot.pos_in_rect(&r)); let mut field = None; Container::new(ui.ctx(), Surface::Canvas).area(area).fixed_pos(at).pivot(pivot).order(egui::Order::Foreground).show(ui.ctx(), |ui| { Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2d19edc94..1d450a834 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -261,6 +261,7 @@ pub mod ui_kit; #[cfg(test)] mod ui_kit_guard_tests; pub mod update; +mod value_step; pub mod view_pick; pub mod viewport; mod viewport_layout; @@ -1754,6 +1755,7 @@ impl SolveApp { /// Lay out the whole window. pub fn ui(&mut self, ui: &mut egui::Ui) { + value_step::set_enabled(ui.ctx(), self.preferences.step_values); let t0 = now_ms(); // The first frames draw with the bundled faces while the system's CJK, Hangul and Thai // faces are read on a thread; the fonts are installed again once they are there. diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 0ab865eb0..8486bf0d9 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -186,6 +186,15 @@ pub(crate) fn pinch_factor(input: &egui::InputState) -> f32 { .fold(1.0, |acc, f| acc * f) } +/// Give this frame's wheel to the widget under the pointer that uses it itself (a value field +/// stepping its number, `value_step`): no scroll area or camera under it moves as well. +pub(crate) fn claim_wheel(ctx: &egui::Context) { + ctx.input_mut(|i| { + i.smooth_scroll_delta = egui::Vec2::ZERO; + i.events.retain(|e| !matches!(e, egui::Event::MouseWheel { .. })); + }); +} + /// Zoom anchor: the model point under the cursor, else the target's depth. /// Preferences › Navigation › Zoom to the cursor (off: toward the view's centre). pub(crate) fn zoom_anchor(app: &mut SolveApp, rect: egui::Rect, hover: Option, surface: bool) -> Option { diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs index d6a3ad3e7..73fcbd6b4 100644 --- a/crates/ui-egui/src/params_dialog.rs +++ b/crates/ui-egui/src/params_dialog.rs @@ -780,10 +780,11 @@ pub(crate) fn unit_token(ctx: &egui::Context, word: &str) -> bool { all.iter().any(|s| s.kind == "unit" && s.text == word) } -/// Offer keyboard and pointer completions under a focused expression box. -/// Returns true when a suggestion was accepted; callers must not submit that frame. +/// Offer keyboard and pointer completions under a focused expression box, and step a plain +/// number in it with Up/Down or the wheel (`value_step`, #2320). +/// Returns true when either changed the text; callers must not submit that frame. pub fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut String) -> bool { - crate::expression_complete::complete(ui, resp, text) + crate::expression_complete::complete(ui, resp, text) || crate::value_step::step(ui, resp, text) } #[cfg(test)] diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 61d9863bc..cf93af5af 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -538,6 +538,9 @@ preference_settings! { /// Decimals shown for lengths and angles. length_decimals: u8 = 2, PAGE_DESIGN; angle_decimals: u8 = 1, PAGE_DESIGN; + /// Up/Down and the wheel over a focused value field step its plain number (`value_step`, + /// #2320). Off by default: the keys move the text cursor and the wheel scrolls, as before. + step_values: bool = false, PAGE_DESIGN => check_id("ui.step_values"); /// `dark`, `light` or `system` (follow the operating system), or a theme file's id: a /// built-in one (`gruvbox-dark`, …) or one of `custom_themes` (#2255). theme: String = "dark".into(), PAGE_INTERFACE; diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs index b8fd9e81b..40c890752 100644 --- a/crates/ui-egui/src/prefs/design.rs +++ b/crates/ui-egui/src/prefs/design.rs @@ -32,6 +32,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::settings_precision_sample(ui, &format!("{:.*}°", usize::from(app.preferences.angle_decimals.min(6)), 45.0)); }); }); + let tip = app.tr("ui.step_values_tip").to_string(); + let step = setting::step_values(app, ui).on_hover_text(tip); + crate::scenario::publish_handle("prefs:step_values", step.rect.center()); }); ui_kit::settings_section(ui, "orientation", app.tr("prefs.orientation"), |ui| { ui.horizontal_wrapped(|ui| { diff --git a/crates/ui-egui/src/value_step.rs b/crates/ui-egui/src/value_step.rs new file mode 100644 index 000000000..a8a0cbfb2 --- /dev/null +++ b/crates/ui-egui/src/value_step.rs @@ -0,0 +1,189 @@ +//! Up/Down and the mouse wheel step the number in a focused value field (#2320): one per press +//! or wheel notch, ten with Shift, a tenth with Alt. Only a plain number steps, alone or with a +//! unit after it ("20", "20 mm", "2,5 mm", "45 deg", `3"`), and it keeps the unit and the decimal +//! mark it is written with; anything else (an expression such as `width / 2`, an empty field) is +//! left as typed, and Up/Down move its text cursor as before. Every expression field gets this +//! through `params_dialog::complete`, after its completions: while the completion list is open it +//! keeps the arrows (`expression_complete::begin_frame` takes them before the field sees them). +//! It is a preference (Preferences › Design, `step_values`), off by default: off, the fields +//! behave as before. + +use egui::{Event, Key, Modifiers, MouseWheelUnit}; + +fn enabled_id() -> egui::Id { + egui::Id::new("value_step_enabled") +} + +/// Turn stepping on or off for this frame, from the preference (the app calls this every frame). +pub(crate) fn set_enabled(ctx: &egui::Context, on: bool) { + ctx.data_mut(|d| d.insert_temp(enabled_id(), on)); +} + +/// Whether value fields step this frame. +pub(crate) fn enabled(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(enabled_id())).unwrap_or(false) +} + +/// Most wheel notches one frame may add, so a runaway or hostile delta can't fling the value. +const MAX_NOTCHES: f32 = 100.0; + +/// Step the number in `text` for this frame's Up/Down presses and, with the pointer over the +/// field, its wheel input, while `resp`'s field has the keyboard. The wheel over such a field +/// steps it instead of scrolling the panel under it. Returns whether the text changed; the whole +/// new text is then selected, so typing replaces it, as after a pick. +pub(crate) fn step(ui: &egui::Ui, resp: &egui::Response, text: &mut String) -> bool { + let wheel_key = resp.id.with("value_step_wheel"); + let hovered = resp.hovered(); + if !hovered { + ui.data_mut(|d| d.remove::(wheel_key)); + } + if !enabled(ui.ctx()) || !resp.has_focus() || plain(text).is_none() { + return false; + } + let mut tenths = ui.input(key_tenths); + if hovered { + tenths = tenths.saturating_add(wheel_tenths(ui, wheel_key)); + crate::navigation::claim_wheel(ui.ctx()); + } + if tenths == 0 { + return false; + } + let Some(new) = stepped(text, tenths) else { return false }; + // Nothing after the field acts on these keys as well. + ui.ctx().input_mut(|i| { + i.events.retain( + |e| !matches!(e, Event::Key { key: Key::ArrowUp | Key::ArrowDown, pressed: true, modifiers, .. } if tenths_for(*modifiers).is_some()), + ); + }); + *text = new; + let n = text.chars().count(); + let mut state = egui::TextEdit::load_state(ui.ctx(), resp.id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n)))); + state.store(ui.ctx(), resp.id); + // The field was drawn with the old text this frame. + ui.ctx().request_repaint(); + true +} + +/// One step in tenths for these modifiers: 10 (one), 100 with Shift, 1 with Alt. `None` with Ctrl +/// or Cmd held, which keep their own meaning (the text cursor's Up/Down, the wheel's zoom). +fn tenths_for(m: Modifiers) -> Option { + if m.ctrl || m.command || m.mac_cmd { + return None; + } + match (m.shift, m.alt) { + (false, false) => Some(10), + (true, false) => Some(100), + (false, true) => Some(1), + (true, true) => None, + } +} + +/// This frame's Up/Down presses, key repeats included, in signed tenths. +fn key_tenths(i: &egui::InputState) -> i64 { + i.events + .iter() + .filter_map(|e| match e { + Event::Key { key: Key::ArrowUp, pressed: true, modifiers, .. } => tenths_for(*modifiers), + Event::Key { key: Key::ArrowDown, pressed: true, modifiers, .. } => tenths_for(*modifiers).map(|t| -t), + _ => None, + }) + .fold(0, i64::saturating_add) +} + +/// This frame's wheel notches over the field in signed tenths. Scrolling up steps up. A mouse +/// wheel reports lines (a notch each); a trackpad reports points, which add up across frames in +/// `key` until they make a notch (a line's worth, `line_scroll_speed`). +fn wheel_tenths(ui: &egui::Ui, key: egui::Id) -> i64 { + let speed = ui.ctx().options(|o| o.input_options.line_scroll_speed).max(1.0); + let mut pending = ui.data(|d| d.get_temp::(key)).unwrap_or(0.0); + let mut out = 0i64; + ui.input(|i| { + for e in &i.events { + let Event::MouseWheel { unit, delta, modifiers, .. } = e else { continue }; + let Some(t) = tenths_for(*modifiers) else { continue }; + // macOS turns Shift+wheel into sideways scrolling. + let d = if delta.y == 0.0 && modifiers.shift { delta.x } else { delta.y }; + let notches = match unit { + MouseWheelUnit::Point => d / speed, + MouseWheelUnit::Line | MouseWheelUnit::Page => d, + }; + if !notches.is_finite() { + continue; + } + pending = (pending + notches).clamp(-MAX_NOTCHES, MAX_NOTCHES); + let whole = pending.trunc(); + pending -= whole; + out = out.saturating_add((whole as i64).saturating_mul(t)); + } + }); + ui.data_mut(|d| d.insert_temp(key, pending)); + out +} + +/// A plain number in a field's text: where the number is, its value, its decimal places and +/// decimal mark. +struct Plain { + start: usize, + end: usize, + value: f64, + places: usize, + comma: bool, +} + +/// `text` as a plain number: an optional sign, digits with at most one decimal mark (a point, or +/// a comma as expressions read it: `2,5 mm`), and at most a unit after it (one `expr::unit_info` +/// knows, or an inch or foot mark); `None` for anything else. +fn plain(text: &str) -> Option { + let start = text.len() - text.trim_start().len(); + let body = text.get(start..)?; + let (mut len, mut digits, mut places, mut mark) = (0, 0, 0, None); + for (i, c) in body.char_indices() { + match c { + '+' | '-' if i == 0 => {} + '0'..='9' => { + digits += 1; + places += usize::from(mark.is_some()); + } + '.' if mark.is_none() => mark = Some(c), + ',' if mark.is_none() && digits > 0 => mark = Some(c), + _ => break, + } + len = i + c.len_utf8(); + } + let unit = body.get(len..)?.trim(); + let unit_ok = unit.is_empty() || matches!(unit, "\"" | "″" | "'" | "′") || solidcraft_engine::doc::expr::unit_info(unit).is_some(); + // A comma reads as a decimal mark only between digits. + if digits == 0 || !unit_ok || (mark == Some(',') && places == 0) { + return None; + } + let value = body.get(..len)?.replace(',', ".").parse::().ok().filter(|v| v.is_finite())?; + Some(Plain { start, end: start + len, value, places, comma: mark == Some(',') }) +} + +/// `text` with its plain number moved by `tenths` tenths, in the places it was written with (one +/// more for a tenth step on a whole number): "20 mm" up one is "21 mm", "2.5" up a tenth "2.6". +/// `None` when `text` is not a plain number. +fn stepped(text: &str, tenths: i64) -> Option { + let p = plain(text)?; + let places = if tenths % 10 == 0 { p.places } else { p.places.max(1) }; + let v = p.value + tenths as f64 / 10.0; + if !v.is_finite() { + return None; + } + let mut number = format!("{v:.places$}"); + // A step to zero from below reads "0", not "-0". + if let Some(magnitude) = number.strip_prefix('-') + && magnitude.chars().all(|c| c == '0' || c == '.') + { + number = magnitude.to_string(); + } + if p.comma { + number = number.replace('.', ","); + } + Some(format!("{}{number}{}", text.get(..p.start)?, text.get(p.end..)?)) +} + +#[cfg(test)] +#[path = "value_step_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/value_step_tests.rs b/crates/ui-egui/src/value_step_tests.rs new file mode 100644 index 000000000..5d651ed4f --- /dev/null +++ b/crates/ui-egui/src/value_step_tests.rs @@ -0,0 +1,368 @@ +use egui::{Event, Key, Modifiers, MouseWheelUnit, TouchPhase, pos2, vec2}; +use serde_json::json; + +use super::*; +use crate::SolveApp; +use crate::scenario::Harness; + +#[test] +fn plain_numbers_step_in_the_unit_they_are_written_in() { + for (text, tenths, want) in [ + ("20 mm", 10, "21 mm"), + ("20mm", -10, "19mm"), + ("20", 100, "30"), + ("2.5", 1, "2.6"), + ("2", 1, "2.1"), + ("2.25 mm", 10, "3.25 mm"), + ("0.5 mm", -10, "-0.5 mm"), + ("-0.5", 10, "0.5"), + ("-1", 10, "0"), + ("-0.1", 1, "0.0"), + (" 45 deg ", 10, " 46 deg "), + ("90°", -100, "80°"), + ("1 in", 1, "1.1 in"), + ("12 µm", 10, "13 µm"), + ("+5", 10, "6"), + (".5", 10, "1.5"), + ("4", 30, "7"), + ("2,5 mm", 10, "3,5 mm"), + ("2,5", 1, "2,6"), + ("-0,5", 5, "0,0"), + ("20\"", 10, "21\""), + ("3 ′", -10, "2 ′"), + ("12 inch", 100, "22 inch"), + ] { + assert_eq!(stepped(text, tenths).as_deref(), Some(want), "{text:?} by {tenths} tenths"); + } +} + +#[test] +fn anything_but_a_plain_number_is_left_as_typed() { + for text in [ + "", + " ", + "width", + "width / 2", + "20 mm + 1", + "2 * 3", + "1e3", + "1,5,3", + "2,", + ",5", + "2 1/8\"", + "20 widths", + "mm", + "-", + ".", + "1.2.3", + "20 mm mm", + "inf", + "NaN", + ] { + assert_eq!(stepped(text, 10), None, "{text:?}"); + } + // Hostile input stays a string: no panic, nothing infinite. + assert_eq!(stepped(&"9".repeat(400), 10), None); + assert!(stepped("1", i64::MAX).is_some()); + assert!(stepped("1", i64::MIN).is_some()); +} + +/// One focused value field (a dialog's, through `params_dialog::complete`) in a scroll area taller +/// than the window, with value stepping on (`Field::new`) or off as by default (`Field::off`). +struct Field { + on: bool, + ctx: egui::Context, + app: SolveApp, + text: String, + id: egui::Id, + changed: bool, + rect: egui::Rect, + scroll: egui::Id, +} + +impl Field { + fn new(text: &str) -> Self { + Self::with(text, true) + } + + fn off(text: &str) -> Self { + Self::with(text, false) + } + + fn with(text: &str, on: bool) -> Self { + let ctx = egui::Context::default(); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + crate::params_dialog::publish(&mut app, &ctx); + let id = egui::Id::new("value_step_test_field"); + let mut f = Self { on, ctx, app, text: text.into(), id, changed: false, rect: egui::Rect::NOTHING, scroll: egui::Id::NULL }; + f.ctx.memory_mut(|m| m.request_focus(id)); + f.frame(Vec::new()); + f.frame(Vec::new()); + f + } + + fn frame(&mut self, events: Vec) { + let mut out = self.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 300.0))), events, ..Default::default() }, + |ui| { + crate::expression_complete::begin_frame(ui.ctx()); + set_enabled(ui.ctx(), self.on); + crate::params_dialog::publish(&mut self.app, ui.ctx()); + self.scroll = egui::ScrollArea::vertical() + .max_height(200.0) + .show(ui, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut self.text).id(self.id)); + self.changed = crate::params_dialog::complete(ui, &r, &mut self.text); + self.rect = r.rect; + ui.add_space(1000.0); + }) + .id; + }, + ); + out.textures_delta.clear(); + } + + fn key(&mut self, key: Key, modifiers: Modifiers) { + self.frame(vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + } + + fn wheel(&mut self, at: egui::Pos2, unit: MouseWheelUnit, dy: f32) { + let wheel = Event::MouseWheel { unit, delta: vec2(0.0, dy), modifiers: Modifiers::NONE, phase: TouchPhase::Move }; + self.frame(vec![Event::PointerMoved(at), wheel]); + } + + fn selection(&self) -> (usize, usize) { + let r = egui::TextEdit::load_state(&self.ctx, self.id).unwrap().cursor.char_range().unwrap(); + let (a, b) = (r.primary.index.0, r.secondary.index.0); + (a.min(b), a.max(b)) + } + + fn scrolled(&self) -> f32 { + egui::scroll_area::State::load(&self.ctx, self.scroll).map_or(0.0, |s| s.offset.y) + } +} + +#[test] +fn arrows_step_a_focused_field_and_select_the_new_value() { + let mut f = Field::new("20 mm"); + f.key(Key::ArrowUp, Modifiers::NONE); + assert_eq!(f.text, "21 mm"); + assert!(f.changed, "callers see the change"); + assert_eq!(f.selection(), (0, 5), "typing replaces the stepped value"); + f.key(Key::ArrowDown, Modifiers::NONE); + f.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(f.text, "19 mm"); + f.key(Key::ArrowUp, Modifiers::SHIFT); + assert_eq!(f.text, "29 mm", "Shift: ten"); + f.key(Key::ArrowDown, Modifiers::ALT); + assert_eq!(f.text, "28.9 mm", "Alt: a tenth"); + f.key(Key::ArrowUp, Modifiers::COMMAND); + assert_eq!(f.text, "28.9 mm", "Ctrl/Cmd keep the text cursor's Up"); + assert!(!f.changed); +} + +#[test] +fn arrows_move_the_cursor_in_an_expression_and_leave_unfocused_fields_alone() { + let mut f = Field::new("width / 2"); + f.key(Key::ArrowUp, Modifiers::NONE); + assert_eq!(f.text, "width / 2"); + assert_eq!(f.selection(), (0, 0), "Up moved the text cursor home, as in any text box"); + let mut f = Field::new("20 mm"); + f.ctx.memory_mut(|m| m.surrender_focus(f.id)); + f.frame(Vec::new()); + f.key(Key::ArrowUp, Modifiers::NONE); + assert_eq!(f.text, "20 mm"); +} + +#[test] +fn an_open_completion_list_keeps_the_arrows() { + // A plain number's unit is a whole name, so the list only opens when asked for (Ctrl+Space). + let mut f = Field::new("20 mm"); + f.key(Key::Space, Modifiers::CTRL); + f.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(f.text, "20 mm", "the arrows go to the list while it shows"); + f.key(Key::Escape, Modifiers::NONE); + f.ctx.memory_mut(|m| m.request_focus(f.id)); + f.frame(Vec::new()); + f.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(f.text, "19 mm", "with the list dismissed they step"); +} + +#[test] +fn the_wheel_over_a_focused_field_steps_it_instead_of_scrolling() { + let mut f = Field::new("20 mm"); + let over = f.rect.center(); + f.wheel(over, MouseWheelUnit::Line, 1.0); + assert_eq!(f.text, "21 mm", "a notch up steps up"); + f.wheel(over, MouseWheelUnit::Line, -2.0); + assert_eq!(f.text, "19 mm"); + // A trackpad's points add up to a notch (a line's worth) before the value moves. + let speed = f.ctx.options(|o| o.input_options.line_scroll_speed); + for _ in 0..3 { + f.wheel(over, MouseWheelUnit::Point, speed / 4.0); + } + assert_eq!(f.text, "19 mm"); + f.wheel(over, MouseWheelUnit::Point, speed / 4.0); + assert_eq!(f.text, "20 mm"); + for _ in 0..30 { + f.frame(vec![Event::PointerMoved(over)]); + } + assert_eq!(f.scrolled(), 0.0, "the panel under the field did not scroll"); + // Off the field the wheel scrolls as before and leaves the value. + f.wheel(pos2(over.x, over.y + 120.0), MouseWheelUnit::Line, -3.0); + for _ in 0..30 { + f.frame(Vec::new()); + } + assert_eq!(f.text, "20 mm"); + assert!(f.scrolled() > 0.0, "the panel scrolls off the field"); +} + +/// An edge Flange dialog open on a 100 x 60 base flange, its Height box (10 mm) beside the edge, +/// with value stepping `on` or off. +fn edge_flange(on: bool) -> Harness { + let mut h = Harness::new(); + h.app.preferences.step_values = on; + h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + let sk = h.app.session.doc.features[0].id; + h.app.session.selection = vec![solidcraft_engine::Sel::Profile { sketch: sk, index: 0 }]; + h.app.start("sheet.flange"); + let d = h.app.dialog.take().unwrap(); + for (id, p) in crate::dialogs::apply_commands(&h.app, &d).unwrap() { + h.app.run(&id, p).unwrap(); + } + let edge = crate::dialogs::edge_sel(&h.app.session, solidcraft_engine::geom::Vec3::new(50.0, 0.0, 2.5)).unwrap(); + h.app.session.selection = vec![edge]; + h.step(&json!({"start": "sheet.flange"})).unwrap(); + h.frames(6); + assert_eq!(flange(&h), (1, "10 mm".into(), String::new()), "an edge flange, 10 mm high"); + h +} + +/// The open Flange dialog's type, height and bend radius. +fn flange(h: &Harness) -> (usize, String, String) { + match &h.app.dialog.as_ref().unwrap().kind { + crate::dialogs::Kind::Sheet(crate::dialogs_sheet::Sm::Flange { ty, height, radius, .. }) => (*ty, height.clone(), radius.clone()), + _ => panic!("flange dialog"), + } +} + +/// #2320 as reported: in an edge Flange, the Height box beside the edge and the Bend Radius row +/// both take Up/Down and the wheel, and OK makes the stepped flange. +#[test] +fn flange_height_and_bend_radius_step_with_arrows_and_wheel() { + let mut h = edge_flange(true); + // The box sits at the arrow's tip, so it moves as the height does. + let at = |h: &Harness| h.ctx.read_response(egui::Id::new("sc_canvas_value")).expect("the Height box beside the edge").rect.center(); + let height = at(&h); + h.step(&json!({"click": [height.x, height.y]})).unwrap(); + h.step(&json!({"key": "ArrowUp"})).unwrap(); + h.frames(2); + assert_eq!(flange(&h).1, "11 mm"); + h.step(&json!({"key": "ArrowUp", "shift": true})).unwrap(); + h.frames(2); + assert_eq!(flange(&h).1, "21 mm"); + // Close in, then notch after notch at one spot: the box stays under the pointer while its arrow + // shrinks, so every notch steps it and none reaches the camera. + h.call("ui.camera", json!({"target": [50, 0, 15], "distance": 40})); + h.frames(4); + let rect = h.ctx.read_response(egui::Id::new("sc_canvas_value")).unwrap().rect; + let tip = h.at(&json!({"handle": "arrow"})).unwrap()[1]; + let cam = h.app.cam; + for _ in 0..4 { + h.call("ui.scroll", json!({"x": rect.center().x, "y": rect.center().y, "delta": -40.0})); + h.frames(2); + } + assert_eq!(flange(&h).1, "17 mm", "four notches down"); + assert_eq!(h.app.cam, cam, "the view did not zoom"); + let moved = (h.at(&json!({"handle": "arrow"})).unwrap()[1] - tip).abs(); + assert!(moved > f64::from(rect.height()), "the tip moved {moved}, further than the box is tall"); + // The Bend Radius row (under Advanced) is found by its label, empty ("from the rule") does not + // step, a number does. + h.step(&json!({"click": {"handle": "dialog:section:Advanced"}})).unwrap(); + h.frames(2); + h.step(&json!({"click": {"handle": "dialog:Bend Radius"}})).unwrap(); + h.step(&json!({"key": "ArrowUp"})).unwrap(); + h.frames(2); + assert_eq!(flange(&h).2, ""); + h.step(&json!({"text": "2 mm"})).unwrap(); + h.step(&json!({"key": "ArrowUp"})).unwrap(); + h.frames(2); + assert_eq!(flange(&h).2, "3 mm"); + h.step(&json!({"widget": "OK"})).unwrap(); + h.frames(2); + let f = h.app.session.doc.features.last().unwrap(); + let solidcraft_engine::doc::FeatureKind::SheetFlange { height, radius, .. } = &f.kind else { panic!("flange feature: {:?}", f.kind) }; + assert_eq!((height.as_str(), radius.as_deref()), ("17 mm", Some("3 mm"))); +} + +/// The Parameters window's expression boxes step too; Enter applies the stepped expression. +#[test] +fn parameter_expressions_step_and_apply() { + let mut h = Harness::new(); + h.app.preferences.step_values = true; + h.app.run("parameters.add", json!({"name": "width", "expression": "10 mm"})).unwrap(); + h.step(&json!({"start": "parameters.change"})).unwrap(); + h.frames(4); + h.step(&json!({"click": {"handle": "param:width"}})).unwrap(); + h.frames(2); + h.step(&json!({"key": "ArrowUp"})).unwrap(); + h.step(&json!({"key": "ArrowUp"})).unwrap(); + h.frames(2); + assert_eq!(h.app.params.as_ref().unwrap().editing.get("width").map(String::as_str), Some("12 mm")); + h.step(&json!({"key": "Enter"})).unwrap(); + h.frames(2); + assert_eq!(h.app.session.doc.param("width").map(|p| p.expr.as_str()), Some("12 mm")); +} + +/// Off, as by default, value fields behave as before: Up moves the text cursor home, the wheel +/// scrolls the panel under the field, and the box beside the geometry follows its arrow. +#[test] +fn off_by_default_the_keys_and_the_wheel_do_what_they_did() { + assert!(!crate::prefs::Prefs::default().step_values); + assert!(!serde_json::from_value::(json!({})).unwrap().step_values, "saved preferences without it"); + let mut f = Field::off("20 mm"); + f.key(Key::ArrowUp, Modifiers::NONE); + assert_eq!((f.text.as_str(), f.selection()), ("20 mm", (0, 0)), "Up moved the cursor home"); + let over = f.rect.center(); + f.wheel(over, MouseWheelUnit::Line, -3.0); + for _ in 0..30 { + f.frame(vec![Event::PointerMoved(over)]); + } + assert_eq!(f.text, "20 mm"); + assert!(f.scrolled() > 0.0, "the wheel scrolled the panel"); + + let mut h = edge_flange(false); + let at = h.ctx.read_response(egui::Id::new("sc_canvas_value")).unwrap().rect.center(); + h.step(&json!({"click": [at.x, at.y]})).unwrap(); + h.step(&json!({"key": "ArrowUp"})).unwrap(); + h.call("ui.scroll", json!({"x": at.x, "y": at.y, "delta": 40.0})); + h.frames(2); + assert_eq!(flange(&h).1, "10 mm", "neither Up nor the wheel stepped the Height box"); + // Typed with the pointer over the box, the box follows the arrow's tip as before. + h.step(&json!({"key": "A", "cmd": true})).unwrap(); + h.step(&json!({"text": "40 mm"})).unwrap(); + h.frames(3); + assert_eq!(flange(&h).1, "40 mm"); + let moved = h.ctx.read_response(egui::Id::new("sc_canvas_value")).unwrap().rect.center(); + assert!((moved.y - at.y).abs() > 5.0, "the box moved with the arrow ({at:?} -> {moved:?})"); +} + +/// The preference is on Preferences › Design, and the control channel sets it. +#[test] +fn the_preference_is_on_the_design_page() { + let mut h = Harness::new(); + crate::prefs::set(&mut h.app, &json!({"step_values": true})).unwrap(); + assert!(h.app.preferences.step_values); + crate::prefs::set(&mut h.app, &json!({"step_values": false})).unwrap(); + h.call("ui.prefs", json!({"open": "Design"})); + h.frames(3); + // The row is below the page's fold: scroll the page down to it, as a user would. + let window = h.ctx.memory(|m| m.area_rect(egui::Id::new("sc_prefs"))).unwrap(); + h.call("ui.scroll", json!({"x": window.center().x, "y": window.center().y, "delta": -400.0})); + h.frames(30); + h.step(&json!({"click": {"handle": "prefs:step_values"}})).unwrap(); + h.frames(2); + assert!(h.app.preferences.step_values, "the Design page's checkbox turns it on"); +} diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md index e6a3d79a6..54a821d8a 100644 --- a/docs/book/src/guide/parameters.md +++ b/docs/book/src/guide/parameters.md @@ -31,6 +31,13 @@ applies what you typed, and **Up/Down** picks one of them first. A unit right af (`10 mm`) is left alone; anywhere else a unit is a prefix like any other, so `rad` followed by **Enter** gives `radius`. +With **Preferences › Design › Step values with the arrow keys and the wheel** on (it is off +by default) and no suggestions open, **Up/Down** step a plain number in any value field (a dialog's rows, +the value box beside the geometry, a sketch dimension, a parameter's expression) by 1 in the +unit it is written in: `20 mm` becomes `21 mm`, `2,5 mm` becomes `3,5 mm`. Hold **Shift** for 10 +or **Alt/Option** for 0.1. The mouse wheel over the focused field does the same, a step a notch, +and the preview follows each step. An expression such as `width / 2` is left as typed. + Expressions are unit-aware: `2 * width + 5 mm`, `angle / 2`, `sqrt(area)`, `1 in + 3 mm`, using `+ - * / ^`, parentheses, `sin cos tan asin acos atan atan2 sqrt abs min max floor ceil round mod trunc` and unit conversion. A decimal comma works too, outside parentheses: `2,5 mm` is diff --git a/docs/book/src/guide/shortcuts.md b/docs/book/src/guide/shortcuts.md index 8fe5fc49f..dff6ea52d 100644 --- a/docs/book/src/guide/shortcuts.md +++ b/docs/book/src/guide/shortcuts.md @@ -62,7 +62,9 @@ Keys handled by the window itself: While a value box has the keyboard (a dimension being added, a dialog field), keys type into it and single-letter shortcuts don't fire. With Sketch Dimension (D), the box opens as soon as you click a line, circle or arc (or the second point or line), so D, click, type the value, -Enter. +Enter. With Preferences › Design › Step values with the arrow keys and the wheel on, ↑ ↓ in a +value box, or the wheel over it, step a plain number by 1 (with Shift by 10, with Alt by 0.1); +see [Parameters and expressions](parameters.md). Mouse and touch: diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 431f3d0ab..18538a5a3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -245,7 +245,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs | | `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) | | `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text | -| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:`), and a pick on a face that has a hole moves it there), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark` and `stand_up_offer` | +| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:`), and a pick on a face that has a hole moves it there), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark` and `stand_up_offer` | | `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits | | `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first | | `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. The pointer shows the command's localized name, including commands inside a closed toolbar group; an animated batch names each command it visits. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it |