Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Pinch zoom: route Ctrl+wheel input to the camera (#8480) (#8539)

Colin Faulkingham81039a0e100c
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 37d2ecfbd9..13ea745578 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -918,17 +918,40 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
}
"ui.scroll" => {
let (Some(x), Some(y)) = (f("x"), f("y")) else { return err("missing x/y") };
- app.synthetic.push(egui::Event::PointerMoved(egui::pos2(x as f32, y as f32)));
// Mouse-wheel semantics (lines): zooms regardless of the trackpad pan
// preference, so scripts and agents keep working. Trackpads report points.
+ // `ctrl: true` replays a Ctrl+wheel pinch in points (#8480). An explicit `unit`
+ // overrides that choice; without ctrl the default remains a line wheel.
let speed = ctx.options(|o| o.input_options.line_scroll_speed).max(1.0);
- let lines = f("delta").unwrap_or(-100.0) / f64::from(speed);
- app.synthetic.push(egui::Event::MouseWheel {
- unit: egui::MouseWheelUnit::Line,
- delta: egui::vec2(0.0, lines as f32),
- modifiers: Default::default(),
- phase: egui::TouchPhase::Move,
- });
+ let points = f("delta").unwrap_or(-100.0);
+ let ctrl = b("ctrl");
+ let unit = match p.get("unit") {
+ Some(Value::String(unit)) if unit == "point" => egui::MouseWheelUnit::Point,
+ Some(Value::String(unit)) if unit == "line" => egui::MouseWheelUnit::Line,
+ Some(_) => return err("`unit` must be point or line"),
+ None if ctrl => egui::MouseWheelUnit::Point,
+ None => egui::MouseWheelUnit::Line,
+ };
+ let delta = match unit {
+ // A point wheel reaches the app as points; a line wheel is scaled up by the
+ // line scroll speed, so divide it out and both land on the same points.
+ egui::MouseWheelUnit::Line => points / f64::from(speed),
+ _ => points,
+ };
+ let (x, y, delta) = (x as f32, y as f32, delta as f32);
+ if !x.is_finite() || !y.is_finite() || !delta.is_finite() {
+ return err("x, y and delta must fit finite screen coordinates");
+ }
+ let modifiers = if ctrl { egui::Modifiers::CTRL } else { Default::default() };
+ let explicit = p.get("ctrl").is_some();
+ app.synthetic.push(egui::Event::PointerMoved(egui::pos2(x, y)));
+ if explicit {
+ app.synthetic.push(egui::Event::ModifiersChanged(modifiers));
+ }
+ app.synthetic.push(egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, delta), modifiers, phase: egui::TouchPhase::Move });
+ if explicit {
+ app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ }
ok(Value::Null)
}
"ui.key" => {
@@ -1273,6 +1296,79 @@ mod tests {
assert!(h.app.viewport.boxsel.is_none());
}
+ /// #8480: `ui.scroll` with `ctrl: true` replays a Ctrl+wheel pinch in points. Without
+ /// `ctrl` the wheel stays a line wheel on the mouse path.
+ #[test]
+ fn scroll_sends_a_native_pinch_with_ctrl() {
+ let mut app = SolveApp::new(Session::default(), Services::default());
+ let ctx = crate::fonts::test_context();
+ let (req, _) = ControlRequest::new("ui.scroll", json!({"x":200,"y":300,"delta":40,"ctrl":true}));
+ assert!(matches!(handle(&mut app, &ctx, &req), Outcome::Done(_)));
+ // The pointer event is delivered a frame before the wheel (one pointer event per frame).
+ let mut events = Vec::new();
+ for _ in 0..3 {
+ let mut raw = egui::RawInput::default();
+ app.raw_input_hook(&mut raw);
+ events.extend(raw.events);
+ }
+ let wheels: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ egui::Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, *modifiers)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(wheels.len(), 1, "one wheel event: {wheels:?}");
+ let (unit, delta, modifiers) = wheels[0];
+ assert_eq!(unit, egui::MouseWheelUnit::Point, "the pinch replay uses points");
+ assert!((delta.y - 40.0).abs() < 1e-6, "points pass through: {delta:?}");
+ assert!(modifiers.matches_any(egui::Modifiers::COMMAND), "Ctrl is held: {modifiers:?}");
+ let changes: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ egui::Event::ModifiersChanged(m) => Some(*m),
+ _ => None,
+ })
+ .collect();
+ assert!(changes.iter().any(|m| m.matches_any(egui::Modifiers::COMMAND)), "Ctrl is set for the wheel: {changes:?}");
+ assert_eq!(changes.last().copied(), Some(egui::Modifiers::NONE), "Ctrl is released after it: {changes:?}");
+ app.synthetic.clear();
+
+ let (req, _) = ControlRequest::new("ui.scroll", json!({"x":200,"y":300,"delta":40}));
+ assert!(matches!(handle(&mut app, &ctx, &req), Outcome::Done(_)));
+ let mut events = Vec::new();
+ for _ in 0..2 {
+ let mut raw = egui::RawInput::default();
+ app.raw_input_hook(&mut raw);
+ events.extend(raw.events);
+ }
+ let wheel = events.iter().find_map(|e| match e {
+ egui::Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, *modifiers)),
+ _ => None,
+ });
+ let (unit, delta, modifiers) = wheel.expect("a wheel event");
+ assert_eq!(unit, egui::MouseWheelUnit::Line, "without ctrl the wheel stays a mouse wheel");
+ assert!((delta.y * ctx.options(|o| o.input_options.line_scroll_speed) - 40.0).abs() < 1e-3, "lines land on the same points: {delta:?}");
+ assert!(!modifiers.matches_any(egui::Modifiers::COMMAND), "no modifier without ctrl");
+ assert!(app.synthetic.is_empty());
+ }
+
+ #[test]
+ fn scroll_rejects_invalid_input_without_queuing_events() {
+ let mut app = SolveApp::new(Session::default(), Services::default());
+ let ctx = crate::fonts::test_context();
+ for invalid in
+ [json!({"unit":"invalid"}), json!({"unit":42}), json!({"unit":null}), json!({"x":1e300}), json!({"y":-1e300}), json!({"delta":1e300})]
+ {
+ let mut params = json!({"x":200,"y":300,"delta":40,"ctrl":true});
+ params.as_object_mut().unwrap().extend(invalid.as_object().unwrap().clone());
+ let (req, _) = ControlRequest::new("ui.scroll", params.clone());
+ let Outcome::Done(reply) = handle(&mut app, &ctx, &req) else { panic!("not a scroll reply") };
+ assert_eq!(reply["ok"], false, "{params}: {reply}");
+ assert!(app.synthetic.is_empty(), "a rejected scroll must not queue input: {params}");
+ }
+ }
+
#[test]
fn touchpad_drag_positioning_releases_previous_motion_modifiers() {
let mut h = crate::scenario::Harness::new();
diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs
index 3939041915..07371432fe 100644
--- a/crates/ui-egui/src/navigation.rs
+++ b/crates/ui-egui/src/navigation.rs
@@ -234,15 +234,34 @@ pub(crate) fn immediate_wheel(
}
/// Combined pinch-to-zoom factor for one frame (1 = no pinch input).
-pub(crate) fn pinch_factor(input: &egui::InputState) -> f32 {
- input
- .events
- .iter()
- .filter_map(|event| {
- let egui::Event::Zoom(f) = event else { return None };
- (*f).is_finite().then_some(*f).filter(|f| *f > 0.0)
- })
- .fold(1.0, |acc, f| acc * f)
+///
+/// Some input paths deliver pinch as a zoom-modified wheel instead of `Event::Zoom`.
+/// Read the raw movement that [`immediate_wheel`] leaves to the zoom modifier, without
+/// replaying egui's smoothed zoom delta on later frames. Gesture boundaries carry no movement.
+pub(crate) fn pinch_factor(input: &egui::InputState, options: egui::InputOptions, page_height: f32) -> f32 {
+ let mut factor = 1.0;
+ for event in &input.events {
+ match event {
+ egui::Event::Zoom(f) => {
+ if f.is_finite() && *f > 0.0 {
+ factor *= f;
+ }
+ }
+ egui::Event::MouseWheel { unit, delta, modifiers, phase: egui::TouchPhase::Move } if modifiers.matches_any(options.zoom_modifier) => {
+ let points = match unit {
+ egui::MouseWheelUnit::Point => *delta,
+ egui::MouseWheelUnit::Line => *delta * options.line_scroll_speed,
+ egui::MouseWheelUnit::Page => *delta * page_height,
+ };
+ let f = (options.scroll_zoom_speed * (points.x + points.y)).exp();
+ if f.is_finite() && f > 0.0 {
+ factor *= f;
+ }
+ }
+ _ => {}
+ }
+ }
+ factor
}
/// Give this frame's wheel to the widget under the pointer that uses it itself (a value field
@@ -518,7 +537,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e
scroll
};
// Pinch-to-zoom (trackpad): direct manipulation, never smoothed.
- let pinch = ui.input(pinch_factor);
+ let pinch = ui.input(|i| pinch_factor(i, options, page_height));
let h = rect.height().max(1.0) as f64;
if inside && pinch != 1.0 {
app.viewport.orbit_free = None;
@@ -1091,7 +1110,7 @@ mod tests {
assert_eq!(events.last(), Some(&egui::Event::Zoom(1.1)));
let mut input = egui::InputState::default();
input.events = events;
- assert!((super::pinch_factor(&input) - 1.1).abs() < 1e-6);
+ assert!((super::pinch_factor(&input, egui::InputOptions::default(), 600.0) - 1.1).abs() < 1e-6);
}
#[test]
@@ -1666,6 +1685,144 @@ mod tests {
}
}
+ /// A zoom-modified wheel must reach the camera even though the ordinary wheel path skips it.
+ #[test]
+ fn native_ctrl_wheel_pinch_zooms_the_view() {
+ use egui::{Event, Modifiers, MouseWheelUnit, TouchPhase, 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 ctx = crate::fonts::test_context();
+ let mut time = 0.0;
+ let at = pos2(200.0, 300.0);
+ let mut frame = |app: &mut crate::SolveApp, events: Vec<Event>| {
+ time += 1.0 / 60.0;
+ 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.id().with("native-pinch"), egui::Sense::click_and_drag());
+ super::handle(app, ui, rect, &resp, super::NavCaps::MODEL);
+ });
+ out.textures_delta.clear();
+ };
+ frame(&mut app, vec![Event::PointerMoved(at)]);
+ let before = app.cam;
+ frame(
+ &mut app,
+ vec![
+ Event::ModifiersChanged(Modifiers::CTRL),
+ Event::PointerMoved(at),
+ Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, 50.0), modifiers: Modifiers::CTRL, phase: TouchPhase::Move },
+ ],
+ );
+ assert!(app.cam.distance < before.distance, "a positive Ctrl+wheel pinch zooms in: {} -> {}", before.distance, app.cam.distance);
+ // Pinch uses egui's zoom speed; the unmodified wheel still uses the wheel path.
+ let mut s = solidcraft_engine::Session::default();
+ s.execute("solid.box", &serde_json::json!({"length":40,"width":30,"height":20})).unwrap();
+ let mut plain = crate::SolveApp::new(s, crate::Services::default());
+ frame(&mut plain, vec![Event::PointerMoved(at)]);
+ let plain_before = plain.cam;
+ frame(
+ &mut plain,
+ vec![
+ Event::PointerMoved(at),
+ Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, 50.0), modifiers: Modifiers::NONE, phase: TouchPhase::Move },
+ ],
+ );
+ let pinched = before.distance / app.cam.distance;
+ let expected = (0.005f64 * 50.0).exp();
+ assert!((pinched / expected - 1.0).abs() < 0.02, "the pinch factor is exp(scroll_zoom_speed * delta) = {expected:.3}x, got {pinched:.3}x");
+ let wheeled = plain_before.distance / plain.cam.distance;
+ assert!(wheeled > 1.0, "the bare wheel still zooms in on its own path: {wheeled:.3}x");
+ }
+
+ #[test]
+ fn ctrl_wheel_replay_zooms_once_in_the_viewport() {
+ use serde_json::json;
+ for preset in ["fusion", "touchpad"] {
+ for smooth in [false, true] {
+ let mut h = crate::scenario::Harness::new();
+ h.app.preferences.nav = preset.into();
+ h.app.preferences.smooth_wheel_zoom = smooth;
+ h.app.preferences.zoom_to_cursor = false;
+ h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap();
+ h.step(&json!({"call":"ui.camera", "params":{"target":[20,15,10],"distance":100}})).unwrap();
+ let at = h.app.viewport.rect.unwrap().center();
+ let before = h.app.cam;
+ if preset == "fusion" && !smooth {
+ h.step(&json!({"shot":"initial"})).unwrap();
+ }
+ h.step(&json!({"call":"ui.scroll", "params":{"x":at.x,"y":at.y,"delta":80,"ctrl":true}})).unwrap();
+ if preset == "fusion" && !smooth {
+ h.step(&json!({"shot":"pinch-result"})).unwrap();
+ }
+ let after = h.app.cam;
+ let expected = before.distance * (-0.4f64).exp();
+ assert!(
+ (after.distance - expected).abs() < 1e-5,
+ "{preset}, smooth={smooth}: {} -> {}, expected {expected}",
+ before.distance,
+ after.distance
+ );
+ assert_eq!(after.target, before.target, "a centred pinch must not pan");
+ assert_eq!(after.back(), before.back(), "a pinch must not orbit");
+ h.frames(90);
+ assert_eq!(h.app.cam, after, "a pinch must not replay egui's smoothing tail");
+ h.step(&json!({"call":"ui.scroll", "params":{"x":at.x,"y":at.y,"delta":-80,"ctrl":true}})).unwrap();
+ assert!((h.app.cam.distance - before.distance).abs() < 1e-5, "the opposite pinch restores the scale");
+ let restored = h.app.cam;
+ h.step(&json!({"call":"ui.scroll", "params":{"x":-20,"y":-20,"delta":80,"ctrl":true}})).unwrap();
+ assert_eq!(h.app.cam, restored, "a pinch outside the viewport must not zoom it");
+ }
+ }
+ }
+
+ #[test]
+ fn pinch_factor_ignores_wheel_phase_markers() {
+ for phase in [egui::TouchPhase::Start, egui::TouchPhase::End, egui::TouchPhase::Cancel] {
+ let mut input = egui::InputState::default();
+ input.events = vec![egui::Event::MouseWheel {
+ unit: egui::MouseWheelUnit::Point,
+ delta: egui::vec2(0.0, 40.0),
+ modifiers: egui::Modifiers::CTRL,
+ phase,
+ }];
+ assert_eq!(super::pinch_factor(&input, egui::InputOptions::default(), 600.0), 1.0, "{phase:?} is a gesture boundary, not movement");
+ }
+ }
+
+ /// The pinch factor reads native Ctrl+wheel pinches in every wheel unit, scaled the way egui
+ /// scales them, and leaves wheels without the zoom modifier to [`immediate_wheel`].
+ #[test]
+ fn pinch_factor_reads_native_ctrl_wheel_in_every_unit() {
+ use egui::{Event, Modifiers, MouseWheelUnit, TouchPhase, vec2};
+ let options = egui::InputOptions::default();
+ let factor = |events: Vec<Event>| {
+ let mut input = egui::InputState::default();
+ input.events = events;
+ super::pinch_factor(&input, options, 600.0)
+ };
+ let wheel = |unit, delta, modifiers| Event::MouseWheel { unit, delta, modifiers, phase: TouchPhase::Move };
+ let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
+ let point = factor(vec![wheel(MouseWheelUnit::Point, vec2(0.0, 40.0), Modifiers::CTRL)]);
+ assert!(close(point, (options.scroll_zoom_speed * 40.0).exp()), "point pinch {point}");
+ let line = factor(vec![wheel(MouseWheelUnit::Line, vec2(0.0, 1.0), Modifiers::CTRL)]);
+ assert!(close(line, (options.scroll_zoom_speed * options.line_scroll_speed).exp()), "line pinch {line}");
+ let page = factor(vec![wheel(MouseWheelUnit::Page, vec2(0.0, 0.5), Modifiers::CTRL)]);
+ assert!(close(page, (options.scroll_zoom_speed * 300.0).exp()), "page pinch {page}");
+ assert_eq!(factor(vec![wheel(MouseWheelUnit::Point, vec2(0.0, 40.0), Modifiers::NONE)]), 1.0, "a bare wheel belongs to the scroll path");
+ assert_eq!(factor(vec![Event::Zoom(1.25)]), 1.25);
+ let both = factor(vec![Event::Zoom(1.25), wheel(MouseWheelUnit::Point, vec2(0.0, 40.0), Modifiers::CTRL)]);
+ assert!(close(both, 1.25 * (options.scroll_zoom_speed * 40.0).exp()), "zoom events and pinch wheel combine {both}");
+ }
+
/// The 3D mouse pans and zooms a flat page with the cap and never turns it, as the mouse
/// does there; pages that orbit turn with it (#1336).
#[test]
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 3101ab0354..d64f438c04 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -307,7 +307,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
| `ui.pick` | `pixels?: [[x,y]…]`, `rays?: [{origin, dir}…]`, `frame?: "window"\|"model"`, `width?`, `height?`, `edges?` (default true), `edge_px?` (default 6), `all?`, `include_ghosted?` | read-only geometry under each pixel or ray (#6304): one entry per input, `null` where nothing is hit — body, face index, exact world `point` and outward `normal`, `depth`, `occurrence`/`component` for placed parts, `edge`/`vertex` within `edge_px` of a pixel, `section_cap: true` on a cut face. `window` pixels are physical pixels of a window screenshot; `model` pixels are pixels of a `ui.render` of `width`×`height` (default 960×600), so it works headless. As `view.pick` through `engine.execute`/`engine.batch`. See `crates/ui-egui/src/view_pick.rs` |
| `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:<command id>` (the button alone: `button:<command id>`; a drop-down row: `dropdown:<command id>`, highlighted `dropdown_hot:<command id>`, its pin `dropdown_pin:<command id>`; Customize Toolbar's check boxes `customize:<command id>`), ribbon tabs `tab:<name>` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL, WELDMENTS; contextual SKETCH; workspace RENDER), panel labels `panel:<tab>:<panel>` (also `ribbon:section:<TAB>:<SECTION>`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row:<label>` and fold arrows `fold:<label>`, manipulator handles; signed-axis tips `axis_view:z`, `axis_view:-y`; optional cube facets `navigation_cube:top`, `navigation_cube:top_front_right`, controls `navigation_cube:control:home` (and other actions), plus signed-axis aliases for visible cube faces; Preferences navigator picker `prefs:navigator`, options `prefs:navigator:Signed axes` and `prefs:navigator:Cube`; in the Motion Study dialog, where the chart puts its first and last step `motion:chart_start` and `motion:chart_end`, the Check collisions button `motion:check` and each collision found `motion:collision:<n>` |
| `ui.editFeature` | `feature` (id or name) | what double-clicking a timeline item does: rolls back to it and opens its dialog filled in (sketches open in sketch mode) |
-| `ui.scroll` | `x`, `y`, `delta?` | wheel zoom at the cursor |
+| `ui.scroll` | `x`, `y`, `delta?`, `ctrl?`, `unit?`: `point` \| `line` | wheel zoom at the cursor. `ctrl: true` replays a Ctrl+wheel pinch (Ctrl held and the wheel in points); `unit` selects the wheel unit and defaults to points with `ctrl` and lines without it. `delta` is in points either way. Invalid units or coordinates outside the finite screen-coordinate range are rejected before queuing input |
| `ui.key` | `key` (egui key name, `Enter`, `Escape`…), `cmd?`, `ctrl?`, `shift?`, `alt?`, `pressed?` | By default, press and release, then release modifiers. With `pressed: true` or `false`, send only that edge; modifiers remain as given. `cmd` retains the legacy primary-modifier alias unless `ctrl` is explicit: `cmd:true, ctrl:false` sends physical Command, and both true sends Control+Command. `ui.move` can change modifiers between edges. |
| `ui.text` | `text` | typed text |
| `ui.screenshot` | `path?` | PNG of the window (needs a presented frame: a minimised or fully covered window answers at once with `hidden: true` and an error; use `ui.render`) |