From 7bd66b7c06a219ceeb855ddef1be0f8bb4a26c2a Mon Sep 17 00:00:00 2001 From: Lars Jansen Date: Wed, 4 Nov 2026 05:12:31 +0000 Subject: [PATCH] Sketch dimensions: enter the value in a small window with step arrows (#7246) (#7251) * claim: #7246 * feat(sketch): enter a dimension's value in a small window with step arrows (#7246) * Dimension window: fit the layer split, and keep the wheel off the camera over the window Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: bherbruck Co-authored-by: Claude Opus 5.5 --- .../pending/sketch-dimension-window.json | 110 ++++++ crates/ui-egui/src/dim_view.rs | 21 +- crates/ui-egui/src/dim_view/window.rs | 345 ++++++++++++++++++ .../ui-egui/src/dimension_create_ui_tests.rs | 209 +++++++++++ crates/ui-egui/src/navigation.rs | 1 + crates/ui-egui/src/prefs.rs | 30 ++ crates/ui-egui/src/prefs/sketch.rs | 33 ++ crates/ui-egui/src/preview.rs | 98 ++--- crates/ui-egui/src/value_step.rs | 21 +- .../scenarios/sketch_dimension_window.json | 21 ++ docs/book/src/guide/sketching.md | 10 + docs/control-protocol.md | 3 + 12 files changed, 853 insertions(+), 49 deletions(-) create mode 100644 assets/locales/pending/sketch-dimension-window.json create mode 100644 crates/ui-egui/src/dim_view/window.rs create mode 100644 crates/ui-egui/tests/scenarios/sketch_dimension_window.json diff --git a/assets/locales/pending/sketch-dimension-window.json b/assets/locales/pending/sketch-dimension-window.json new file mode 100644 index 000000000..1daf8e5ae --- /dev/null +++ b/assets/locales/pending/sketch-dimension-window.json @@ -0,0 +1,110 @@ +{ + "en": { + "dialog.dimension_step_down": "Down by {step}", + "dialog.dimension_step_expression": "Only a number steps; an expression stays as typed", + "dialog.dimension_step_up": "Up by {step}", + "prefs.dimension_step_angle": "What the window's arrows, Up/Down and the wheel add to an angle", + "prefs.dimension_step_length": "What the window's arrows, Up/Down and the wheel add to a length", + "prefs.dimension_steps": "Window steps", + "prefs.dimension_values": "Dimension values", + "prefs.dimension_values_note": "Where you type a dimension's value. A window has arrows that step it; the Dimension tool places the text first.", + "prefs.dimension_values_view": "In the view", + "prefs.dimension_values_window": "In a window" + }, + "ja": { + "dialog.dimension_step_down": "{step} 減らす", + "dialog.dimension_step_expression": "増減できるのは数値だけです。式はそのまま残ります", + "dialog.dimension_step_up": "{step} 増やす", + "prefs.dimension_step_angle": "ウィンドウの矢印、上下キー、ホイールで角度に加える量", + "prefs.dimension_step_length": "ウィンドウの矢印、上下キー、ホイールで長さに加える量", + "prefs.dimension_steps": "ウィンドウの増減量", + "prefs.dimension_values": "寸法値の入力", + "prefs.dimension_values_note": "寸法値を入力する場所です。ウィンドウでは矢印で値を増減でき、寸法ツールは先に文字を配置します。", + "prefs.dimension_values_view": "ビュー内", + "prefs.dimension_values_window": "ウィンドウ" + }, + "zh": { + "dialog.dimension_step_down": "减少 {step}", + "dialog.dimension_step_expression": "只有数字可以增减;表达式保持不变", + "dialog.dimension_step_up": "增加 {step}", + "prefs.dimension_step_angle": "窗口的箭头、上下方向键和滚轮给角度增减的量", + "prefs.dimension_step_length": "窗口的箭头、上下方向键和滚轮给长度增减的量", + "prefs.dimension_steps": "窗口步长", + "prefs.dimension_values": "尺寸值", + "prefs.dimension_values_note": "输入尺寸值的位置。窗口带有可增减数值的箭头;尺寸工具会先放置文字。", + "prefs.dimension_values_view": "在视图中", + "prefs.dimension_values_window": "在窗口中" + }, + "de": { + "dialog.dimension_step_down": "Um {step} verringern", + "dialog.dimension_step_expression": "Nur eine Zahl lässt sich schrittweise ändern; ein Ausdruck bleibt, wie er eingegeben ist", + "dialog.dimension_step_up": "Um {step} erhöhen", + "prefs.dimension_step_angle": "Was die Pfeile des Fensters, Auf/Ab und das Mausrad zu einem Winkel addieren", + "prefs.dimension_step_length": "Was die Pfeile des Fensters, Auf/Ab und das Mausrad zu einer Länge addieren", + "prefs.dimension_steps": "Schritte im Fenster", + "prefs.dimension_values": "Bemaßungswerte", + "prefs.dimension_values_note": "Wo der Wert einer Bemaßung eingegeben wird. Ein Fenster hat Pfeile, die ihn schrittweise ändern; das Bemaßungswerkzeug platziert zuerst den Text.", + "prefs.dimension_values_view": "In der Ansicht", + "prefs.dimension_values_window": "In einem Fenster" + }, + "ko": { + "dialog.dimension_step_down": "{step} 줄이기", + "dialog.dimension_step_expression": "숫자만 증감할 수 있으며 수식은 입력한 그대로 유지됩니다", + "dialog.dimension_step_up": "{step} 늘리기", + "prefs.dimension_step_angle": "창의 화살표, 위/아래 키와 휠이 각도에 더하는 값", + "prefs.dimension_step_length": "창의 화살표, 위/아래 키와 휠이 길이에 더하는 값", + "prefs.dimension_steps": "창의 증감 단위", + "prefs.dimension_values": "치수 값", + "prefs.dimension_values_note": "치수 값을 입력하는 위치입니다. 창에는 값을 증감하는 화살표가 있으며, 치수 도구는 텍스트를 먼저 배치합니다.", + "prefs.dimension_values_view": "뷰에서", + "prefs.dimension_values_window": "창에서" + }, + "nl": { + "dialog.dimension_step_down": "{step} omlaag", + "dialog.dimension_step_expression": "Alleen een getal verspringt; een uitdrukking blijft zoals ingevoerd", + "dialog.dimension_step_up": "{step} omhoog", + "prefs.dimension_step_angle": "Wat de pijlen van het venster, Omhoog/Omlaag en het wieltje bij een hoek optellen", + "prefs.dimension_step_length": "Wat de pijlen van het venster, Omhoog/Omlaag en het wieltje bij een lengte optellen", + "prefs.dimension_steps": "Stappen in het venster", + "prefs.dimension_values": "Maatwaarden", + "prefs.dimension_values_note": "Waar de waarde van een maat wordt ingevoerd. Een venster heeft pijlen die de waarde laten verspringen; het maatgereedschap plaatst eerst de tekst.", + "prefs.dimension_values_view": "In de weergave", + "prefs.dimension_values_window": "In een venster" + }, + "ar": { + "dialog.dimension_step_down": "إنقاص بمقدار {step}", + "dialog.dimension_step_expression": "يتغير الرقم فقط بالخطوات؛ يبقى التعبير كما كُتب", + "dialog.dimension_step_up": "زيادة بمقدار {step}", + "prefs.dimension_step_angle": "ما تضيفه أسهم النافذة وأعلى/أسفل والعجلة إلى الزاوية", + "prefs.dimension_step_length": "ما تضيفه أسهم النافذة وأعلى/أسفل والعجلة إلى الطول", + "prefs.dimension_steps": "خطوات النافذة", + "prefs.dimension_values": "قيم الأبعاد", + "prefs.dimension_values_note": "مكان كتابة قيمة البعد. للنافذة أسهم تغيّرها بخطوات؛ تضع أداة البعد النص أولًا.", + "prefs.dimension_values_view": "في العرض", + "prefs.dimension_values_window": "في نافذة" + }, + "he": { + "dialog.dimension_step_down": "הפחתה ב־{step}", + "dialog.dimension_step_expression": "רק מספר משתנה בצעדים; ביטוי נשאר כפי שנכתב", + "dialog.dimension_step_up": "הוספה של {step}", + "prefs.dimension_step_angle": "מה שהחצים בחלון, למעלה/למטה והגלגלת מוסיפים לזווית", + "prefs.dimension_step_length": "מה שהחצים בחלון, למעלה/למטה והגלגלת מוסיפים לאורך", + "prefs.dimension_steps": "צעדי החלון", + "prefs.dimension_values": "ערכי מידות", + "prefs.dimension_values_note": "היכן מקלידים את ערך המידה. לחלון יש חצים שמשנים אותו בצעדים; כלי המידה מציב קודם את הטקסט.", + "prefs.dimension_values_view": "בתצוגה", + "prefs.dimension_values_window": "בחלון" + }, + "vi": { + "dialog.dimension_step_down": "Giảm {step}", + "dialog.dimension_step_expression": "Chỉ số mới thay đổi theo bước; biểu thức giữ nguyên như đã nhập", + "dialog.dimension_step_up": "Tăng {step}", + "prefs.dimension_step_angle": "Lượng mà mũi tên của cửa sổ, Lên/Xuống và con lăn cộng vào một góc", + "prefs.dimension_step_length": "Lượng mà mũi tên của cửa sổ, Lên/Xuống và con lăn cộng vào một độ dài", + "prefs.dimension_steps": "Bước của cửa sổ", + "prefs.dimension_values": "Giá trị kích thước", + "prefs.dimension_values_note": "Nơi bạn nhập giá trị kích thước. Cửa sổ có mũi tên để thay đổi theo bước; công cụ Kích thước đặt văn bản trước.", + "prefs.dimension_values_view": "Trong khung nhìn", + "prefs.dimension_values_window": "Trong một cửa sổ" + } +} diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index 381145289..ecb6727bb 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -31,6 +31,8 @@ use crate::SolveApp; use crate::theme::Tokens; use crate::viewport::Proj; +pub(crate) mod window; + /// A dimension as drawn this frame (screen space), for hit testing. #[derive(Clone, Debug)] struct Drawn { @@ -153,6 +155,7 @@ fn shown_error(id: &str, e: &str) -> String { pub fn cancel() { EDIT.with(|edit| *edit.borrow_mut() = None); PLACEMENT.with(|preview| *preview.borrow_mut() = None); + window::forget(); } /// Infer the measured value through the same command as scripts, without creating a real @@ -192,6 +195,11 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec, at: Vec2) -> R /// it. Midpoint pairs and dimensions that would only be driven keep the place-first flow: /// the pointer chooses the orientation, and a click places the text before entering a value. pub fn begin_live(app: &mut SolveApp, entities: Vec, pointer: Option) -> Result { + // The value window opens on placed text (`window`): a window following the pointer could + // not be reached. + if window::on(app) { + return Ok(false); + } // A midpoint pair chooses its orientation and text position before entering a value. // This also permits switching freely between driving and reference spans. let midpoint_pair = entities.len() == 2 && entities.iter().all(|id| id.starts_with("mid:")); @@ -844,6 +852,7 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P } } DRAWN.with(|d| *d.borrow_mut() = drawn); + window::paint(app, painter, proj); edit_box(app, ui.ctx()); } @@ -1005,6 +1014,10 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) { } return; }; + if window::on(app) { + let (done, escaped) = window::show(app, ctx, &mut e, at); + return settle(app, e, done, escaped); + } let id = egui::Id::new("sc_dim_edit"); let mut done: Option = None; let mut escaped = false; @@ -1074,8 +1087,14 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) { }); }); }); - e.fresh = e.fresh.saturating_sub(1); e.shown = Some(anchor); + settle(app, e, done, escaped); +} + +/// Apply or drop the edit as the box or the window answered (`done`: Some(true) applies, Some(false) +/// drops it, and `escaped` the Dimension tool's picks with it), or keep it open. +fn settle(app: &mut SolveApp, mut e: Edit, done: Option, escaped: bool) { + e.fresh = e.fresh.saturating_sub(1); match done { Some(true) => { let result = if let Some(draft) = &e.draft { diff --git a/crates/ui-egui/src/dim_view/window.rs b/crates/ui-egui/src/dim_view/window.rs new file mode 100644 index 000000000..00d68744c --- /dev/null +++ b/crates/ui-egui/src/dim_view/window.rs @@ -0,0 +1,345 @@ +//! The dimension value window (Preferences › Sketch › Dimension values: In a window, #7246). +//! Placing a dimension with the Dimension tool, or double-clicking one, opens a small window at +//! its text, kept inside the view, instead of the box on the dimension: +//! - the value field, which takes what the box takes (numbers, units, expressions, parameter +//! names, `w = 20`; a click on another dimension inserts its name); +//! - arrows that step a plain number by the step preferences: a length by `dimension_step_mm`, +//! written in the unit the value is written in (none: the design's), an angle by +//! `dimension_step_deg`. Up/Down and the mouse wheel over the field step it too (Shift: ten +//! steps, Alt: a tenth, as in the other value fields). An expression is left as typed; +//! - a check (OK, also Enter) and a cross (Cancel, also Esc). +//! +//! While it is open the sketch shows the value: what it moves is drawn in the preview colour, and +//! why OK would refuse it shows under the field. Nothing reaches the design until OK, which +//! applies through the box's own path (`edit_box`), so undo, driven dimensions and refusals are +//! the same as there. Cancel drops this edit only: a new dimension is not added, and the +//! Dimension tool stays on for the next one. A click elsewhere drops it as well, as it does the +//! box. +//! +//! With the window the Dimension tool places a new dimension's text first (`begin_live` keeps the +//! place-first flow), and the window opens on the placed text: a window following the pointer +//! could never be reached. + +use super::*; +use crate::prefs::{DIMENSION_STEP_DEG, DIMENSION_STEP_MM, DimensionInput}; +use solidcraft_engine::doc::expr::{Kind, unit_info}; + +/// The window's area. +const AREA: &str = "sc_dim_window"; + +/// The window is on (Preferences › Sketch). +pub(super) fn on(app: &SolveApp) -> bool { + app.preferences.dimension_input == DimensionInput::Window +} + +/// What a step adds to a length (millimetres) and to an angle (degrees). A saved value outside +/// what Preferences accepts (a hand edit) steps by the default. +fn steps(app: &SolveApp) -> (f64, f64) { + let or_default = |value: f64, accepted: std::ops::RangeInclusive| if accepted.contains(&value) { value } else { 1.0 }; + (or_default(app.preferences.dimension_step_mm, DIMENSION_STEP_MM), or_default(app.preferences.dimension_step_deg, DIMENSION_STEP_DEG)) +} + +/// Whether a dimension's value is a length or an angle, from its parameter's unit. +fn kind(doc: &solidcraft_engine::doc::Document, param: &str) -> Kind { + doc.param(param).and_then(|p| unit_info(&p.unit)).map_or(Kind::Length, |(kind, _)| kind) +} + +/// `text` moved by `steps` steps (negative: down) of `step_mm` (a length) or `step_deg` (an +/// angle). A plain number keeps the unit it is written in (none: `design_unit` for a length, +/// degrees for an angle) and its decimal mark, gaining the decimal places the step needs in that +/// unit. `None` for anything else: an expression is left as typed. +pub(crate) fn stepped(text: &str, steps: f64, kind: Kind, design_unit: &str, step_mm: f64, step_deg: f64) -> Option { + crate::value_step::shifted(text, |written| { + let unit = match written { + "" if kind == Kind::Angle => "deg", + "" => design_unit, + "\"" | "″" => "in", + "'" | "′" => "ft", + unit => unit, + }; + let (unit_kind, per_unit) = unit_info(unit)?; + let step = match (kind, unit_kind) { + (Kind::Length, Kind::Length) => step_mm, + (Kind::Angle, Kind::Angle) => step_deg.to_radians(), + _ => return None, + }; + let amount = step / per_unit * steps; + (amount.is_finite() && per_unit > 0.0).then(|| (amount, places(amount))) + }) +} + +/// The fewest decimal places, at most six, that write `amount` as it is. +fn places(amount: f64) -> usize { + let a = amount.abs(); + (0..6) + .find(|p| { + let scale = 10f64.powi(*p); + ((a * scale).round() / scale - a).abs() <= a * 1e-9 + }) + .map_or(6, |p| p as usize) +} + +/// What OK would make of an existing dimension's typed value, worked out once per text: the +/// sketch it gives, or the refusal OK would show. It runs OK's own command on a scratch copy of +/// the session, so nothing reaches the design. +struct Existing { + doc: Arc, + param: String, + expr: String, + sketch: Option>, + error: Option, +} + +thread_local! { + static EXISTING: RefCell> = const { RefCell::new(None) }; + /// Where the open window sits, for which parameter, and the frame it was last drawn in. It + /// stays where it opened while it is open, so its arrows stay under the pointer while the + /// stepped value moves the dimension's text. + static ANCHOR: RefCell> = const { RefCell::new(None) }; +} + +/// Whether the open window is under `p`: the wheel there steps its value, so the camera under it +/// does not zoom (navigation asks). +pub(crate) fn covers(ctx: &egui::Context, p: Pos2) -> bool { + super::editing() && ctx.memory(|m| m.area_rect(egui::Id::new(AREA))).is_some_and(|r| r.contains(p)) +} + +/// Forget the worked-out value (the edit closed). +pub(super) fn forget() { + EXISTING.with(|e| *e.borrow_mut() = None); +} + +fn existing(app: &SolveApp, param: &str, expr: &str) -> (Option>, Option) { + EXISTING.with(|cell| { + let mut cell = cell.borrow_mut(); + let current = cell.as_ref().is_some_and(|x| Arc::ptr_eq(&x.doc, &app.session.doc) && x.param == param && x.expr == expr); + if !current { + let expression = crate::length_input::expression(&app.session.doc, expr, kind(&app.session.doc, param)); + let mut scratch = app.session.scratch(); + let (sketch, error) = match scratch.execute("parameters.change", &json!({"name": param, "expression": expression})) { + Ok(_) => { + (app.session.active_sketch.and_then(|id| scratch.world_state().ok()?.sketches.iter().find(|s| s.feature == id).cloned()), None) + } + Err(e) => (None, Some(shown_error("parameters.change", &e.to_string()))), + }; + *cell = Some(Existing { doc: app.session.doc.clone(), param: param.to_string(), expr: expr.to_string(), sketch, error }); + } + cell.as_ref().map(|x| (x.sketch.clone(), x.error.clone())).unwrap_or_default() + }) +} + +/// Draw what the open window's value moves in the sketch, in the preview colour, over the sketch +/// as it is. A value OK would refuse shows nothing. +pub(super) fn paint(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { + if !on(app) { + return; + } + let Some((param, expr, draft)) = EDIT.with(|edit| { + let edit = edit.borrow(); + let e = edit.as_ref()?; + let draft = e.draft.as_ref().map(|d| (d.sketch, d.preview.clone(), d.error.is_some())); + Some((e.param.clone(), e.expr.clone(), draft)) + }) else { + return; + }; + let Some(sketch) = app.session.active_sketch else { return }; + let after = match draft { + Some((id, preview, false)) => preview.sketches.iter().find(|s| s.feature == id).cloned(), + Some((_, _, true)) => None, + None => existing(app, ¶m, &expr).0, + }; + let state = app.session.world_state().ok(); + let changes = after.and_then(|after| crate::preview::sketch_changes(state.as_ref().and_then(|state| state.sketch(sketch)), &after)); + let mut budget = solidcraft_engine::render::SamplingBudget::new(32_768, 65_536); + let curves = changes.map_or(0, |changes| crate::preview::paint_sketch(&changes, painter, proj, &mut budget)); + crate::scenario::publish_count("dimwin:preview_curves", curves as f64); +} + +/// Where the window goes: where it already is while it stays open, else under the dimension's +/// text `at` (over it where the view has no room below); always inside the view's free area. +/// `size` is the window's as drawn last frame. +fn place(app: &SolveApp, ctx: &egui::Context, param: &str, at: Pos2, size: egui::Vec2) -> Pos2 { + let frame = ctx.cumulative_frame_nr(); + let view = app.viewport.layout.as_ref().map(|layout| layout.drawable).filter(|r| r.is_finite() && r.is_positive()); + ANCHOR.with(|anchor| { + let mut anchor = anchor.borrow_mut(); + let open = anchor.as_ref().filter(|(open, drawn, _)| open == param && drawn.saturating_add(1) >= frame).map(|x| x.2); + let mut pos = open.unwrap_or_else(|| { + let gap = Tokens::get().space_12; + let below = Pos2::new(at.x - size.x * 0.5, at.y + gap); + if view.is_some_and(|rect| below.y + size.y > rect.bottom()) { Pos2::new(below.x, at.y - gap - size.y) } else { below } + }); + if let Some(rect) = view { + pos.x = pos.x.clamp(rect.left(), (rect.right() - size.x).max(rect.left())); + pos.y = pos.y.clamp(rect.top(), (rect.bottom() - size.y).max(rect.top())); + } + *anchor = Some((param.to_string(), frame, pos)); + pos + }) +} + +/// The check or the cross in `rect`, its icon in colour as the view's own OK and Cancel draw it +/// (`view_confirm`): hover, the pointing hand, its tooltip, and its handle `key` for scenarios and +/// the control channel. True when clicked. +fn button(ui: &mut egui::Ui, rect: Rect, key: &str, tip: &str, icon: &str) -> bool { + let t = Tokens::get(); + let response = ui.interact(rect, ui.id().with(key), egui::Sense::click()); + if response.hovered() { + ui.painter().rect_filled(rect, t.control_radius, t.hover); + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + crate::icons::paint_icon(ui.painter(), rect.shrink(t.space_4), icon, 1.0); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tip)); + crate::scenario::publish_target(key, rect); + response.on_hover_text(tip).clicked() +} + +/// Draw the window for the open edit `e` at its dimension's text `at` (screen) and answer it: +/// `Some(true)` applies it (the check, Enter), `Some(false)` drops it; the second value says +/// whether a new dimension's picks go too (the cross, Esc), as Esc in the box does. +pub(super) fn show(app: &mut SolveApp, ctx: &egui::Context, e: &mut Edit, at: Pos2) -> (Option, bool) { + let t = Tokens::get(); + let id = egui::Id::new("sc_dim_edit"); + let area = egui::Id::new(AREA); + let (kind, error) = match &e.draft { + Some(draft) => (kind(&draft.preview_doc, &e.param), draft.error.clone()), + None => (kind(&app.session.doc, &e.param), existing(app, &e.param, &e.expr).1), + }; + let (step_mm, step_deg) = steps(app); + let unit = crate::length_input::unit(&app.session.doc).to_string(); + let step = |text: &str, steps: f64| stepped(text, steps, kind, &unit, step_mm, step_deg); + let step_text = if kind == Kind::Angle { + format!("{:.*}°", usize::from(app.preferences.angle_decimals), step_deg) + } else { + crate::prefs::format_length(step_mm, &app.session.doc.units, app.preferences.length_decimals) + }; + let last = ctx.memory(|m| m.area_rect(area)); + let width = t.space_24 * 8.0; + let guess = egui::vec2(width + t.space_6 * 2.0, t.control_height * 2.0 + t.space_6 * 3.0); + let anchor = place(app, ctx, &e.param, at, last.map_or(guess, |r| r.size())); + // A click on the window (an arrow) takes the keyboard from its field, as any click away does; + // the field takes it back instead of closing. + let on_window = ctx.input(|i| i.pointer.any_click() && i.pointer.interact_pos().is_some_and(|p| last.is_some_and(|r| r.contains(p)))); + let mut answer: Option = None; + let mut escaped = false; + let mut by = 0.0; + Container::new(ctx, Surface::Canvas).area(area).fixed_pos(anchor).order(egui::Order::Foreground).show(ctx, |ui| { + Container::popup_frame(ui.style()).fill(t.dialog_body).inner_margin(t.space_6).show(ui, |ui| { + crate::ui_kit::scope(ui, |ui| { + ui.set_width(width); + // The parameter's name, then the check and the cross. + let (title, _) = ui.allocate_exact_size(egui::vec2(width, t.control_height), egui::Sense::hover()); + let name = crate::i18n::format("dialog.dimension_name", &[("name", &e.param)]); + ui.scope_builder(egui::UiBuilder::new().max_rect(title).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { + crate::ui_kit::text(ui, &name, crate::ui_kit::Text::Inline).on_hover_text(crate::i18n::tr("dialog.dimension_insert_hint")); + }); + let side = t.control_height; + let cancel = Rect::from_min_size(egui::pos2(title.right() - side, title.top()), egui::vec2(side, side)); + let ok = cancel.translate(egui::vec2(-(side + t.space_2), 0.0)); + if button(ui, ok, "dimwin:ok", crate::i18n::tr("ui.heading_ok"), "finish") { + answer = Some(true); + } + if button(ui, cancel, "dimwin:cancel", crate::i18n::tr("ui.cancel"), "close") { + answer = Some(false); + escaped = true; + } + // The value, with its arrows at its right (the kit's own up and down arrows). + let (row, _) = ui.allocate_exact_size(egui::vec2(width, t.control_height), egui::Sense::hover()); + let arrows = 2.0 * (t.form_close_size - t.space_4) + t.space_2; + let (r, up, down) = ui + .scope_builder(egui::UiBuilder::new().max_rect(row).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { + ui.spacing_mut().item_spacing.x = t.space_2; + let field = egui::vec2((row.width() - arrows - t.space_2).max(t.space_24), t.control_height); + let r = ui.allocate_ui(field, |ui| crate::ui_kit::cell_editor(ui, id, &mut e.expr, "", false)).inner; + crate::scenario::publish_target("dimwin:value", r.rect); + if r.has_focus() { + e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range()); + } + if crate::expression_complete::complete(ui, &r, &mut e.expr) { + e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range()); + } + let can_step = step(&e.expr, 1.0).is_some(); + let tip = |id: &str| { + if can_step { + crate::i18n::format(id, &[("step", &step_text)]) + } else { + crate::i18n::tr("dialog.dimension_step_expression").to_string() + } + }; + let up = crate::ui_kit::compact_button(ui, crate::ui_kit::MOVE_UP, &tip("dialog.dimension_step_up"), can_step, false); + crate::scenario::publish_target("dimwin:up", up.rect); + let down = crate::ui_kit::compact_button(ui, crate::ui_kit::MOVE_DOWN, &tip("dialog.dimension_step_down"), can_step, false); + crate::scenario::publish_target("dimwin:down", down.rect); + (r, up.clicked(), down.clicked()) + }) + .inner; + if up { + by += 1.0; + } + if down { + by -= 1.0; + } + // Up/Down in the field and the wheel over it or its arrows step too. + if r.has_focus() { + by += ui.input(crate::value_step::key_tenths) as f64 / 10.0; + } + let wheel = id.with("dimwin_wheel"); + if ui.rect_contains_pointer(row) { + by += crate::value_step::wheel_tenths(ui, wheel) as f64 / 10.0; + crate::navigation::claim_wheel(ui.ctx()); + } else { + ui.data_mut(|d| d.remove::(wheel)); + } + if let Some(error) = &error { + crate::ui_kit::text(ui, error, crate::ui_kit::Text::Report("dimension_error", true)); + } + if e.fresh == FRESH { + select_all(ctx, id, e); + } + let enter = ui.input(|i| i.key_pressed(egui::Key::Enter)); + let field = if r.lost_focus() && enter { + Some(true) + } else if e.fresh > 0 || on_window || by != 0.0 { + if !r.has_focus() { + r.request_focus(); + } + None + } else if r.lost_focus() { + Some(false) + } else { + None + }; + answer = answer.or(field); + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + answer = Some(false); + escaped = true; + } + }); + }); + }); + if let Some(rect) = ctx.memory(|m| m.area_rect(area)) { + crate::scenario::publish_rect("dimwin", rect); + } + if by != 0.0 + && answer.is_none() + && let Some(stepped) = step(&e.expr, by) + { + e.expr = stepped; + // The whole new value is selected, so typing replaces it. + select_all(ctx, id, e); + ctx.request_repaint(); + } + if answer.is_some() { + forget(); + } + (answer, escaped) +} + +/// Select the whole value in the field, so typing replaces it. +fn select_all(ctx: &egui::Context, id: egui::Id, e: &mut Edit) { + let n = e.expr.chars().count(); + let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n)))); + e.selection = state.cursor.char_range(); + state.store(ctx, id); +} diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs index 986fff3b9..7693c18a1 100644 --- a/crates/ui-egui/src/dimension_create_ui_tests.rs +++ b/crates/ui-egui/src/dimension_create_ui_tests.rs @@ -192,6 +192,215 @@ fn dimension_tool_click_respects_the_selection_filter() { crate::dim_view::cancel(); } +/// A line from the origin to `end` with Preferences › Sketch › Dimension values set to In a +/// window (#7246). +fn windowed(end: [f64; 2]) -> Harness { + let mut h = line(end); + h.call("ui.prefs", json!({"dimension_input": "window"})); + h +} + +/// The value the open new dimension's window holds. +fn draft_value() -> String { + crate::dim_view::draft_preview().map(|(expr, _, _)| expr).unwrap_or_default() +} + +/// In a window, the Dimension tool places the text first and the window opens on it. Its arrows, +/// Up/Down and the wheel over the field step the value while the sketch previews it, nothing +/// reaches the design before the check, the check adds the dimension in one undo step, and the +/// tool stays on for the next dimension. +#[test] +fn a_new_dimension_in_the_window_steps_previews_and_applies_once() { + let mut h = windowed([20., 0.]); + let original = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"world":[10,0,0]}})).unwrap(); + assert_eq!(crate::dim_view::live(), None, "no value follows the pointer before the text is placed"); + assert!(!crate::dim_view::editing()); + h.step(&json!({"click":{"world":[10,6,0]}})).unwrap(); + h.frames(3); + assert!(crate::dim_view::editing(), "placing the text opens the window"); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(egui::Id::new("sc_dim_edit")), "its field takes the keyboard"); + let window = crate::scenario::rect_of("dimwin").expect("the window is shown"); + let drawable = h.app.viewport.layout.as_ref().unwrap().drawable; + assert!(drawable.contains_rect(window), "the window {window:?} stays in the view {drawable:?}"); + assert_eq!(draft_value(), "20 mm"); + let arrow = crate::scenario::handle_at("dimwin:up"); + for _ in 0..3 { + h.step(&json!({"click":{"handle":"dimwin:up"}})).unwrap(); + } + h.frames(2); + assert_eq!(crate::scenario::handle_at("dimwin:up"), arrow, "the window stays put while the value moves the text"); + let (value, dimension, _) = crate::dim_view::draft_preview().unwrap(); + assert_eq!(value, "23 mm"); + assert!((dimension.kind.value().unwrap() - 23.).abs() < 1e-6, "the sketch previews the stepped value"); + assert!(crate::scenario::count_of("dimwin:preview_curves").unwrap_or(0.0) > 0.0, "what the value moves is drawn"); + assert_eq!(h.app.session.doc.to_json(), original, "nothing reaches the design before OK"); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(egui::Id::new("sc_dim_edit")), "the arrows leave the keyboard with the field"); + // The wheel over the field steps it instead of zooming the view. + let cam = h.app.cam; + let field = crate::scenario::rect_of("dimwin:value").unwrap(); + h.call("ui.scroll", json!({"x": field.center().x, "y": field.center().y, "delta": -40.0})); + h.frames(2); + assert_eq!(draft_value(), "22 mm"); + assert_eq!(h.app.cam, cam, "the view did not zoom"); + h.step(&json!({"key":"ArrowUp"})).unwrap(); + h.frames(2); + assert_eq!(draft_value(), "23 mm"); + h.step(&json!({"click":{"handle":"dimwin:ok"}})).unwrap(); + h.frames(2); + assert!(!crate::dim_view::editing(), "{}", h.call("ui.inspect", json!({}))); + assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step"); + let state = h.app.session.world_state().unwrap(); + let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + let dimension = sk.constraints.iter().find(|c| c.param.is_some()).expect("the dimension was added"); + assert!((dimension.kind.value().unwrap() - 23.).abs() < 1e-6); + assert_eq!(h.app.tool.as_ref().map(|t| (t.cmd, t.picks.len())), Some(("sketch.dimension", 0)), "the tool stays on for the next one"); + crate::dim_view::cancel(); +} + +/// The cross and Esc drop only the dimension in the window: nothing is added and the Dimension +/// tool stays on. Esc with no window open then puts the tool down, as before. +#[test] +fn the_window_cross_and_escape_drop_only_this_dimension() { + let mut h = windowed([20., 0.]); + let original = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + place(&mut h, &[[10., 0.]], [10., 6.]); + h.step(&json!({"click":{"handle":"dimwin:up"}})).unwrap(); + h.step(&json!({"click":{"handle":"dimwin:cancel"}})).unwrap(); + h.frames(2); + assert!(!crate::dim_view::editing()); + assert_eq!(h.app.session.doc.to_json(), original); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.tool.as_ref().map(|t| (t.cmd, t.picks.len())), Some(("sketch.dimension", 0))); + place(&mut h, &[[10., 0.]], [10., 6.]); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!crate::dim_view::editing()); + assert_eq!(h.app.session.doc.to_json(), original); + assert_eq!(h.app.tool.as_ref().map(|t| t.cmd), Some("sketch.dimension"), "Esc in the window leaves the tool on"); + h.frames(40); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(h.app.tool.is_none(), "Esc with no window open ends the tool"); + crate::dim_view::cancel(); +} + +/// Double-clicking an existing dimension opens the window too. Typing and stepping preview the +/// sketch without touching the design, a value OK would refuse says why under the field, an +/// expression is left as typed by the arrows, and Enter applies the value in one undo step. +#[test] +fn double_clicking_a_dimension_opens_the_window_with_a_live_preview() { + let mut h = windowed([20., 0.]); + h.app.run("parameters.add", json!({"name":"width","expression":"30 mm"})).unwrap(); + h.app.run("sketch.dimension", json!({"entities":["l1"],"value":20,"text_at":[10,8]})).unwrap(); + h.settle(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.frames(40); + h.step(&json!({"click":{"dimension":"d1"},"double":true})).unwrap(); + h.frames(3); + assert!(crate::dim_view::editing() && crate::scenario::rect_of("dimwin").is_some(), "the window opens on the dimension"); + type_value(&mut h, "26"); + h.frames(2); + assert!(crate::scenario::count_of("dimwin:preview_curves").unwrap_or(0.0) > 0.0, "the sketch previews 26"); + h.step(&json!({"key":"ArrowUp"})).unwrap(); + h.frames(2); + assert!(h.widget("27").is_some(), "Up stepped the value: {}", h.call("ui.inspect", json!({}))); + assert_eq!(h.app.session.doc.to_json(), before, "nothing reaches the design before OK"); + type_value(&mut h, "no_such_name"); + h.frames(2); + assert!(crate::scenario::rect_of("dialog:report:dimension_error").is_some(), "the refusal shows under the field"); + assert_eq!(crate::scenario::count_of("dimwin:preview_curves"), Some(0.0), "a refused value previews nothing"); + type_value(&mut h, "width - 4"); + h.step(&json!({"click":{"handle":"dimwin:up"}})).unwrap(); + h.frames(2); + assert!(h.widget("width - 4").is_some(), "an expression is left as typed"); + type_value(&mut h, "27"); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(2); + assert!(!crate::dim_view::editing()); + assert!((h.app.session.doc.eval("d1", solidcraft_engine::doc::expr::Kind::Length).unwrap() - 27.).abs() < 1e-6); + assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step"); + crate::dim_view::cancel(); +} + +/// The arrows keep the unit and decimal mark a value is written in: a length steps by the length +/// step converted to that unit (a bare number is in the design's unit), an angle by the angle +/// step, and anything but a plain number is left alone. +#[test] +fn window_steps_keep_the_written_unit_and_decimal_mark() { + use crate::dim_view::window::stepped; + use solidcraft_engine::doc::expr::Kind::{Angle, Length}; + assert_eq!(stepped("20 mm", 1.0, Length, "mm", 1.0, 1.0).as_deref(), Some("21 mm")); + assert_eq!(stepped("20", -1.0, Length, "mm", 0.5, 1.0).as_deref(), Some("19.5")); + assert_eq!(stepped("1 in", 1.0, Length, "mm", 2.54, 1.0).as_deref(), Some("1.1 in")); + assert_eq!(stepped("1", 1.0, Length, "in", 2.54, 1.0).as_deref(), Some("1.1"), "a bare length is in the design's unit"); + assert_eq!(stepped("3\"", 10.0, Length, "mm", 2.54, 1.0).as_deref(), Some("4\"")); + assert_eq!(stepped("2,5 cm", 1.0, Length, "mm", 1.0, 1.0).as_deref(), Some("2,6 cm")); + assert_eq!(stepped("45 deg", -1.0, Angle, "mm", 1.0, 5.0).as_deref(), Some("40 deg")); + assert_eq!(stepped("45", 0.1, Angle, "in", 1.0, 1.0).as_deref(), Some("45.1"), "a bare angle is in degrees"); + assert_eq!(stepped("width / 2", 1.0, Length, "mm", 1.0, 1.0), None); + assert_eq!(stepped("20 deg", 1.0, Length, "mm", 1.0, 1.0), None, "a length does not step an angle"); +} + +/// Dimension values default to In the view with steps of 1 mm and 1°; the choice and the steps +/// save, out-of-range steps and unknown choices are refused, and the Sketch page's Restore +/// Defaults and Cancel treat them as the page's own. +#[test] +fn the_dimension_window_preferences_default_save_and_reset() { + use crate::prefs::{DimensionInput, Prefs, control}; + let d = Prefs::default(); + assert_eq!((d.dimension_input, d.dimension_step_mm, d.dimension_step_deg), (DimensionInput::View, 1.0, 1.0)); + let old: Prefs = serde_json::from_value(json!({})).unwrap(); + assert_eq!(old.dimension_input, DimensionInput::View, "saved preferences without it keep the box"); + let read = crate::prefs::lenient(&json!({"dimension_input": "sideways", "dimension_step_mm": 2.0})); + assert_eq!((read.dimension_input, read.dimension_step_mm), (DimensionInput::View, 2.0), "an unknown choice costs only itself"); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + for refused in [ + json!({"dimension_input": "sideways"}), + json!({"dimension_step_mm": 0.0}), + json!({"dimension_step_mm": 5000.0}), + json!({"dimension_step_deg": 0.0}), + json!({"dimension_step_deg": 200.0}), + ] { + assert!(control(&mut app, &refused).is_err(), "{refused}"); + } + assert_eq!(app.preferences, Prefs::default(), "a refusal changes nothing"); + control(&mut app, &json!({"open": "Sketch", "dimension_input": "window", "dimension_step_mm": 0.5, "dimension_step_deg": 15.0})).unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!( + (other.preferences.dimension_input, other.preferences.dimension_step_mm, other.preferences.dimension_step_deg), + (DimensionInput::Window, 0.5, 15.0) + ); + control(&mut app, &json!({"button": "defaults"})).unwrap(); + assert_eq!( + (app.preferences.dimension_input, app.preferences.dimension_step_mm, app.preferences.dimension_step_deg), + (DimensionInput::View, 1.0, 1.0) + ); + control(&mut app, &json!({"button": "cancel"})).unwrap(); + assert_eq!( + (app.preferences.dimension_input, app.preferences.dimension_step_mm, app.preferences.dimension_step_deg), + (DimensionInput::Window, 0.5, 15.0) + ); +} + +/// The Sketch page's Dimension values switch is a real control. +#[test] +fn the_sketch_page_switches_dimension_values_to_a_window() { + let mut h = Harness::new(); + h.call("ui.prefs", json!({"open": "Sketch"})); + h.frames(4); + let handle = format!("dialog:{}:{}", crate::i18n::tr("prefs.dimension_values"), crate::i18n::tr("prefs.dimension_values_window")); + crate::prefs::reveal_preference(&mut h, &handle); + h.step(&json!({"click":{"handle": handle}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.dimension_input, crate::prefs::DimensionInput::Window); +} + #[test] fn dimension_parameters_use_typing_and_ctrl_space_completion() { for (prefix, expected) in [("wid", "width"), ("", "width"), ("d", "d1")] { diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 6456b8fb7..76cc3eab2 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -582,6 +582,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e let wheel_inside = inside || (ui.is_enabled() && !crate::value_step::enabled(ui.ctx()) + && !hover.is_some_and(|p| crate::dim_view::window::covers(ui.ctx(), p)) && hover.is_some_and(|p| { rect.contains(p) && !axes.contains(p) diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index f81cc0755..0966e4b68 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -676,6 +676,21 @@ impl OriginPlaneNames { } } +/// Where a sketch dimension's value is typed (Preferences › Sketch, "Dimension values", #7246). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DimensionInput { + /// In a box on the dimension (also what a value this version doesn't know reads as). + #[default] + View, + /// In a small window at the dimension, with arrows that step the value (`dim_view::window`). + Window, +} + +/// The lengths (millimetres) and angles (degrees) the dimension window's arrows may step by. +pub const DIMENSION_STEP_MM: std::ops::RangeInclusive = 0.001..=1000.0; +pub const DIMENSION_STEP_DEG: std::ops::RangeInclusive = 0.001..=180.0; + /// What an orbit turns around (Preferences: "Orbit around"). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -1567,6 +1582,13 @@ preference_settings! { line_hover_tangent_arc: bool = false, PAGE_SKETCH; /// Include hidden geometry and a small pointer neighbourhood in Select Other. select_other_hidden: bool = true, PAGE_SKETCH; + /// Where a dimension's value is typed: in a box on the dimension (the default), or in a small + /// window at it whose arrows step the value (#7246, `dim_view::window`). + dimension_input: DimensionInput = DimensionInput::View, PAGE_SKETCH; + /// What the dimension window's arrows, Up/Down and the wheel add to a length (millimetres, + /// converted to the unit the value is written in) and to an angle (degrees). + dimension_step_mm: f64 = 1.0, PAGE_SKETCH, accept(DIMENSION_STEP_MM); + dimension_step_deg: f64 = 1.0, PAGE_SKETCH, accept(DIMENSION_STEP_DEG); /// When true: Shift+click adds without removing; Primary toggles. /// When false (default): Shift and Primary both toggle. selection_shift_add_only: bool = false, PAGE_SKETCH; @@ -3983,6 +4005,11 @@ fn prepare_preferences( { return Err("`stand_up_unknown` must be ask, note or off".into()); } + if let Some(v) = p.get("dimension_input") + && !matches!(v.as_str(), Some("view" | "window")) + { + return Err("`dimension_input` must be view or window".into()); + } let mut new: Prefs = serde_json::from_value(cur).map_err(|e| e.to_string())?; migrate_gruvbox(&mut new); if let Some(update) = p.get("theme_options") { @@ -4076,6 +4103,9 @@ fn prepare_preferences( if !accepted::perspective_fov(&new) { return Err("`perspective_fov` must be 15°…90° in radians (0.2618…1.5708)".into()); } + if !accepted::dimension_step_mm(&new) || !accepted::dimension_step_deg(&new) { + return Err("`dimension_step_mm` must be 0.001…1000 and `dimension_step_deg` 0.001…180".into()); + } if solidcraft_engine::doc::display_quality::DisplayQuality::parse(&new.display_quality).is_none() { return Err("`display_quality` must be coarse, normal, fine or ultra".into()); } diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs index ede212693..d8e88e0f3 100644 --- a/crates/ui-egui/src/prefs/sketch.rs +++ b/crates/ui-egui/src/prefs/sketch.rs @@ -172,6 +172,7 @@ fn drawing(app: &mut SolveApp, ui: &mut egui::Ui) { ); }); }); + dimension_values(app, ui, t.space_24 * 8.0 + t.space_8); }); } @@ -480,3 +481,35 @@ fn targets(key: &str, response: &egui::Response) { }; crate::scenario::publish_target(&format!("dialog:{legacy}"), response.rect); } + +/// Where a dimension's value is typed, and what the window's arrows step lengths and angles by +/// (#7246). The steps only matter in the window, so they wait for it. +fn dimension_values(app: &mut SolveApp, ui: &mut egui::Ui, label_width: f32) { + let label = app.tr("prefs.dimension_values").to_string(); + ui_kit::settings_block_hint(ui, &label, app.tr("prefs.dimension_values_note"), label_width, |ui| { + let options = [app.tr("prefs.dimension_values_view"), app.tr("prefs.dimension_values_window")]; + let mut selected = usize::from(app.preferences.dimension_input == DimensionInput::Window); + if ui_kit::settings_segments(ui, &label, &mut selected, &options) { + app.preferences.dimension_input = if selected == 1 { DimensionInput::Window } else { DimensionInput::View }; + } + }); + let window = app.preferences.dimension_input == DimensionInput::Window; + let units = app.session.doc.units.clone(); + let decimals = app.preferences.length_decimals; + ui_kit::settings_block(ui, app.tr("prefs.dimension_steps"), label_width, |ui| { + ui.add_enabled_ui(window, |ui| { + ui.horizontal(|ui| { + let t = Tokens::get(); + ui_kit::settings_control_width(ui, t.form_label_width, |ui| { + let p = &mut app.preferences; + ui_kit::bounded_length_field(ui, &mut p.dimension_step_mm, &units, decimals, DIMENSION_STEP_MM, 0.1) + .on_hover_text(crate::i18n::tr("prefs.dimension_step_length")); + }); + ui_kit::settings_control_width(ui, t.form_label_width, |ui| { + ui_kit::number_field(ui, &mut app.preferences.dimension_step_deg, DIMENSION_STEP_DEG, 0.1, "°") + .on_hover_text(crate::i18n::tr("prefs.dimension_step_angle")); + }); + }); + }); + }); +} diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 6ee7f0078..cc5889fd5 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -774,38 +774,7 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { replaced.push(b.name.clone()); } } - let sketches = after - .sketches - .iter() - .filter_map(|sketch| { - let old = before.sketch(sketch.feature); - let old_curves = - old.into_iter().flat_map(|s| s.sketch.curves.iter().map(|c| (c.id.as_str(), c))).collect::>(); - let old_points = - old.into_iter().flat_map(|s| s.sketch.points.iter().map(|p| (p.id.as_str(), p.pos))).collect::>(); - let indices = sketch - .sketch - .curves - .iter() - .enumerate() - .filter_map(|(index, curve)| { - let unchanged = old_curves.get(curve.id.as_str()).is_some_and(|previous| { - previous.kind == curve.kind - && curve.kind.point_ids().iter().all(|i| old.and_then(|s| s.sketch.point(*i)) == sketch.sketch.point(*i)) - }); - if unchanged { None } else { Some(index) } - }) - .collect::>(); - let points = sketch - .sketch - .points - .iter() - .enumerate() - .filter_map(|(i, p)| if old_points.get(p.id.as_str()) == Some(&p.pos) { None } else { Some(i) }) - .collect::>(); - if indices.is_empty() && points.is_empty() { None } else { Some(SketchPreview { sketch: sketch.clone(), curves: indices, points }) } - }) - .collect(); + let sketches = after.sketches.iter().filter_map(|sketch| sketch_changes(before.sketch(sketch.feature), sketch)).collect(); Built { scene: sc, sketches, replaced, error: None, bounds: Aabb3::EMPTY, applied: None, tapered: Vec::new(), stopped: None } } @@ -821,6 +790,37 @@ fn on_surface(index: &SurfaceIndex, [a, b, c]: [Vec3; 3]) -> bool { /// bounded, so a modeled thread's thousands of faces still cost little. const FACE_SAMPLES: usize = 24; +/// What of `sketch` differs from `old`, the same sketch before a change: the curves whose shape +/// or points moved and the points that moved (`None`: nothing did). +pub(crate) fn sketch_changes( + old: Option<&solidcraft_engine::doc::SolvedSketch>, + sketch: &std::sync::Arc, +) -> Option { + let old_curves = old.into_iter().flat_map(|s| s.sketch.curves.iter().map(|c| (c.id.as_str(), c))).collect::>(); + let old_points = + old.into_iter().flat_map(|s| s.sketch.points.iter().map(|p| (p.id.as_str(), p.pos))).collect::>(); + let indices = sketch + .sketch + .curves + .iter() + .enumerate() + .filter_map(|(index, curve)| { + let unchanged = old_curves.get(curve.id.as_str()).is_some_and(|previous| { + previous.kind == curve.kind && curve.kind.point_ids().iter().all(|i| old.and_then(|s| s.sketch.point(*i)) == sketch.sketch.point(*i)) + }); + if unchanged { None } else { Some(index) } + }) + .collect::>(); + let points = sketch + .sketch + .points + .iter() + .enumerate() + .filter_map(|(i, p)| if old_points.get(p.id.as_str()) == Some(&p.pos) { None } else { Some(i) }) + .collect::>(); + if indices.is_empty() && points.is_empty() { None } else { Some(SketchPreview { sketch: sketch.clone(), curves: indices, points }) } +} + /// Which of the `nf` faces of `m` are new surface, i.e. not on the old mesh? Each is decided by /// a vote of points on it (triangle centroids spread over the face). One pass over `m`'s /// triangles gathers the centroids, and the old mesh is indexed once, so the cost stays @@ -962,22 +962,30 @@ pub fn paint_sketches(app: &SolveApp, painter: &egui::Painter, proj: &crate::vie { return; } - let stroke = egui::Stroke::new(2.5, Tokens::get().preview_sketch); let mut budget = solidcraft_engine::render::SamplingBudget::new(32_768, 65_536); - let mut curves = 0; - for preview in &app.preview.sketches { - let sketch = &preview.sketch; - for index in &preview.curves { - crate::tools::paint_curve(&sketch.sketch, *index, &sketch.plane, painter, proj, stroke, &mut budget); - curves += 1; - } - for index in &preview.points { - if let Some(point) = sketch.sketch.point(*index).and_then(|p| proj.to_screen(sketch.plane.to_world(p))) { - painter.circle_filled(point, 3.0, stroke.color); - } + let curves: usize = app.preview.sketches.iter().map(|preview| paint_sketch(preview, painter, proj, &mut budget)).sum(); + crate::scenario::publish_count("sketch_preview_curves", curves as f64); +} + +/// Draw what a change moves in a sketch, its curves and points, in the preview colour; returns +/// how many curves it drew. +pub(crate) fn paint_sketch( + preview: &SketchPreview, + painter: &egui::Painter, + proj: &crate::viewport::Proj, + budget: &mut solidcraft_engine::render::SamplingBudget, +) -> usize { + let stroke = egui::Stroke::new(2.5, Tokens::get().preview_sketch); + let sketch = &preview.sketch; + for index in &preview.curves { + crate::tools::paint_curve(&sketch.sketch, *index, &sketch.plane, painter, proj, stroke, budget); + } + for index in &preview.points { + if let Some(point) = sketch.sketch.point(*index).and_then(|p| proj.to_screen(sketch.plane.to_world(p))) { + painter.circle_filled(point, 3.0, stroke.color); } } - crate::scenario::publish_count("sketch_preview_curves", curves as f64); + preview.curves.len() } #[cfg(test)] diff --git a/crates/ui-egui/src/value_step.rs b/crates/ui-egui/src/value_step.rs index a8a0cbfb2..b8022ab5c 100644 --- a/crates/ui-egui/src/value_step.rs +++ b/crates/ui-egui/src/value_step.rs @@ -80,7 +80,7 @@ fn tenths_for(m: Modifiers) -> Option { } /// This frame's Up/Down presses, key repeats included, in signed tenths. -fn key_tenths(i: &egui::InputState) -> i64 { +pub(crate) fn key_tenths(i: &egui::InputState) -> i64 { i.events .iter() .filter_map(|e| match e { @@ -94,7 +94,7 @@ fn key_tenths(i: &egui::InputState) -> i64 { /// 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 { +pub(crate) 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; @@ -167,7 +167,22 @@ fn plain(text: &str) -> Option { 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; + rewritten(text, &p, p.value + tenths as f64 / 10.0, places) +} + +/// `text` with its plain number moved by what `by` answers for the unit it is written in (the +/// text after the number, empty for none): an amount and the decimal places it needs, written +/// with at least the places the number had (`dim_view::window` steps by a length or an angle +/// this way). `None` when `text` is not a plain number or `by` has no answer. +pub(crate) fn shifted(text: &str, by: impl FnOnce(&str) -> Option<(f64, usize)>) -> Option { + let p = plain(text)?; + let (amount, places) = by(text.get(p.end..)?.trim())?; + rewritten(text, &p, p.value + amount, places.max(p.places)) +} + +/// `text` with its plain number `p` replaced by `v` written with `places` decimals, in the decimal +/// mark it had. +fn rewritten(text: &str, p: &Plain, v: f64, places: usize) -> Option { if !v.is_finite() { return None; } diff --git a/crates/ui-egui/tests/scenarios/sketch_dimension_window.json b/crates/ui-egui/tests/scenarios/sketch_dimension_window.json new file mode 100644 index 000000000..3114639af --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_dimension_window.json @@ -0,0 +1,21 @@ +[ + {"note": "#7246: with Preferences › Sketch › Dimension values set to In a window, the Dimension tool places the text first and a small window opens on it. Its arrows step the value, the check applies it in one step, and the tool stays on for the next dimension."}, + {"call": "ui.prefs", "params": {"dimension_input": "window"}}, + {"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}}, + {"call": "engine.execute", "params": {"command": "sketch.line", "params": {"points": [[0, 0], [30, 0]], "ids": ["l1"]}}}, + {"call": "ui.view", "params": {"view": "top"}}, + {"call": "ui.view", "params": {"view": "fit"}}, + {"start": "sketch.dimension"}, + {"click": {"sketch": [15, 0]}}, + {"click": {"sketch": [15, 6]}}, + {"frames": 5}, + {"expect": {"shown_handles": ["dimwin:value", "dimwin:up", "dimwin:down", "dimwin:ok", "dimwin:cancel"]}}, + {"click": {"handle": "dimwin:up"}}, + {"click": {"handle": "dimwin:up"}}, + {"click": {"handle": "dimwin:ok"}}, + {"frames": 3}, + {"expect": {"errors": 0}}, + {"expect": {"hidden_handles": ["dimwin:value"]}}, + {"expect": {"tool": "sketch.dimension"}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 0, "end_at", 0], "value": 32}}} +] diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index 8fed36e2d..a9cec30da 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -368,6 +368,16 @@ nothing picked yet, click it once: its value box opens with the value selected, and the tool stays on for the next dimension. The dimension's text always takes the click; its lines take it only away from sketch points and curves, which still start a new dimension. +To type values in a small window instead, set **Preferences › Sketch › Dimension values** to +**In a window**. The Dimension tool then places the text first: click what you want to +measure, then where the text goes, and the window opens there (double-clicking a dimension +opens it too). Its field takes the same numbers, units, expressions and parameter names as the +box, and the sketch shows the value as you type. The arrows beside the field, Up and Down, and +the mouse wheel over the field step a number by **Window steps** (1 mm and 1° unless you change +them; Shift steps ten times as far, Alt a tenth), keeping the unit it is written in. The check +(or Enter) applies the value as one undo step and the tool stays on for the next dimension; the +cross (or Esc) drops this dimension only, and Esc with no window open puts the tool down. + To have shapes dimensioned as you draw them, turn on **Dimension new shapes** in Preferences › Sketch (it is off by default). Each line, rectangle, circle, arc, slot, polygon or ellipse you draw then gets all its dimensions at the sizes you drew: a line its length and angle, a rectangle its diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4949c5b31..9e5e35304 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -702,6 +702,9 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `default_units` - `dialog_buttons` (`bottom` (default), `top`: a feature dialog's OK, Cancel and Apply sit in its title row instead of under its inputs, #6708; the buttons keep their handles, and `dialog:close` is then Cancel's; the Sketch panel's Finish Sketch row moves above its options, #9860) - `dialog_place` (`edge` (default) or `left_column`: command dialogs open in the left column in place of the browser and the History, #6707) +- `dimension_input` (`view` (default): a sketch dimension's value is typed in a box on the dimension; `window`: placing a dimension with the Dimension tool, or double-clicking one, opens a small window at it with the value field (handle `dimwin:value`), arrows that step the value (`dimwin:up`, `dimwin:down`), a check (`dimwin:ok`, also Enter) and a cross (`dimwin:cancel`, also Esc), #7246) +- `dimension_step_deg` (default 1, 0.001…180: what the dimension window's arrows, Up/Down and the wheel over its field add to an angle, in degrees) +- `dimension_step_mm` (default 1, 0.001…1000: what the window's arrows, Up/Down and the wheel over its field add to a length, in millimetres, written in the unit the value is written in) - `extrude_auto_to_object` (default true: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object, unless the Profiles box was clicked into; it applies to Extrude dialogs opened afterwards) - `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) - `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence)