1
//! Application-level hotplug events — devices and monitors arriving or leaving.
2
//!
3
//! These differ from every other manager in this directory: they are not
4
//! per-node and not hit-tested. A monitor being unplugged belongs to the
5
//! application, not to whichever node happened to be under the cursor, so the
6
//! events dispatch at the root and reach subscribers by propagation. That is
7
//! what the `ApplicationEventFilter` family is for.
8
//!
9
//! The family was structurally unreachable before this arc — `matches_filter_phase`
10
//! returned a flat `false` for it — so nothing had ever needed a producer and
11
//! no queue existed for the shells to push into. This is that queue.
12
//!
13
//! Gamepads do NOT go through here: `GamepadManager` already owns pad state and
14
//! detects its own arrive/leave edges, so routing them here as well would
15
//! double-fire.
16

            
17
use alloc::vec::Vec;
18

            
19
use azul_core::{
20
    dom::DomNodeId,
21
    events::{EventData, EventProvider, EventSource, EventType, SyntheticEvent},
22
    task::Instant,
23
};
24

            
25
/// What kind of thing was plugged or unplugged.
26
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27
pub enum HotplugKind {
28
    /// An input device (keyboard, pointer, touch, tablet tool or pad).
29
    Device,
30
    /// A display.
31
    Monitor,
32
}
33

            
34
/// One hotplug transition awaiting emission.
35
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36
pub struct Hotplug {
37
    /// Device or monitor.
38
    pub kind: HotplugKind,
39
    /// `true` = arrived, `false` = left.
40
    pub connected: bool,
41
}
42

            
43
/// Raw pointer motion awaiting dispatch, in device units.
44
#[derive(Debug, Clone, Copy, PartialEq, Default)]
45
pub struct PendingRawMotion {
46
    pub dx: f64,
47
    pub dy: f64,
48
    pub device_id: u64,
49
}
50

            
51
/// Collects hotplug transitions from the platform backends and yields them as
52
/// `ApplicationEventFilter` events.
53
// No Eq: raw motion is f64, and a float has no total equality.
54
#[derive(Debug, Clone, Default, PartialEq)]
55
pub struct DeviceEventManager {
56
    pending: Vec<Hotplug>,
57
    /// Raw motion accumulated since the last drain. Coalesced rather than
58
    /// queued: a gaming mouse reports up to 1000 times a second, and one
59
    /// callback per report would swamp an app that only wants to know how far
60
    /// the pointer moved this frame.
61
    pending_raw_motion: Option<PendingRawMotion>,
62
}
63

            
64
impl DeviceEventManager {
65
    #[must_use]
66
7579
    pub fn new() -> Self {
67
7579
        Self::default()
68
7579
    }
69

            
70
    /// Record that an input device arrived or left.
71
    ///
72
    /// Called from the backends that can actually observe it: Wayland
73
    /// `wl_seat.capabilities` and the `zwp_tablet_seat_v2` add/remove events,
74
    /// X11 `XI_HierarchyChanged`, Win32 `WM_DEVICECHANGE`.
75
    pub fn note_device(&mut self, connected: bool) {
76
        self.pending.push(Hotplug {
77
            kind: HotplugKind::Device,
78
            connected,
79
        });
80
    }
81

            
82
    /// Record that a monitor arrived or left.
83
    ///
84
    /// Wayland gets this from `wl_registry.global`/`global_remove` for
85
    /// `wl_output`, Win32 from `WM_DISPLAYCHANGE`, macOS from
86
    /// `NSApplicationDidChangeScreenParameters`, X11 from `RandR`.
87
4
    pub fn note_monitor(&mut self, connected: bool) {
88
4
        self.pending.push(Hotplug {
89
4
            kind: HotplugKind::Monitor,
90
4
            connected,
91
4
        });
92
4
    }
93

            
94
    /// Record a monitor-count change as the arrivals/departures it implies.
95
    ///
96
    /// The backends mostly learn "the display topology changed, here is the
97
    /// new list" rather than "monitor X left", so this turns a before/after
98
    /// count into events. Equal counts emit nothing — a resolution or
99
    /// position change is `WindowMonitorChanged`, not a hotplug.
100
4
    pub fn note_monitor_count_change(&mut self, before: usize, after: usize) {
101
4
        for _ in before..after {
102
2
            self.note_monitor(true);
103
2
        }
104
4
        for _ in after..before {
105
2
            self.note_monitor(false);
106
2
        }
107
4
    }
108

            
109
    /// Accumulate raw pointer motion. Called by the backends while the
110
    /// pointer is locked.
111
    pub fn note_raw_motion(&mut self, dx: f64, dy: f64, device_id: u64) {
112
        let e = self.pending_raw_motion.get_or_insert(PendingRawMotion {
113
            dx: 0.0,
114
            dy: 0.0,
115
            device_id,
116
        });
117
        e.dx += dx;
118
        e.dy += dy;
119
        e.device_id = device_id;
120
    }
121

            
122
    /// Read the accumulated raw motion without consuming it — what a
123
    /// callback does while the event is being dispatched.
124
    #[must_use]
125
8
    pub const fn peek_raw_motion(&self) -> Option<PendingRawMotion> {
126
8
        self.pending_raw_motion
127
8
    }
128

            
129
    /// Drain the accumulated raw motion.
130
    pub const fn take_raw_motion(&mut self) -> Option<PendingRawMotion> {
131
        self.pending_raw_motion.take()
132
    }
133

            
134
    /// Whether anything is queued (lets a backend skip the drain entirely).
135
    #[must_use]
136
8
    pub const fn has_pending(&self) -> bool {
137
8
        !self.pending.is_empty()
138
8
    }
139

            
140
    /// Drain the queue.
141
    pub fn take_pending(&mut self) -> Vec<Hotplug> {
142
        core::mem::take(&mut self.pending)
143
    }
144
}
145

            
146
impl EventProvider for DeviceEventManager {
147
    /// Yield `DeviceConnected` / `DeviceDisconnected` / `MonitorConnected` /
148
    /// `MonitorDisconnected` at the root for each queued transition.
149
12
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
150
12
        let mut events: Vec<SyntheticEvent> = Vec::new();
151
12
        if let Some(m) = self.pending_raw_motion {
152
            events.push(SyntheticEvent::new(
153
                EventType::RawMouseMotion,
154
                EventSource::User,
155
                DomNodeId::ROOT,
156
                timestamp.clone(),
157
                EventData::RawMotion(azul_core::events::RawMotionEventData {
158
                    dx: m.dx,
159
                    dy: m.dy,
160
                    device_id: m.device_id,
161
                }),
162
            ));
163
12
        }
164
12
        events.extend(self.pending.iter().map(|h| {
165
4
            let event_type = match (h.kind, h.connected) {
166
                (HotplugKind::Device, true) => EventType::DeviceConnected,
167
                (HotplugKind::Device, false) => EventType::DeviceDisconnected,
168
2
                (HotplugKind::Monitor, true) => EventType::MonitorConnected,
169
2
                (HotplugKind::Monitor, false) => EventType::MonitorDisconnected,
170
            };
171
4
            SyntheticEvent::new(
172
4
                event_type,
173
4
                EventSource::User,
174
                DomNodeId::ROOT,
175
4
                timestamp.clone(),
176
4
                EventData::None,
177
            )
178
4
        }));
179
12
        events
180
12
    }
181
}
182

            
183
#[cfg(test)]
184
mod monitor_hotplug_tests {
185
    use azul_core::events::{EventProvider, EventType};
186

            
187
    use super::DeviceEventManager;
188

            
189
4
    fn kinds(m: &DeviceEventManager) -> Vec<EventType> {
190
4
        let ts = azul_core::task::Instant::Tick(azul_core::task::SystemTick::new(0));
191
4
        m.get_pending_events(ts)
192
4
            .iter()
193
4
            .map(|e| e.event_type)
194
4
            .collect()
195
4
    }
196

            
197
    /// A count diff becomes the arrivals and departures it implies.
198
    ///
199
    /// The backends mostly learn "the display topology changed, here is the
200
    /// new list" rather than "output HDMI-1 left" — RandR, `WM_DISPLAYCHANGE`
201
    /// and `didChangeScreenParameters` all report it that way — so the count
202
    /// is what there is to work from.
203
    #[test]
204
1
    fn a_monitor_count_change_becomes_arrivals_and_departures() {
205
1
        let mut m = DeviceEventManager::default();
206
1
        m.note_monitor_count_change(1, 3);
207
1
        assert_eq!(
208
1
            kinds(&m),
209
1
            vec![EventType::MonitorConnected, EventType::MonitorConnected],
210
            "two monitors arrived",
211
        );
212

            
213
1
        let mut m = DeviceEventManager::default();
214
1
        m.note_monitor_count_change(3, 1);
215
1
        assert_eq!(
216
1
            kinds(&m),
217
1
            vec![
218
1
                EventType::MonitorDisconnected,
219
1
                EventType::MonitorDisconnected
220
            ],
221
            "two monitors left",
222
        );
223
1
    }
224

            
225
    /// An UNCHANGED count is not a hotplug.
226
    ///
227
    /// A screen-configuration event fires for a resolution or position change
228
    /// too, and reporting those as a disconnect-plus-connect would make an app
229
    /// tear down and rebuild per-monitor state on every mode switch. That is
230
    /// `WindowMonitorChanged`, not a hotplug.
231
    #[test]
232
1
    fn an_unchanged_monitor_count_emits_nothing() {
233
1
        let mut m = DeviceEventManager::default();
234
1
        m.note_monitor_count_change(2, 2);
235
1
        assert!(kinds(&m).is_empty());
236
1
        m.note_monitor_count_change(0, 0);
237
1
        assert!(kinds(&m).is_empty());
238
1
    }
239
}