#![expect(unsafe_code, reason = "Objective-C messages to Core Motion")]
use std::{
sync::{Arc, Mutex, MutexGuard, PoisonError},
time::Duration,
};
use block2::RcBlock;
use cranpose_services::{
DeviceMotionError, DeviceMotionPermission, DeviceMotionSensor, MotionClock, MotionConfig,
MotionRate, MotionReference, Quaternion, publish_device_motion, set_platform_device_motion,
};
use objc2::rc::Retained;
use objc2_core_motion::{CMAttitudeReferenceFrame, CMDeviceMotion, CMMotionManager};
use objc2_foundation::{NSError, NSOperationQueue, NSProcessInfo, NSQualityOfService};
use super::mobile::on_main_after;
const FASTEST_INTERVAL_SECONDS: f64 = 0.001;
struct Held {
manager: Retained<CMMotionManager>,
queue: Retained<NSOperationQueue>,
}
unsafe impl Send for Held {}
static HELD: Mutex<Option<Held>> = Mutex::new(None);
fn held() -> MutexGuard<'static, Option<Held>> {
HELD.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn register() {
on_main_after(Duration::ZERO, |_| {
let manager = unsafe { CMMotionManager::new() };
let available = unsafe { manager.isDeviceMotionAvailable() };
let queue = NSOperationQueue::new();
queue.setMaxConcurrentOperationCount(1);
queue.setQualityOfService(NSQualityOfService::UserInteractive);
*held() = Some(Held { manager, queue });
set_platform_device_motion(Arc::new(AppleDeviceMotion { available }));
});
}
struct AppleDeviceMotion {
available: bool,
}
impl DeviceMotionSensor for AppleDeviceMotion {
fn clock(&self) -> MotionClock {
MotionClock::SystemUptime
}
fn now_ns(&self) -> u64 {
(NSProcessInfo::processInfo().systemUptime() * 1.0e9) as u64
}
fn available(&self) -> bool {
self.available
}
fn permission(&self) -> DeviceMotionPermission {
DeviceMotionPermission::Granted
}
fn request_permission(&self) {}
fn start(&self, config: MotionConfig) -> Result<(), DeviceMotionError> {
on_main_after(Duration::ZERO, move |_| begin(config));
Ok(())
}
fn stop(&self) {
on_main_after(Duration::ZERO, |_| {
if let Some(held) = held().as_ref() {
unsafe { held.manager.stopDeviceMotionUpdates() };
}
});
}
}
fn begin(config: MotionConfig) {
let held = held();
let Some(held) = held.as_ref() else {
return;
};
let frames = unsafe { CMMotionManager::availableAttitudeReferenceFrames() };
let (frame, reference) = match config.reference {
MotionReference::MagneticNorth
if frames.contains(CMAttitudeReferenceFrame::XMagneticNorthZVertical) =>
{
(
CMAttitudeReferenceFrame::XMagneticNorthZVertical,
MotionReference::MagneticNorth,
)
}
_ => (
CMAttitudeReferenceFrame::XArbitraryZVertical,
MotionReference::ArbitraryHeading,
),
};
let interval = match config.rate {
MotionRate::Fastest => FASTEST_INTERVAL_SECONDS,
MotionRate::Period(period) => period.as_secs_f64().max(FASTEST_INTERVAL_SECONDS),
};
let handler = RcBlock::new(move |motion: *mut CMDeviceMotion, _error: *mut NSError| {
let Some(motion) = (unsafe { motion.as_ref() }) else {
return;
};
let (timestamp, attitude) = unsafe { (motion.timestamp(), motion.attitude().quaternion()) };
publish_device_motion(
Quaternion::from_core_motion(attitude.x, attitude.y, attitude.z, attitude.w),
(timestamp * 1.0e9) as u64,
reference,
);
});
unsafe {
held.manager.stopDeviceMotionUpdates();
held.manager.setDeviceMotionUpdateInterval(interval);
held.manager
.startDeviceMotionUpdatesUsingReferenceFrame_toQueue_withHandler(
frame,
&held.queue,
RcBlock::as_ptr(&handler),
);
}
}