diff --git a/assets/locales/en.json b/assets/locales/en.json index 708ac23f0..aff0a26e6 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1324,6 +1324,8 @@ "ui.loft": "Loft", "ui.look_at": "Look At", "ui.look_at_anim_desc": "Axis view, Look At, Home and Fit", + "ui.manipulator_free_alt": "Manipulator free drag also on Alt/Option", + "ui.manipulator_free_alt_tip": "On: Alt/Option or Ctrl/Cmd on extrude / gizmo arrows disables value snapping. Off: Ctrl/Cmd only.", "ui.manufacture": "Manufacture", "ui.material_review.axes": "Material-local axes; no body orientation is assigned.", "ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.", @@ -1464,6 +1466,9 @@ "ui.selectTangentChain": "Select Tangent Chain", "ui.select_other_hint": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there.", "ui.selection": "Selection", + "ui.selection_modifiers": "Selection modifiers", + "ui.selection_shift_add_only": "Shift+click adds without removing", + "ui.selection_shift_add_only_tip": "On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle.", "ui.send": "Send", "ui.send_to_slicer": "Send to slicer", "ui.sent_to_slicer": "Sent to {slicer}", @@ -1488,6 +1493,7 @@ "ui.sketch": "Sketch", "ui.sketch_dimension": "Sketch Dimension", "ui.sketch_grid": "Sketch Grid", + "ui.sketch_modifiers": "Sketch modifiers", "ui.sketch_scale": "Sketch Scale", "ui.sketch_status": "Sketch Status", "ui.sketches": "Sketches", @@ -1514,6 +1520,8 @@ "ui.supersampling_adaptive": "Only when the view is still", "ui.supersampling_off": "Off (1×)", "ui.suppress": "Suppress", + "ui.suppress_auto_snap": "Suppress auto-snap while drawing / dragging", + "ui.suppress_auto_snap_note": "Default: Ctrl/Cmd or Alt/Option each suppress sketch snapping. Choose a single key to narrow it.", "ui.sweep": "Sweep", "ui.sweep_follow_direction": "Follow Direction", "ui.sweep_keep_as_drawn": "Keep as Drawn", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index eeb2011c9..205309ba6 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1324,6 +1324,8 @@ "ui.loft": "ロフト", "ui.look_at": "正面視", "ui.look_at_anim_desc": "軸ビュー、正面視、ホーム、全体表示", + "ui.manipulator_free_alt": "マニピュレータのフリードラッグを Alt/Option でも有効", + "ui.manipulator_free_alt_tip": "オン: 押し出し/ギズモ矢印で Alt/Option または Ctrl/Cmd が値スナップを無効にします。オフ: Ctrl/Cmd のみ。", "ui.manufacture": "製造", "ui.material_review.axes": "材料ローカル軸。ボディの方向は割り当てません。", "ui.material_review.claims": "出典とライセンスの申告は未確認です。欠落値は不明のままです。", @@ -1464,6 +1466,9 @@ "ui.selectTangentChain": "接線チェーンを選択", "ui.select_other_hint": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。", "ui.selection": "選択", + "ui.selection_modifiers": "選択修飾キー", + "ui.selection_shift_add_only": "Shift+クリックで追加のみ(解除なし)", + "ui.selection_shift_add_only_tip": "オン: Shift は追加、Ctrl/Cmd はトグル。オフ(既定): Shift と Ctrl/Cmd の両方がトグル。", "ui.send": "送信", "ui.send_to_slicer": "スライサーに送る", "ui.sent_to_slicer": "{slicer} に送信しました", @@ -1488,6 +1493,7 @@ "ui.sketch": "スケッチ", "ui.sketch_dimension": "スケッチ寸法", "ui.sketch_grid": "スケッチ グリッド", + "ui.sketch_modifiers": "スケッチ修飾キー", "ui.sketch_scale": "スケッチ尺度", "ui.sketch_status": "スケッチの状態", "ui.sketches": "スケッチ", @@ -1514,6 +1520,8 @@ "ui.supersampling_adaptive": "ビューが静止しているときのみ", "ui.supersampling_off": "オフ (1×)", "ui.suppress": "抑制", + "ui.suppress_auto_snap": "作図・ドラッグ中の自動スナップを抑制", + "ui.suppress_auto_snap_note": "既定: Ctrl/Cmd または Alt/Option のどれでもスケッチスナップを抑制します。単一キーに絞ることもできます。", "ui.sweep": "スイープ", "ui.sweep_follow_direction": "方向に従う", "ui.sweep_keep_as_drawn": "描いた向きを保持", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 96b2405e0..c5181f0ec 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1324,6 +1324,8 @@ "ui.loft": "放样", "ui.look_at": "朝向", "ui.look_at_anim_desc": "轴视图、注视、主视图与适合窗口", + "ui.manipulator_free_alt": "操纵器自由拖动也适用于 Alt/Option", + "ui.manipulator_free_alt_tip": "开:在拉伸/小控件箭头上按 Alt/Option 或 Ctrl/Cmd 可关闭数值捕捉。关:仅 Ctrl/Cmd。", "ui.manufacture": "制造", "ui.material_review.axes": "材料局部坐标轴;不指定实体方向。", "ui.material_review.claims": "来源和许可证声明未经核实。缺失值保持未知。", @@ -1464,6 +1466,9 @@ "ui.selectTangentChain": "选择相切链", "ui.select_other_hint": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。", "ui.selection": "选择", + "ui.selection_modifiers": "选择修饰键", + "ui.selection_shift_add_only": "Shift+点击仅添加、不取消选择", + "ui.selection_shift_add_only_tip": "开:Shift 添加,Ctrl/Cmd 切换。关(默认):Shift 与 Ctrl/Cmd 均可切换。", "ui.send": "发送", "ui.send_to_slicer": "发送到切片软件", "ui.sent_to_slicer": "已发送到 {slicer}", @@ -1488,6 +1493,7 @@ "ui.sketch": "草图", "ui.sketch_dimension": "草图尺寸", "ui.sketch_grid": "草图网格", + "ui.sketch_modifiers": "草图修饰键", "ui.sketch_scale": "草图比例", "ui.sketch_status": "草图状态", "ui.sketches": "草图", @@ -1514,6 +1520,8 @@ "ui.supersampling_adaptive": "仅在视图静止时", "ui.supersampling_off": "关 (1×)", "ui.suppress": "抑制", + "ui.suppress_auto_snap": "绘制/拖动时抑制自动捕捉", + "ui.suppress_auto_snap_note": "默认:Ctrl/Cmd 或 Alt/Option 均可抑制草图捕捉。也可改成只认其中一个键。", "ui.sweep": "扫掠", "ui.sweep_follow_direction": "跟随方向", "ui.sweep_keep_as_drawn": "保持绘制方向", diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index befd54736..4ec11a29b 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -314,6 +314,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces hl_slot: empty(), pv_key: 0, pv_slot: empty(), + pv_hide: false, view_proj: cam.view_proj(f64::from(width) / f64::from(height.max(1)), scene.radius.max(1.0)).to_f32(), back: cam.back().to_f32(), size_px: [width as f32, height as f32], diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 2225c0900..c1b162c74 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -224,6 +224,8 @@ pub struct Frame { /// The live preview scene and its key. pub pv_key: u64, pub pv_slot: SceneSlot, + /// Preview reselect: skip drawing the preview while Primary rolls it back. + pub pv_hide: bool, /// Column-major view-projection. pub view_proj: [[f32; 4]; 4], /// Direction toward the eye (for lighting). @@ -1419,8 +1421,13 @@ impl Renderer { } } }; - let (m, sk, h, pv) = - if cb.product { (&res.product, &res.empty, &res.empty, &res.empty) } else { (&res.model, &res.sketch, &res.highlight, &res.preview) }; + let (m, sk, h, pv) = if cb.product { + (&res.product, &res.empty, &res.empty, &res.empty) + } else if cb.pv_hide { + (&res.model, &res.sketch, &res.highlight, &res.empty) + } else { + (&res.model, &res.sketch, &res.highlight, &res.preview) + }; lines(pass, &res.overlay, &m.under); lines(pass, &res.overlay, &sk.under); pass.set_bind_group(1, &res.access_bind, &[]); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 28b05b856..c4f880487 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -606,8 +606,9 @@ fn drag_arrow( && let Some(p) = r.interact_pointer_pos() && let Some(v) = along(proj, p, base, n) { + crate::tool_modifiers::set_manipulator_dragging(true); let v = v - ui.data(|d| d.get_temp::(grab)).unwrap_or(0.0); - let free = ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command); + let free = crate::tool_modifiers::manipulator_free(); let step = snap_step(half_height); let mut v = if free { v } else { (v / step).round() * step }; if !signed { @@ -780,7 +781,8 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain && let Some(p) = r.interact_pointer_pos() && let Some(v) = along(proj, p, at(*u), e.n) { - let free = ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command); + crate::tool_modifiers::set_manipulator_dragging(true); + let free = crate::tool_modifiers::manipulator_free(); let step = snap_step(half_height); let v = if free { v } else { (v / step).round() * step }; // Zero only at an end, where the round closes to a point. @@ -974,9 +976,10 @@ fn taper_handle( && let Some(p) = r.interact_pointer_pos() && let Some(s) = along(proj, p, foot + span, e) { + crate::tool_modifiers::set_manipulator_dragging(true); let mut deg = s.atan2(l).to_degrees(); let (lo, hi) = limits; - if ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command) { + if crate::tool_modifiers::manipulator_free() { deg = deg.clamp(lo, hi); } else { // Whole degrees, rounded towards zero at a limit so they stay inside it. @@ -1255,7 +1258,7 @@ fn rotation_handle( .min_by(|a, b| (a - boundary).abs().total_cmp(&(b - boundary).abs())) .unwrap_or_else(|| raw.clamp(bounds.0, bounds.1)); let mut angle = (boundary_angle.clamp(bounds.0, bounds.1) * scale + offset).to_degrees(); - if !ui.input(|input| input.modifiers.alt || input.modifiers.ctrl || input.modifiers.command) { + if !crate::tool_modifiers::manipulator_free() { angle = (angle / 5.0).round() * 5.0; } if angle.abs() < 0.05 { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1f12a250b..f06e5ef3b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -15,8 +15,58 @@ use solidcraft_engine::geom::{Aabb3, Vec3}; use crate::SolveApp; use crate::selection::{self, AXES, Accept, BODIES, CURVES, EDGES, FACES, PLANAR_FACES, PLANES, PROFILES, SelInput}; use crate::theme::Tokens; +use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; use crate::viewport::Hit; +const SELECT_ONLY: &[Scope] = &[Scope::Selection, Scope::FeaturePreview]; +const SELECT_MANIP: &[Scope] = &[Scope::Selection, Scope::Manipulator, Scope::FeaturePreview]; + +/// Per-tool modifier descriptors owned by this host file (SOLID / construct / inspect dialogs). +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.create", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.extrude", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.revolve", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.fillet", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.chamfer", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.shell", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.draft", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.mirror", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.rib", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.web", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.emboss", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.replace_face", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.boundary_fill", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.align", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.remove", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + // Pattern parameters are dialog-only - no viewport modifier chords. + ToolModifiers { tool: "solid.pattern.path", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.pattern.rectangular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.pattern.circular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.pipe", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.bounding_solid", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "construct.plane.offset", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "construct.plane.along_path", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "construct.plane.at_angle", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.split_body", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.scale", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.offset_face", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.thread", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "material.assign", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.section", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.measure", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.loft", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.sweep", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + // Move: no Alt-copy / inventable chords; inherits Selection + Manipulator only. + ToolModifiers { tool: "solid.move", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.hole", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.box", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.cylinder", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.sphere", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.torus", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.coil", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.combine", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, +]; + pub(crate) const OPS: [&str; 4] = ["new", "join", "cut", "intersect"]; pub(crate) const OP_LABELS: [&str; 4] = ["New Body", "Join", "Cut", "Intersect"]; const DIRS: [&str; 4] = ["positive", "negative", "symmetric", "positive"]; diff --git a/crates/ui-egui/src/drag_snap.rs b/crates/ui-egui/src/drag_snap.rs index c3708c275..5646239a7 100644 --- a/crates/ui-egui/src/drag_snap.rs +++ b/crates/ui-egui/src/drag_snap.rs @@ -1,8 +1,8 @@ -//! Snapping while a sketch point or a line is dragged: the dragged point snaps to -//! other points (ends, centres, the origin, projected points), to the middle of a line and onto -//! curves, and lines up horizontally or vertically with other points (a dashed guide). Letting -//! go on a point, a midpoint or a curve adds the matching constraint; lining up adds none. Ctrl -//! or Alt held: no snapping (here and while drawing). +//! Snapping while a sketch point or a line is dragged: the dragged point snaps to other points +//! (ends, centres, the origin, projected points), to the middle of a line and onto curves, and +//! lines up horizontally or vertically with other points (a dashed guide). Letting go on a point, +//! a midpoint or a curve adds the matching constraint; lining up adds none. The suppress-snap +//! chord is configurable (default Ctrl/Cmd or Alt/Option; see `prefs::suppress_sketch_snap`). use std::cell::{Cell, RefCell}; @@ -60,7 +60,7 @@ thread_local! { static SUPPRESSED: Cell = const { Cell::new(false) }; } -/// Ctrl or Alt held this frame (no snapping). +/// Whether sketch snap is suppressed this frame (set from the viewport via `prefs::suppress_sketch_snap_held`). pub fn set_suppressed(on: bool) { SUPPRESSED.with(|s| s.set(on)); } diff --git a/crates/ui-egui/src/gizmo.rs b/crates/ui-egui/src/gizmo.rs index f3d2a9162..ebc4d23e1 100644 --- a/crates/ui-egui/src/gizmo.rs +++ b/crates/ui-egui/src/gizmo.rs @@ -277,7 +277,11 @@ pub fn show(ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, id: egui::I active?; ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); let r = ui.interact(Rect::from_center_size(p, vec2(24.0, 24.0)), id.with("hit"), Sense::drag()); - let free = ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command); + // Free drag is driven by the per-frame thread-local set from prefs::manipulator_free_held. + let free = crate::tool_modifiers::manipulator_free(); + if state.is_some() || r.dragged() || r.drag_started() { + crate::tool_modifiers::set_manipulator_dragging(true); + } let view = proj.ray(sh.ball).1; let plane_normal = |h: Handle| match h { Handle::Plane(i) | Handle::Ring(i) => DIRS[i], diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 0dd840176..4179ebedf 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -270,6 +270,7 @@ fn offscreen( hl_slot: Arc::new(Mutex::new(highlight)), pv_key: 0, pv_slot: none(), + pv_hide: false, view_proj, back, size_px: [size as f32; 2], diff --git a/crates/ui-egui/src/joint_browser_tests.rs b/crates/ui-egui/src/joint_browser_tests.rs index 603c8daef..9d055bec4 100644 --- a/crates/ui-egui/src/joint_browser_tests.rs +++ b/crates/ui-egui/src/joint_browser_tests.rs @@ -92,7 +92,7 @@ fn a_hidden_joint_still_drives_and_shows_while_picked() { assert_eq!(h.app.tree.picked_joints, [hinge]); assert!(drawn(&h).contains(&(hinge, true)), "{:?}", drawn(&h)); assert!(!h.app.session.joint_visible(hinge), "picking doesn't show it"); - crate::viewport::select(&mut h.app, None, false); + crate::viewport::select(&mut h.app, None, false, false); assert!(h.app.tree.picked_joints.is_empty()); assert!(!drawn(&h).iter().any(|(j, _)| *j == hinge)); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d165e9129..c68afd2d6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -187,6 +187,7 @@ mod thin_extrude_tests; pub mod timeline; pub mod timeline_left; pub mod titlebar; +pub mod tool_modifiers; pub mod toolbar; pub mod toolbar_custom; pub mod tools; diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index a8083ae15..657d5d423 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -282,8 +282,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e // with no window or menu above it. let inside = resp.contains_pointer() && ui.rect_contains_pointer(rect) && hover.is_some_and(|p| !axes.contains(p)); app.viewport.mouse = hover.filter(|_| inside); - // Ctrl or Alt held: drawing and dragging don't snap. - crate::drag_snap::set_suppressed(mods.ctrl || mods.alt || mods.command); + // Sketch snap suppression is set once in `viewport::show` from preferences. middle_double_click(app, ui, inside); // The 3D mouse's motion this frame, with what this page's camera may do. device(app, rect, caps); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index f7fc8f00a..47963d692 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -27,6 +27,7 @@ pub fn stored(get: impl Fn(&str) -> Option) -> Option { use crate::SolveApp; use crate::theme::Tokens; +use crate::tool_modifiers::ModifierCombo; use crate::viewport::NavMode; pub const UNITS: [&str; 5] = ["mm", "cm", "m", "in", "ft"]; @@ -391,6 +392,16 @@ pub struct Prefs { pub agent_chat_window: Option<[f32; 4]>, /// Changes the agent may make for one message. pub agent_chat_turn_limit: u32, + + // ---- Sketch / selection modifier bindings (classic defaults; alternate mapping is opt-in) ---- + /// Modifier that suppresses sketch auto-snap while drawing or dragging a sketch point. + /// Default: Alt/Option. Set to Ctrl/Cmd for the alternate mapping. + pub suppress_sketch_snap: ModifierCombo, + /// Whether Alt/Option also frees gizmo / canvas manipulator arrows (Primary always does). + pub manipulator_free_alt: bool, + /// When true: Shift+click adds without removing; Primary toggles. + /// When false (default): Shift and Primary both toggle. + pub selection_shift_add_only: bool, } /// What a middle-button double-click in the view does. @@ -487,6 +498,9 @@ impl Default for Prefs { agent_chat_popped: false, agent_chat_window: None, agent_chat_turn_limit: crate::agent_chat::gate::DEFAULT_TURN_LIMIT, + suppress_sketch_snap: ModifierCombo::CTRL_ALT, + manipulator_free_alt: true, + selection_shift_add_only: false, } } } @@ -776,8 +790,15 @@ fn defaults(app: &mut SolveApp, page: usize) { save_graphics(app); } } - 5 => app.session.auto_project = true, - _ => app.ui.pick_bodies = false, + 5 => { + app.session.auto_project = true; + p.suppress_sketch_snap = d.suppress_sketch_snap; + p.manipulator_free_alt = d.manipulator_free_alt; + } + _ => { + app.ui.pick_bodies = false; + p.selection_shift_add_only = d.selection_shift_add_only; + } } } @@ -861,6 +882,25 @@ pub fn pan_sign_x(app: &SolveApp) -> f32 { if app.preferences.pan_reverse_x { -1.0 } else { 1.0 } } +/// Whether the configured suppress-snap chord is held. +pub fn suppress_sketch_snap_held(app: &SolveApp, m: Modifiers) -> bool { + let c = app.preferences.suppress_sketch_snap; + let held = crate::tool_modifiers::Held::from_modifiers(m); + // Classic default (`CTRL_ALT`): Ctrl/Cmd **or** Alt/Option each suppress snap. + // A single-key preference keeps the usual AtLeast match for that key only. + if c == ModifierCombo::CTRL_ALT { + return held.primary || held.alt; + } + c.held(m) +} + +/// Primary always frees manipulator arrows; Alt/Option also frees when `manipulator_free_alt` is on. +pub fn manipulator_free_held(app: &SolveApp, m: Modifiers) -> bool { + use crate::tool_modifiers::Held; + let held = Held::from_modifiers(m); + held.primary || (app.preferences.manipulator_free_alt && held.alt) +} + /// +1, or −1 when the wheel zooms the other way. pub fn zoom_sign(app: &SolveApp) -> f64 { if app.preferences.zoom_reverse { -1.0 } else { 1.0 } @@ -1489,11 +1529,50 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { let _ = app.run("sketch.auto_project", json!({ "value": auto })); } ui.end_row(); + + ui.label(""); + ui.end_row(); + ui.label(RichText::new(crate::i18n::tr_label("Sketch modifiers")).strong()); + ui.label(""); + ui.end_row(); + + ui.label(crate::i18n::tr_label("Suppress auto-snap while drawing / dragging")); + snap_suppress_picker(ui, "pref_suppress_sketch_snap", &mut app.preferences.suppress_sketch_snap); + ui.end_row(); + note(ui, crate::i18n::tr_label("ui.suppress_auto_snap_note")); + + ui.label(crate::i18n::tr_label("Manipulator free drag also on Alt/Option")); + ui.checkbox(&mut app.preferences.manipulator_free_alt, "").on_hover_text(crate::i18n::tr_label( + "On: Alt/Option or Ctrl/Cmd on extrude / gizmo arrows disables value snapping. Off: Ctrl/Cmd only.", + )); + ui.end_row(); } _ => { ui.label(crate::i18n::tr_label("Click selects whole bodies")); ui.checkbox(&mut app.ui.pick_bodies, ""); ui.end_row(); + + ui.label(""); + ui.end_row(); + ui.label(RichText::new(crate::i18n::tr_label("Selection modifiers")).strong()); + ui.label(""); + ui.end_row(); + + ui.label(crate::i18n::tr_label("Shift+click adds without removing")); + ui.checkbox(&mut app.preferences.selection_shift_add_only, "").on_hover_text(crate::i18n::tr_label( + "On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle.", + )); + ui.end_row(); + } + }); +} + +/// Sketch snap-suppress picker: classic Ctrl/Cmd-or-Alt first, then single keys. +fn snap_suppress_picker(ui: &mut egui::Ui, salt: &str, combo: &mut ModifierCombo) { + let label = combo.label(); + egui::ComboBox::from_id_salt(salt).selected_text(label).show_ui(ui, |ui| { + for c in ModifierCombo::SNAP_SUPPRESS_CHOICES { + ui.selectable_value(combo, c, c.label()); } }); } @@ -2102,6 +2181,47 @@ mod tests { assert!(h.app.preferences.radial_context_menu, "Cancel restores the last Apply"); } + #[test] + fn tool_modifier_prefs_default_classic_and_persist() { + let d = Prefs::default(); + assert_eq!(d.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(d.manipulator_free_alt); + assert!(!d.selection_shift_add_only); + let old: Prefs = serde_json::from_value(json!({"nav": "solidworks"})).unwrap(); + assert_eq!(old.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(!old.selection_shift_add_only); + // Classic default: Ctrl/Cmd or Alt each suppress (`command` is primary on all hosts). + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let ctrl = Modifiers { ctrl: true, command: true, ..Default::default() }; + let alt = Modifiers { alt: true, ..Default::default() }; + let shift = Modifiers { shift: true, ..Default::default() }; + assert!(suppress_sketch_snap_held(&app, ctrl)); + assert!(suppress_sketch_snap_held(&app, alt)); + assert!(!suppress_sketch_snap_held(&app, shift)); + control( + &mut app, + &json!({"open": "Sketch", "suppress_sketch_snap": {"shift": false, "ctrl": true, "alt": false}, "manipulator_free_alt": false}), + ) + .unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + control(&mut app, &json!({"open": "Selection", "selection_shift_add_only": true})).unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + assert!(!app.preferences.manipulator_free_alt); + assert!(app.preferences.selection_shift_add_only); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + assert!(!other.preferences.manipulator_free_alt); + assert!(other.preferences.selection_shift_add_only); + control(&mut app, &json!({"open": "Sketch", "button": "defaults"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(app.preferences.manipulator_free_alt); + assert!(app.preferences.selection_shift_add_only, "Selection page setting stays until that page resets"); + control(&mut app, &json!({"button": "cancel"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + } + #[test] fn wheel_smoothing_persists_and_follows_dialog_buttons() { assert!(serde_json::from_value::(json!({})).unwrap().smooth_wheel_zoom); diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 355d760e8..633d6e7db 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -99,9 +99,21 @@ pub struct PreviewState { /// The radius splines the previewed fillet tapered its edges with. pub tapered: Vec<(Vec3, solidcraft_engine::kernel::Taper)>, straight: crate::extrude_preview::StraightPreview, + /// PreviewReselect: Primary held - hide the preview and restore replaced bodies for picks. + pub rolled_back: bool, } impl PreviewState { + /// Bodies the model scene should hide for the preview (empty while rolled back). + pub fn effective_replaced(&self) -> &[String] { + if self.rolled_back { &[] } else { &self.replaced } + } + + /// Whether the preview scene should be drawn. + pub fn draw_active(&self) -> bool { + self.active && !self.rolled_back + } + fn clear(&mut self) { self.straight.clear(); self.running = None; @@ -114,6 +126,7 @@ impl PreviewState { self.tapered.clear(); self.sketches.clear(); self.busy = false; + self.rolled_back = false; if self.active || !self.replaced.is_empty() { self.active = false; self.bounds = Aabb3::EMPTY; @@ -761,6 +774,9 @@ pub fn point_triangle_dist(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 { /// The same computed sketch preview is drawn over both native GPU and CPU viewports. pub fn paint_sketches(app: &SolveApp, painter: &egui::Painter, proj: &crate::viewport::Proj) { + if app.preview.rolled_back { + return; + } if !app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::SketchModify(_)) && d.previews()) { return; } diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index bdcbe43ba..e59adfe6f 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -528,6 +528,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { hl_slot: slot.clone(), pv_key: 0, pv_slot: slot, + pv_hide: false, view_proj: camera.view_proj(f64::from(rect.width() / rect.height().max(1.0)), radius).to_f32(), back: camera.back().to_f32(), size_px: [rect.width() * ppp, rect.height() * ppp], diff --git a/crates/ui-egui/src/select_other.rs b/crates/ui-egui/src/select_other.rs index bbe3f07e3..210ec8591 100644 --- a/crates/ui-egui/src/select_other.rs +++ b/crates/ui-egui/src/select_other.rs @@ -318,23 +318,26 @@ pub fn is_open(app: &SolveApp) -> bool { app.viewport.select_other.popup.is_some() } -/// Pick row `i` of the open list (`add`: Shift/Ctrl, add to the selection) and close it. -pub fn choose(app: &mut SolveApp, i: usize, add: bool) -> Result { +/// Pick row `i` of the open list and close it. +/// +/// `add` / `toggle` match viewport selection (Shift pure-add, Primary toggle when +/// `selection_shift_add_only` is on). +pub fn choose(app: &mut SolveApp, i: usize, add: bool, toggle: bool) -> Result { let Some(p) = app.viewport.select_other.popup.as_ref() else { return Err("Select Other is not open".into()) }; let at = p.at; let row = p.rows.get(i).cloned().ok_or_else(|| format!("no row {i} (the list has {})", p.rows.len()))?; close(app); - apply(app, &row, add); + apply(app, &row, add, toggle); remember(app, at, if add { None } else { Some(row.sel.clone()) }); Ok(row) } /// Select a row's entity: into the dialog's active input, or as a click does. -fn apply(app: &mut SolveApp, row: &Row, add: bool) { +fn apply(app: &mut SolveApp, row: &Row, add: bool, toggle: bool) { if app.dialog.as_ref().is_some_and(|d| d.wants_picks()) { crate::viewport::dialog_pick(app, &row.hit, row.sel.clone()); } else { - crate::viewport::select(app, Some(row.sel.clone()), add); + crate::viewport::select(app, Some(row.sel.clone()), add, toggle); } } @@ -376,7 +379,9 @@ pub fn control(app: &mut SolveApp, p: &Value) -> Result { return Ok(describe(app)); } if let Some(i) = p.get("pick").and_then(Value::as_u64) { - let row = choose(app, i as usize, p.get("add").and_then(Value::as_bool).unwrap_or(false))?; + // Control channel: `add` enables both add and toggle (legacy API). + let add = p.get("add").and_then(Value::as_bool).unwrap_or(false); + let row = choose(app, i as usize, add, add)?; return Ok(json!({ "picked": row.label, "sel": row.sel, "selection": app.session.selection })); } Ok(describe(app)) @@ -487,7 +492,7 @@ pub fn cycle_click(app: &mut SolveApp, proj: &Proj, at: Pos2) -> bool { } let next = rows.iter().position(|r| crate::selection::same_item(&r.sel, &c.chosen)).map_or(0, |k| (k + 1) % rows.len()); let Some(row) = rows.get(next).cloned() else { return false }; - apply(app, &row, false); + apply(app, &row, false, false); app.set_status(format!("{} ({} of {})", row.label, next + 1, rows.len()), false); remember(app, c.at, Some(row.sel)); true @@ -552,7 +557,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } let (pressed, pointer, mods) = ctx.input(|i| (i.pointer.any_pressed(), i.pointer.interact_pos(), i.modifiers)); if let Some(i) = picked { - let _ = choose(app, i, mods.shift || mods.ctrl || mods.command); + let held = crate::tool_modifiers::Held::from_modifiers(mods); + let (add, toggle) = crate::tool_modifiers::selection_click(held, app.preferences.selection_shift_add_only); + let _ = choose(app, i, add, toggle); } else if pressed && !pointer.is_some_and(|q| resp.response.rect.contains(q)) { // A press elsewhere only closes the list. close(app); diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index b06713106..be9644d23 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -33,8 +33,28 @@ use solidcraft_engine::sketch::PatternAlignment; use crate::SolveApp; use crate::dialogs::{CHAMFER_TYPES, Dialog, Kind, check, field, icon_choice, pattern_toggle, row_label}; use crate::selection::{AXES, CURVES, SKETCH_POINTS, SelInput}; +use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; use crate::viewport::{Hit, Proj}; +const SELECT_MANIP: &[Scope] = &[Scope::Selection, Scope::Manipulator, Scope::FeaturePreview]; +const SELECT_ONLY: &[Scope] = &[Scope::Selection, Scope::FeaturePreview]; + +/// Per-tool modifier descriptors owned by this host file. +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.scale", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.offset", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.mirror", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + // Sketch Move: dialog/manipulator inherit only - no invented Alt-copy. + ToolModifiers { tool: "sketch.move", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + // Pattern spacing/count live in the dialog - no viewport modifier chords. + ToolModifiers { tool: "sketch.pattern.rectangular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.pattern.circular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.fillet", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.chamfer.equal_distance", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.chamfer.two_distance", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.chamfer.distance_angle", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, +]; + /// The three chamfer types, drawn as the cut each one makes, in `CHAMFER_TYPES` order. const CHAMFER_TYPE_ICONS: [&str; 3] = ["sketch_chamfer_equal", "sketch_chamfer_two", "sketch_chamfer_angle"]; diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index ce0be3ee2..f4edda24f 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -12,9 +12,61 @@ use serde_json::{Value, json}; use solidcraft_engine::geom::{Vec2, Vec3}; use crate::SolveApp; +use crate::tool_modifiers::{Audit, Binding, Match, ModAction, ModifierCombo, Scope, ToolModifiers, Trigger}; use crate::tools::{Kind, Tool}; use crate::viewport::{Hit, Proj, pick, sketch_point_at}; +const DRAW_SCOPES: &[Scope] = &[Scope::SketchDraw, Scope::SketchDrag]; +const NONE: &[Scope] = &[]; + +const ISOCURVE_ALT: &[Binding] = &[Binding { + action: ModAction::IsoCurveAlternate, + defaults: &[ModifierCombo::SHIFT], + matching: Match::AtLeast, + trigger: Trigger::Press, + rebindable: true, +}]; + +/// Per-tool modifier descriptors owned by this host file. +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.project", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.intersect", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.include_3d", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.fit_curves_to_section", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.isoparametric_curve", scopes: NONE, bindings: ISOCURVE_ALT, audit: Audit::Implemented }, + ToolModifiers { tool: "inspect.curvature_comb", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.minimum_radius", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.center_of_mass", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.isocurve", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "canvas.insert", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "canvas.decal", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.trim", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.extend", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.break", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.line.midpoint", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.arc.tangent", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.ellipse", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.conic", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.center_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.arc_three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.arc_center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.spline.fit_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.spline.control_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.spline.control_point_5", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.text", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.edit_text", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.blend_curve", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.constraint.curvature", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.circle.two_tangent", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.circle.three_tangent", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constrainer", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.polygon", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.centerline", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.project_to_surface", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.intersection_curve", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.spun_profile", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, +]; + thread_local! { /// Shift held this frame. static SHIFT: Cell = const { Cell::new(false) }; @@ -280,6 +332,9 @@ pub fn refine_snap( return Some((plane.to_local(point), Some(format!("vertex:{},{},{}", point.x, point.y, point.z)))); } } + let mid_only = crate::tool_modifiers::target_midpoint(); + // Shift midpoint mode: widen the midpoint capture a little and skip other inferences. + let mid_tol = if mid_only { tol * 1.5 } else { tol }; let mut best: Option<(f64, &'static str, Vec2)> = None; let mut mid_of: Option = None; for (i, c) in sk.curves.iter().enumerate() { @@ -288,7 +343,7 @@ pub fn refine_snap( { let m = (a + b) * 0.5; let d = m.dist(lp); - if d < tol && best.is_none_or(|x| d < x.0) { + if d < mid_tol && best.is_none_or(|x| d < x.0) { best = Some((d, "Mid", m)); mid_of = Some(c.id.clone()); } @@ -306,7 +361,8 @@ pub fn refine_snap( }; // Line tool: the tangent point of a circle or arc (before plain "on the curve"). let line_tool = app.tool.as_ref().is_none_or(|t| t.cmd == "sketch.line"); - if best.is_none() + if !mid_only + && best.is_none() && line_tool && let Some(prev) = prev && let Some(i) = crate::inference::tangent(sk, prev, lp, tol) @@ -314,7 +370,7 @@ pub fn refine_snap( best = Some((i.dist, i.label(), i.at)); } // On a curve (coincident with it). - if best.is_none() { + if !mid_only && best.is_none() { for (i, c) in sk.curves.iter().enumerate() { let Some(sh) = sk.shape(i) else { continue }; let d = sh.dist(lp); @@ -325,7 +381,8 @@ pub fn refine_snap( } } } - if best.is_none() + if !mid_only + && best.is_none() && let Some(prev) = prev { let (dx, dy) = ((lp.x - prev.x).abs(), (lp.y - prev.y).abs()); @@ -339,7 +396,8 @@ pub fn refine_snap( } } // Line tool: parallel or perpendicular to a line, or on a line's extension. - if best.is_none() + if !mid_only + && best.is_none() && line_tool && let Some(prev) = prev && let Some(i) = crate::inference::lines(sk, prev, lp, tol) @@ -1205,7 +1263,10 @@ fn snap_hint(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { /// Per frame, after the viewport is drawn: constraint glyphs, snap hints and analysis marks. pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &Proj) { - SHIFT.with(|c| c.set(ui.input(|i| i.modifiers.shift))); + // IsoCurveAlternate (Shift default) for sketch.isoparametric_curve - via resolve, not raw shift. + let held = crate::tool_modifiers::Held::from_modifiers(ui.input(|i| i.modifiers)); + let iso = crate::tool_modifiers::resolve(&[], crate::tool_modifiers::descriptor("sketch.isoparametric_curve"), held, Trigger::Press); + SHIFT.with(|c| c.set(iso.contains(ModAction::IsoCurveAlternate))); glyphs(app, painter, proj, ui.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(proj.rect))); snap_hint(app, painter, proj); combs(app, painter, proj); diff --git a/crates/ui-egui/src/tool_modifiers.rs b/crates/ui-egui/src/tool_modifiers.rs new file mode 100644 index 000000000..10f0e3cba --- /dev/null +++ b/crates/ui-egui/src/tool_modifiers.rs @@ -0,0 +1,670 @@ +//! Centralised modifier-key binding types for sketch and selection behaviours. +//! +//! [`ModifierCombo`] is a serialisable set of modifier keys. Modifier state that +//! must cross the boundary between the viewport event-loop and rendering helpers +//! (gizmo, canvas) that do not carry `&SolveApp` is communicated through +//! per-frame thread-local flags — the same pattern as [`crate::drag_snap`] — +//! so that neither gizmo nor canvas needs access to application state. +//! +//! Strategy: bindings name a chord; call sites ask whether the chord matches the +//! held keys (`held` / `matches_exact`) instead of reading `Modifiers` fields +//! directly. Platform primary is Ctrl on Windows/Linux and Cmd on macOS; the +//! physical Ctrl key on macOS is never treated as primary. + +use std::cell::Cell; + +use egui::Modifiers; +use serde::{Deserialize, Serialize}; + +/// Runtime platform for labels and primary-key normalisation. +/// Prefer [`Platform::of`] over `cfg!(target_os)` so wasm on a Mac still says Cmd. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Platform { + Mac, + Other, +} + +impl Platform { + pub fn of(ctx: &egui::Context) -> Self { + match ctx.os() { + egui::os::OperatingSystem::Mac | egui::os::OperatingSystem::IOS => Self::Mac, + _ => Self::Other, + } + } + + /// Compile-time fallback for unit tests and call sites without a context. + pub fn host() -> Self { + if cfg!(target_os = "macos") { Self::Mac } else { Self::Other } + } +} + +/// Held keys, normalised for binding matches. +/// +/// `primary` is Ctrl on Windows/Linux and Cmd on macOS (`Modifiers::command`). +/// On macOS, physical Ctrl (`Modifiers::ctrl`) is `other` and never counts as primary. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct Held { + pub shift: bool, + pub primary: bool, + pub alt: bool, + /// A key no chord names (physical Ctrl on macOS). Fails exact matches. + pub other: bool, +} + +impl Held { + pub fn new(m: Modifiers, platform: Platform) -> Self { + // On Windows and Linux, Ctrl is primary even when an event sets only `ctrl` + // (`Modifiers::CTRL`). On macOS, primary is Command; physical Ctrl is a different key. + let primary = m.command || (platform != Platform::Mac && m.ctrl); + Self { shift: m.shift, primary, alt: m.alt, other: platform == Platform::Mac && m.ctrl && !m.command } + } + + /// Host-platform normalisation without an egui context (tests, prefs helpers). + pub fn from_modifiers(m: Modifiers) -> Self { + Self::new(m, Platform::host()) + } +} + +/// How a chord matches held keys. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Match { + /// Exactly these keys and no others. + Exact, + /// At least these keys; extras allowed. + AtLeast, +} + +/// A set of modifier keys for a binding. +/// +/// `ctrl` is the persisted field name for **primary** (Ctrl on Windows/Linux, Cmd on macOS). +/// Matching uses [`Held::primary`] (`Modifiers::command`), not physical Ctrl on macOS. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +pub struct ModifierCombo { + pub shift: bool, + /// Primary: Ctrl (Windows/Linux) or Cmd (macOS). Serde key stays `ctrl` for prefs stability. + pub ctrl: bool, + pub alt: bool, +} + +impl ModifierCombo { + pub const NONE: Self = Self { shift: false, ctrl: false, alt: false }; + pub const SHIFT: Self = Self { shift: true, ctrl: false, alt: false }; + pub const CTRL: Self = Self { shift: false, ctrl: true, alt: false }; + pub const ALT: Self = Self { shift: false, ctrl: false, alt: true }; + pub const CTRL_ALT: Self = Self { shift: false, ctrl: true, alt: true }; + + pub const fn key_count(self) -> u8 { + self.shift as u8 + self.ctrl as u8 + self.alt as u8 + } + + pub fn matches(self, held: Held, how: Match) -> bool { + match how { + Match::Exact => !held.other && self.shift == held.shift && self.ctrl == held.primary && self.alt == held.alt, + Match::AtLeast => (!self.shift || held.shift) && (!self.ctrl || held.primary) && (!self.alt || held.alt), + } + } + + /// True if **exactly** these modifiers (and no others) are held. + pub fn matches_exact(self, m: Modifiers) -> bool { + self.matches(Held::from_modifiers(m), Match::Exact) + } + + /// True if **at least** these modifiers are held (subset / "held" match). + pub fn held(self, m: Modifiers) -> bool { + self.matches(Held::from_modifiers(m), Match::AtLeast) + } + + /// Human-readable display label for the host platform. + pub fn label(self) -> String { + self.label_for(Platform::host()) + } + + /// Human-readable display label for a specific platform. + pub fn label_for(self, platform: Platform) -> String { + // Classic default: either primary or Alt/Option suppresses snap. + if self == Self::CTRL_ALT { + return format!("{} or {}", ctrl_name_for(platform), alt_name_for(platform)); + } + let mut parts: Vec<&str> = Vec::new(); + if self.shift { + parts.push("Shift"); + } + if self.ctrl { + parts.push(ctrl_name_for(platform)); + } + if self.alt { + parts.push(alt_name_for(platform)); + } + if parts.is_empty() { + return "None".into(); + } + parts.join("+") + } + + /// Combos offered by the sketch snap-suppress picker (classic OR first). + pub const SNAP_SUPPRESS_CHOICES: [Self; 4] = [Self::CTRL_ALT, Self::CTRL, Self::ALT, Self::SHIFT]; + + /// All single-key combos, in display order (for a picker widget). + pub const SINGLE_KEYS: [Self; 3] = [Self::CTRL, Self::ALT, Self::SHIFT]; +} + +/// "Ctrl/Cmd" on Windows/Linux, "Cmd" on macOS. +pub fn ctrl_name() -> &'static str { + ctrl_name_for(Platform::host()) +} + +pub fn ctrl_name_for(platform: Platform) -> &'static str { + match platform { + Platform::Mac => "Cmd", + Platform::Other => "Ctrl/Cmd", + } +} + +/// "Alt" on Windows/Linux, "Option" on macOS. +pub fn alt_name() -> &'static str { + alt_name_for(Platform::host()) +} + +pub fn alt_name_for(platform: Platform) -> &'static str { + match platform { + Platform::Mac => "Option", + Platform::Other => "Alt", + } +} + +thread_local! { + /// Set once per frame from the viewport event-loop; read by gizmo and canvas + /// helpers that do not receive `&SolveApp`. Communicates whether the current + /// modifier state enables free (unsnapped) manipulator drags. + static MANIPULATOR_FREE: Cell = const { Cell::new(false) }; + /// Shift while sketching forces midpoint targeting (see [`ModAction::TargetMidpoint`]). + static TARGET_MIDPOINT: Cell = const { Cell::new(false) }; + /// True while a canvas / gizmo manipulator drag is active this frame (or last frame until cleared). + static MANIPULATOR_DRAGGING: Cell = const { Cell::new(false) }; +} + +/// Set whether manipulator drags are free (no snap) this frame. +/// +/// Call from the viewport *before* canvas / gizmo rendering, passing the result of +/// [`crate::prefs::manipulator_free_held`]. +pub fn set_manipulator_free(on: bool) { + MANIPULATOR_FREE.with(|c| c.set(on)); +} + +/// Whether manipulator drags are free this frame (set by [`set_manipulator_free`]). +pub fn manipulator_free() -> bool { + MANIPULATOR_FREE.with(Cell::get) +} + +/// Set whether sketch refine-snap should target midpoints only this frame. +pub fn set_target_midpoint(on: bool) { + TARGET_MIDPOINT.with(|c| c.set(on)); +} + +/// Whether sketch refine-snap is in midpoint-only mode. +pub fn target_midpoint() -> bool { + TARGET_MIDPOINT.with(Cell::get) +} + +/// Set whether a manipulator (arrow / gizmo) drag is active. +pub fn set_manipulator_dragging(on: bool) { + MANIPULATOR_DRAGGING.with(|c| c.set(on)); +} + +/// Whether a manipulator drag is active (see [`set_manipulator_dragging`]). +pub fn manipulator_dragging() -> bool { + MANIPULATOR_DRAGGING.with(Cell::get) +} + +/// Semantic modifier actions. `id()` is persisted in prefs: never rename one, only add. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum ModAction { + SuppressSnap = 0, + FreeManipulatorDrag = 1, + SelectToggle = 2, + SelectAdd = 3, + TargetMidpoint = 4, + Cycle3dSketchPlane = 5, + PreviewReselect = 6, + TextSingleLetter = 7, + TextHandleConstrain = 8, + IsoCurveAlternate = 9, +} + +impl ModAction { + pub const ALL: &'static [Self] = &[ + Self::SuppressSnap, + Self::FreeManipulatorDrag, + Self::SelectToggle, + Self::SelectAdd, + Self::TargetMidpoint, + Self::Cycle3dSketchPlane, + Self::PreviewReselect, + Self::TextSingleLetter, + Self::TextHandleConstrain, + Self::IsoCurveAlternate, + ]; + + pub const fn id(self) -> &'static str { + match self { + Self::SuppressSnap => "suppress_snap", + Self::FreeManipulatorDrag => "free_manipulator_drag", + Self::SelectToggle => "select_toggle", + Self::SelectAdd => "select_add", + Self::TargetMidpoint => "target_midpoint", + Self::Cycle3dSketchPlane => "cycle_3d_sketch_plane", + Self::PreviewReselect => "preview_reselect", + Self::TextSingleLetter => "text_single_letter", + Self::TextHandleConstrain => "text_handle_constrain", + Self::IsoCurveAlternate => "isocurve_alternate", + } + } + + pub fn from_id(id: &str) -> Option { + Self::ALL.iter().copied().find(|a| a.id() == id) + } + + pub const fn group(self) -> Option { + match self { + Self::SelectToggle | Self::SelectAdd => Some(Group::SelectionClick), + _ => None, + } + } +} + +/// Actions that cannot both apply to one gesture: the most specific matching chord wins. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Group { + SelectionClick, +} + +/// When a binding is sampled relative to a pointer gesture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Trigger { + /// Re-evaluated every frame (snap suppression, free drag). + Live, + /// Sampled at primary press and latched until release (click selection). + Press, +} + +/// Whether a tool's modifier bindings have been reviewed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Audit { + Unaudited, + /// No tool-specific bindings beyond inherited scopes. + VerifiedNoOp, + Implemented, + /// A behaviour was considered and deliberately left out. + Declined, +} + +/// One binding: an action, default chords, match mode, and rebind flag. +#[derive(Clone, Copy, Debug)] +pub struct Binding { + pub action: ModAction, + /// Any one of these activates the action; empty means off by default. + pub defaults: &'static [ModifierCombo], + pub matching: Match, + pub trigger: Trigger, + pub rebindable: bool, +} + +/// Bindings shared by every tool active in that context. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + Selection, + SketchDraw, + SketchDrag, + Manipulator, + /// Feature dialogs with a live preview (Primary can roll the preview back for reselect). + FeaturePreview, +} + +impl Scope { + pub const fn bindings(self) -> &'static [Binding] { + match self { + Self::Selection => SELECTION_BINDINGS, + Self::SketchDraw | Self::SketchDrag => SKETCH_SNAP_BINDINGS, + Self::Manipulator => MANIPULATOR_BINDINGS, + Self::FeaturePreview => FEATURE_PREVIEW_BINDINGS, + } + } +} + +const SELECTION_BINDINGS: &[Binding] = &[ + Binding { action: ModAction::SelectAdd, defaults: &[ModifierCombo::SHIFT], matching: Match::AtLeast, trigger: Trigger::Press, rebindable: true }, + Binding { + action: ModAction::SelectToggle, + defaults: &[ModifierCombo::CTRL], + matching: Match::AtLeast, + trigger: Trigger::Press, + rebindable: true, + }, +]; + +const SKETCH_SNAP_BINDINGS: &[Binding] = &[ + Binding { + action: ModAction::SuppressSnap, + // Classic SolidCraft: Ctrl/Cmd or Alt/Option each suppress snap. + defaults: &[ModifierCombo::CTRL, ModifierCombo::ALT], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, + }, + Binding { + // Shift while sketching / coincident targeting prefers a line midpoint. + action: ModAction::TargetMidpoint, + defaults: &[ModifierCombo::SHIFT], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, + }, +]; + +const MANIPULATOR_BINDINGS: &[Binding] = &[Binding { + action: ModAction::FreeManipulatorDrag, + defaults: &[ModifierCombo::CTRL, ModifierCombo::ALT], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, +}]; + +const FEATURE_PREVIEW_BINDINGS: &[Binding] = &[Binding { + // Hold Primary to roll the command preview back so obscured geometry can be (re)selected. + action: ModAction::PreviewReselect, + defaults: &[ModifierCombo::CTRL], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, +}]; + +/// One entry per interactive command id. +#[derive(Clone, Copy, Debug)] +pub struct ToolModifiers { + pub tool: &'static str, + pub scopes: &'static [Scope], + /// Overrides scope bindings for the same action. + pub bindings: &'static [Binding], + pub audit: Audit, +} + +/// Host slices filled by each tool module. +pub const HOSTS: &[&[ToolModifiers]] = + &[crate::tools::MODIFIERS, crate::sketch_tools::MODIFIERS, crate::sketch_modify_ui::MODIFIERS, crate::dialogs::MODIFIERS]; + +pub fn descriptor(tool: &str) -> Option<&'static ToolModifiers> { + HOSTS.iter().flat_map(|h| h.iter()).find(|t| t.tool == tool) +} + +/// Bit set of active [`ModAction`]s for the current frame or press. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ActionSet(u64); + +impl ActionSet { + pub fn insert(&mut self, a: ModAction) { + self.0 |= 1 << (a as u8); + } + + pub fn contains(self, a: ModAction) -> bool { + self.0 & (1 << (a as u8)) != 0 + } +} + +/// Selection click flags from held modifiers and the shift-add-only preference. +/// +/// Returns `(add, allow_toggle)`. When `shift_add_only`, Shift is pure-add and Primary toggles. +pub fn selection_click(held: Held, shift_add_only: bool) -> (bool, bool) { + let actions = resolve(&[Scope::Selection], None, held, Trigger::Press); + let toggle = actions.contains(ModAction::SelectToggle); + let add = toggle || actions.contains(ModAction::SelectAdd); + let allow_toggle = if shift_add_only { toggle } else { add }; + (add, allow_toggle) +} + +/// Whether preview reselect should apply: Primary chord matched and no manipulator drag under way. +pub fn preview_reselect(held: Held, manipulator_dragging: bool) -> bool { + if manipulator_dragging { + return false; + } + resolve(&[Scope::FeaturePreview], None, held, Trigger::Live).contains(ModAction::PreviewReselect) +} + +/// Resolve which actions are active for `held` under the given scopes and optional tool. +pub fn resolve(context: &[Scope], tool: Option<&ToolModifiers>, held: Held, trigger: Trigger) -> ActionSet { + let mut set = ActionSet::default(); + let mut bindings: Vec<&Binding> = context.iter().flat_map(|s| s.bindings()).collect(); + if let Some(t) = tool { + for s in t.scopes { + bindings.extend(s.bindings()); + } + for b in t.bindings { + // Tool-specific bindings replace earlier ones with the same action. + bindings.retain(|x| x.action != b.action); + bindings.push(b); + } + } + // Most specific chord wins within a group. + let mut best_group: [Option<(u8, ModAction)>; 1] = [None]; + for b in bindings { + if b.trigger != trigger { + continue; + } + if b.defaults.is_empty() { + continue; + } + let matched = b.defaults.iter().any(|c| { + if matches!(b.matching, Match::AtLeast) && c.key_count() == 0 { + return false; + } + c.matches(held, b.matching) + }); + if !matched { + continue; + } + if let Some(g) = b.action.group() { + let idx = match g { + Group::SelectionClick => 0, + }; + let specificity = b.defaults.iter().map(|c| c.key_count()).max().unwrap_or(0); + match best_group[idx] { + Some((s, _)) if s > specificity => {} + Some((s, prev)) if s == specificity => { + // Tie: earlier ModAction::ALL order wins. + let prev_i = ModAction::ALL.iter().position(|a| *a == prev).unwrap_or(0); + let cur_i = ModAction::ALL.iter().position(|a| *a == b.action).unwrap_or(0); + if cur_i < prev_i { + best_group[idx] = Some((specificity, b.action)); + } + } + _ => best_group[idx] = Some((specificity, b.action)), + } + } else { + set.insert(b.action); + } + } + for slot in best_group.into_iter().flatten() { + set.insert(slot.1); + } + set +} + +#[cfg(test)] +mod tests { + use super::*; + + fn mods(shift: bool, ctrl: bool, alt: bool) -> Modifiers { + Modifiers { shift, ctrl, alt, command: ctrl, ..Default::default() } + } + + #[test] + fn exact_match_requires_no_extra_keys() { + let ctrl = ModifierCombo::CTRL; + assert!(ctrl.matches_exact(mods(false, true, false))); + assert!(!ctrl.matches_exact(mods(true, true, false)), "extra shift must fail"); + assert!(!ctrl.matches_exact(mods(false, false, false))); + } + + #[test] + fn held_match_allows_extra_keys() { + let ctrl = ModifierCombo::CTRL; + assert!(ctrl.held(mods(false, true, false))); + assert!(ctrl.held(mods(true, true, false)), "shift+ctrl is fine for a ctrl binding"); + assert!(!ctrl.held(mods(false, false, false))); + } + + #[test] + fn physical_ctrl_is_primary_off_mac() { + let ctrl_only = Modifiers::CTRL; + assert!(ModifierCombo::CTRL.matches(Held::new(ctrl_only, Platform::Other), Match::AtLeast)); + assert!(!ModifierCombo::CTRL.matches(Held::new(ctrl_only, Platform::Mac), Match::AtLeast)); + assert_eq!(selection_click(Held::new(ctrl_only, Platform::Other), false), (true, true)); + } + + #[test] + fn cmd_normalises_to_ctrl() { + let ctrl = ModifierCombo::CTRL; + let cmd_mods = Modifiers { command: true, ..Default::default() }; + assert!(ctrl.held(cmd_mods), "Cmd on macOS should match a ctrl binding"); + assert!(ctrl.matches_exact(cmd_mods), "exact match also normalises command"); + } + + #[test] + fn mac_physical_ctrl_is_not_primary() { + let ctrl = ModifierCombo::CTRL; + let physical = Modifiers { ctrl: true, command: false, ..Default::default() }; + let held = Held::new(physical, Platform::Mac); + assert!(!held.primary && held.other); + assert!(!ctrl.matches(held, Match::AtLeast)); + assert!(!ctrl.matches(held, Match::Exact)); + let win = Held::new(Modifiers { ctrl: true, command: true, ..Default::default() }, Platform::Other); + assert!(ctrl.matches(win, Match::AtLeast)); + } + + #[test] + fn label_formats_correctly() { + assert_eq!(ModifierCombo::CTRL.label_for(Platform::Other), "Ctrl/Cmd"); + assert_eq!(ModifierCombo::CTRL.label_for(Platform::Mac), "Cmd"); + assert_eq!(ModifierCombo::NONE.label_for(Platform::Other), "None"); + assert_eq!(ModifierCombo::CTRL_ALT.label_for(Platform::Other), "Ctrl/Cmd or Alt"); + assert_eq!(ModifierCombo::CTRL_ALT.label_for(Platform::Mac), "Cmd or Option"); + assert_eq!(ModifierCombo { shift: true, ctrl: true, alt: false }.label_for(Platform::Other), "Shift+Ctrl/Cmd"); + } + + #[test] + fn manipulator_free_thread_local_roundtrip() { + set_manipulator_free(true); + assert!(manipulator_free()); + set_manipulator_free(false); + assert!(!manipulator_free()); + } + + #[test] + fn target_midpoint_live_resolves_from_sketch_scopes() { + set_target_midpoint(false); + let shift = Held { shift: true, ..Default::default() }; + let set = resolve(&[Scope::SketchDraw], None, shift, Trigger::Live); + assert!(set.contains(ModAction::TargetMidpoint)); + assert!(!set.contains(ModAction::SuppressSnap)); + set_target_midpoint(true); + assert!(target_midpoint()); + set_target_midpoint(false); + assert!(!target_midpoint()); + } + + #[test] + fn preview_reselect_resolves_from_feature_preview_scope() { + let primary = Held { primary: true, ..Default::default() }; + let set = resolve(&[Scope::FeaturePreview], None, primary, Trigger::Live); + assert!(set.contains(ModAction::PreviewReselect)); + let press = resolve(&[Scope::FeaturePreview], None, primary, Trigger::Press); + assert!(!press.contains(ModAction::PreviewReselect)); + } + + #[test] + fn preview_reselect_skips_while_manipulator_dragging() { + let primary = Held { primary: true, ..Default::default() }; + assert!(preview_reselect(primary, false)); + assert!(!preview_reselect(primary, true), "Ctrl free-drag must not hide the preview"); + set_manipulator_dragging(true); + assert!(manipulator_dragging()); + set_manipulator_dragging(false); + assert!(!manipulator_dragging()); + } + + #[test] + fn selection_scope_resolves_shift_add_and_primary_toggle() { + let shift = Held { shift: true, ..Default::default() }; + let primary = Held { primary: true, ..Default::default() }; + let both = Held { shift: true, primary: true, ..Default::default() }; + let add = resolve(&[Scope::Selection], None, shift, Trigger::Press); + assert!(add.contains(ModAction::SelectAdd)); + assert!(!add.contains(ModAction::SelectToggle)); + let toggle = resolve(&[Scope::Selection], None, primary, Trigger::Press); + assert!(toggle.contains(ModAction::SelectToggle)); + assert!(!toggle.contains(ModAction::SelectAdd)); + // Shift+Primary: single-key tie → SelectToggle wins (earlier in ModAction::ALL). + let combo = resolve(&[Scope::Selection], None, both, Trigger::Press); + assert!(combo.contains(ModAction::SelectToggle)); + assert!(!combo.contains(ModAction::SelectAdd)); + } + + #[test] + fn selection_click_respects_shift_add_only_pref() { + let shift = Held { shift: true, ..Default::default() }; + let primary = Held { primary: true, ..Default::default() }; + assert_eq!(selection_click(shift, true), (true, false)); + assert_eq!(selection_click(shift, false), (true, true)); + assert_eq!(selection_click(primary, true), (true, true)); + assert_eq!(selection_click(Held::default(), true), (false, false)); + } + + #[test] + fn isocurve_shift_resolves_via_descriptor() { + let held = Held { shift: true, ..Default::default() }; + let set = resolve(&[], descriptor("sketch.isoparametric_curve"), held, Trigger::Press); + assert!(set.contains(ModAction::IsoCurveAlternate)); + let bare = resolve(&[], None, held, Trigger::Press); + assert!(!bare.contains(ModAction::IsoCurveAlternate)); + } + + #[test] + fn action_ids_are_unique() { + let mut seen = std::collections::BTreeSet::new(); + for a in ModAction::ALL { + assert!(seen.insert(a.id()), "duplicate id {}", a.id()); + assert_eq!(ModAction::from_id(a.id()), Some(*a)); + } + } + + #[test] + fn tools_host_covers_interactive_sketch_create_commands() { + for entry in crate::tools::MODIFIERS { + assert!(crate::tools::Tool::for_command(entry.tool).is_some(), "orphan descriptor {}", entry.tool); + assert_eq!(descriptor(entry.tool).map(|d| d.tool), Some(entry.tool)); + } + // Every command owned directly by tools.rs (not sketch_tools) has a descriptor. + for id in ["sketch.line", "sketch.rectangle.two_point", "sketch.circle.center", "sketch.constraint.coincident", "sketch.dimension"] { + assert!(descriptor(id).is_some(), "missing descriptor for {id}"); + } + } + + #[test] + fn hosts_have_unique_tool_ids_and_cover_seeded_commands() { + let mut seen = std::collections::BTreeSet::new(); + for entry in HOSTS.iter().flat_map(|h| h.iter()) { + assert!(seen.insert(entry.tool), "duplicate tool id {}", entry.tool); + } + for id in ["sketch.isoparametric_curve", "sketch.pattern.rectangular", "solid.pattern.circular", "solid.extrude", "sketch.move"] { + assert!(descriptor(id).is_some(), "missing descriptor for {id}"); + } + assert_eq!(descriptor("sketch.pattern.rectangular").unwrap().audit, Audit::VerifiedNoOp); + assert_eq!(descriptor("solid.pattern.circular").unwrap().audit, Audit::VerifiedNoOp); + assert_eq!(descriptor("sketch.isoparametric_curve").unwrap().audit, Audit::Implemented); + assert_eq!(descriptor("sketch.line").unwrap().audit, Audit::Implemented); + // Seeded hosts: no Unaudited leftovers once scopes are assigned. + for entry in HOSTS.iter().flat_map(|h| h.iter()) { + assert_ne!(entry.audit, Audit::Unaudited, "{} still Unaudited", entry.tool); + } + } +} diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index cd23fc7b6..e34e2068e 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -6,8 +6,44 @@ use serde_json::{Value, json}; use solidcraft_engine::geom::Vec2; use crate::SolveApp; +use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; use crate::viewport::{Hit, Proj, pick, sketch_point_at}; +const DRAW_SCOPES: &[Scope] = &[Scope::SketchDraw, Scope::SketchDrag]; + +/// Per-tool modifier descriptors owned by this host file (coordinator seeds / audits these). +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.line", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.two_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.rounded", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.circle.center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.circle.two_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.circle.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.arc.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.arc.center_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.polygon.inscribed", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.polygon.circumscribed", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.polygon.edge", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.center_to_center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.overall", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.dimension", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + // Constraint tools: pick-only; no tool-specific modifier chords. + ToolModifiers { tool: "sketch.constraint.horizontal_vertical", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.fix", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.coincident", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.tangent", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.equal", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.parallel", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.perpendicular", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.concentric", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.collinear", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.midpoint", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.symmetry", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, +]; + #[cfg(test)] #[path = "sketch_display_preview_tests.rs"] mod display_preview_tests; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 8ee4c5f44..8e3264ba4 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -311,7 +311,8 @@ fn scene_key(app: &SolveApp) -> u64 { app.ui.hidden_profiles.hash(&mut h); app.session.active_component.hash(&mut h); app.session.active_occurrence_path.hash(&mut h); - app.preview.replaced.hash(&mut h); + app.preview.effective_replaced().hash(&mut h); + app.preview.rolled_back.hash(&mut h); app.tree.redefine.hash(&mut h); crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); @@ -501,7 +502,7 @@ fn update_refinement(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) { if b.name != *name || b.body.is_mesh() { continue; } - let shown = app.session.body_visible(&b.name) && !app.preview.replaced.contains(&b.name); + let shown = app.session.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name); let on_screen = match screen_box(proj, bx, 0.0).filter(|_| shown) { Some(r) => r.intersects(proj.rect).then(|| f64::from(r.width().max(r.height())) * ppp), // A corner behind the eye: the view is inside or right by the box. @@ -649,7 +650,7 @@ fn build_scene(app: &SolveApp) -> GpuScene { let mut run: Vec = Vec::new(); let mut run_key = std::collections::hash_map::DefaultHasher::new(); for b in &st.bodies { - if !app.session.body_visible(&b.name) || app.preview.replaced.contains(&b.name) { + if !app.session.body_visible(&b.name) || app.preview.effective_replaced().contains(&b.name) { continue; } let faded = body_faded(app, b, &active_bodies); @@ -1480,7 +1481,7 @@ fn feature_geometry(app: &SolveApp, id: u64) -> Vec { let prefix = format!("F{id}:"); let mut out = Vec::new(); for b in &st.bodies { - if !app.session.body_visible(&b.name) || app.preview.replaced.contains(&b.name) { + if !app.session.body_visible(&b.name) || app.preview.effective_replaced().contains(&b.name) { continue; } if b.feature == id { @@ -1903,7 +1904,8 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { (app.dialog.is_some(), app.tool.is_some()).hash(&mut h); crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); - app.preview.replaced.hash(&mut h); + app.preview.effective_replaced().hash(&mut h); + app.preview.rolled_back.hash(&mut h); app.origin_visible().hash(&mut h); app.picking_sketch_plane().hash(&mut h); app.session.visibility.hidden_origin.hash(&mut h); @@ -2033,7 +2035,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { match x { Sel::Face { body, index, .. } => { // A live preview stands in for the body: its old faces would fight with it. - if let Some(b) = st.body(body).filter(|_| app.session.body_visible(body) && !app.preview.replaced.contains(body)) { + if let Some(b) = st.body(body).filter(|_| app.session.body_visible(body) && !app.preview.effective_replaced().contains(body)) { face_tris(&mut feedback, &shown(b), *index, c4(t.sel_face), false); hidden_face_outline(&mut feedback, &drawn_mesh(app, b), *index, t.sel_edge); } @@ -2096,7 +2098,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { // Timeline modifiers light only their resulting faces; browser rows light whole bodies. let mut hovered = app.viewport.hover_feature.map(|id| feature_geometry(app, id)).unwrap_or_default(); hovered.extend(app.viewport.hover_bodies.iter().map(|name| Sel::Body { name: name.clone() })); - for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name) && !app.preview.replaced.contains(&b.name)) { + for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name)) { let whole = hovered.iter().any(|x| matches!(x, Sel::Body { name } if name == &b.name)); let faces: Vec<_> = if whole { (0..b.body.face_count()).collect() @@ -2156,7 +2158,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { } } Some(Hit::Face { body, index, .. }) - if !app.preview.replaced.contains(body) + if !app.preview.effective_replaced().contains(body) && !sel.iter().any(|x| matches!(x, Sel::Face { body: b, index: i, .. } if b == body && i == index)) => { if let Some(b) = st.body(body) { @@ -2290,6 +2292,14 @@ pub fn delete_selection(app: &mut SolveApp) { crate::delete::delete_selection(app); } +/// Whether Primary should hide the live command preview so obscured geometry can be reselected. +/// +/// Shared by [`show`] so tests can lock the same path: a manipulator drag never rolls the +/// preview back, even when Primary (preview-reselect) is held. +pub(crate) fn preview_should_roll_back(app: &SolveApp, held: crate::tool_modifiers::Held, manipulator_dragging: bool) -> bool { + app.dialog.as_ref().is_some_and(|d| d.previews()) && app.preview.active && crate::tool_modifiers::preview_reselect(held, manipulator_dragging) +} + pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); let rect = ui.max_rect(); @@ -2319,6 +2329,28 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { mode, } = input; app.viewport.physical_scale = ui.ctx().pixels_per_point(); + // Suppress-snap chord and manipulator-free prefs; Shift midpoint targeting while sketching. + // Preview reselect uses Primary but is skipped while a manipulator drag is under way. + crate::drag_snap::set_suppressed(crate::prefs::suppress_sketch_snap_held(app, mods)); + crate::tool_modifiers::set_manipulator_free(crate::prefs::manipulator_free_held(app, mods)); + let manipulator_dragging = crate::tool_modifiers::manipulator_dragging(); + crate::tool_modifiers::set_manipulator_dragging(false); + { + let held = crate::tool_modifiers::Held::from_modifiers(mods); + let mid = if let Some(cmd) = app.tool.as_ref().map(|t| t.cmd) { + let live = crate::tool_modifiers::resolve( + &[crate::tool_modifiers::Scope::SketchDraw, crate::tool_modifiers::Scope::SketchDrag], + crate::tool_modifiers::descriptor(cmd), + held, + crate::tool_modifiers::Trigger::Live, + ); + live.contains(crate::tool_modifiers::ModAction::TargetMidpoint) + } else { + false + }; + crate::tool_modifiers::set_target_midpoint(mid); + app.preview.rolled_back = preview_should_roll_back(app, held, manipulator_dragging); + } let proj = projection(app, rect); if let Ok(mut cache) = app.viewport.display.lock() { cache.prepare(app.session.world_state(), &proj, app.viewport.pixels_per_point()); @@ -2412,6 +2444,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { hl_slot: app.viewport.hl_slot.clone(), pv_key: app.preview.key, pv_slot: app.preview.slot.clone(), + pv_hide: app.preview.rolled_back, clip: section_clip(app), cap: t.section_cap.to_normalized_gamma_f32(), view_proj: proj.vp.to_f32(), @@ -2455,7 +2488,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::tools::on_hover(app, &proj, p); } } - let add = mods.shift || mods.command || mods.ctrl; + // Selection chords via resolve (add-only Shift is a preference; default both toggle). + let held_mods = crate::tool_modifiers::Held::from_modifiers(mods); + let (add, allow_toggle) = crate::tool_modifiers::selection_click(held_mods, app.preferences.selection_shift_add_only); crate::sketch_text::set_one_letter(mods.shift); if let Some(p) = hover.filter(|_| inside) { if app.tool.is_some() { @@ -2509,13 +2544,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // A text's resize or rotation handle: the text stays selected. } else if !crate::sketch3d::click(app, &proj, p) { match on_dim.or(on_glyph) { - Some(id) => select(app, Some(Sel::SketchConstraint { id }), add), + Some(id) => select(app, Some(Sel::SketchConstraint { id }), add, allow_toggle), // Clicking again on the same spot selects the next thing under it (not // the second click of a double-click, which has its own actions). None if !add && !resp.double_clicked() && crate::select_other::cycle_click(app, &proj, p) => {} None => { let sel = cand.and_then(|c| c.1); - select(app, sel.clone(), add); + select(app, sel.clone(), add, allow_toggle); crate::select_other::note_click(app, p, if add { None } else { sel }); } } @@ -2843,9 +2878,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } } -/// A click without a command: select the candidate (replacing the selection, or toggling it -/// in with Shift/Ctrl); a click on nothing clears. -pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool) { +/// A click without a command: select the candidate (replacing the selection, or adding / +/// toggling with modifiers); a click on nothing clears. +/// +/// `toggle`: whether already-selected items may be removed by this click (Ctrl/Cmd held). +/// When `add` is true but `toggle` is false (Shift add-only preference), picked items +/// are only added. +pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool, toggle: bool) { if !add { // A joint picked in the browser (highlighted even when hidden) lets go. app.tree.picked_joints.clear(); @@ -2853,7 +2892,8 @@ pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool) { match sel { Some(x) => { let items = picked_selection(&app.session, &x); - if add && items.iter().all(|x| app.session.selection.iter().any(|y| crate::selection::same_item(x, y))) { + // Toggle-removal: all picked items are already selected and toggle is allowed. + if add && toggle && items.iter().all(|x| app.session.selection.iter().any(|y| crate::selection::same_item(x, y))) { let rest: Vec = app.session.selection.iter().filter(|y| !items.iter().any(|x| crate::selection::same_item(x, y))).cloned().collect(); let _ = app.run("select.set", json!({ "items": rest })); @@ -5238,12 +5278,12 @@ mod tests { app.viewport.hover = Some(Hit::Edge { body: b.name.clone(), index: i, mid }); assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); - select(&mut app, Some(item.clone()), false); + select(&mut app, Some(item.clone()), false, false); assert_eq!(app.session.selection.len(), 2); // Selecting both pieces must not draw each highlight twice. assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); // Ctrl/Shift clicking either half deselects the entire rim. - select(&mut app, Some(item.clone()), true); + select(&mut app, Some(item.clone()), true, true); assert!(app.session.selection.is_empty()); let mut d = crate::dialogs::Dialog::for_command(&app, "solid.chamfer").unwrap(); if let crate::dialogs::Kind::Fillet { chain, .. } = &mut d.kind { @@ -5287,7 +5327,7 @@ mod tests { app.viewport.hover = Some(Hit::Face { body: b.name.clone(), index, point }); assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); - select(&mut app, Some(item.clone()), false); + select(&mut app, Some(item.clone()), false, false); assert_eq!(app.session.selection.len(), 2); assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); assert_eq!(app.session.selection.first(), Some(&item), "keep the original tool placement point first"); @@ -5299,7 +5339,7 @@ mod tests { assert_eq!(dialog.items().len(), 2); // A point elsewhere on the opposite half still toggles the whole surface off. let other = faces.iter().find(|&&x| x != f).unwrap(); - select(&mut app, Some(Sel::Face { body: b.name.clone(), index: *other as usize, point: m.positions[0] }), true); + select(&mut app, Some(Sel::Face { body: b.name.clone(), index: *other as usize, point: m.positions[0] }), true, true); assert!(app.session.selection.is_empty()); } // Planar caps and box corners stay separate. @@ -6436,4 +6476,21 @@ mod grid_plane_tests { let sc = build_highlight(&app); assert!(sc.xray.is_empty() && !sc.guide_trans.is_empty(), "outside Create Sketch the planes are depth-tested"); } + + /// Primary rolls a live preview back for reselect, but not while a manipulator is dragged + /// (same gate [`show`] uses via [`preview_should_roll_back`]). + #[test] + fn preview_rollback_stays_off_while_manipulator_dragging() { + let mut s = solidcraft_engine::Session::default(); + s.execute("sketch.create", &json!({"plane": "xy"})).unwrap(); + s.execute("sketch.line", &json!({"points": [[0, 0], [20, 0]]})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.dialog = crate::dialogs::Dialog::for_command(&app, "solid.extrude"); + assert!(app.dialog.as_ref().is_some_and(|d| d.previews()), "extrude opens a preview dialog"); + app.preview.active = true; + let primary = crate::tool_modifiers::Held { primary: true, ..Default::default() }; + assert!(preview_should_roll_back(&app, primary, false), "Primary alone rolls the preview back when a preview dialog is open"); + assert!(!preview_should_roll_back(&app, primary, true), "Primary must not roll the preview back while a manipulator arrow is dragged"); + } } diff --git a/docs/book/src/guide/shortcuts.md b/docs/book/src/guide/shortcuts.md index 9b937313b..65c928af9 100644 --- a/docs/book/src/guide/shortcuts.md +++ b/docs/book/src/guide/shortcuts.md @@ -50,3 +50,15 @@ With the **Touchpad** navigation preset, hold **Shift** while moving the pointer **Alt/Option** to orbit, without pressing a mouse button. Vertical scrolling zooms. These viewport gestures are separate from rebindable command shortcuts; mouse-button selection and editing keep their existing modifiers. + +### Sketch modifiers + +While drawing or dragging a sketch point: + +| Keys | Action | +|---|---| +| Ctrl/Cmd or Alt/Option (default) | suppress auto-snap for that gesture | +| Shift | prefer a line midpoint when targeting | + +Change the snap-suppress chord in Preferences › Sketch. Selection still uses Shift and +Ctrl/Cmd to add or toggle (Preferences › Selection can make Shift add-only). diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index c407e9561..ea8ff9c88 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -16,7 +16,7 @@ origin, bodies, sketches, construction planes, canvases, joints and components. The eye shows or hides an item, a component's radio button makes it the active component, and right-clicking any row gives that item's menu. Rows drag into groups and other components. -- **Viewport.** Click to select, Shift or Ctrl to add, drag for a window or crossing box. To +- **Viewport.** Click to select, Shift or Ctrl to add (Preferences › Selection), drag for a window or crossing box. While sketching, Ctrl/Cmd or Alt/Option suppress auto-snap by default; Shift prefers a midpoint. To reach something under something else (two lines drawn on top of each other, coincident points, an edge in front of a face, overlapping bodies), hold the left button still for half a second (long-press on a touch screen) or right-click › **Select Other…**: a list of everything under