1
//! Generic-HID plumbing: the channel a platform backend parks reports in.
2
//!
3
//! - The **platform backend** (`dll/src/desktop/extra/hid/<plat>.rs`) opens the raw HID devices and
4
//!   calls [`push_hid_report`] / [`set_hid_devices`].
5
//! - The dll **capability pump** drains both via [`drain_hid_reports`] and [`take_hid_devices`] and
6
//!   folds them into `HidManager`.
7
//! - **Callbacks** read them through `CallbackInfo::get_hid_reports()` / `get_hid_devices()`.
8
//!
9
//! `HidManager` itself lives in azul-core and is pure data; this is only the
10
//! cross-thread channel, mirroring `sensors.rs` verbatim so the two behave the
11
//! same way under a poisoned lock.
12
//!
13
//! # Why reports are a QUEUE and devices are a SNAPSHOT
14
//!
15
//! Every report matters - they are a stream of state changes from a device the
16
//! engine does not model, and dropping one loses an axis movement or a button
17
//! press outright. The device LIST is the opposite: only the newest matters,
18
//! and a backend that re-enumerates on hotplug would otherwise pile up
19
//! successively-stale copies.
20

            
21
use azul_core::hid::{HidDevice, HidReport};
22

            
23
/// The channel: a bounded report queue and a devices snapshot, as a VALUE.
24
///
25
/// A struct rather than two statics so that the process-wide instance the
26
/// platform backends and the capability pump share (`CHANNEL`) is an
27
/// instance — and a test can own its own instead of racing its siblings on a
28
/// global. The free functions below are that instance's methods; callers do
29
/// not change.
30
#[derive(Debug, Default)]
31
pub struct HidChannel {
32
    pending_reports: std::sync::Mutex<Vec<HidReport>>,
33
    devices: std::sync::Mutex<Option<Vec<HidDevice>>>,
34
}
35

            
36
/// The process-wide channel. A global by DESIGN, not by accident: the
37
/// producers are OS callbacks (`IOHIDManager` on macOS, raw input on Windows,
38
/// hidraw reader threads on Linux) that hold no handle to any window, and the
39
/// one consumer is the capability pump on the main thread.
40
static CHANNEL: HidChannel = HidChannel::new();
41

            
42
/// Cap on the parked queue.
43
///
44
/// A HID device can report faster than the frame rate - a 1000 Hz gaming mouse
45
/// or a wheel with force feedback easily does - and if no callback is draining
46
/// (no app subscribed, or the window is not pumping) the queue would grow
47
/// without bound for the life of the process. Oldest are dropped, because the
48
/// newest reports are the ones that still describe the device's state.
49
const MAX_PENDING_REPORTS: usize = 4096;
50

            
51
impl HidChannel {
52
    /// An empty channel. `const` so the process-wide one can be a `static`.
53
    #[must_use]
54
3
    pub const fn new() -> Self {
55
3
        Self {
56
3
            pending_reports: std::sync::Mutex::new(Vec::new()),
57
3
            devices: std::sync::Mutex::new(None),
58
3
        }
59
3
    }
60

            
61
    /// Park a report. Thread-safe; poison-recovering, so a panicking backend
62
    /// thread cannot wedge input.
63
4108
    pub fn push_report(&self, report: HidReport) {
64
4108
        let mut q = self
65
4108
            .pending_reports
66
4108
            .lock()
67
4108
            .unwrap_or_else(std::sync::PoisonError::into_inner);
68
4108
        if q.len() >= MAX_PENDING_REPORTS {
69
10
            // Drop from the FRONT: a bounded queue that dropped the newest
70
10
            // would freeze the device's apparent state at the moment it
71
10
            // overflowed.
72
10
            let overflow = q.len() + 1 - MAX_PENDING_REPORTS;
73
10
            q.drain(..overflow);
74
4098
        }
75
4108
        q.push(report);
76
4108
    }
77

            
78
    /// Drain every parked report, in arrival order.
79
    #[must_use]
80
3
    pub fn drain_reports(&self) -> Vec<HidReport> {
81
3
        let mut q = self
82
3
            .pending_reports
83
3
            .lock()
84
3
            .unwrap_or_else(std::sync::PoisonError::into_inner);
85
3
        core::mem::take(&mut *q)
86
3
    }
87

            
88
    /// Publish the enumerated device list, replacing any previous one.
89
2
    pub fn set_devices(&self, devices: Vec<HidDevice>) {
90
2
        let mut d = self
91
2
            .devices
92
2
            .lock()
93
2
            .unwrap_or_else(std::sync::PoisonError::into_inner);
94
2
        *d = Some(devices);
95
2
    }
96

            
97
    /// Take the device list if a backend published a new one.
98
    ///
99
    /// `None` means "unchanged", NOT "no devices" - the caller must leave the
100
    /// manager's existing list alone, or every pass with no re-enumeration
101
    /// would clear it.
102
    #[must_use]
103
4
    pub fn take_devices(&self) -> Option<Vec<HidDevice>> {
104
4
        let mut d = self
105
4
            .devices
106
4
            .lock()
107
4
            .unwrap_or_else(std::sync::PoisonError::into_inner);
108
4
        d.take()
109
4
    }
110
}
111

            
112
/// Park a report delivered by a platform backend (on the process-wide channel).
113
pub fn push_hid_report(report: HidReport) {
114
    CHANNEL.push_report(report);
115
}
116

            
117
/// Drain every parked report, in arrival order.
118
pub fn drain_hid_reports() -> Vec<HidReport> {
119
    CHANNEL.drain_reports()
120
}
121

            
122
/// Publish the enumerated device list, replacing any previous one.
123
1
pub fn set_hid_devices(devices: Vec<HidDevice>) {
124
1
    CHANNEL.set_devices(devices);
125
1
}
126

            
127
/// Take the device list if a backend published a new one (see
128
/// [`HidChannel::take_devices`] for why `None` means unchanged).
129
2
pub fn take_hid_devices() -> Option<Vec<HidDevice>> {
130
2
    CHANNEL.take_devices()
131
2
}
132

            
133
#[cfg(test)]
134
mod tests {
135
    use super::*;
136

            
137
4109
    fn report(id: u8) -> HidReport {
138
4109
        HidReport {
139
4109
            device: HidDevice {
140
4109
                vendor_id: 1,
141
4109
                product_id: 2,
142
4109
                usage_page: 1,
143
4109
                usage: 4,
144
4109
                name: "test".into(),
145
4109
                serial: "".into(),
146
4109
                instance: 1,
147
4109
            },
148
4109
            report_id: id,
149
4109
            bytes: Vec::new().into(),
150
4109
        }
151
4109
    }
152

            
153
    #[test]
154
1
    fn reports_drain_in_arrival_order() {
155
        // Each test owns its channel. On the parallel runner, tests sharing
156
        // the process-wide one landed their pushes in each other's drains
157
        // (27 reports where 2 were queued).
158
1
        let ch = HidChannel::new();
159
1
        ch.push_report(report(1));
160
1
        ch.push_report(report(2));
161
1
        let got = ch.drain_reports();
162
1
        assert_eq!(got.len(), 2);
163
1
        assert_eq!(got[0].report_id, 1);
164
1
        assert_eq!(got[1].report_id, 2);
165
1
        assert!(ch.drain_reports().is_empty(), "drain must empty the queue");
166
1
    }
167

            
168
    /// A 1000 Hz device with nothing draining would otherwise grow the queue
169
    /// for the life of the process.
170
    #[test]
171
1
    fn the_queue_is_bounded_and_drops_the_oldest() {
172
1
        let ch = HidChannel::new();
173
4106
        for i in 0..(MAX_PENDING_REPORTS + 10) {
174
4106
            ch.push_report(report((i % 251) as u8));
175
4106
        }
176
1
        let got = ch.drain_reports();
177
1
        assert_eq!(
178
1
            got.len(),
179
            MAX_PENDING_REPORTS,
180
            "the queue must stay bounded"
181
        );
182
        // The SURVIVORS must be the newest: dropping the newest instead would
183
        // freeze the device's apparent state at the overflow point.
184
1
        let expected_first = 10_u8;
185
1
        assert_eq!(got[0].report_id, expected_first);
186
1
    }
187

            
188
    /// `None` means UNCHANGED, not empty - a caller that treated it as empty
189
    /// would clear the device list on every pass that did not re-enumerate.
190
    #[test]
191
1
    fn taking_devices_twice_reports_unchanged_the_second_time() {
192
1
        let ch = HidChannel::new();
193
1
        ch.set_devices(vec![report(0).device]);
194
1
        assert_eq!(ch.take_devices().map(|d| d.len()), Some(1));
195
1
        assert!(
196
1
            ch.take_devices().is_none(),
197
            "a second take must say UNCHANGED, not empty"
198
        );
199
1
    }
200

            
201
    #[test]
202
1
    fn an_empty_device_list_is_distinguishable_from_unchanged() {
203
1
        let _ = take_hid_devices();
204
1
        set_hid_devices(Vec::new());
205
1
        assert_eq!(
206
1
            take_hid_devices().map(|d| d.len()),
207
            Some(0),
208
            "publishing zero devices must be observable"
209
        );
210
1
    }
211
}