iohidmanager 0.10.4

Safe Rust bindings for Apple's IOKit HID — enumerate, inspect, and subscribe to HID devices on macOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use core::ffi::c_void;
use core::ptr;

use doom_fish_utils::panic_safe::catch_user_panic;

#[allow(clippy::wildcard_imports)]
use super::*;
use crate::ffi_impl as ffi;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ManagerDeviceCallbackKind {
    Matching,
    Removal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ManagerReportCallbackKind {
    Untimestamped,
    Timestamped,
}

#[allow(clippy::type_complexity)]
struct ManagerDeviceContext {
    callback: *mut Box<dyn Fn(HidDevice) + Send + Sync + 'static>,
}

#[allow(clippy::type_complexity)]
struct ManagerReportContext {
    callback: *mut Box<dyn Fn(HidDevice, HidInputReport) + Send + Sync + 'static>,
}

#[allow(clippy::type_complexity)]
struct ManagerValueContext {
    callback: *mut Box<dyn Fn(HidDevice, &HidValue) + Send + Sync + 'static>,
}

unsafe extern "C" fn manager_device_trampoline(
    context: *mut c_void,
    result: ffi::IOReturn,
    _sender: *mut c_void,
    device: ffi::IOHIDDeviceRef,
) {
    if context.is_null() || device.is_null() || result != ffi::kIOReturnSuccess {
        return;
    }
    unsafe { ffi::CFRetain(device) };
    // SAFETY: context is non-null (checked above) and points to a
    // `ManagerDeviceContext` whose `callback` field was `Box::into_raw`'d
    // when the subscription was created.
    let callback = unsafe { &*(*context.cast::<ManagerDeviceContext>()).callback };
    catch_user_panic("manager_device_trampoline", || {
        callback(HidDevice { raw: device });
    });
}

unsafe extern "C" fn manager_report_trampoline(
    context: *mut c_void,
    result: ffi::IOReturn,
    sender: *mut c_void,
    report_type: ffi::IOHIDReportType,
    report_id: u32,
    report: *mut u8,
    report_length: ffi::CFIndex,
) {
    if context.is_null() || sender.is_null() || report.is_null() || result != ffi::kIOReturnSuccess
    {
        return;
    }
    let Some(device) = retained_device_from_sender(sender) else {
        return;
    };
    let length = usize::try_from(report_length).unwrap_or(0);
    let bytes = unsafe { core::slice::from_raw_parts(report.cast_const(), length) }.to_vec();
    // SAFETY: context is non-null (checked above) and points to a
    // `ManagerReportContext` whose `callback` field was `Box::into_raw`'d
    // when the subscription was created.
    let callback = unsafe { &*(*context.cast::<ManagerReportContext>()).callback };
    catch_user_panic("manager_report_trampoline", || {
        callback(
            device,
            HidInputReport {
                report_type: HidReportType::from_raw(report_type),
                report_id,
                bytes,
                timestamp: 0,
            },
        );
    });
}

unsafe extern "C" fn manager_timestamped_report_trampoline(
    context: *mut c_void,
    result: ffi::IOReturn,
    sender: *mut c_void,
    report_type: ffi::IOHIDReportType,
    report_id: u32,
    report: *mut u8,
    report_length: ffi::CFIndex,
    timestamp: u64,
) {
    if context.is_null() || sender.is_null() || report.is_null() || result != ffi::kIOReturnSuccess
    {
        return;
    }
    let Some(device) = retained_device_from_sender(sender) else {
        return;
    };
    let length = usize::try_from(report_length).unwrap_or(0);
    let bytes = unsafe { core::slice::from_raw_parts(report.cast_const(), length) }.to_vec();
    // SAFETY: context is non-null (checked above) and points to a
    // `ManagerReportContext` whose `callback` field was `Box::into_raw`'d
    // when the subscription was created.
    let callback = unsafe { &*(*context.cast::<ManagerReportContext>()).callback };
    catch_user_panic("manager_timestamped_report_trampoline", || {
        callback(
            device,
            HidInputReport {
                report_type: HidReportType::from_raw(report_type),
                report_id,
                bytes,
                timestamp,
            },
        );
    });
}

unsafe extern "C" fn manager_value_trampoline(
    context: *mut c_void,
    result: ffi::IOReturn,
    sender: *mut c_void,
    value: ffi::IOHIDValueRef,
) {
    if context.is_null() || sender.is_null() || value.is_null() || result != ffi::kIOReturnSuccess {
        return;
    }
    let Some(device) = retained_device_from_sender(sender) else {
        return;
    };
    let Some(value) = clone_value_ref(value) else {
        return;
    };
    // SAFETY: context is non-null (checked above) and points to a
    // `ManagerValueContext` whose `callback` field was `Box::into_raw`'d
    // when the subscription was created.
    let callback = unsafe { &*(*context.cast::<ManagerValueContext>()).callback };
    catch_user_panic("manager_value_trampoline", || {
        callback(device, &value);
    });
}

fn retained_device_from_sender(sender: *mut c_void) -> Option<HidDevice> {
    let device = sender.cast::<c_void>();
    if device.is_null() {
        return None;
    }
    unsafe { ffi::CFRetain(device) };
    Some(HidDevice { raw: device.cast() })
}

fn schedule_manager(manager: ffi::IOHIDManagerRef) -> ffi::CFRunLoopRef {
    let run_loop = unsafe { ffi::CFRunLoopGetCurrent() };
    unsafe {
        ffi::IOHIDManagerScheduleWithRunLoop(manager, run_loop, ffi::kCFRunLoopDefaultMode);
    }
    run_loop
}

unsafe fn unschedule_manager(manager: ffi::IOHIDManagerRef, run_loop: ffi::CFRunLoopRef) {
    ffi::IOHIDManagerUnscheduleFromRunLoop(manager, run_loop, ffi::kCFRunLoopDefaultMode);
}

/// Owns a registration from `IOHIDManagerRegisterDeviceMatchingCallback` or `IOHIDManagerRegisterDeviceRemovalCallback`.
pub struct ManagerDeviceSubscription {
    manager: ffi::IOHIDManagerRef,
    run_loop: ffi::CFRunLoopRef,
    context: *mut ManagerDeviceContext,
    kind: ManagerDeviceCallbackKind,
}

unsafe impl Send for ManagerDeviceSubscription {}

impl Drop for ManagerDeviceSubscription {
    fn drop(&mut self) {
        if self.manager.is_null() || self.context.is_null() {
            return;
        }
        unsafe {
            match self.kind {
                ManagerDeviceCallbackKind::Matching => {
                    ffi::IOHIDManagerRegisterDeviceMatchingCallback(
                        self.manager,
                        None,
                        ptr::null_mut(),
                    );
                }
                ManagerDeviceCallbackKind::Removal => {
                    ffi::IOHIDManagerRegisterDeviceRemovalCallback(
                        self.manager,
                        None,
                        ptr::null_mut(),
                    );
                }
            }
            unschedule_manager(self.manager, self.run_loop);
            ffi::CFRelease(self.manager);
            let context = Box::from_raw(self.context);
            let _ = Box::from_raw(context.callback);
        }
        self.manager = ptr::null();
        self.context = ptr::null_mut();
    }
}

/// Owns a registration from `IOHIDManagerRegisterInputReportCallback` or `IOHIDManagerRegisterInputReportWithTimeStampCallback`.
pub struct ManagerReportSubscription {
    manager: ffi::IOHIDManagerRef,
    run_loop: ffi::CFRunLoopRef,
    context: *mut ManagerReportContext,
    kind: ManagerReportCallbackKind,
}

unsafe impl Send for ManagerReportSubscription {}

impl Drop for ManagerReportSubscription {
    fn drop(&mut self) {
        if self.manager.is_null() || self.context.is_null() {
            return;
        }
        unsafe {
            match self.kind {
                ManagerReportCallbackKind::Untimestamped => {
                    ffi::IOHIDManagerRegisterInputReportCallback(
                        self.manager,
                        None,
                        ptr::null_mut(),
                    );
                }
                ManagerReportCallbackKind::Timestamped => {
                    ffi::IOHIDManagerRegisterInputReportWithTimeStampCallback(
                        self.manager,
                        None,
                        ptr::null_mut(),
                    );
                }
            }
            unschedule_manager(self.manager, self.run_loop);
            ffi::CFRelease(self.manager);
            let context = Box::from_raw(self.context);
            let _ = Box::from_raw(context.callback);
        }
        self.manager = ptr::null();
        self.context = ptr::null_mut();
    }
}

/// Owns a registration from `IOHIDManagerRegisterInputValueCallback`.
pub struct ManagerValueSubscription {
    manager: ffi::IOHIDManagerRef,
    run_loop: ffi::CFRunLoopRef,
    context: *mut ManagerValueContext,
}

unsafe impl Send for ManagerValueSubscription {}

impl Drop for ManagerValueSubscription {
    fn drop(&mut self) {
        if self.manager.is_null() || self.context.is_null() {
            return;
        }
        unsafe {
            ffi::IOHIDManagerRegisterInputValueCallback(self.manager, None, ptr::null_mut());
            unschedule_manager(self.manager, self.run_loop);
            ffi::CFRelease(self.manager);
            let context = Box::from_raw(self.context);
            let _ = Box::from_raw(context.callback);
        }
        self.manager = ptr::null();
        self.context = ptr::null_mut();
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
/// Wraps the `IOHIDManagerOptions` bitfield used by `IOHIDManagerCreate`.
pub struct HidManagerOptions(u32);

impl HidManagerOptions {
    /// Mirrors `kIOHIDManagerOptionNone`.
    pub const NONE: Self = Self(ffi::kIOHIDManagerOptionNone);
    /// Mirrors `kIOHIDManagerOptionUsePersistentProperties`.
    pub const USE_PERSISTENT_PROPERTIES: Self =
        Self(ffi::kIOHIDManagerOptionUsePersistentProperties);
    /// Mirrors `kIOHIDManagerOptionDoNotLoadProperties`.
    pub const DO_NOT_LOAD_PROPERTIES: Self = Self(ffi::kIOHIDManagerOptionDoNotLoadProperties);
    /// Mirrors `kIOHIDManagerOptionDoNotSaveProperties`.
    pub const DO_NOT_SAVE_PROPERTIES: Self = Self(ffi::kIOHIDManagerOptionDoNotSaveProperties);
    /// Mirrors `kIOHIDManagerOptionIndependentDevices`.
    pub const INDEPENDENT_DEVICES: Self = Self(ffi::kIOHIDManagerOptionIndependentDevices);

    #[must_use]
    /// Mirrors `IOHIDManagerOptions`.
    pub const fn bits(self) -> ffi::IOHIDManagerOptions {
        self.0
    }

    #[must_use]
    /// Mirrors `IOHIDManagerOptions`.
    pub const fn from_bits(bits: ffi::IOHIDManagerOptions) -> Self {
        Self(bits)
    }
}

impl core::ops::BitOr for HidManagerOptions {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

impl core::ops::BitOrAssign for HidManagerOptions {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

#[allow(clippy::missing_errors_doc, clippy::type_complexity)]
impl HidManager {
    /// Wraps `IOHIDManagerCreate` and `IOHIDManagerOpen`.
    pub fn with_options(options: HidManagerOptions) -> Result<Self, HidError> {
        let bits = options.bits();
        let raw = unsafe { ffi::IOHIDManagerCreate(ffi::kCFAllocatorDefault, bits) };
        if raw.is_null() {
            return Err(HidError::ManagerCreateFailed);
        }
        let status = unsafe { ffi::IOHIDManagerOpen(raw, bits) };
        if status != ffi::kIOReturnSuccess {
            unsafe { ffi::CFRelease(raw) };
            return Err(HidError::ManagerOpenFailed(status));
        }
        Ok(Self { raw })
    }

    /// Wraps `IOHIDManagerSaveToPropertyDomain` with `HidManagerOptions`.
    pub fn save_to_property_domain_with_options(
        &self,
        application_id: &str,
        user_name: &str,
        host_name: &str,
        options: HidManagerOptions,
    ) -> Result<(), HidError> {
        self.save_to_property_domain(application_id, user_name, host_name, options.bits())
    }
    /// Wraps `IOHIDManagerActivate`.
    pub fn activate(&self) {
        unsafe { ffi::IOHIDManagerActivate(self.raw) };
    }

    /// Wraps `IOHIDManagerCancel`.
    pub fn cancel(&self) {
        unsafe { ffi::IOHIDManagerCancel(self.raw) };
    }

    /// Wraps `IOHIDManagerSetInputValueMatching`.
    pub fn set_input_value_matching(
        &self,
        matching: Option<&ElementMatch>,
    ) -> Result<(), HidError> {
        match matching {
            None => unsafe {
                ffi::IOHIDManagerSetInputValueMatching(self.raw, ptr::null());
                Ok(())
            },
            Some(matching) => {
                let dict = matching.to_cf_dictionary()?;
                unsafe {
                    ffi::IOHIDManagerSetInputValueMatching(self.raw, dict);
                    ffi::CFRelease(dict.cast());
                }
                Ok(())
            }
        }
    }

    /// Wraps `IOHIDManagerSetInputValueMatchingMultiple`.
    pub fn set_input_value_matching_multiple(
        &self,
        matches: &[ElementMatch],
    ) -> Result<(), HidError> {
        if matches.is_empty() {
            unsafe {
                ffi::IOHIDManagerSetInputValueMatchingMultiple(self.raw, ptr::null());
            }
            return Ok(());
        }
        let array = build_cf_dictionary_array(matches, ElementMatch::to_cf_dictionary)?;
        unsafe {
            ffi::IOHIDManagerSetInputValueMatchingMultiple(self.raw, array);
            ffi::CFRelease(array.cast());
        }
        Ok(())
    }

    /// Wraps `IOHIDManagerRegisterDeviceMatchingCallback`.
    pub fn on_device_matching<F>(&self, callback: F) -> Result<ManagerDeviceSubscription, HidError>
    where
        F: Fn(HidDevice) + Send + Sync + 'static,
    {
        let run_loop = schedule_manager(self.raw);
        let callback: Box<dyn Fn(HidDevice) + Send + Sync + 'static> = Box::new(callback);
        let callback_ptr = Box::into_raw(Box::new(callback));
        let context_ptr = Box::into_raw(Box::new(ManagerDeviceContext {
            callback: callback_ptr,
        }));
        unsafe {
            ffi::IOHIDManagerRegisterDeviceMatchingCallback(
                self.raw,
                Some(manager_device_trampoline),
                context_ptr.cast(),
            );
            ffi::CFRetain(self.raw);
        }
        Ok(ManagerDeviceSubscription {
            manager: self.raw,
            run_loop,
            context: context_ptr,
            kind: ManagerDeviceCallbackKind::Matching,
        })
    }

    /// Wraps `IOHIDManagerRegisterDeviceRemovalCallback`.
    pub fn on_device_removal<F>(&self, callback: F) -> Result<ManagerDeviceSubscription, HidError>
    where
        F: Fn(HidDevice) + Send + Sync + 'static,
    {
        let run_loop = schedule_manager(self.raw);
        let callback: Box<dyn Fn(HidDevice) + Send + Sync + 'static> = Box::new(callback);
        let callback_ptr = Box::into_raw(Box::new(callback));
        let context_ptr = Box::into_raw(Box::new(ManagerDeviceContext {
            callback: callback_ptr,
        }));
        unsafe {
            ffi::IOHIDManagerRegisterDeviceRemovalCallback(
                self.raw,
                Some(manager_device_trampoline),
                context_ptr.cast(),
            );
            ffi::CFRetain(self.raw);
        }
        Ok(ManagerDeviceSubscription {
            manager: self.raw,
            run_loop,
            context: context_ptr,
            kind: ManagerDeviceCallbackKind::Removal,
        })
    }

    /// Wraps `IOHIDManagerRegisterInputReportCallback`.
    pub fn on_input_report<F>(&self, callback: F) -> Result<ManagerReportSubscription, HidError>
    where
        F: Fn(HidDevice, HidInputReport) + Send + Sync + 'static,
    {
        let run_loop = schedule_manager(self.raw);
        let callback: Box<dyn Fn(HidDevice, HidInputReport) + Send + Sync + 'static> =
            Box::new(callback);
        let callback_ptr = Box::into_raw(Box::new(callback));
        let context_ptr = Box::into_raw(Box::new(ManagerReportContext {
            callback: callback_ptr,
        }));
        unsafe {
            ffi::IOHIDManagerRegisterInputReportCallback(
                self.raw,
                Some(manager_report_trampoline),
                context_ptr.cast(),
            );
            ffi::CFRetain(self.raw);
        }
        Ok(ManagerReportSubscription {
            manager: self.raw,
            run_loop,
            context: context_ptr,
            kind: ManagerReportCallbackKind::Untimestamped,
        })
    }

    /// Wraps `IOHIDManagerRegisterInputReportWithTimeStampCallback`.
    pub fn on_input_report_with_timestamp<F>(
        &self,
        callback: F,
    ) -> Result<ManagerReportSubscription, HidError>
    where
        F: Fn(HidDevice, HidInputReport) + Send + Sync + 'static,
    {
        let run_loop = schedule_manager(self.raw);
        let callback: Box<dyn Fn(HidDevice, HidInputReport) + Send + Sync + 'static> =
            Box::new(callback);
        let callback_ptr = Box::into_raw(Box::new(callback));
        let context_ptr = Box::into_raw(Box::new(ManagerReportContext {
            callback: callback_ptr,
        }));
        unsafe {
            ffi::IOHIDManagerRegisterInputReportWithTimeStampCallback(
                self.raw,
                Some(manager_timestamped_report_trampoline),
                context_ptr.cast(),
            );
            ffi::CFRetain(self.raw);
        }
        Ok(ManagerReportSubscription {
            manager: self.raw,
            run_loop,
            context: context_ptr,
            kind: ManagerReportCallbackKind::Timestamped,
        })
    }

    /// Wraps `IOHIDManagerRegisterInputValueCallback`.
    pub fn on_input_value<F>(&self, callback: F) -> Result<ManagerValueSubscription, HidError>
    where
        F: Fn(HidDevice, &HidValue) + Send + Sync + 'static,
    {
        let run_loop = schedule_manager(self.raw);
        let callback: Box<dyn Fn(HidDevice, &HidValue) + Send + Sync + 'static> =
            Box::new(callback);
        let callback_ptr = Box::into_raw(Box::new(callback));
        let context_ptr = Box::into_raw(Box::new(ManagerValueContext {
            callback: callback_ptr,
        }));
        unsafe {
            ffi::IOHIDManagerRegisterInputValueCallback(
                self.raw,
                Some(manager_value_trampoline),
                context_ptr.cast(),
            );
            ffi::CFRetain(self.raw);
        }
        Ok(ManagerValueSubscription {
            manager: self.raw,
            run_loop,
            context: context_ptr,
        })
    }
}