Skip to content

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

Navigation bridge: a device's own app moves the view (#6094)

MAKAO30f951ecf997
diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs
index 6c8a10b715..f97ff09941 100644
--- a/apps/solidcraft/src/main.rs
+++ b/apps/solidcraft/src/main.rs
@@ -28,6 +28,7 @@ mod native_crash;
mod native_frame;
#[cfg(target_os = "macos")]
mod native_menu;
+mod nav_bridge;
#[cfg(target_os = "macos")]
mod open_documents;
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
@@ -87,6 +88,8 @@ struct App {
space_mouse: space_mouse::SpaceMouse,
#[cfg(target_os = "macos")]
native_menu: Option<native_menu::NativeMenu>,
+ /// A device's own app moving the view (Preferences › Navigation, off by default).
+ nav_bridge: nav_bridge::NavBridge,
}
impl eframe::App for App {
@@ -145,6 +148,8 @@ impl eframe::App for App {
if !self.solve.file_picker_busy() {
self.space_mouse.tick(&mut self.solve, ctx);
}
+ // Every frame, so switching the bridge off reaches the reader while a picker is open too.
+ self.nav_bridge.tick(&mut self.solve, ctx);
if self.solve.quit_requested {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
@@ -933,8 +938,9 @@ fn main() -> eframe::Result {
if !notes.is_empty() {
app.set_status(notes.join(" "), true);
}
+ let nav_bridge = nav_bridge::NavBridge::start(&cc.egui_ctx);
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
- let space_mouse = space_mouse::SpaceMouse::start(&cc.egui_ctx);
+ let space_mouse = space_mouse::SpaceMouse::start(&cc.egui_ctx, nav_bridge.claim());
#[cfg(target_os = "macos")]
let native_menu = match native_menu::NativeMenu::new(&app, &cc.egui_ctx) {
Ok(menu) => Some(menu),
@@ -959,6 +965,7 @@ fn main() -> eframe::Result {
space_mouse,
#[cfg(target_os = "macos")]
native_menu,
+ nav_bridge,
}))
}),
);
diff --git a/apps/solidcraft/src/nav_bridge.rs b/apps/solidcraft/src/nav_bridge.rs
new file mode 100644
index 0000000000..9e6fd95bfd
--- /dev/null
+++ b/apps/solidcraft/src/nav_bridge.rs
@@ -0,0 +1,463 @@
+//! The navigation bridge: a 3D input device's own program (a homemade device's driver app) moves
+//! the view over a loopback connection, the way a 3D mouse driver hands its axes to the programs
+//! it supports, so the device emulates no mouse and the pointer stays the user's.
+//!
+//! The device app listens on `127.0.0.1:<port>`; with Preferences › Navigation › "Navigate with a
+//! device app" on (off by default), SolidCraft connects to it, says hello and reads one JSON
+//! object per line (docs/3d-mouse.md). The reader thread only sums the motion; the egui thread
+//! hands it to the view once per frame (`space_mouse::bridge_frame`). A device the app says it
+//! reads is left to it by the 3D mouse reader ([`Claim`]), so the view doesn't move twice.
+
+use std::io::{ErrorKind, Read, Write};
+use std::net::{Ipv4Addr, SocketAddr, TcpStream};
+use std::sync::{Arc, Mutex, MutexGuard};
+use std::time::Duration;
+
+use egui::Context;
+use serde_json::{Value, json};
+use solidcraft_ui_egui::SolveApp;
+use solidcraft_ui_egui::space_mouse::{BRIDGE_VIEWS, BridgeMotion, bridge_frame, bridge_step};
+
+/// The longest line read; a longer one is skipped to its end.
+const MAX_LINE: usize = 4096;
+/// Standard views waiting for the next frame; past this many, more are a flood and dropped.
+const MAX_VIEWS: usize = 8;
+/// The longest name a device app may give for itself or its device, in characters.
+const MAX_NAME: usize = 64;
+/// How long a connection attempt waits.
+const CONNECT_TIMEOUT: Duration = Duration::from_millis(500);
+/// How long a read waits for data before the reader looks at the preferences again.
+const READ_WAKE: Duration = Duration::from_millis(250);
+/// The wait before connecting again when no device app answered or one went away.
+const RETRY_AFTER: Duration = Duration::from_secs(1);
+/// In zoom mode, a motion of this many points along Y is one zoom step: with 8 % a step, the 1 %
+/// a point that a zoom drag moves.
+const POINTS_PER_ZOOM_STEP: f64 = 8.0;
+
+/// What the device's motion drives, as the device app last said (`mode`).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+enum Mode {
+ #[default]
+ Orbit,
+ Pan,
+ Zoom,
+}
+
+/// What the reader thread and the egui thread share.
+#[derive(Debug, Default)]
+struct Shared {
+ /// The port the preferences ask to connect to; none while the bridge is off.
+ wanted: Option<u16>,
+ /// The device app connected, by the name it gave ("?" until it gives one).
+ connected: Option<String>,
+ /// The device the connected app reads, as it named it: the 3D mouse reader leaves that one alone.
+ device: Option<String>,
+ /// Motion since the egui thread last took it.
+ motion: BridgeMotion,
+ /// Standard views asked for since then.
+ views: Vec<String>,
+}
+
+fn lock(shared: &Mutex<Shared>) -> Option<MutexGuard<'_, Shared>> {
+ shared.lock().ok()
+}
+
+/// A name a device app gave, without control characters and cut to [`MAX_NAME`]; none when empty.
+fn name(value: Option<&Value>) -> Option<String> {
+ let name: String = value?.as_str()?.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect();
+ let name = name.trim();
+ (!name.is_empty()).then(|| name.to_string())
+}
+
+/// A number of a message, finite and in range; none when it isn't one.
+fn number(msg: &Value, key: &str) -> f64 {
+ bridge_step(msg.get(key).and_then(Value::as_f64).unwrap_or(0.0))
+}
+
+/// Takes one line from the device app into `shared`. Lines that aren't a message this version
+/// knows are ignored. Returns whether the view has something new to show.
+fn consume(line: &[u8], mode: &mut Mode, shared: &mut Shared) -> bool {
+ let Ok(msg) = serde_json::from_slice::<Value>(line) else { return false };
+ let add = |shared: &mut Shared, motion: BridgeMotion| {
+ shared.motion = shared.motion.plus(motion);
+ !motion.is_still()
+ };
+ match msg.get("t").and_then(Value::as_str) {
+ Some("axis") => {
+ let (x, y) = (number(&msg, "x"), number(&msg, "y"));
+ let motion = match mode {
+ Mode::Orbit => BridgeMotion { orbit: [x, y], ..Default::default() },
+ Mode::Pan => BridgeMotion { pan: [x, y], ..Default::default() },
+ // Up zooms in, as a zoom drag does.
+ Mode::Zoom => BridgeMotion { zoom: -y / POINTS_PER_ZOOM_STEP, ..Default::default() },
+ };
+ add(shared, motion)
+ }
+ Some("zoom") => add(shared, BridgeMotion { zoom: number(&msg, "d"), ..Default::default() }),
+ Some("mode") => {
+ let on = msg.get("on").and_then(Value::as_bool).unwrap_or(false);
+ *mode = match msg.get("mode").and_then(Value::as_str) {
+ Some("pan") if on => Mode::Pan,
+ Some("zoom") if on => Mode::Zoom,
+ _ => Mode::Orbit,
+ };
+ false
+ }
+ Some("view") => {
+ let view = msg.get("name").and_then(Value::as_str).and_then(|n| BRIDGE_VIEWS.iter().find(|v| **v == n));
+ match view {
+ Some(view) if shared.views.len() < MAX_VIEWS => {
+ shared.views.push((*view).to_string());
+ true
+ }
+ _ => false,
+ }
+ }
+ Some("hello") => {
+ shared.connected = name(msg.get("server")).or_else(|| shared.connected.clone());
+ shared.device = name(msg.get("device"));
+ true
+ }
+ _ => false,
+ }
+}
+
+/// Splits what arrives into lines, across reads. A line longer than [`MAX_LINE`] is dropped up to
+/// its newline, so a peer that never sends one can't make the reader hold more than that.
+#[derive(Default)]
+struct Lines {
+ line: Vec<u8>,
+ skipping: bool,
+}
+
+impl Lines {
+ fn feed(&mut self, mut data: &[u8], mut each: impl FnMut(&[u8])) {
+ while !data.is_empty() {
+ let end = data.iter().position(|b| *b == b'\n');
+ let (part, rest) = match end {
+ Some(i) => (data.get(..i).unwrap_or_default(), data.get(i + 1..).unwrap_or_default()),
+ None => (data, &[][..]),
+ };
+ if !self.skipping {
+ let room = (MAX_LINE + 1).saturating_sub(self.line.len());
+ self.line.extend_from_slice(part.get(..room.min(part.len())).unwrap_or_default());
+ if self.line.len() > MAX_LINE {
+ self.line.clear();
+ self.skipping = true;
+ }
+ }
+ if end.is_some() {
+ if !self.skipping {
+ each(self.line.strip_suffix(b"\r").unwrap_or(&self.line));
+ }
+ self.line.clear();
+ self.skipping = false;
+ }
+ data = rest;
+ }
+ }
+}
+
+/// What SolidCraft says first, so the device app knows which program it is driving.
+fn hello() -> Value {
+ json!({"t": "hello", "app": "solidcraft", "version": env!("CARGO_PKG_VERSION")})
+}
+
+/// Reads one connection until the device app closes it, it fails, or the preferences no longer
+/// ask for this port; then forgets what it had.
+fn serve(mut stream: TcpStream, port: u16, ctx: &Context, shared: &Mutex<Shared>) {
+ // Without a read timeout the reader couldn't notice the bridge being switched off.
+ if stream.set_read_timeout(Some(READ_WAKE)).is_err() || writeln!(stream, "{}", hello()).is_err() {
+ return;
+ }
+ let _ = stream.set_nodelay(true);
+ log::info!("navigation bridge: connected to 127.0.0.1:{port}");
+ if let Some(mut shared) = lock(shared) {
+ shared.connected = Some("?".into());
+ }
+ ctx.request_repaint();
+ let (mut lines, mut mode) = (Lines::default(), Mode::default());
+ let mut chunk = [0_u8; 4096];
+ while lock(shared).is_some_and(|shared| shared.wanted == Some(port)) {
+ match stream.read(&mut chunk) {
+ Ok(0) => break,
+ Ok(size) => {
+ let mut news = false;
+ if let Some(mut shared) = lock(shared) {
+ lines.feed(chunk.get(..size).unwrap_or_default(), |line| news |= consume(line, &mut mode, &mut shared));
+ }
+ if news {
+ ctx.request_repaint();
+ }
+ }
+ Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted) => {}
+ Err(error) => {
+ log::info!("navigation bridge: connection lost: {error}");
+ break;
+ }
+ }
+ }
+ if let Some(mut shared) = lock(shared) {
+ *shared = Shared { wanted: shared.wanted, ..Shared::default() };
+ }
+ ctx.request_repaint();
+}
+
+/// Connects to the device app while the preferences ask for it, again whenever it goes away.
+fn reader(ctx: Context, shared: Arc<Mutex<Shared>>) {
+ loop {
+ let Some(port) = lock(&shared).and_then(|shared| shared.wanted) else {
+ std::thread::sleep(READ_WAKE);
+ continue;
+ };
+ if let Ok(stream) = TcpStream::connect_timeout(&SocketAddr::from((Ipv4Addr::LOCALHOST, port)), CONNECT_TIMEOUT) {
+ serve(stream, port, &ctx, &shared);
+ }
+ std::thread::sleep(RETRY_AFTER);
+ }
+}
+
+/// Which 3D mouse the connected device app reads, for the 3D mouse reader to leave alone. Only
+/// the Windows and macOS readers know a device's strings to compare.
+#[derive(Clone)]
+#[cfg_attr(not(any(target_os = "windows", target_os = "macos")), allow(dead_code))]
+pub struct Claim(Arc<Mutex<Shared>>);
+
+#[cfg_attr(not(any(target_os = "windows", target_os = "macos")), allow(dead_code))]
+impl Claim {
+ /// Whether a device with these manufacturer and product strings is the one the connected
+ /// device app reads (its name appears in one, ignoring case).
+ pub fn claims(&self, strings: &[String]) -> bool {
+ let Some(device) = lock(&self.0).and_then(|shared| shared.device.clone()) else { return false };
+ let device = device.to_lowercase();
+ strings.iter().any(|s| s.to_lowercase().contains(&device))
+ }
+}
+
+pub struct NavBridge {
+ shared: Arc<Mutex<Shared>>,
+}
+
+impl NavBridge {
+ pub fn start(ctx: &Context) -> Self {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let (worker_ctx, worker_state) = (ctx.clone(), Arc::clone(&shared));
+ if let Err(error) = std::thread::Builder::new().name("solidcraft-nav-bridge".into()).spawn(move || reader(worker_ctx, worker_state)) {
+ log::warn!("navigation bridge: reader could not start: {error}");
+ }
+ Self { shared }
+ }
+
+ #[cfg_attr(not(any(target_os = "windows", target_os = "macos")), allow(dead_code))]
+ pub fn claim(&self) -> Claim {
+ Claim(Arc::clone(&self.shared))
+ }
+
+ /// Each frame: passes the preferences to the reader, and the motion and views since the last
+ /// frame to the view. Motion that arrived while the window had no focus is dropped with it.
+ pub fn tick(&mut self, app: &mut SolveApp, ctx: &Context) {
+ let wanted = Some(app.preferences.nav_bridge_port).filter(|port| app.preferences.nav_bridge_enabled && *port != 0);
+ let Some((motion, views, connected)) = lock(&self.shared).map(|mut shared| {
+ shared.wanted = wanted;
+ (std::mem::take(&mut shared.motion), std::mem::take(&mut shared.views), shared.connected.clone())
+ }) else {
+ return;
+ };
+ app.space_mouse.bridge = connected.filter(|_| wanted.is_some());
+ if !motion.is_still() || !views.is_empty() {
+ bridge_frame(app, ctx, motion, &views);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{BufRead, BufReader};
+ use std::net::TcpListener;
+ use std::time::Instant;
+
+ fn feed(shared: &mut Shared, mode: &mut Mode, text: &str) -> bool {
+ let mut news = false;
+ Lines::default().feed(text.as_bytes(), |line| news |= consume(line, mode, shared));
+ news
+ }
+
+ #[test]
+ fn axis_motion_orbits_pans_or_zooms_as_the_mode_says() {
+ let (mut shared, mut mode) = (Shared::default(), Mode::default());
+ assert!(feed(&mut shared, &mut mode, "{\"t\":\"axis\",\"x\":3,\"y\":-2}\n{\"t\":\"axis\",\"x\":1.5,\"y\":0}\n"));
+ assert_eq!(shared.motion, BridgeMotion { orbit: [4.5, -2.0], ..Default::default() });
+ feed(&mut shared, &mut mode, "{\"t\":\"mode\",\"mode\":\"pan\",\"on\":true}\n{\"t\":\"axis\",\"x\":5,\"y\":6}\n");
+ assert_eq!(mode, Mode::Pan);
+ assert_eq!(shared.motion.pan, [5.0, 6.0]);
+ feed(&mut shared, &mut mode, "{\"t\":\"mode\",\"mode\":\"zoom\",\"on\":true}\n{\"t\":\"axis\",\"x\":0,\"y\":-16}\n");
+ assert_eq!(shared.motion.zoom, 2.0, "up zooms in, 8 points a step");
+ // Off, whichever mode it names, is back to orbit.
+ feed(&mut shared, &mut mode, "{\"t\":\"mode\",\"mode\":\"pan\",\"on\":false}\n");
+ assert_eq!(mode, Mode::Orbit);
+ // The ring's steps add up with the zoom mode's.
+ feed(&mut shared, &mut mode, "{\"t\":\"zoom\",\"d\":-0.5}\n");
+ assert_eq!(shared.motion.zoom, 1.5);
+ }
+
+ #[test]
+ fn views_are_queued_by_their_known_names_only() {
+ let (mut shared, mut mode) = (Shared::default(), Mode::default());
+ assert!(feed(&mut shared, &mut mode, "{\"t\":\"view\",\"name\":\"iso\"}\n{\"t\":\"view\",\"name\":\"fit\"}\n"));
+ assert!(!feed(&mut shared, &mut mode, "{\"t\":\"view\",\"name\":\"ISO\"}\n{\"t\":\"view\",\"name\":\"../etc\"}\n{\"t\":\"view\"}\n"));
+ assert_eq!(shared.views, ["iso", "fit"]);
+ let flood = "{\"t\":\"view\",\"name\":\"top\"}\n".repeat(100);
+ feed(&mut shared, &mut mode, &flood);
+ assert_eq!(shared.views.len(), MAX_VIEWS);
+ }
+
+ #[test]
+ fn hostile_lines_never_move_the_view_out_of_range() {
+ let (mut shared, mut mode) = (Shared::default(), Mode::default());
+ let lines = [
+ "not json",
+ "{\"t\":\"axis\",\"x\":\"5\",\"y\":null}",
+ "{\"t\":\"axis\",\"x\":1e308,\"y\":-1e308}",
+ "{\"t\":\"axis\",\"x\":1e999}",
+ "{\"t\":\"zoom\",\"d\":[1]}",
+ "{\"t\":42}",
+ "[1,2,3]",
+ "{\"t\":\"mode\",\"mode\":{\"x\":1},\"on\":\"yes\"}",
+ "\u{0}\u{1}\u{2}",
+ ];
+ for line in lines {
+ Lines::default().feed(format!("{line}\n").as_bytes(), |l| {
+ consume(l, &mut mode, &mut shared);
+ });
+ }
+ let limit = solidcraft_ui_egui::space_mouse::BRIDGE_MAX_STEP;
+ let values = shared.motion.orbit.into_iter().chain(shared.motion.pan).chain([shared.motion.zoom]);
+ for value in values {
+ assert!(value.is_finite() && value.abs() <= limit, "{value}");
+ }
+ assert_eq!(mode, Mode::Orbit);
+ // Invalid UTF-8 is no message either.
+ assert!(!consume(&[0xff, 0xfe, b'{', b'}'], &mut mode, &mut shared));
+ }
+
+ #[test]
+ fn lines_split_across_reads_and_long_ones_are_skipped_to_their_end() {
+ let mut got = Vec::new();
+ let mut lines = Lines::default();
+ for part in ["{\"t\":", "\"zoom\"}\r\n{\"a\"", ":1}\n"] {
+ lines.feed(part.as_bytes(), |line| got.push(String::from_utf8_lossy(line).to_string()));
+ }
+ assert_eq!(got, ["{\"t\":\"zoom\"}", "{\"a\":1}"]);
+ got.clear();
+ let long = vec![b'x'; MAX_LINE * 3];
+ lines.feed(&long, |line| got.push(String::from_utf8_lossy(line).to_string()));
+ lines.feed(&long, |line| got.push(String::from_utf8_lossy(line).to_string()));
+ assert!(lines.line.len() <= MAX_LINE + 1, "never holds more than one line");
+ lines.feed(b"tail\nnext\n", |line| got.push(String::from_utf8_lossy(line).to_string()));
+ assert_eq!(got, ["next"], "the long line is dropped to its newline, the next one read");
+ }
+
+ #[test]
+ fn the_device_app_names_itself_and_the_device_it_leaves_alone() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let claim = Claim(Arc::clone(&shared));
+ let strings = ["STMicroelectronics".to_string(), "MAKMOUSE 3D".to_string()];
+ assert!(!claim.claims(&strings), "nothing is claimed before an app says so");
+ let mut mode = Mode::default();
+ if let Ok(mut shared) = shared.lock() {
+ let hello = format!("{{\"t\":\"hello\",\"server\":\"Dev\\u0007App {}\",\"device\":\"makmouse\"}}\n", "x".repeat(200));
+ feed(&mut shared, &mut mode, &hello);
+ assert_eq!(shared.connected.as_deref().map(|n| n.chars().count()), Some(MAX_NAME));
+ assert!(shared.connected.as_deref().is_some_and(|n| n.starts_with("DevApp")));
+ }
+ assert!(claim.claims(&strings), "the name matches ignoring case");
+ assert!(!claim.claims(&["3Dconnexion".to_string(), "SpaceMouse Compact".to_string()]), "another 3D mouse stays the reader's");
+ }
+
+ /// Waits until `check` holds, or fails after a few seconds.
+ fn wait_for(what: &str, mut check: impl FnMut() -> bool) {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while !check() {
+ assert!(Instant::now() < deadline, "timed out waiting for {what}");
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ }
+
+ #[test]
+ fn a_connection_says_hello_reads_the_stream_and_ends_when_the_bridge_is_switched_off() {
+ let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let shared = Arc::new(Mutex::new(Shared { wanted: Some(port), ..Default::default() }));
+ let client = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap();
+ let (mut server, _) = listener.accept().unwrap();
+ let worker = {
+ let shared = Arc::clone(&shared);
+ std::thread::spawn(move || serve(client, port, &Context::default(), &shared))
+ };
+ let mut hello_line = String::new();
+ BufReader::new(server.try_clone().unwrap()).read_line(&mut hello_line).unwrap();
+ let hello: Value = serde_json::from_str(&hello_line).unwrap();
+ assert_eq!((hello["t"].as_str(), hello["app"].as_str()), (Some("hello"), Some("solidcraft")));
+ server
+ .write_all(b"{\"t\":\"hello\",\"server\":\"MAKMOUSE\",\"device\":\"MAKMOUSE\"}\n{\"t\":\"axis\",\"x\":2,\"y\":1}\n{\"t\":\"view\",\"name\":\"top\"}\n")
+ .unwrap();
+ wait_for("the stream", || shared.lock().is_ok_and(|s| s.motion.orbit == [2.0, 1.0] && s.views == ["top"]));
+ assert_eq!(shared.lock().unwrap().connected.as_deref(), Some("MAKMOUSE"));
+ // Switched off: the connection ends and what it had is forgotten.
+ shared.lock().unwrap().wanted = None;
+ worker.join().unwrap();
+ let after = shared.lock().unwrap();
+ assert!(after.connected.is_none() && after.device.is_none() && after.motion.is_still() && after.views.is_empty());
+ }
+
+ #[test]
+ fn a_closed_connection_forgets_the_app() {
+ let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let shared = Arc::new(Mutex::new(Shared { wanted: Some(port), ..Default::default() }));
+ let client = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap();
+ let (server, _) = listener.accept().unwrap();
+ let worker = {
+ let shared = Arc::clone(&shared);
+ std::thread::spawn(move || serve(client, port, &Context::default(), &shared))
+ };
+ wait_for("the connection", || shared.lock().is_ok_and(|s| s.connected.is_some()));
+ drop(server);
+ worker.join().unwrap();
+ let after = shared.lock().unwrap();
+ assert_eq!((after.connected.as_deref(), after.wanted), (None, Some(port)), "still wanted, so the reader connects again");
+ }
+
+ #[test]
+ fn each_frame_hands_the_view_the_motion_and_passes_the_preferences_on() {
+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default());
+ app.home.open = false;
+ let ctx = Context::default();
+ let _ = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |_| {});
+ let mut bridge = NavBridge { shared: Arc::new(Mutex::new(Shared::default())) };
+ let queue = |bridge: &NavBridge| {
+ let mut shared = bridge.shared.lock().unwrap();
+ shared.connected = Some("MAKMOUSE".into());
+ shared.motion = BridgeMotion { orbit: [10.0, 0.0], ..Default::default() };
+ };
+ // Off (the default): nothing is wanted, nothing reaches the view.
+ queue(&bridge);
+ bridge.tick(&mut app, &ctx);
+ assert_eq!(bridge.shared.lock().unwrap().wanted, None);
+ assert!(app.viewport.bridge_motion.is_none() && app.space_mouse.bridge.is_none());
+ // On: the port is passed to the reader and the motion to the view, once.
+ app.preferences.nav_bridge_enabled = true;
+ app.preferences.nav_bridge_port = 9123;
+ queue(&bridge);
+ bridge.tick(&mut app, &ctx);
+ assert_eq!(bridge.shared.lock().unwrap().wanted, Some(9123));
+ assert_eq!(app.space_mouse.bridge.as_deref(), Some("MAKMOUSE"));
+ assert_eq!(app.viewport.bridge_motion.map(|m| m.orbit), Some([10.0, 0.0]));
+ assert!(bridge.shared.lock().unwrap().motion.is_still(), "taken, not handed over twice");
+ // Port 0 is no port.
+ app.preferences.nav_bridge_port = 0;
+ bridge.tick(&mut app, &ctx);
+ assert_eq!(bridge.shared.lock().unwrap().wanted, None);
+ }
+}
diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs
index 2951dca048..af7cefd642 100644
--- a/apps/solidcraft/src/space_mouse.rs
+++ b/apps/solidcraft/src/space_mouse.rs
@@ -528,6 +528,9 @@ struct Candidate<D> {
device: D,
layout: Layout,
ids: (u16, u16),
+ /// The device's manufacturer and product strings ([`device_strings`]).
+ #[cfg_attr(not(any(target_os = "windows", target_os = "macos")), allow(dead_code))]
+ strings: Vec<String>,
}
/// Input reports read with a timeout in milliseconds: hidapi's devices, and the tests' simulated
@@ -634,8 +637,15 @@ fn follow<D: ReportSource>(mut candidates: Vec<Candidate<D>>, now: impl Fn() ->
}
}
+/// The device's manufacturer and product strings, which say whether a device app has it
+/// ([`crate::nav_bridge::Claim`]). Asked of the opened 3D mouse only.
#[cfg(any(target_os = "windows", target_os = "macos"))]
-fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
+fn device_strings(device: &hidapi::HidDevice) -> Vec<String> {
+ [device.get_manufacturer_string(), device.get_product_string()].into_iter().filter_map(|s| s.ok().flatten()).collect()
+}
+
+#[cfg(any(target_os = "windows", target_os = "macos"))]
+fn reader(ctx: Context, shared: Arc<Mutex<Reading>>, bridge: crate::nav_bridge::Claim) {
let Ok(mut api) = hid_api() else {
log::warn!("3D mouse: HID initialization failed");
return;
@@ -657,11 +667,17 @@ fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
// Read when the device was opened, from this device alone.
let info = device.get_device_info().ok()?;
let layout = device_layout(&device, info.vendor_id())?;
- Some(Candidate { device, layout, ids: (info.vendor_id(), info.product_id()) })
+ let strings = device_strings(&device);
+ Some(Candidate { device, layout, ids: (info.vendor_id(), info.product_id()), strings })
})
.collect();
+ let names: Vec<_> = open.iter().map(|candidate| (candidate.ids, candidate.strings.clone())).collect();
+ // Whether the device read now is one a device app has: it moves the view over the navigation
+ // bridge, so read here as well the device would move it twice. What was read before ages out.
+ let mut strings: &[String] = &[];
follow(open, Instant::now, |event| match event {
Followed::Device(ids, buttons) => {
+ strings = names.iter().find(|(known, _)| *known == ids).map_or(&[][..], |(_, strings)| strings.as_slice());
connected(&ctx, &shared, Source::Hid(Some(ids)));
// Taken over from another device: what it reported meanwhile is its baseline.
if let Some(buttons) = buttons
@@ -670,6 +686,7 @@ fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
reading.set_buttons(buttons);
}
}
+ Followed::Report(..) if bridge.claims(strings) => {}
Followed::Report(layout, report) => publish(&ctx, &shared, *layout, report),
Followed::Gone => reset(&ctx, &shared),
});
@@ -1054,7 +1071,8 @@ pub struct SpaceMouse {
}
impl SpaceMouse {
- pub fn start(ctx: &Context) -> Self {
+ /// Starts the reader. A device that `bridge` says its own app reads is left to that app.
+ pub fn start(ctx: &Context, bridge: crate::nav_bridge::Claim) -> Self {
let now = Instant::now();
let shared = Arc::new(Mutex::new(Reading::new(now)));
let worker_state = Arc::clone(&shared);
@@ -1063,11 +1081,14 @@ impl SpaceMouse {
let drivers = Arc::new(Drivers::default());
#[cfg(target_os = "linux")]
let worker_drivers = Arc::clone(&drivers);
+ // hidraw names no device's strings to compare (`Claim`).
+ #[cfg(target_os = "linux")]
+ let _ = bridge;
let spawned = std::thread::Builder::new().name("solidcraft-3d-mouse".into()).spawn(move || {
#[cfg(target_os = "linux")]
reader(worker_ctx, worker_state, worker_drivers, Machine);
#[cfg(not(target_os = "linux"))]
- reader(worker_ctx, worker_state);
+ reader(worker_ctx, worker_state, bridge);
});
if let Err(error) = spawned {
log::warn!("3D mouse: reader could not start: {error}");
@@ -1458,6 +1479,7 @@ mod tests {
},
layout,
ids: (0x256f, *product),
+ strings: Vec::new(),
})
.collect();
let (mut seen, mut read) = (Vec::new(), 0);
diff --git a/assets/locales/pending/nav-bridge.json b/assets/locales/pending/nav-bridge.json
new file mode 100644
index 0000000000..358cac95ac
--- /dev/null
+++ b/assets/locales/pending/nav-bridge.json
@@ -0,0 +1,30 @@
+{
+ "en": {
+ "ui.nav_bridge": "Navigate with a device app on this computer",
+ "ui.nav_bridge_connected": "Connected",
+ "ui.nav_bridge_port": "Port",
+ "ui.nav_bridge_tip": "A 3D input device's own program (for example a homemade 3D mouse's driver) moves the view over a local connection, so the mouse pointer stays yours. SolidCraft connects to it on this port on this computer only.",
+ "ui.nav_bridge_waiting": "Waiting for the device app"
+ },
+ "ja": {
+ "ui.nav_bridge": "このコンピューター上のデバイスアプリで操作",
+ "ui.nav_bridge_connected": "接続済み",
+ "ui.nav_bridge_port": "ポート",
+ "ui.nav_bridge_tip": "3D 入力デバイス専用のプログラム(自作 3D マウスのドライバーなど)がローカル接続でビューを動かすので、マウスポインターはそのまま使えます。SolidCraft はこのコンピューター上のこのポートにだけ接続します。",
+ "ui.nav_bridge_waiting": "デバイスアプリを待機中"
+ },
+ "pl": {
+ "ui.nav_bridge": "Nawiguj programem urządzenia na tym komputerze",
+ "ui.nav_bridge_connected": "Połączono",
+ "ui.nav_bridge_port": "Port",
+ "ui.nav_bridge_tip": "Własny program urządzenia wejściowego 3D (np. sterownik domowej myszy 3D) porusza widokiem przez połączenie lokalne, więc kursor myszy zostaje Twój. SolidCraft łączy się z nim na tym porcie, tylko na tym komputerze.",
+ "ui.nav_bridge_waiting": "Czekam na program urządzenia"
+ },
+ "zh": {
+ "ui.nav_bridge": "使用本机上的设备程序导航",
+ "ui.nav_bridge_connected": "已连接",
+ "ui.nav_bridge_port": "端口",
+ "ui.nav_bridge_tip": "3D 输入设备自带的程序(例如自制 3D 鼠标的驱动程序)通过本地连接移动视图,鼠标指针仍由你使用。SolidCraft 只在本机的此端口上连接它。",
+ "ui.nav_bridge_waiting": "正在等待设备程序"
+ }
+}
diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs
index c881f9f578..9551b1b17a 100644
--- a/crates/ui-egui/src/navigation.rs
+++ b/crates/ui-egui/src/navigation.rs
@@ -6,7 +6,7 @@
//! view and moves `app.cam` the way Preferences › Navigation says: the navigation preset (Fusion,
//! SolidWorks, Blender, Touchpad…), Orbit around, zoom to the cursor, the middle double-click and
//! orbit snapping. The 3D mouse's motion goes through [`device`] too, with the page's
-//! [`NavCaps`]. The view keys and the navigators act on `app.cam` independently of the page. New
+//! [`NavCaps`], and so does a device app's over the navigation bridge. The view keys and the navigators act on `app.cam` independently of the page. New
//! canvases must call `navigation::handle` rather than reading drags or the wheel themselves;
//! `hand_rolled_camera_input_is_rejected` fails when they do.
@@ -17,7 +17,7 @@ use solidcraft_engine::render::Camera;
use crate::SolveApp;
use crate::prefs::{OrbitAround, pivot_under};
-use crate::space_mouse::Motion;
+use crate::space_mouse::{BridgeMotion, Motion};
use crate::viewport::{Hit, NavMode, axis_rect, nearest_quarter_turn, pick, pick_cached, projection};
/// What a page's camera may do.
@@ -656,7 +656,9 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e
/// stays off while the camera is in its initial sketch orientation. [`handle`] calls it for its page; the 3D
/// mouse only reads the device and queues the motion ([`crate::space_mouse::navigate_frame`]).
pub(crate) fn device(app: &mut SolveApp, rect: Rect, caps: NavCaps) {
- let Some(queued) = app.viewport.device_motion.take() else { return };
+ if app.viewport.device_motion.is_none() && app.viewport.bridge_motion.is_none() {
+ return;
+ }
let sketch_view_is_initial = solidcraft_engine::view::open_sketch_plane(&app.session).is_some_and(|plane| {
let normal = plane.normal();
let mut initial = app.cam.looking_from(normal);
@@ -669,7 +671,44 @@ pub(crate) fn device(app: &mut SolveApp, rect: Rect, caps: NavCaps) {
});
let turn = caps.orbit && !sketch_view_is_initial;
let height = f64::from(rect.height().max(1.0));
- device_camera(&mut app.cam, queued.motion, queued.seconds, height, turn, app.preferences.zoom_reverse, app.preferences.free_orbit);
+ if let Some(queued) = app.viewport.device_motion.take() {
+ device_camera(&mut app.cam, queued.motion, queued.seconds, height, turn, app.preferences.zoom_reverse, app.preferences.free_orbit);
+ }
+ // A device app's motion (the navigation bridge), on the same terms.
+ if let Some(queued) = app.viewport.bridge_motion.take() {
+ bridge_camera(&mut app.cam, queued, height, turn, app.preferences.zoom_reverse, app.preferences.free_orbit);
+ }
+}
+
+/// How far one zoom step of a device app (a click of its ring or wheel) moves the camera: this
+/// share of its distance, compounded, so zooming in and back out returns where it was.
+const BRIDGE_ZOOM_PER_STEP: f64 = 0.08;
+
+/// A device app's `motion` (`space_mouse::bridge_frame`) on `cam`, in a view `height` points
+/// tall: orbit and pan as a pointer drag of that many points, zoom by steps. With `turn` off (a
+/// flat page, a sketch being edited) the view keeps its orientation and the orbit motion pans
+/// instead, so the device still moves the view.
+pub(crate) fn bridge_camera(cam: &mut Camera, motion: BridgeMotion, height: f64, turn: bool, reverse_zoom: bool, free_orbit: bool) {
+ let motion = BridgeMotion::default().plus(motion);
+ let [mut px, mut py] = motion.pan;
+ let [ox, oy] = motion.orbit;
+ if turn {
+ if free_orbit {
+ cam.rotate_in_view(Vec3::new(-oy * 0.008, -ox * 0.008, 0.0));
+ } else {
+ cam.orbit(ox, oy);
+ }
+ } else {
+ px += ox;
+ py += oy;
+ }
+ if px != 0.0 || py != 0.0 {
+ cam.pan(px, py, height);
+ }
+ if motion.zoom != 0.0 {
+ let zoom_sign = if reverse_zoom { -1.0 } else { 1.0 };
+ cam.zoom_at((-motion.zoom * zoom_sign * BRIDGE_ZOOM_PER_STEP).exp(), None);
+ }
}
/// `seconds` of 3D mouse `motion` on `cam`, in a view `height` points tall. A full deflection
@@ -1396,6 +1435,36 @@ mod tests {
}
}
+ /// 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]
+ fn a_device_apps_orbit_pans_where_the_view_may_not_turn() {
+ use crate::space_mouse::BridgeMotion;
+ let orbit = BridgeMotion { orbit: [30.0, 20.0], ..Default::default() };
+ let page = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
+ let flat = super::NavCaps { orbit: false, pick: false };
+ let mut sketching = solidcraft_engine::Session::default();
+ sketching.execute("sketch.create", &serde_json::json!({"plane": "XY"})).unwrap();
+ for (session, caps, turns) in [
+ (solidcraft_engine::Session::default(), super::NavCaps::MODEL, true),
+ (solidcraft_engine::Session::default(), flat, false),
+ (sketching, super::NavCaps::MODEL, false),
+ ] {
+ let mut app = crate::SolveApp::new(session, crate::Services::default());
+ if app.session.active_sketch.is_some() {
+ // Square to the sketch, as a sketch opens.
+ app.cam = solidcraft_engine::render::Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, ..Default::default() };
+ }
+ let before = app.cam;
+ app.viewport.bridge_motion = Some(orbit);
+ super::device(&mut app, page, caps);
+ assert!(app.viewport.bridge_motion.is_none(), "{caps:?}: the page takes the motion");
+ let turned = (app.cam.yaw, app.cam.pitch, app.cam.roll) != (before.yaw, before.pitch, before.roll);
+ assert_eq!(turned, turns, "{caps:?}");
+ assert_eq!(app.cam.target != before.target, !turns, "{caps:?}: pans where it doesn't turn");
+ }
+ }
+
/// While a sketch is edited the cap pans and zooms without turning a square-on view; after the
/// view is tilted away from the sketch, the cap can turn it again.
#[test]
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 90cc2e348e..4fe267542c 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -556,6 +556,12 @@ preference_settings! {
/// the page would otherwise bring the offer back for every device.
#[serde(deserialize_with = "devices_that_read")]
space_mouse_offered: std::collections::BTreeSet<String> = Default::default();
+ /// A device's own app on this computer moves the view (the navigation bridge, docs/3d-mouse.md):
+ /// the desktop app connects to it on `nav_bridge_port`. Off unless asked for, so the app
+ /// doesn't connect to whatever else listens on that port.
+ nav_bridge_enabled: bool = false, PAGE_NAVIGATION;
+ /// The loopback port the device app listens on (0: none).
+ nav_bridge_port: u16 = 8765, PAGE_NAVIGATION;
/// Anti-aliasing samples (applies on restart).
msaa: u32 = 4, PAGE_GRAPHICS;
/// Linux: the window system the app opens with at its next start (#3083): `auto` (XWayland
@@ -1594,6 +1600,9 @@ fn space_mouse_rows(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
});
+ // A device whose own app drives the view instead (the navigation bridge).
+ ui_kit::divider(ui, "nav_bridge");
+ navigation::nav_bridge(app, ui);
// The rarely needed settings sit behind one disclosure, closed until the reader opens it.
ui_kit::section(ui, "space_mouse_advanced", crate::i18n::tr_label("Advanced"), false, |ui| {
ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| {
diff --git a/crates/ui-egui/src/prefs/navigation.rs b/crates/ui-egui/src/prefs/navigation.rs
index 40895ccf6f..540414d484 100644
--- a/crates/ui-egui/src/prefs/navigation.rs
+++ b/crates/ui-egui/src/prefs/navigation.rs
@@ -172,3 +172,27 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
// (`prefs::space_mouse_section`).
space_mouse_section(app, ui);
}
+
+/// A device's own app on this computer driving the view (the navigation bridge): on or off, its
+/// port, and whether an app is connected. Part of the 3D mouse section (`space_mouse_rows`).
+pub(super) fn nav_bridge(app: &mut SolveApp, ui: &mut egui::Ui) {
+ let (label, tip, port) = (app.tr("ui.nav_bridge").to_owned(), app.tr("ui.nav_bridge_tip").to_owned(), app.tr("ui.nav_bridge_port").to_owned());
+ let status = match (&app.space_mouse.bridge, app.preferences.nav_bridge_enabled) {
+ (_, false) => None,
+ (Some(name), true) => Some((format!("{} · {name}", app.tr("ui.nav_bridge_connected")), false)),
+ (None, true) => Some((app.tr("ui.nav_bridge_waiting").to_owned(), true)),
+ };
+ ui.horizontal_wrapped(|ui| {
+ ui_kit::checkbox(ui, &label, &mut app.preferences.nav_bridge_enabled).on_hover_text(&tip);
+ if let Some((status, waiting)) = &status {
+ ui_kit::settings_badge(ui, status, *waiting);
+ }
+ });
+ ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| {
+ ui_kit::row(ui, &port, |ui| {
+ ui.add_enabled_ui(app.preferences.nav_bridge_enabled, |ui| {
+ ui_kit::number_field(ui, &mut app.preferences.nav_bridge_port, 1..=u16::MAX, 1.0, "");
+ });
+ });
+ });
+}
diff --git a/crates/ui-egui/src/space_mouse.rs b/crates/ui-egui/src/space_mouse.rs
index d1f0fe8197..15da52ae43 100644
--- a/crates/ui-egui/src/space_mouse.rs
+++ b/crates/ui-egui/src/space_mouse.rs
@@ -2,7 +2,9 @@
//! desktop through HID, the web app through the browser's Gamepad API) and hands its six raw axes
//! to [`navigate_frame`] once per frame. This module maps them, applies the dead zone and drops
//! 3DxWare's emulated wheel; the page showing the camera moves it (`navigation::device`), so the
-//! cap does what that page's camera may do.
+//! cap does what that page's camera may do. A device with a program of its own can drive the view
+//! through that program instead: the desktop app reads it over the navigation bridge and hands
+//! its motion to [`bridge_frame`], which goes to the same page.
use std::time::Duration;
@@ -94,6 +96,9 @@ pub struct Input {
/// Which of the Linux readers exist, as the app's reader last saw them; none where there is
/// only one way to read the device.
pub drivers: Option<DriversPresent>,
+ /// The device app connected over the navigation bridge, by the name it gave (or "?" before it
+ /// gave one); none while no app is connected, and in builds without a bridge.
+ pub bridge: Option<String>,
}
/// What the Linux reader found: the spacenavd socket and a direct (hidraw) 3D mouse, and whether that
@@ -598,6 +603,76 @@ pub fn navigate_frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMa
true
}
+/// How far one message of a device app may move the view along one of its motions (points, or
+/// zoom steps), and how far a frame may sum to: a flood of large values can't throw the camera out.
+pub const BRIDGE_MAX_STEP: f64 = 10_000.0;
+
+/// The standard views a device app may ask for over the navigation bridge, by the names
+/// `SolveApp::animate_view` takes ("fit" frames everything, as Fit does).
+pub const BRIDGE_VIEWS: [&str; 8] = ["front", "back", "left", "right", "top", "bottom", "iso", "fit"];
+
+/// What a device app (a homemade 3D input device's own program, read by the desktop app through
+/// its navigation bridge) moved the view by since the last frame. Unlike a 3D mouse's deflection,
+/// these are distances: orbit and pan as a pointer drag of that many points would move the view
+/// (the model follows), and zoom in steps (positive zooms in, as a wheel turned forward).
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct BridgeMotion {
+ pub orbit: [f64; 2],
+ pub pan: [f64; 2],
+ pub zoom: f64,
+}
+
+impl BridgeMotion {
+ /// Nothing to move.
+ pub fn is_still(self) -> bool {
+ self == Self::default()
+ }
+
+ /// Both motions summed, each within [`BRIDGE_MAX_STEP`]; a value that isn't a finite number
+ /// counts as none.
+ pub fn plus(self, other: Self) -> Self {
+ let sum = |a: f64, b: f64| (bridge_step(a) + bridge_step(b)).clamp(-BRIDGE_MAX_STEP, BRIDGE_MAX_STEP);
+ Self {
+ orbit: [sum(self.orbit[0], other.orbit[0]), sum(self.orbit[1], other.orbit[1])],
+ pan: [sum(self.pan[0], other.pan[0]), sum(self.pan[1], other.pan[1])],
+ zoom: sum(self.zoom, other.zoom),
+ }
+ }
+}
+
+/// One value of a device app's message: finite and within [`BRIDGE_MAX_STEP`], else none.
+pub fn bridge_step(value: f64) -> f64 {
+ if value.is_finite() { value.clamp(-BRIDGE_MAX_STEP, BRIDGE_MAX_STEP) } else { 0.0 }
+}
+
+/// Hands one frame of a device app's navigation to the page showing the camera, and shows the
+/// standard `views` it asked for (names outside [`BRIDGE_VIEWS`] are ignored). As with a 3D mouse,
+/// nothing happens with the bridge switched off, on the start page or while a file picker is open,
+/// or in a window without focus. Returns whether there was anything to hand over.
+pub fn bridge_frame(app: &mut SolveApp, ctx: &egui::Context, motion: BridgeMotion, views: &[String]) -> bool {
+ if !app.preferences.nav_bridge_enabled || app.home.open || app.file_picker_busy() || !ctx.input(|i| i.focused) {
+ return false;
+ }
+ let motion = BridgeMotion::default().plus(motion);
+ let moved = !motion.is_still();
+ if moved {
+ app.begin_external_navigation();
+ app.viewport.bridge_motion = Some(app.viewport.bridge_motion.unwrap_or_default().plus(motion));
+ ctx.request_repaint();
+ }
+ // After the motion, which would stop the view's animation.
+ let mut viewed = false;
+ for view in views.iter().filter_map(|name| BRIDGE_VIEWS.iter().find(|v| **v == name.as_str())) {
+ if *view == "fit" {
+ app.animate_fit_all();
+ } else {
+ app.animate_view(view);
+ }
+ viewed = true;
+ }
+ moved || viewed
+}
+
/// A small dead zone avoids drift at rest. A full cap deflection takes roughly one viewport
/// per second to pan and about two radians per second to turn, independent of frame rate.
fn normalized(value: i16) -> f64 {
@@ -1653,6 +1728,99 @@ mod tests {
assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}");
}
+ /// One frame of a device app's navigation, taken by the modelling viewport.
+ fn bridge(app: &mut SolveApp, ctx: &egui::Context, motion: BridgeMotion, views: &[&str]) -> bool {
+ let views: Vec<String> = views.iter().map(|v| v.to_string()).collect();
+ let handed = bridge_frame(app, ctx, motion, &views);
+ let page = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
+ crate::navigation::device(app, page, crate::navigation::NavCaps::MODEL);
+ handed
+ }
+
+ const ORBIT: BridgeMotion = BridgeMotion { orbit: [40.0, 10.0], pan: [0.0; 2], zoom: 0.0 };
+
+ #[test]
+ fn a_device_app_moves_the_view_only_with_the_bridge_on_and_the_window_focused() {
+ let ctx = window(true);
+ let mut off = app();
+ let before = off.cam;
+ assert!(!bridge(&mut off, &ctx, ORBIT, &[]), "the bridge is off by default");
+ assert_eq!(off.cam, before);
+ let on = || {
+ let mut app = app();
+ app.preferences.nav_bridge_enabled = true;
+ app
+ };
+ let mut home = on();
+ home.home.open = true;
+ assert!(!bridge(&mut home, &ctx, ORBIT, &[]));
+ let mut unfocused = on();
+ assert!(!bridge(&mut unfocused, &window(false), ORBIT, &[]));
+ assert_eq!((home.cam, unfocused.cam), (before, before));
+ let mut app = on();
+ assert!(bridge(&mut app, &ctx, ORBIT, &[]));
+ assert_ne!((app.cam.yaw, app.cam.pitch), (before.yaw, before.pitch), "orbit turns the view");
+ assert!(app.viewport.bridge_motion.is_none(), "the page took the motion");
+ // At rest, nothing to hand over.
+ assert!(!bridge(&mut app, &ctx, BridgeMotion::default(), &[]));
+ }
+
+ #[test]
+ fn a_device_apps_motion_pans_and_zooms_as_a_drag_and_the_wheel_would() {
+ let ctx = window(true);
+ let mut app = app();
+ app.preferences.nav_bridge_enabled = true;
+ let before = app.cam;
+ bridge(&mut app, &ctx, BridgeMotion { pan: [30.0, -20.0], ..Default::default() }, &[]);
+ let mut dragged = before;
+ dragged.pan(30.0, -20.0, 600.0);
+ assert_eq!(app.cam, dragged, "a pan of so many points is a pan drag of as many");
+ let panned = app.cam;
+ bridge(&mut app, &ctx, BridgeMotion { zoom: 2.0, ..Default::default() }, &[]);
+ assert!(app.cam.distance < panned.distance, "positive steps zoom in");
+ bridge(&mut app, &ctx, BridgeMotion { zoom: -2.0, ..Default::default() }, &[]);
+ assert!((app.cam.distance - panned.distance).abs() < 1e-9, "and back out to where it was");
+ // Reverse zoom direction reverses it, as it does the wheel's.
+ app.preferences.zoom_reverse = true;
+ bridge(&mut app, &ctx, BridgeMotion { zoom: 2.0, ..Default::default() }, &[]);
+ assert!(app.cam.distance > panned.distance);
+ }
+
+ #[test]
+ fn a_device_app_asks_for_standard_views_by_name() {
+ let ctx = window(true);
+ let mut app = app();
+ app.preferences.nav_bridge_enabled = true;
+ app.preferences.look_at_anim = false;
+ assert!(bridge(&mut app, &ctx, BridgeMotion::default(), &["top"]));
+ let mut top = Camera::default();
+ top.set_view(solidcraft_engine::render::StandardView::Top);
+ let target = app.cam_anim.map_or(app.cam, |a| a.to);
+ assert_eq!((target.yaw, target.pitch), (top.yaw, top.pitch));
+ // Names it doesn't know are no view.
+ let still = app.cam;
+ assert!(!bridge(&mut app, &ctx, BridgeMotion::default(), &["TOP", "named view", ""]));
+ assert_eq!(app.cam, still);
+ }
+
+ #[test]
+ fn a_flood_of_device_app_motion_stays_within_range() {
+ let ctx = window(true);
+ let mut app = app();
+ app.preferences.nav_bridge_enabled = true;
+ let hostile = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, -f64::MAX, 1e12];
+ for value in hostile {
+ let motion = BridgeMotion { orbit: [value, -value], pan: [value, value], zoom: value };
+ for _ in 0..3 {
+ bridge(&mut app, &ctx, motion, &[]);
+ assert!(app.cam.is_valid(), "{value}");
+ }
+ }
+ let summed = (0..10).fold(BridgeMotion::default(), |sum, _| sum.plus(BridgeMotion { pan: [f64::MAX, 1.0], ..Default::default() }));
+ assert_eq!(summed.pan, [BRIDGE_MAX_STEP, 10.0]);
+ assert_eq!(BridgeMotion { zoom: f64::NAN, ..Default::default() }.plus(BridgeMotion::default()), BridgeMotion::default());
+ }
+
#[test]
fn a_saved_axis_assignment_that_doesnt_drive_each_axis_once_loads_as_the_default() {
let mut saved = serde_json::to_value(crate::prefs::Prefs::default()).unwrap();
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 9da98539f7..8712f58d89 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -150,6 +150,9 @@ pub struct ViewportState {
/// The 3D mouse's motion this frame, for the page showing the camera to apply with what its
/// camera may do (`navigation::device`).
pub device_motion: Option<crate::space_mouse::DeviceMotion>,
+ /// A device app's motion since the page last took it (`space_mouse::bridge_frame`), applied
+ /// the same way.
+ pub bridge_motion: Option<crate::space_mouse::BridgeMotion>,
/// After immediate zoom, ignore egui's outstanding smoothing until the gesture ends.
pub(crate) wheel_zoom_raw_until_idle: bool,
/// While trackpad scrolling runs, ignore egui's smoothing tail for zoom so
diff --git a/docs/3d-mouse.md b/docs/3d-mouse.md
index 647993f4b1..dd3981ce1b 100644
--- a/docs/3d-mouse.md
+++ b/docs/3d-mouse.md
@@ -50,3 +50,30 @@ The driver keeps the device to itself, and sends it only to a program it can ide
as an `.app` (the packaged app). Without the driver, or with its helper not running, SolidCraft reads the device through IOKit like on Windows.
SolidCraft does not follow 3DxWare's profile on macOS. Its default is 3DxWare's object mode.
+
+## Device apps: the navigation bridge
+
+Some homemade input devices come with a program of their own that reads the device and turns its
+knobs, rings and buttons into navigation (profiles, sensitivity, button actions). Such a program can
+move SolidCraft's view directly instead of emulating mouse drags, so the mouse pointer stays the
+user's and both can be used at once. Turn on **Navigate with a device app on this computer** in
+Preferences › Navigation › 3D mouse (off by default) and set the port the program listens on
+(8765 unless the program says otherwise). The desktop app then connects to `127.0.0.1:<port>`,
+retries every second while nothing answers, and shows **Connected** with the program's name once it
+is. Only the window with focus moves, and not on the start page or while a file dialog is open.
+
+The program is the server; SolidCraft connects and first sends one line,
+`{"t":"hello","app":"solidcraft","version":"<version>"}`. Then the program sends one JSON object per
+line (UTF-8, `\n`-terminated, at most 4096 bytes); anything else, and any message SolidCraft doesn't
+know, is ignored:
+
+| Message | Meaning |
+|---|---|
+| `{"t":"hello","server":"MAKMOUSE","device":"MAKMOUSE"}` | The program's name (shown in Preferences) and, optionally, a name in the device's USB manufacturer or product string. A 3D mouse with that name is then left to the program, so its motion doesn't reach the view twice. |
+| `{"t":"axis","x":4.0,"y":-2.5}` | Motion since the last message, in points: it orbits as a drag of that many points would (the model follows), or pans or zooms in the current mode. Where the view can't turn (a sketch being edited, a flat page) an orbit pans. |
+| `{"t":"zoom","d":1.0}` | Zoom steps (8 % of the distance each); positive zooms in, as a wheel turned forward. Reverse zoom direction applies. |
+| `{"t":"mode","mode":"pan","on":true}` | What `axis` drives: `orbit` (the default), `pan` or `zoom` (up zooms in, 8 points a step). `"on":false` goes back to orbit. |
+| `{"t":"view","name":"iso"}` | A standard view: `front`, `back`, `left`, `right`, `top`, `bottom`, `iso`, or `fit` to frame everything. |
+
+Values that aren't finite numbers count as none, and each is limited to ±10 000 per message and per
+frame. The protocol is the one the MAKMOUSE driver app uses for its add-ins.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 53e307c3ca..0c8c4032cf 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -303,7 +303,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
| `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs |
| `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) |
| `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text |
-| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `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), `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned)), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `viewport_theme` (`theme` (default: the theme's own), `light`, `dark`: the 3D view in the Light or Dark theme's colours whatever the window uses, #4146), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `view_confirm_corner` (default false: while a dialog or a sketch is open, a check and a cross at the view's top right, handles `view:confirm:ok` and `view:confirm:cancel`, do what the dialog's OK and Cancel do, or Finish Sketch and Cancel Sketch; the axis view or cube moves down below them, #6709), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark) and `stand_up_offer` |
+| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `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), `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned)), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `viewport_theme` (`theme` (default: the theme's own), `light`, `dark`: the 3D view in the Light or Dark theme's colours whatever the window uses, #4146), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `view_confirm_corner` (default false: while a dialog or a sketch is open, a check and a cross at the view's top right, handles `view:confirm:ok` and `view:confirm:cancel`, do what the dialog's OK and Cancel do, or Finish Sketch and Cancel Sketch; the axis view or cube moves down below them, #6709), `check_updates` (default true; [updates](book/src/guide/updates.md)), `nav_bridge_enabled` (default false) and `nav_bridge_port` (default 8765: a device's own app on this computer moves the view, [the navigation bridge](3d-mouse.md#device-apps-the-navigation-bridge)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark) and `stand_up_offer` |
| `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits |
| `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first |
| `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. The pointer shows the command's localized name, including commands inside a closed toolbar group; an animated batch names each command it visits. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it |