Skip to content

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

macOS 3D mouse: unregister from the driver when the app ends, so the next launch gets the mouse (#6114) (#6115)

Jesper We0c4eb458df85
diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs
index f9979e71fa..8a4f795b10 100644
--- a/apps/solidcraft/src/main.rs
+++ b/apps/solidcraft/src/main.rs
@@ -182,6 +182,10 @@ impl eframe::App for App {
}
solidcraft_ui_egui::recovery_ui::close(&mut self.solve);
solidcraft_ui_egui::open_elsewhere::close(&mut self.solve);
+ // Before a restart below starts the next instance, which would otherwise get nothing from
+ // the 3D mouse driver (`solidcraft_3dx_client::stop`).
+ #[cfg(target_os = "macos")]
+ solidcraft_3dx_client::stop();
solidcraft_engine::crash::end_session();
if let Some(lost_at) = self.gpu.as_ref().and_then(|g| g.lost_at) {
device_lost::restart(self.gpu.as_ref().is_some_and(|g| g.restart_on_software), lost_at);
@@ -633,6 +637,18 @@ fn app_viewport(custom_titlebar: bool) -> Result<egui::ViewportBuilder, eframe::
/// The window's app id: it names the desktop entry, so it is the packages' reverse-DNS id.
const APP_ID: &str = solidcraft_engine::io::APP_ID;
+/// Disconnects from the 3D mouse driver when dropped, as `main` returns or a panic unwinds out
+/// of it (`solidcraft_3dx_client::stop`).
+#[cfg(target_os = "macos")]
+struct DriverClient;
+
+#[cfg(target_os = "macos")]
+impl Drop for DriverClient {
+ fn drop(&mut self) {
+ solidcraft_3dx_client::stop();
+ }
+}
+
fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
objc2_foundation::NSProcessInfo::processInfo().setProcessName(objc2_foundation::ns_string!("SolidCraft"));
@@ -775,6 +791,10 @@ fn main() -> eframe::Result {
let created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let created_in_app = created.clone();
let starting = settings.clone();
+ // A panic on the window's thread ends the app without `on_exit`; this disconnects from the
+ // 3D mouse driver then too.
+ #[cfg(target_os = "macos")]
+ let _driver_client = DriverClient;
mark("run_native");
let result = eframe::run_native(
"SolidCraft",
diff --git a/crates/threedx-client/src/lib.rs b/crates/threedx-client/src/lib.rs
index 15082ed998..af22673ade 100644
--- a/crates/threedx-client/src/lib.rs
+++ b/crates/threedx-client/src/lib.rs
@@ -67,7 +67,7 @@ impl std::error::Error for Error {}
/// Connects to the driver and calls `sink` (on the client's own thread) for everything it reports.
/// `name` is how the driver lists this app. Only one client per process; the connection lasts
-/// until the process ends. Returns once the client thread runs, without waiting for the driver
+/// until [`stop`]. Returns once the client thread runs, without waiting for the driver
/// (which needs the main thread to register the client); `connected` gets that outcome later, on
/// the client's thread.
pub fn start(
@@ -85,3 +85,12 @@ pub fn start(
Err(Error::Unsupported)
}
}
+
+/// Disconnects from the driver; call it as the app ends. The driver keeps a client registered
+/// after its process is gone, and while it does, a client registered later gets nothing until
+/// the device is unplugged and plugged in again. Does nothing when no client was started, and on
+/// other platforms.
+pub fn stop() {
+ #[cfg(target_os = "macos")]
+ macos::stop();
+}
diff --git a/crates/threedx-client/src/macos.rs b/crates/threedx-client/src/macos.rs
index 5549425dd9..840fd9cf9d 100644
--- a/crates/threedx-client/src/macos.rs
+++ b/crates/threedx-client/src/macos.rs
@@ -51,11 +51,20 @@ type DeviceHandler = extern "C" fn(u32);
type InstallHandlers = unsafe extern "C" fn(Option<MessageHandler>, Option<DeviceHandler>, Option<DeviceHandler>) -> i16;
type RegisterClient = unsafe extern "C" fn(u32, *const u8, u16, u32) -> u16;
type SetMask = unsafe extern "C" fn(u16, u32);
+type UnregisterClient = unsafe extern "C" fn(u16);
+type CleanupHandlers = unsafe extern "C" fn();
type Sink = Box<dyn Fn(Event) + Send + Sync>;
type Connected = Box<dyn FnOnce(Result<(), Error>) + Send>;
+/// What [`stop`] calls: the framework's `UnregisterConnexionClient` and `CleanupConnexionHandlers`.
+struct Shutdown {
+ unregister: UnregisterClient,
+ cleanup: CleanupHandlers,
+}
+
static SINK: OnceLock<Sink> = OnceLock::new();
+static SHUTDOWN: OnceLock<Shutdown> = OnceLock::new();
/// The id the driver gave this client: it broadcasts every message to every client.
static CLIENT: AtomicU16 = AtomicU16::new(0);
@@ -146,6 +155,16 @@ fn connect(name: &str) -> Result<(), Error> {
return Err(Error::Register);
}
CLIENT.store(id, Ordering::Relaxed);
+ if let (Ok(unregister), Ok(cleanup)) = (symbol(handle, "UnregisterConnexionClient"), symbol(handle, "CleanupConnexionHandlers")) {
+ // SAFETY: the framework declares these functions with exactly these signatures.
+ let shutdown = unsafe {
+ Shutdown {
+ unregister: std::mem::transmute::<*mut c_void, UnregisterClient>(unregister),
+ cleanup: std::mem::transmute::<*mut c_void, CleanupHandlers>(cleanup),
+ }
+ };
+ let _ = SHUTDOWN.set(shutdown);
+ }
// Newer drivers want the masks again once the client has an id. Both are optional.
for (name, mask) in [("SetConnexionClientMask", MASK_ALL), ("SetConnexionClientButtonMask", u32::MAX)] {
if let Ok(set) = symbol(handle, name) {
@@ -184,6 +203,21 @@ pub fn start(name: &str, sink: Sink, connected: Connected) -> Result<(), Error>
.map_err(|error| Error::Thread(error.to_string()))
}
+/// Unregisters the client and removes the handlers, once; nothing when the client never registered.
+pub fn stop() {
+ let id = CLIENT.swap(0, Ordering::Relaxed);
+ if id == 0 {
+ return;
+ }
+ if let Some(shutdown) = SHUTDOWN.get() {
+ // SAFETY: `id` is the id the driver gave this client, and the handlers were installed.
+ unsafe {
+ (shutdown.unregister)(id);
+ (shutdown.cleanup)();
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -220,4 +254,11 @@ mod tests {
fn a_short_message_is_ignored() {
assert_eq!(decode(&[0; 10], 0), None);
}
+
+ #[test]
+ fn stopping_without_a_client_does_nothing() {
+ stop();
+ stop();
+ assert_eq!(CLIENT.load(Ordering::Relaxed), 0);
+ }
}