SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Orbit drags keep turning at the edge of the view (#3459)
Sloptimum8e55033d9adb
diff --git a/assets/locales/pending/orbit-cursor-wrap.json b/assets/locales/pending/orbit-cursor-wrap.jsonnew file mode 100644index 0000000000..dc9c2202bb--- /dev/null+++ b/assets/locales/pending/orbit-cursor-wrap.json@@ -0,0 +1,26 @@+{+ "en": {+ "nav.orbit_cursor_wrap.label": "Wrap the cursor while orbiting",+ "nav.orbit_cursor_wrap.help": "An orbit drag that reaches the edge of the view moves the cursor to the opposite edge and keeps turning. Off: the drag stops at the edge of the screen. Has no effect on Wayland or in the browser."+ },+ "ar": {+ "nav.orbit_cursor_wrap.label": "نقل المؤشر إلى الجهة المقابلة أثناء التدوير",+ "nav.orbit_cursor_wrap.help": "عندما يصل سحب التدوير إلى حافة العرض، ينتقل المؤشر إلى الحافة المقابلة ويستمر التدوير. عند الإيقاف: يتوقف السحب عند حافة الشاشة. لا تأثير له على Wayland أو داخل المتصفح."+ },+ "he": {+ "nav.orbit_cursor_wrap.label": "העברת הסמן לצד השני בזמן סיבוב",+ "nav.orbit_cursor_wrap.help": "גרירת סיבוב שמגיעה לקצה המבט מעבירה את הסמן לקצה הנגדי וממשיכה לסובב. כבוי: הגרירה נעצרת בקצה המסך. ללא השפעה ב־Wayland או בדפדפן."+ },+ "ja": {+ "nav.orbit_cursor_wrap.label": "回転中にカーソルを反対側へ移す",+ "nav.orbit_cursor_wrap.help": "回転のドラッグがビューの端に達すると、カーソルが反対側の端へ移り、そのまま回転を続けます。オフ:ドラッグは画面の端で止まります。Wayland とブラウザーでは効果がありません。"+ },+ "vi": {+ "nav.orbit_cursor_wrap.label": "Chuyển con trỏ sang cạnh đối diện khi xoay",+ "nav.orbit_cursor_wrap.help": "Khi thao tác kéo để xoay chạm tới cạnh khung nhìn, con trỏ được chuyển sang cạnh đối diện và tiếp tục xoay. Khi tắt: thao tác kéo dừng lại ở cạnh màn hình. Không có tác dụng trên Wayland hoặc trên trình duyệt."+ },+ "zh": {+ "nav.orbit_cursor_wrap.label": "旋转时光标循环",+ "nav.orbit_cursor_wrap.help": "旋转拖动到达视图边缘时,光标移到对侧边缘并继续旋转。关闭时,拖动在屏幕边缘停止。在 Wayland 和浏览器中无效。"+ }+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 3ac9441552..45eb26fa0f 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -755,6 +755,8 @@ pub struct SolveApp {pub synthetic_mods: egui::Modifiers,/// A click that came in the same frame as typing before it, held for the next frame.held_click: Vec<egui::Event>,+ /// A synthetic press is held: its drag never moves the real cursor (`navigation::wrap_cursor`).+ pub(crate) synthetic_press: bool,control_rx: Option<Receiver<ControlRequest>>,/// Control requests that change the design, held while a file loads or an agent's design/// change computes.@@ -945,6 +947,7 @@ impl SolveApp {synthetic: Vec::new(),synthetic_mods: egui::Modifiers::default(),held_click: Vec::new(),+ synthetic_press: false,control_rx: None,agent_chat: Default::default(),ai_connect: Default::default(),@@ -3271,6 +3274,7 @@ impl SolveApp {raw.events.push(egui::Event::ModifiersChanged(*modifiers));// A drag keeps its press's modifiers until the release.self.synthetic_mods = if *pressed { *modifiers } else { egui::Modifiers::NONE };+ self.synthetic_press = *pressed;}egui::Event::Key { modifiers, .. } => raw.events.push(egui::Event::ModifiersChanged(*modifiers)),egui::Event::PointerMoved(_) => raw.events.push(egui::Event::ModifiersChanged(self.synthetic_mods)),diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rsindex a849a22661..4199b21e8f 100644--- a/crates/ui-egui/src/navigation.rs+++ b/crates/ui-egui/src/navigation.rs@@ -608,6 +608,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e)});let hover = hover.filter(|p| !crate::frame::dock_dragging(ui.ctx()) && !crate::shell::covered(app, *p));+ let delta = unwrapped_delta(app, delta);// The right button belongs to the marking menu while it is open.let secondary_down = secondary_down && app.viewport.context_menu.is_none();// The axis view handles its own clicks; the model underneath must not see them.@@ -887,6 +888,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &eNone => app.viewport.nav.is_some(),};orbit_drag(app, rect, f64::from(delta.x), f64::from(delta.y), press, snap, true);+ wrap_cursor(app, ui, rect);} else {if app.viewport.axis_drag.is_none() {app.viewport.orbit_free = None;@@ -912,6 +914,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &eif !dragging && motion.is_none() && !(trackpad_orbit && app.viewport.trackpad_gesture) {app.viewport.orbit_pivot = None;app.viewport.orbit_from = None;+ app.viewport.cursor_wrap = None;}if app.viewport.spin {// A click on the navigation bar (its own button) is not a stop.@@ -954,6 +957,58 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &eCameraInput { hover, scroll, mods, middle, secondary_down, primary_down, primary_pressed, inside, axes, pinch, pan, primary_nav, mode }}+/// How close to the view's edge (points) an orbit drag moves the cursor to the other side.+const WRAP_MARGIN: f32 = 4.0;++/// An orbit drag that reaches the edge of the view keeps turning: the cursor moves to the other+/// side of the view, so the drag can go on round the model as far as the user likes instead of+/// stopping where the screen ends. One move at a time; the next waits until the pointer has+/// reported the jump ([`unwrapped_delta`]). Where the cursor can't be moved (Wayland, the+/// browser) the request does nothing, the jump never arrives and the drag stops at the edge. A+/// synthetic drag (control channel, scripts) has no real cursor to move. With+/// `orbit_cursor_wrap` off in the preferences the drag stops at the edge of the screen.+pub(crate) fn wrap_cursor(app: &mut SolveApp, ui: &egui::Ui, rect: Rect) {+ if !app.preferences.orbit_cursor_wrap || app.viewport.cursor_wrap.is_some() || app.synthetic_press {+ return;+ }+ let Some(at) = ui.input(|i| i.pointer.latest_pos()) else { return };+ let Some(to) = wrapped(rect, at) else { return };+ ui.ctx().send_viewport_cmd(egui::ViewportCommand::CursorPosition(to));+ app.viewport.cursor_wrap = Some(to - at);+}++/// Where a pointer at `at`, at or past the edge of `rect`, continues on the opposite side; `None`+/// while it is well inside.+pub(crate) fn wrapped(rect: Rect, at: Pos2) -> Option<Pos2> {+ let inner = rect.shrink(WRAP_MARGIN);+ if !at.is_finite() || !inner.is_finite() || inner.width() < 2.0 * WRAP_MARGIN || inner.height() < 2.0 * WRAP_MARGIN {+ return None;+ }+ let across = |v: f32, lo: f32, hi: f32| {+ if v < lo {+ v + (hi - lo)+ } else if v > hi {+ v - (hi - lo)+ } else {+ v+ }+ };+ let to = inner.clamp(pos2(across(at.x, inner.min.x, inner.max.x), across(at.y, inner.min.y, inner.max.y)));+ (to != at).then_some(to)+}++/// The pointer's motion this frame without the jump of a cursor wrap: the frame that reports it+/// moves the camera only by what the hand did.+fn unwrapped_delta(app: &mut SolveApp, delta: egui::Vec2) -> egui::Vec2 {+ let Some(jump) = app.viewport.cursor_wrap else { return delta };+ if (delta - jump).length() < jump.length() * 0.5 {+ app.viewport.cursor_wrap = None;+ delta - jump+ } else {+ delta+ }+}+/// The 3D mouse's motion this frame (#1336), on a page `rect` whose camera may do `caps`: the cap/// pans and zooms every page, and turns the view where the page may orbit. In a sketch, turning/// stays off while the camera is in its initial sketch orientation, unless the user lets the 3D@@ -2540,6 +2595,103 @@ mod tests {}}+ /// Past an edge of the view the pointer continues from the opposite edge; well inside, it+ /// stays where it is.+ #[test]+ fn the_cursor_wraps_to_the_opposite_edge() {+ use egui::{Rect, pos2, vec2};+ let view = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0));+ assert_eq!(super::wrapped(view, pos2(500.0, 300.0)), None);+ assert_eq!(super::wrapped(view, pos2(104.0, 54.0)), None, "on the margin itself");+ assert_eq!(super::wrapped(view, pos2(900.0, 300.0)), Some(pos2(108.0, 300.0)), "right to left");+ assert_eq!(super::wrapped(view, pos2(100.0, 300.0)), Some(pos2(892.0, 300.0)), "left to right");+ assert_eq!(super::wrapped(view, pos2(500.0, 650.0)), Some(pos2(500.0, 58.0)), "bottom to top");+ assert_eq!(super::wrapped(view, pos2(500.0, 40.0)), Some(pos2(500.0, 632.0)), "top to bottom, from outside");+ assert_eq!(super::wrapped(view, pos2(901.0, 651.0)), Some(pos2(109.0, 59.0)), "a corner wraps both ways");+ assert_eq!(super::wrapped(view, pos2(5000.0, 300.0)), Some(pos2(896.0, 300.0)), "far outside lands inside");+ assert_eq!(super::wrapped(view, pos2(f32::NAN, 300.0)), None);+ assert_eq!(super::wrapped(Rect::from_min_size(pos2(0.0, 0.0), vec2(10.0, 10.0)), pos2(20.0, 5.0)), None, "too small a view");+ }++ /// An orbit drag that reaches the edge of the view keeps turning round the model: the cursor+ /// moves to the other side, and the frame that reports the jump turns the view only by the+ /// hand's motion. Events from before the move don't ask for a second one. With+ /// `orbit_cursor_wrap` off the cursor is never moved.+ #[test]+ fn an_orbit_drag_at_the_edge_moves_the_cursor_across_and_keeps_turning() {+ use crate::prefs::NavButton;+ use egui::{Event, Modifiers, PointerButton, ViewportCommand, pos2, vec2};+ let mut s = solidcraft_engine::Session::default();+ s.execute("solid.box", &serde_json::json!({"length":40,"width":30,"height":20})).unwrap();+ let mut app = crate::SolveApp::new(s, crate::Services::default());+ let (button, mods) = [(PointerButton::Secondary, NavButton::Right), (PointerButton::Middle, NavButton::Middle)]+ .into_iter()+ .flat_map(|b| [Modifiers::NONE, Modifiers::SHIFT].map(move |m| (b, m)))+ .find(|((_, b), m)| crate::prefs::nav_mode(&app, *b, *m) == Some(crate::viewport::NavMode::Orbit))+ .map(|((p, _), m)| (p, m))+ .expect("the default preset orbits with the right or middle button");+ let ctx = egui::Context::default();+ let mut time = 0.0;+ let mut frame = |app: &mut crate::SolveApp, events: Vec<Event>| {+ time += 1.0 / 60.0;+ let events = std::iter::once(Event::ModifiersChanged(mods)).chain(events).collect();+ let raw = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0))),+ time: Some(time),+ focused: true,+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(raw, |ui| {+ let rect = ui.max_rect();+ app.viewport.rect = Some(rect);+ let resp = ui.interact(rect, ui.scope_id().with("model"), egui::Sense::click_and_drag());+ super::handle(app, ui, rect, &resp, super::NavCaps::MODEL);+ });+ out.textures_delta.clear();+ let commands = out.viewport_output.remove(&egui::ViewportId::ROOT).map(|v| v.commands).unwrap_or_default();+ commands.into_iter().filter_map(|c| if let ViewportCommand::CursorPosition(p) = c { Some(p) } else { None }).collect::<Vec<_>>()+ };+ let turn = |a: f64, b: f64| (b - a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI;+ let at = pos2(600.0, 300.0);+ frame(&mut app, vec![Event::PointerMoved(at)]);+ frame(&mut app, vec![Event::PointerButton { pos: at, button, pressed: true, modifiers: mods }]);+ let mut x = at.x;+ let mut step = 0.0;+ while x < 780.0 {+ x += 20.0;+ let before = app.cam.yaw;+ assert!(frame(&mut app, vec![Event::PointerMoved(pos2(x, 300.0))]).is_empty(), "no move inside the view ({x})");+ step = turn(before, app.cam.yaw);+ }+ assert!(step.abs() > 1e-4, "the drag turns the view");+ // Past the right edge: the cursor goes to the left edge.+ let before = app.cam.yaw;+ assert_eq!(frame(&mut app, vec![Event::PointerMoved(pos2(800.0, 300.0))]), vec![pos2(8.0, 300.0)]);+ assert!((turn(before, app.cam.yaw) - step).abs() < step.abs() * 0.01, "and the view turns on as usual");+ // A move the window had queued before the cursor moved: no second request.+ assert!(frame(&mut app, vec![Event::PointerMoved(pos2(806.0, 300.0))]).is_empty());+ // The pointer reports the jump plus 20 points more of the hand's motion.+ let before = app.cam.yaw;+ assert!(frame(&mut app, vec![Event::PointerMoved(pos2(34.0, 300.0))]).is_empty());+ let after = turn(before, app.cam.yaw);+ assert!((after - step).abs() < step.abs() * 0.01, "the jump doesn't turn the view: {after} vs {step}");+ assert_eq!(app.viewport.cursor_wrap, None);+ let before = app.cam.yaw;+ frame(&mut app, vec![Event::PointerMoved(pos2(54.0, 300.0))]);+ assert!((turn(before, app.cam.yaw) - step).abs() < step.abs() * 0.01, "and keeps turning the same way");+ frame(&mut app, vec![Event::PointerButton { pos: pos2(54.0, 300.0), button, pressed: false, modifiers: mods }]);+ frame(&mut app, vec![]);+ assert_eq!(app.viewport.cursor_wrap, None);+ // With the preference off, the same drag reaches the edge and the cursor stays there.+ app.preferences.orbit_cursor_wrap = false;+ frame(&mut app, vec![Event::PointerButton { pos: at, button, pressed: true, modifiers: mods }]);+ for x in [620.0, 700.0, 780.0, 800.0, 806.0] {+ assert!(frame(&mut app, vec![Event::PointerMoved(pos2(x, 300.0))]).is_empty(), "no cursor move with wrapping off ({x})");+ }+ assert_eq!(app.viewport.cursor_wrap, None);+ }+/// A device app's orbit turns pages that orbit and pans the others (a flat page, a sketch seen/// square-on), so the device still moves the view there without turning it.#[test]diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex 23a4798aaa..be77275487 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -1067,6 +1067,9 @@ preference_settings! {/// left drag with the mapping's keys does: letting go of Shift partway through a Shift+middle/// orbit doesn't turn it into a pan (#9557). Off: the keys held decide on every frame, as before.nav_drag_keeps_mode: bool = true, PAGE_NAVIGATION => check_tr("nav.drag_keeps_mode.label");+ /// An orbit drag that reaches the edge of the view moves the cursor to the opposite edge and+ /// keeps turning; false stops the drag at the edge of the screen, as before.+ orbit_cursor_wrap: bool = true, PAGE_NAVIGATION => check_tr("nav.orbit_cursor_wrap.label");/// View orientation widget: original signed axes (default) or compact cube.navigator_style: NavigatorStyle = NavigatorStyle::default(), PAGE_NAVIGATION;/// The custom view gizmo's colours: the cube's (themed) or the body's own (modeled).@@ -9577,6 +9580,24 @@ mod tests {}}+ #[test]+ fn orbit_cursor_wrap_defaults_on_and_can_be_turned_off() {+ let old: Prefs = serde_json::from_value(json!({"nav":"solidworks"})).unwrap();+ assert!(old.orbit_cursor_wrap, "saved preferences from before the option wrap");+ let mut h = crate::scenario::Harness::new();+ h.call("ui.prefs", json!({"open":"Navigation"}));+ h.step(&json!({"click":{"handle":"prefs:orbit_cursor_wrap"}})).unwrap();+ assert!(!h.app.preferences.orbit_cursor_wrap);+ h.call("ui.prefs", json!({"button":"apply"}));+ let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default());+ restored.load_prefs(&h.app.prefs());+ assert!(!restored.preferences.orbit_cursor_wrap);+ h.call("ui.prefs", json!({"button":"defaults"}));+ assert!(h.app.preferences.orbit_cursor_wrap);+ h.call("ui.prefs", json!({"orbit_cursor_wrap":false,"button":"apply"}));+ assert!(!h.app.preferences.orbit_cursor_wrap);+ }+#[test]fn free_orbit_defaults_off_and_follows_preferences_transactions() {let old: Prefs = serde_json::from_value(json!({"nav":"solidworks"})).unwrap();diff --git a/crates/ui-egui/src/prefs/navigation.rs b/crates/ui-egui/src/prefs/navigation.rsindex a015d60e2d..fdce6e39e4 100644--- a/crates/ui-egui/src/prefs/navigation.rs+++ b/crates/ui-egui/src/prefs/navigation.rs@@ -112,6 +112,8 @@ fn mouse(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {}let keeps = setting::nav_drag_keeps_mode(app, ui).backing_on_hover_text(crate::i18n::tr("nav.drag_keeps_mode.help"));crate::scenario::publish_target("prefs:nav_drag_keeps_mode", keeps.rect);+ let wrap = setting::orbit_cursor_wrap(app, ui).backing_on_hover_text(crate::i18n::tr("nav.orbit_cursor_wrap.help"));+ crate::scenario::publish_target("prefs:orbit_cursor_wrap", wrap.rect);setting::radial_context_menu(app, ui).backing_on_hover_text(crate::i18n::tr("prefs.navigation.radial_help"));let label = app.tr("Middle double-click");let width = ui_kit::ContentWidth::label(ui, label);diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex 92c183f713..020a50f357 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -217,6 +217,9 @@ pub struct ViewportState {pub orbit_pivot: Option<Vec3>,/// The orbit drag under way, summed from where it began (see [`crate::navigation::orbit`]).pub orbit_from: Option<crate::navigation::OrbitFrom>,+ /// An orbit drag moved the cursor to the view's other side: the jump, until the pointer+ /// reports it (see [`crate::navigation::wrap_cursor`]).+ pub(crate) cursor_wrap: Option<egui::Vec2>,/// Continuous orbit: the view turns about the vertical until the next click or key.pub spin: bool,/// The point continuous orbit turns about (Orbit around: origin or the cursor's model point),diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.mdindex 924a0a0cd9..65f8ea3b14 100644--- a/docs/book/src/guide/ui-tour.md+++ b/docs/book/src/guide/ui-tour.md@@ -85,6 +85,9 @@ view.in the default and Inventor presets. In every preset, Ctrl+left drag (Cmd on macOS) that startson empty space orbits; a Ctrl+click still adds to the selection. Shift+right-drag snaps to the nearest standard ordiagonal view; Shift does not request snapping when the preset already requires it to orbit.+ An orbit drag that reaches the edge of the view carries on: the cursor reappears at the opposite+ edge, so you can keep turning round the model without letting go (not on Wayland or in the browser).+ **Preferences › Navigation › Wrap the cursor while orbiting** turns this off.Enable **Preferences → Navigation → Free orbit** to rotate the mouse and 3D mouse continuouslythrough both poles, preserving roll. During an orbit drag, Shift snaps the view direction anddiff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 52393502d8..81d50a3e33 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -895,6 +895,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own- `navigator_texture` (`themed` (default): the custom view navigator in the cube's colours; `modeled`: in its body's own appearance and edge colour)- `offer_stand_up`- `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true)+- `orbit_cursor_wrap` (default true: an orbit drag that reaches the edge of the view moves the cursor to the opposite edge and keeps turning)- `orbit_reverse` (default false: Shift with two-finger scrolling orbits the other way)- `origin_plane_names` (`xyz` (default) or `top_front_right`: the browser, dialogs and lists call the origin planes Top, Front and Right; their ids, commands and saved designs keep XY, XZ and YZ)- `pan_reverse_x` (default false: horizontal scrolling pans the other way)