1
//! Media keys arriving from OUTSIDE the keyboard stream.
2
//!
3
//! On Linux the desktop environment usually grabs the media keys, so
4
//! `XF86AudioPlay` and friends never reach the application as keysyms - the
5
//! 9h-i keysym table only sees them when nothing grabbed them. The transport in
6
//! that case is MPRIS over D-Bus, which arrives on a D-Bus thread rather than
7
//! in a window's event stream, so it needs a channel like the sensor and HID
8
//! backends have.
9
//!
10
//! What comes out is an ordinary [`VirtualKeyCode`], because that is the
11
//! contract every other media-key producer already follows: the Win32
12
//! `WM_APPCOMMAND` arm and the X11/Wayland keysym table both deliver
13
//! `PlayPause` as a normal key, so an app binding it works unchanged
14
//! everywhere.
15

            
16
use azul_core::window::VirtualKeyCode;
17

            
18
static PENDING: std::sync::Mutex<Vec<VirtualKeyCode>> = std::sync::Mutex::new(Vec::new());
19

            
20
/// A person cannot press play more often than this between frames; anything
21
/// beyond it is a stuck sender, and an unbounded queue would grow for the life
22
/// of the process.
23
const MAX_PENDING: usize = 64;
24

            
25
/// Park a media key delivered by a platform backend, from any thread.
26
///
27
/// # A key already pending is DROPPED, and that is what makes two transports
28
/// safe
29
///
30
/// On Windows both `WM_APPCOMMAND` and the SMTC `ButtonPressed` event can
31
/// report the same physical press, and which of the two fires depends on
32
/// whether an app has registered a media session - a question that cannot be
33
/// answered from here, and answering it wrong either doubles every press or
34
/// loses all of them. Collapsing a key that is ALREADY WAITING in this batch
35
/// removes the question: one press produces one key however many transports
36
/// saw it.
37
///
38
/// This is not a time window and needs no constant. The queue is drained once
39
/// per event pass, so "already pending" means "reported since the last frame";
40
/// a person cannot press play twice inside one frame, and a genuine double
41
/// press lands in different batches and survives. Same argument the haptic
42
/// queue's adjacent-dedup makes.
43
122
pub fn push_media_key(key: VirtualKeyCode) {
44
122
    let mut q = PENDING
45
122
        .lock()
46
122
        .unwrap_or_else(std::sync::PoisonError::into_inner);
47
122
    if q.len() >= MAX_PENDING {
48
        return;
49
122
    }
50
122
    if q.contains(&key) {
51
111
        return;
52
11
    }
53
11
    q.push(key);
54
122
}
55

            
56
/// Drain the parked media keys, in arrival order.
57
10
pub fn drain_media_keys() -> Vec<VirtualKeyCode> {
58
10
    let mut q = PENDING
59
10
        .lock()
60
10
        .unwrap_or_else(std::sync::PoisonError::into_inner);
61
10
    core::mem::take(&mut *q)
62
10
}
63

            
64
/// Seeks from the platform's media controls (9h-i-a-i-a), queued the same way
65
/// as the keys above and for the same reason: the D-Bus / SMTC / remote
66
/// command callbacks run on their own threads, and the window drains them at
67
/// the top of its pass.
68
static PENDING_REQUESTS: std::sync::Mutex<Vec<azul_core::media_session::MediaControlRequest>> =
69
    std::sync::Mutex::new(Vec::new());
70

            
71
/// Queue one seek request. Unlike keys, seeks are NOT de-duplicated: two
72
/// `Seek(+5s)` in one batch mean ten seconds, and a `SetPosition` after a
73
/// `Seek` is a different destination.
74
pub fn push_media_control(request: azul_core::media_session::MediaControlRequest) {
75
    if let Ok(mut q) = PENDING_REQUESTS.lock() {
76
        q.push(request);
77
    }
78
}
79

            
80
/// Take every queued seek, oldest first.
81
pub fn drain_media_controls() -> Vec<azul_core::media_session::MediaControlRequest> {
82
    PENDING_REQUESTS
83
        .lock()
84
        .map(|mut q| core::mem::take(&mut *q))
85
        .unwrap_or_default()
86
}
87

            
88
/// System audio changes (9h-i-a-i-d-i) - an iOS interruption notification,
89
/// an Android focus change - arriving on their own threads, queued like the
90
/// requests above and drained at the top of the pass. NOT de-duplicated:
91
/// `Interrupted` then `Resumed` in one batch is two things the app must do.
92
static PENDING_AUDIO_CHANGES: std::sync::Mutex<Vec<azul_core::media_session::SystemAudioChange>> =
93
    std::sync::Mutex::new(Vec::new());
94

            
95
/// Queue one system audio change.
96
pub fn push_system_audio_change(change: azul_core::media_session::SystemAudioChange) {
97
    if let Ok(mut q) = PENDING_AUDIO_CHANGES.lock() {
98
        q.push(change);
99
    }
100
}
101

            
102
/// Take every queued change, oldest first.
103
pub fn drain_system_audio_changes() -> Vec<azul_core::media_session::SystemAudioChange> {
104
    PENDING_AUDIO_CHANGES
105
        .lock()
106
        .map(|mut q| core::mem::take(&mut *q))
107
        .unwrap_or_default()
108
}
109

            
110
#[cfg(test)]
111
mod tests {
112
    use super::*;
113

            
114
    /// `PENDING` is a process-global, and the test harness runs these in
115
    /// parallel - so without this one test drains another's keys and the
116
    /// failure looks like a bug in the queue. Serialising is the standard fix
117
    /// and is cheaper than making the queue per-test.
118
    static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
119

            
120
3
    fn exclusive() -> std::sync::MutexGuard<'static, ()> {
121
3
        let g = SERIAL
122
3
            .lock()
123
3
            .unwrap_or_else(std::sync::PoisonError::into_inner);
124
3
        let _ = drain_media_keys();
125
3
        g
126
3
    }
127

            
128
    #[test]
129
1
    fn keys_drain_in_arrival_order_and_empty_the_queue() {
130
1
        let _guard = exclusive();
131
1
        push_media_key(VirtualKeyCode::PlayPause);
132
1
        push_media_key(VirtualKeyCode::NextTrack);
133
1
        let got = drain_media_keys();
134
1
        assert_eq!(
135
            got,
136
1
            vec![VirtualKeyCode::PlayPause, VirtualKeyCode::NextTrack]
137
        );
138
1
        assert!(drain_media_keys().is_empty());
139
1
    }
140

            
141
    /// A stuck sender must not grow the queue without bound.
142
    /// TWO TRANSPORTS, ONE PRESS. Windows can report the same media key
143
    /// through `WM_APPCOMMAND` and through SMTC's `ButtonPressed`; without
144
    /// this, a single play press would toggle playback twice and land back
145
    /// where it started.
146
    #[test]
147
1
    fn the_same_key_reported_twice_in_one_batch_collapses() {
148
1
        let _guard = exclusive();
149
1
        push_media_key(VirtualKeyCode::PlayPause);
150
1
        push_media_key(VirtualKeyCode::PlayPause);
151
1
        assert_eq!(drain_media_keys(), vec![VirtualKeyCode::PlayPause]);
152

            
153
        // DIFFERENT keys in one batch are two real presses and both survive.
154
1
        push_media_key(VirtualKeyCode::NextTrack);
155
1
        push_media_key(VirtualKeyCode::PlayPause);
156
1
        assert_eq!(
157
1
            drain_media_keys(),
158
1
            vec![VirtualKeyCode::NextTrack, VirtualKeyCode::PlayPause]
159
        );
160

            
161
        // And a genuine double press in SEPARATE batches is not collapsed -
162
        // the whole point of keying on "still pending" rather than on a timer.
163
1
        push_media_key(VirtualKeyCode::PlayPause);
164
1
        assert_eq!(drain_media_keys(), vec![VirtualKeyCode::PlayPause]);
165
1
        push_media_key(VirtualKeyCode::PlayPause);
166
1
        assert_eq!(drain_media_keys(), vec![VirtualKeyCode::PlayPause]);
167
1
    }
168

            
169
    #[test]
170
1
    fn a_stuck_sender_cannot_grow_the_queue() {
171
1
        let _guard = exclusive();
172
        // A STUCK SENDER CANNOT GROW THE QUEUE AT ALL any more, which is a
173
        // stronger statement than the old `MAX_PENDING` cap: the dedup bounds
174
        // the queue by the number of DISTINCT keys, and there are four media
175
        // keys. `MAX_PENDING` stays as a belt-and-braces guard for a future
176
        // key set, so this asserts the real invariant rather than a cap it can
177
        // no longer reach.
178
1
        let keys = [
179
1
            VirtualKeyCode::PlayPause,
180
1
            VirtualKeyCode::NextTrack,
181
1
            VirtualKeyCode::PrevTrack,
182
1
            VirtualKeyCode::MediaStop,
183
1
        ];
184
114
        for i in 0..(MAX_PENDING + 50) {
185
114
            push_media_key(keys[i % keys.len()]);
186
114
        }
187
1
        let drained = drain_media_keys();
188
1
        assert_eq!(
189
1
            drained.len(),
190
1
            keys.len(),
191
            "a sender repeating four keys forever must leave exactly four, got {drained:?}"
192
        );
193
1
        assert!(drained.len() <= MAX_PENDING);
194
1
    }
195
}