From f1c2f67d635141c9e9d9fa84710e3e99312b4829 Mon Sep 17 00:00:00 2001 From: Kai Evans Date: Fri, 30 Oct 2026 15:46:01 +0000 Subject: [PATCH] Quick measurement: the selection's length, area or distance in the view's corner (#7000) (#7513) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Quick measurement: the selection's length, area or distance in the view's corner (#7000) With edges, faces, sketch curves or points selected, the view's bottom right corner above History shows what they measure, as the Measure tool lists it: an edge's length (Ø and R for a round one), a face's area, a point's position; two items' distance and angle; several edges' or faces' count and total. It is computed off the window thread from a copy of the session whenever the selection or the design changes, and a click copies it. Preferences > Interface turns it off. The Measure dialog's rows come from the same function. * Quick measurement: off by default, turned on under Preferences > Interface (#7000) The quick_measure preference now defaults to false, so nothing changes until it is turned on. Its tests turn it on, and a new test checks that nothing shows until it is. --- assets/locales/pending/quick-measure.json | 50 +++++ crates/ui-egui/src/dialogs_dense.rs | 31 +-- crates/ui-egui/src/lib.rs | 6 + crates/ui-egui/src/prefs.rs | 4 + crates/ui-egui/src/prefs/interface.rs | 5 + crates/ui-egui/src/quick_measure.rs | 249 ++++++++++++++++++++++ crates/ui-egui/src/quick_measure_tests.rs | 210 ++++++++++++++++++ crates/ui-egui/src/render_ui/mod.rs | 2 +- crates/ui-egui/src/viewport.rs | 19 +- docs/book/src/guide/features.md | 6 + docs/control-protocol.md | 1 + 11 files changed, 550 insertions(+), 33 deletions(-) create mode 100644 assets/locales/pending/quick-measure.json create mode 100644 crates/ui-egui/src/quick_measure.rs create mode 100644 crates/ui-egui/src/quick_measure_tests.rs diff --git a/assets/locales/pending/quick-measure.json b/assets/locales/pending/quick-measure.json new file mode 100644 index 000000000..520905b57 --- /dev/null +++ b/assets/locales/pending/quick-measure.json @@ -0,0 +1,50 @@ +{ + "en": { + "measure.quick_copied": "Measurement copied", + "measure.quick_copy": "Click to copy the measurement", + "measure.quick_edges": "{count} edges", + "measure.quick_faces": "{count} faces", + "prefs.quick_measure": "Quick measurement in the view's corner", + "prefs.quick_measure_note": "The selection's size in the view's bottom right corner: an edge's length, or Ø and R for a round one, a face's area, a point's position, two items' distance and angle, several edges' or faces' total. A click copies it." + }, + "ar": { + "measure.quick_copied": "تم نسخ القياس", + "measure.quick_copy": "انقر لنسخ القياس", + "measure.quick_edges": "{count} حواف", + "measure.quick_faces": "{count} أوجه", + "prefs.quick_measure": "قياس سريع في زاوية العرض", + "prefs.quick_measure_note": "يعرض مقاس العناصر المحددة في الزاوية اليمنى السفلية من العرض فوق السجل: طول الحافة (أو Ø وR للحافة الدائرية)، ومساحة الوجه، وموضع النقطة، والمسافة والزاوية بين عنصرين، ومجموع عدة حواف أو أوجه. النقر ينسخه." + }, + "he": { + "measure.quick_copied": "המדידה הועתקה", + "measure.quick_copy": "לחיצה מעתיקה את המדידה", + "measure.quick_edges": "{count} מקצועות", + "measure.quick_faces": "{count} פאות", + "prefs.quick_measure": "מדידה מהירה בפינת התצוגה", + "prefs.quick_measure_note": "מציג את מידות הבחירה בפינה הימנית התחתונה של התצוגה, מעל ההיסטוריה: אורך מקצוע (או Ø ו-R למקצוע עגול), שטח פאה, מיקום נקודה, המרחק והזווית בין שני פריטים, והסכום של כמה מקצועות או פאות. לחיצה מעתיקה אותו." + }, + "ja": { + "measure.quick_copied": "測定値をコピーしました", + "measure.quick_copy": "クリックで測定値をコピー", + "measure.quick_edges": "エッジ {count} 本", + "measure.quick_faces": "面 {count} 個", + "prefs.quick_measure": "ビューの隅にクイック測定", + "prefs.quick_measure_note": "選択したものの寸法をビューの右下、履歴の上に表示します: エッジの長さ(円形のものは Ø と R)、面の面積、点の位置、2 つの項目の距離と角度、複数のエッジや面の合計。クリックでコピーします。" + }, + "vi": { + "measure.quick_copied": "Đã sao chép số đo", + "measure.quick_copy": "Nhấp để sao chép số đo", + "measure.quick_edges": "{count} cạnh", + "measure.quick_faces": "{count} mặt", + "prefs.quick_measure": "Đo nhanh ở góc khung nhìn", + "prefs.quick_measure_note": "Hiển thị kích thước của đối tượng được chọn ở góc dưới bên phải khung nhìn, phía trên Lịch sử: chiều dài của cạnh (hoặc Ø và R với cạnh tròn), diện tích của mặt, vị trí của điểm, khoảng cách và góc giữa hai đối tượng, tổng của nhiều cạnh hoặc mặt. Nhấp để sao chép." + }, + "zh": { + "measure.quick_copied": "已复制测量值", + "measure.quick_copy": "点击复制测量值", + "measure.quick_edges": "{count} 条边", + "measure.quick_faces": "{count} 个面", + "prefs.quick_measure": "在视图角落显示快速测量", + "prefs.quick_measure_note": "在视图右下角、历史记录上方显示所选对象的尺寸:边的长度(圆形边显示 Ø 和 R)、面的面积、点的位置、两个对象之间的距离和角度、多条边或多个面的总和。点击即可复制。" + } +} diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index ae2b85aa9..5235e7380 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -927,36 +927,7 @@ fn measure_rows(app: &SolveApp, ui: &mut egui::Ui, r: Option<&Value>, show: &mut }); }; for (i, it) in r["items"].as_array().into_iter().flatten().enumerate() { - // Round items: Ø first, then R, then the length (circumference, or the arc's length - // and angle). - let mut lines: Vec = Vec::new(); - if it.get("diameter").is_some() { - lines.push(format!("Ø {}", mm(&it["diameter"]))); - lines.push(format!("R {}", mm(&it["radius"]))); - if it.get("circumference").is_some() { - lines.push(format!("{} {}", tr("Circumference"), mm(&it["circumference"]))); - } else if let Some(a) = it["angle_deg"].as_f64() { - lines.push(format!("{} {}", tr("Arc length"), mm(&it["arc_length"]))); - lines.push(format!("{} {a:.2}°", crate::i18n::tr_label("Angle"))); - } - } - if let Some(sl) = it.get("slot") { - lines.push(format!("{} {}", tr("Slot width"), mm(&sl["width"]))); - lines.push(format!("{} {}", tr("Centre to centre"), mm(&sl["center_distance"]))); - lines.push(format!("{} {}", tr("Overall length"), mm(&sl["overall_length"]))); - } - let round = it.get("diameter").is_some(); - match it["type"].as_str() { - Some("edge" | "sketch_curve") if !round => lines.push(format!("{} {}", tr("Length"), mm(&it["length_mm"]))), - Some("face" | "profile") => { - lines.push(format!("{} {}", tr("Area"), crate::prefs::show_mm(app, it["area_mm2"].as_f64().unwrap_or(0.0), 2))) - } - Some("vertex" | "sketch_point") => { - let p = &it["position"]; - lines.push(format!("{} {}, {}, {}", tr("measure.at"), mm(&p[0]), mm(&p[1]), mm(&p[2]))); - } - _ => {} - } + let lines = crate::quick_measure::item_lines(app, it); for (k, line) in lines.into_iter().enumerate() { let label = if k == 0 { crate::i18n::format("measure.item", &[("number", &(i + 1).to_string())]) } else { String::new() }; value(ui, &label, &line); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 15b834cc3..38564ac8a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -208,6 +208,9 @@ mod primitive_placement; #[cfg(test)] mod primitive_units_tests; mod print_face_ui; +pub(crate) mod quick_measure; +#[cfg(test)] +mod quick_measure_tests; pub mod recovery_ui; pub mod ref_images; mod render_ui; @@ -614,6 +617,8 @@ pub struct SolveApp { pub recoverable: Vec, /// Discard all was clicked in the recovery window: its confirmation is showing (#9299). pub recovery_discard_all: bool, + /// The selection's measurement in the view's corner (#7000). + pub(crate) quick_measure: quick_measure::QuickMeasure, /// The bodies of a just-opened Y-up file, offered to be stood up (`stand_up`). pub stand_up: Option>, /// The placement of the component that file came in as: the offer turns it. @@ -806,6 +811,7 @@ impl SolveApp { network_prompt: None, recoverable: Vec::new(), recovery_discard_all: false, + quick_measure: Default::default(), stand_up: None, stand_up_occurrence: None, stand_up_reason: false, diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 0963d2757..87615a6ec 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1095,6 +1095,9 @@ preference_settings! { /// A thin bar along the window's bottom edge: what is being edited, the open sketch's state /// and the design's units (#7243). Off by default. status_bar: bool = false, PAGE_INTERFACE => check_id("prefs.status_bar"); + /// The selection's length, area or distance in the view's bottom right corner (#7000). Off by + /// default. + quick_measure: bool = false, PAGE_INTERFACE => check_id("prefs.quick_measure"); /// Put the feature history to the left of the browser instead of below the viewport. timeline_left: bool = false, PAGE_INTERFACE; /// Measured outer width; the contents react to this width without a names mode. @@ -5036,6 +5039,7 @@ mod tests { ("view_confirm_corner", json!(true), PAGE_INTERFACE), ("status_bar", json!(true), PAGE_INTERFACE), ("browser_eye_left", json!(true), PAGE_INTERFACE), + ("quick_measure", json!(true), PAGE_INTERFACE), ("nav", json!("blender"), PAGE_NAVIGATION), ("look_at_anim", json!(false), PAGE_NAVIGATION), ("selection_shift_add_only", json!(true), PAGE_SKETCH), diff --git a/crates/ui-egui/src/prefs/interface.rs b/crates/ui-egui/src/prefs/interface.rs index ca655d90f..30d29892d 100644 --- a/crates/ui-egui/src/prefs/interface.rs +++ b/crates/ui-egui/src/prefs/interface.rs @@ -279,6 +279,11 @@ pub(super) fn interface(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { let check = setting::status_bar(app, ui).on_hover_text(app.tr("prefs.status_bar_note")); crate::scenario::publish_target("prefs:status_bar", check.rect); }); + // The selection's measurement in the view's corner (#7000). + ui_kit::row(ui, "", |ui| { + let check = setting::quick_measure(app, ui).on_hover_text(app.tr("prefs.quick_measure_note")); + crate::scenario::publish_target("prefs:quick_measure", check.rect); + }); ui_kit::text(ui, app.tr("prefs.layout_note"), ui_kit::Text::Hint("layout")); ui_kit::text(ui, app.tr("prefs.history_sketches_note"), ui_kit::Text::Hint("history_sketches")); ui_kit::LayoutPreview { diff --git a/crates/ui-egui/src/quick_measure.rs b/crates/ui-egui/src/quick_measure.rs new file mode 100644 index 000000000..d5b490b33 --- /dev/null +++ b/crates/ui-egui/src/quick_measure.rs @@ -0,0 +1,249 @@ +//! Quick measurement (#7000): what the selection measures, in the view's bottom right corner above +//! History, so a simple size needs no Measure tool. One item gives the Measure tool's rows (an +//! edge's length, Ø and R for a round one, a face's area, a point's position); two give their +//! distance and angle; several edges or several faces their count and total length or area. +//! Computed off the window thread from a copy of the session ([`Session::measure_items`]) whenever +//! the selection or the design changes; nothing shows while it computes, or for a selection with +//! nothing to measure. A click copies the readout. + +use serde_json::{Value, json}; +use solidcraft_engine::Sel; + +use crate::SolveApp; + +/// Items summed into a total, at most. +const MAX_SUMMED: usize = 200; + +/// What a selection and design were measured as, and the measurement once it is in. +#[derive(Default)] +pub struct QuickMeasure { + /// The selection and design the measurement is for. + key: Option, + job: Option>>, + result: Option, +} + +#[derive(Clone, PartialEq)] +struct Key { + selection: Vec, + doc: usize, + revision: u64, +} + +impl QuickMeasure { + /// The readout as shown: each line a label and its value. + pub(crate) fn lines(&self, app: &SolveApp) -> Vec<(String, String)> { + self.result.as_ref().map(|r| lines(app, r)).unwrap_or_default() + } +} + +/// Is the readout wanted at all: the preference, a design shown, no Measure tool saying the same. +fn wanted(app: &SolveApp) -> bool { + app.preferences.quick_measure + && !app.home.open + && !crate::render_workspace::active(app) + && !app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::Measure { .. })) +} + +/// Can `sel` be measured here? A sketch's curves, points and regions are, open or only shown. +fn measurable(sel: &Sel) -> bool { + matches!( + sel, + Sel::Edge { .. } + | Sel::Face { .. } + | Sel::Vertex { .. } + | Sel::SketchCurve { .. } + | Sel::SketchPoint { .. } + | Sel::ExternalSketchCurve { .. } + | Sel::ExternalSketchPoint { .. } + | Sel::Profile { .. } + ) +} + +/// Each frame: start measuring a selection that changed, take a measurement that is in. +pub(crate) fn poll(app: &mut SolveApp, ctx: &egui::Context) { + let selection: Vec = app.session.selection.iter().filter(|s| measurable(s)).cloned().collect(); + if !wanted(app) || selection.is_empty() || selection.len() != app.session.selection.len() { + app.quick_measure = QuickMeasure::default(); + return; + } + let key = Key { selection, doc: std::sync::Arc::as_ptr(&app.session.doc) as usize, revision: app.session.revision }; + if app.quick_measure.key.as_ref() != Some(&key) { + app.quick_measure = QuickMeasure { job: start(app, &key.selection), key: Some(key), result: None }; + } + if let Some(job) = &app.quick_measure.job { + match job.try_recv() { + Ok(result) => { + app.quick_measure.result = result; + app.quick_measure.job = None; + } + Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(30)), + Err(std::sync::mpsc::TryRecvError::Disconnected) => app.quick_measure.job = None, + } + } +} + +/// Measure `selection` on a copy of the session, off the window thread. +fn start(app: &SolveApp, selection: &[Sel]) -> Option>> { + let session = app.session.scratch(); + let selection = selection.to_vec(); + let (tx, rx) = std::sync::mpsc::channel(); + let measure = move || { + let _ = tx.send(measure(&session, &selection)); + }; + #[cfg(not(target_arch = "wasm32"))] + { + std::thread::Builder::new().name("quick measure".into()).spawn(measure).ok()?; + } + #[cfg(target_arch = "wasm32")] + measure(); + Some(rx) +} + +/// One or two items as the Measure tool measures them; more, their count and total length (edges +/// and sketch curves) or area (faces and sketch regions). `None`: nothing to show. +fn measure(session: &solidcraft_engine::Session, selection: &[Sel]) -> Option { + if selection.len() <= 2 { + let r = session.measure_items(selection); + return r.get("error").is_none().then_some(r); + } + let lengths = selection.iter().all(|s| matches!(s, Sel::Edge { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. })); + let areas = selection.iter().all(|s| matches!(s, Sel::Face { .. } | Sel::Profile { .. })); + if !(lengths || areas) || selection.len() > MAX_SUMMED { + return None; + } + let mut total = 0.0; + for sel in selection { + let r = session.measure_items(std::slice::from_ref(sel)); + let it = r.get("items").and_then(|items| items.get(0))?; + total += if areas { + it["area_mm2"].as_f64()? + } else { + it["length_mm"].as_f64().or_else(|| it["circumference"].as_f64()).or_else(|| it["arc_length"].as_f64())? + }; + } + Some(json!({"count": selection.len(), if areas { "total_area_mm2" } else { "total_length_mm" }: total})) +} + +/// One measured item's rows, each "label value": Ø, R and the length of a round one (its +/// circumference, or an arc's length and angle), a slot's sizes, a straight edge's length, a face's +/// area, a point's position. The Measure tool lists the same. +pub(crate) fn item_lines(app: &SolveApp, it: &Value) -> Vec { + let tr = crate::i18n::tr; + let mm = |v: &Value| v.as_f64().map(|x| crate::prefs::show_mm(app, x, 1)).unwrap_or_default(); + let mut lines: Vec = Vec::new(); + if it.get("diameter").is_some() { + lines.push(format!("Ø {}", mm(&it["diameter"]))); + lines.push(format!("R {}", mm(&it["radius"]))); + if it.get("circumference").is_some() { + lines.push(format!("{} {}", tr("Circumference"), mm(&it["circumference"]))); + } else if let Some(a) = it["angle_deg"].as_f64() { + lines.push(format!("{} {}", tr("Arc length"), mm(&it["arc_length"]))); + lines.push(format!("{} {a:.2}°", crate::i18n::tr_label("Angle"))); + } + } + if let Some(sl) = it.get("slot") { + lines.push(format!("{} {}", tr("Slot width"), mm(&sl["width"]))); + lines.push(format!("{} {}", tr("Centre to centre"), mm(&sl["center_distance"]))); + lines.push(format!("{} {}", tr("Overall length"), mm(&sl["overall_length"]))); + } + let round = it.get("diameter").is_some(); + match it["type"].as_str() { + Some("edge" | "sketch_curve") if !round => lines.push(format!("{} {}", tr("Length"), mm(&it["length_mm"]))), + Some("face" | "profile") => lines.push(format!("{} {}", tr("Area"), crate::prefs::show_mm(app, it["area_mm2"].as_f64().unwrap_or(0.0), 2))), + Some("vertex" | "sketch_point") => { + let p = &it["position"]; + lines.push(format!("{} {}, {}, {}", tr("measure.at"), mm(&p[0]), mm(&p[1]), mm(&p[2]))); + } + _ => {} + } + lines +} + +/// The readout's rows for a measurement. +fn lines(app: &SolveApp, r: &Value) -> Vec<(String, String)> { + let split = |line: String| match line.split_once(" ") { + Some((label, value)) => (label.to_string(), value.to_string()), + None => (String::new(), line), + }; + if let Some(n) = r["count"].as_u64() { + let n = n.to_string(); + return match (r["total_length_mm"].as_f64(), r["total_area_mm2"].as_f64()) { + (Some(l), _) => vec![(crate::i18n::format("measure.quick_edges", &[("count", &n)]), crate::prefs::show_mm(app, l, 1))], + (_, Some(a)) => vec![(crate::i18n::format("measure.quick_faces", &[("count", &n)]), crate::prefs::show_mm(app, a, 2))], + _ => Vec::new(), + }; + } + let items = r["items"].as_array().map(Vec::as_slice).unwrap_or_default(); + if let [one] = items { + return item_lines(app, one).into_iter().map(split).collect(); + } + let mut rows = Vec::new(); + if let Some(d) = r["center_distance"].as_f64() { + rows.push((crate::i18n::tr("Centre to centre").to_string(), crate::prefs::show_mm(app, d, 1))); + } + if let Some(d) = r["distance_mm"].as_f64() { + rows.push((crate::i18n::tr_label("Distance").to_string(), crate::prefs::show_mm(app, d, 1))); + } + if let Some(a) = r["angle_deg"].as_f64() { + rows.push((crate::i18n::tr_label("Angle").to_string(), format!("{a:.2}°"))); + } + rows +} + +/// The readout in the bottom right corner of the view, above History, kept clear of `taken` (the +/// panels and cards over the view, the navigation bar): left of one standing along the right edge, +/// above any other. Returns where it is. +pub(crate) fn show(app: &mut SolveApp, ui: &egui::Ui, view: egui::Rect, taken: &[egui::Rect]) -> Option { + let rows = app.quick_measure.lines(app); + if rows.is_empty() || !view.is_finite() || !view.is_positive() { + return None; + } + let t = crate::theme::Tokens::get(); + let painter = ui.painter().clone(); + let font = egui::FontId::proportional(t.font_label); + let pad = egui::vec2(t.space_8, t.space_4); + let gap = t.space_8; + let galleys: Vec<_> = rows + .iter() + .map(|(label, value)| { + (painter.layout_no_wrap(label.clone(), font.clone(), t.text_dim), painter.layout_no_wrap(value.clone(), font.clone(), t.text)) + }) + .collect(); + let label_w = galleys.iter().map(|(l, _)| l.size().x).fold(0.0, f32::max); + let value_w = galleys.iter().map(|(_, v)| v.size().x).fold(0.0, f32::max); + let row_h = galleys.iter().map(|(l, v)| l.size().y.max(v.size().y)).fold(0.0, f32::max); + let size = egui::vec2(pad.x * 2.0 + label_w + gap + value_w, pad.y * 2.0 + row_h * galleys.len() as f32); + let mut r = egui::Rect::from_min_size(view.right_bottom() - size - egui::vec2(t.space_8, t.space_8), size); + // Each step clears one rectangle, so this ends after at most two moves per one. + for _ in 0..=2 * taken.len() { + let Some(o) = taken.iter().find(|o| o.expand(t.space_4).intersects(r)) else { break }; + r = if o.height() > view.height() * 0.5 { + r.translate(egui::vec2(o.left() - t.space_8 - r.right(), 0.0)) + } else { + r.translate(egui::vec2(0.0, o.top() - t.space_8 - r.bottom())) + }; + } + if !view.contains_rect(r) { + return None; + } + let response = ui.interact(r, egui::Id::new("sc_quick_measure"), egui::Sense::click()).on_hover_text(crate::i18n::tr("measure.quick_copy")); + crate::scenario::publish_rect("measure:quick", r); + painter.rect_filled(r, t.radius_sm, if response.hovered() { t.hover } else { t.overlay }); + painter.rect_stroke(r, t.radius_sm, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + for (i, (label, value)) in galleys.into_iter().enumerate() { + let y = r.top() + pad.y + row_h * i as f32; + painter.galley(egui::pos2(r.left() + pad.x, y), label, t.text_dim); + painter.galley(egui::pos2(r.right() - pad.x - value.size().x, y), value, t.text); + } + if response.clicked() { + let text = rows + .iter() + .map(|(label, value)| if label.is_empty() { value.clone() } else { format!("{label} {value}") }) + .collect::>() + .join("\n"); + ui.ctx().copy_text(text); + app.set_status(crate::i18n::tr("measure.quick_copied"), false); + } + Some(r) +} diff --git a/crates/ui-egui/src/quick_measure_tests.rs b/crates/ui-egui/src/quick_measure_tests.rs new file mode 100644 index 000000000..d2f4ba6ea --- /dev/null +++ b/crates/ui-egui/src/quick_measure_tests.rs @@ -0,0 +1,210 @@ +//! Quick measurement in the view's corner (#7000): what the selection measures, computed off the +//! window thread, shown above History, copied on a click. + +use serde_json::json; +use solidcraft_engine::Sel; +use solidcraft_engine::geom::Vec3; + +use crate::scenario::Harness; + +/// A design shown, with quick measurement turned on. +fn harness() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.quick_measure = true; + h +} + +/// A 10 × 20 × 30 box at the origin. +fn block() -> Harness { + let mut h = harness(); + h.app.run("solid.box", json!({"length": 10, "width": 20, "height": 30})).unwrap(); + h.frames(2); + h +} + +fn edge(h: &Harness, p: Vec3) -> Sel { + let st = h.app.session.world_state(); + let m = st.body("Body1").unwrap().mesh(); + let index = m.edges.iter().position(|e| e.windows(2).any(|w| p.dist_to_segment(w[0], w[1]) < 1e-9)).expect("an edge there"); + Sel::Edge { body: "Body1".into(), index, point: p } +} + +/// The face with a triangle wholly at height `z`. +fn face_at_height(h: &Harness, z: f64) -> Sel { + let st = h.app.session.world_state(); + let m = st.body("Body1").unwrap().mesh(); + let (t, f) = m.triangles.iter().zip(&m.tri_face).find(|(t, _)| m.tri(t).is_some_and(|ps| ps.iter().all(|p| (p.z - z).abs() < 1e-9))).unwrap(); + let ps = m.tri(t).unwrap(); + Sel::Face { body: "Body1".into(), index: *f as usize, point: (ps[0] + ps[1] + ps[2]) * (1.0 / 3.0) } +} + +/// The readout once its measurement is in (empty if none comes). +fn readout(h: &mut Harness) -> Vec<(String, String)> { + for _ in 0..300 { + // As each frame does before drawing it: a changed selection is measured afresh. + crate::quick_measure::poll(&mut h.app, &h.ctx); + let rows = h.app.quick_measure.lines(&h.app); + if !rows.is_empty() { + return rows; + } + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + Vec::new() +} + +fn row(label: &str, value: String) -> (String, String) { + (label.to_string(), value) +} + +#[test] +fn an_edge_shows_its_length() { + let mut h = block(); + h.app.session.selection = vec![edge(&h, Vec3::new(5.0, 0.0, 0.0))]; + let length = crate::prefs::show_mm(&h.app, 10.0, 1); + assert_eq!(readout(&mut h), vec![row("Length", length)]); +} + +#[test] +fn a_round_edge_shows_its_diameter_radius_and_circumference() { + let mut h = harness(); + h.app.run("solid.cylinder", json!({"radius": 5, "height": 10})).unwrap(); + h.frames(2); + // The top circle, by a point between two of its polyline's points (its first is on the seam). + let on_rim = { + let st = h.app.session.world_state(); + let m = st.body("Body1").unwrap().mesh(); + let rim = m.edges.iter().find(|e| e.len() > 2 && e.iter().all(|p| (p.z - 10.0).abs() < 1e-9)).expect("the top circle"); + (rim[1] + rim[2]) * 0.5 + }; + h.app.session.selection = vec![edge(&h, on_rim)]; + let rows = readout(&mut h); + assert_eq!(rows.first(), Some(&row("Ø", crate::prefs::show_mm(&h.app, 10.0, 1))), "{rows:?}"); + assert_eq!(rows.get(1), Some(&row("R", crate::prefs::show_mm(&h.app, 5.0, 1))), "{rows:?}"); + assert!(rows.iter().any(|(l, _)| l == "Circumference"), "{rows:?}"); +} + +#[test] +fn a_face_shows_its_area() { + let mut h = block(); + h.app.session.selection = vec![face_at_height(&h, 30.0)]; + assert_eq!(readout(&mut h), vec![row("Area", crate::prefs::show_mm(&h.app, 200.0, 2))]); +} + +#[test] +fn a_sketch_line_shows_its_length() { + let mut h = harness(); + h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + h.app.run("sketch.line", json!({"points": [[0, 0], [30, 40]]})).unwrap(); + h.app.session.selection = vec![Sel::SketchCurve { id: "l1".into(), sketch: None }]; + assert_eq!(readout(&mut h), vec![row("Length", crate::prefs::show_mm(&h.app, 50.0, 1))]); +} + +/// A sketch that is only shown, not open: a click picks its curves, points and regions, and they +/// measure as they do in the sketch. +#[test] +fn a_shown_sketchs_line_point_and_region_measure_too() { + let mut h = harness(); + let sketch = h.app.run("sketch.create", json!({"plane": "XY"})).unwrap()["sketch"].as_u64().unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [30, 40]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + assert_eq!(h.app.session.active_sketch, None); + let sk = h.app.session.doc.sketch(sketch).unwrap(); + let side = sk.curves.first().unwrap().id.clone(); + let corner = sk.points.first().unwrap().id.clone(); + h.app.session.selection = vec![Sel::ExternalSketchCurve { sketch, id: side }]; + let rows = readout(&mut h); + assert!(rows.iter().any(|(l, v)| l == "Length" && [30.0, 40.0].iter().any(|n| *v == crate::prefs::show_mm(&h.app, *n, 1))), "{rows:?}"); + h.app.session.selection = vec![Sel::ExternalSketchPoint { sketch, id: corner }]; + assert!(readout(&mut h).iter().any(|(l, _)| l == "At"), "a point's position"); + h.app.session.selection = vec![Sel::Profile { sketch, index: 0 }]; + assert_eq!(readout(&mut h), vec![row("Area", crate::prefs::show_mm(&h.app, 1200.0, 2))]); +} + +#[test] +fn two_points_show_their_distance() { + let mut h = block(); + h.app.session.selection = [[0.0, 0.0, 0.0], [10.0, 20.0, 30.0]].map(|p| Sel::Vertex { body: "Body1".into(), point: p.into() }).to_vec(); + let rows = readout(&mut h); + assert!(rows.contains(&row("Distance", crate::prefs::show_mm(&h.app, 1400f64.sqrt(), 1))), "{rows:?}"); +} + +#[test] +fn several_edges_show_their_count_and_total_length() { + let mut h = block(); + h.app.session.selection = [[5.0, 0.0, 0.0], [5.0, 20.0, 0.0], [5.0, 0.0, 30.0]].map(|[x, y, z]| edge(&h, Vec3::new(x, y, z))).to_vec(); + assert_eq!(readout(&mut h), vec![row("3 edges", crate::prefs::show_mm(&h.app, 30.0, 1))]); +} + +/// Off by default: nothing shows until Preferences › Interface turns it on. +#[test] +fn quick_measurement_is_off_until_turned_on() { + assert!(!crate::prefs::Prefs::default().quick_measure); + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length": 10, "width": 20, "height": 30})).unwrap(); + h.frames(2); + assert!(!h.app.preferences.quick_measure); + h.app.session.selection = vec![edge(&h, Vec3::new(5.0, 0.0, 0.0))]; + assert!(readout(&mut h).is_empty(), "off by default"); + h.frames(2); + assert!(crate::scenario::rect_of("measure:quick").is_none(), "nothing drawn"); + h.call("ui.prefs", json!({"quick_measure": true})); + assert_eq!(readout(&mut h), vec![row("Length", crate::prefs::show_mm(&h.app, 10.0, 1))]); +} + +/// Nothing shows with the preference off, with nothing selected, for something with nothing to +/// measure (a body) or while the Measure tool, which says the same, is open. +#[test] +fn the_readout_stays_away_when_it_has_nothing_to_add() { + let mut h = block(); + let e = edge(&h, Vec3::new(5.0, 0.0, 0.0)); + h.app.session.selection = vec![e.clone()]; + assert!(!readout(&mut h).is_empty()); + h.call("ui.prefs", json!({"quick_measure": false})); + h.frames(2); + assert!(h.app.quick_measure.lines(&h.app).is_empty(), "preference off"); + h.call("ui.prefs", json!({"quick_measure": true})); + h.app.session.selection.clear(); + h.frames(2); + assert!(h.app.quick_measure.lines(&h.app).is_empty(), "nothing selected"); + h.app.session.selection = vec![Sel::Body { name: "Body1".into() }]; + h.frames(2); + assert!(readout(&mut h).is_empty(), "a body"); + h.app.session.selection = vec![e]; + h.app.start("inspect.measure"); + h.frames(2); + assert!(h.app.quick_measure.lines(&h.app).is_empty(), "the Measure tool is open"); +} + +/// The readout sits in the view's bottom right corner above History; a click on it copies it. +#[test] +fn the_readout_sits_above_history_and_a_click_copies_it() { + let mut h = block(); + h.app.session.selection = vec![edge(&h, Vec3::new(5.0, 0.0, 0.0))]; + assert!(!readout(&mut h).is_empty()); + h.frames(2); + let r = crate::scenario::rect_of("measure:quick").expect("the readout is drawn"); + let history = h.app.shell.history.expect("History is shown"); + assert!(r.bottom() <= history.top(), "{r:?} above History {history:?}"); + assert!(r.right() > 1600.0 * 0.6, "{r:?} on the right"); + let at = r.center(); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frame_with(vec![button(true)]); + h.frame_with(vec![button(false)]); + let copied = h.output.commands.iter().find_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }); + assert_eq!(copied, Some(format!("Length {}", crate::prefs::show_mm(&h.app, 10.0, 1)))); +} + +/// The measurement is computed off the window thread: right after the selection changes it is +/// still coming, and it lands a frame or so later. +#[test] +fn the_measurement_computes_off_the_window_thread() { + let mut h = block(); + h.app.session.selection = vec![edge(&h, Vec3::new(5.0, 0.0, 0.0))]; + crate::quick_measure::poll(&mut h.app, &h.ctx); + assert!(h.app.quick_measure.lines(&h.app).is_empty(), "computing"); + assert!(!readout(&mut h).is_empty(), "then in"); +} diff --git a/crates/ui-egui/src/render_ui/mod.rs b/crates/ui-egui/src/render_ui/mod.rs index 3634f9243..f7f5766e7 100644 --- a/crates/ui-egui/src/render_ui/mod.rs +++ b/crates/ui-egui/src/render_ui/mod.rs @@ -201,7 +201,7 @@ pub(crate) fn overlays(app: &mut SolveApp, ui: &mut egui::Ui) { if !focused(app) { shots_pill(app, ui, free); } - crate::viewport::transient_messages(app, ui, viewport); + crate::viewport::transient_messages(app, ui, viewport, None); } /// Shared kit chip at the Browser's remembered side, below the stage bar. diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 5104edf1b..67138952c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -4939,7 +4939,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::viewport_status::show(app, ui.ctx(), rect); crate::viewport_status_fixture::show(app, ui.ctx(), rect); // The notices and the agent chip first, so the 3D mouse picture can keep clear of them. - let toasts = transient_messages(app, ui, rect); + // The selection's measurement in the corner, before the notices so they keep clear of it. + let readout = quick_measure_readout(app, ui, rect); + let toasts = transient_messages(app, ui, rect, readout); if app.preferences.space_mouse_in_view && app.space_mouse.calibrating.is_none() && let Some(device) = &app.space_mouse.device @@ -5042,9 +5044,21 @@ fn agent_chip(app: &mut SolveApp, ui: &egui::Ui, view: Rect, taken: &[Rect]) -> /// How long a status message stays in the view (milliseconds). const STATUS_TOAST_MS: f64 = 6000.0; +/// The selection's measurement in the view's bottom right corner (`quick_measure`), clear of the +/// panels and cards over the view and its navigation bar. +fn quick_measure_readout(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Option { + crate::quick_measure::poll(app, ui.ctx()); + let mut taken = crate::shell::covered_rects(app); + if let Some(layout) = &app.viewport.layout { + taken.extend([layout.navigation, layout.axis_view]); + } + let view = crate::shell::content_rect(app, viewport); + crate::quick_measure::show(app, ui, view, &taken) +} + /// A single visual pattern for ongoing work, the existing six-second status, the 3D mouse /// calibration offer and the stand-up note, stacked from the bottom of the free view. Returns the toasts' rects. -pub(crate) fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec { +pub(crate) fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect, readout: Option) -> Vec { let placement_hint = app.tool.as_ref().filter(|tool| matches!(tool.cmd, "canvas.insert" | "canvas.decal")).map(|tool| crate::tools::hint(tool.cmd)); // Nothing to show or time: an idle window skips the layout. The offer is checked too, as its clock @@ -5064,6 +5078,7 @@ pub(crate) fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Re if let Some(layout) = &app.viewport.layout { obstacles.extend([layout.navigation, layout.axis_view]); } + obstacles.extend(readout); let view = crate::shell::content_rect(app, viewport); let mut free = crate::viewport_layout::free_rect(view, &obstacles).shrink(t.space_8); if ToastPlace::current(ui.ctx()) == ToastPlace::Corner { diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index 0ae750e97..dc6909c9b 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -15,6 +15,12 @@ it. | Construct | offset plane (at a distance or through a point), plane at angle, plane along path | | Inspect | measure, section analysis, interference, compare bodies, curvature comb and map, zebra, draft, minimum radius, isocurves, centre of mass | +**Quick measurement** (off by default; turn it on under Preferences › Interface): with edges, +faces, sketch curves or points selected, the view's bottom right corner, above History, shows +what they measure: an edge's length (Ø and R for a round one), a face's area, a point's position, +two items' distance and angle, several edges' or faces' total. A click copies it. The Measure tool +(I) does more. + Extrude, Revolve, Sweep, Loft, Coil and the Box, Cylinder, Sphere and Torus choose their operation from what their material does, until you pick one: **Join** when it makes one body with a body it touches (a block against a wall, a ring round a hole, a boss meeting only part of a diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6f4a083f0..7e566c444 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -441,6 +441,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `perspective_fov` (Perspective view's vertical field of view in radians, 0.2618…1.5708 (15°…90°), default 0.6; when it changes, the camera's distance scales so the view keeps its size) - `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it) - `print_face_highlight` (0…1, default 0.2: how strongly a print face is tinted and outlined in the view, #8429; 0 draws no highlight) +- `quick_measure` (default false: the selection's length, area or distance in the view's bottom right corner, the rect `measure:quick`; #7000) - `ribbon_reveal` (default false: hovering a result in Search commands switches the ribbon to the command's tab and marks its button, or opens the panel drop-down that holds it on its row, handle `ribbon:reveal`; leaving the results goes back to the tab before; a command started from the search blinks there, and a running command from a drop-down marks its panel label, `ribbon:running_section::
`, #7287) - `right_drag_orbits` (default true; false: a right drag the mouse preset would orbit leaves the camera alone, #6492) - `select_other_hidden` (default true: Select Other includes hidden geometry near the pointer; false restores the original visible-only list under the pointer)