1
//! Eyedropper manager - the state behind `CallbackInfo::pick_screen_color`.
2
//!
3
//! **Request-driven**, like the biometric manager, and shaped the same way:
4
//!
5
//! - A **callback** (the colour picker's eyedropper icon) calls
6
//!   `CallbackInfo::pick_screen_color()`. That allocates a request id, records it on THIS window's
7
//!   manager and parks the request in the process-global channel [`push_request`].
8
//!
9
//! - The dll's event pass drains the channel ([`drain_requests`]) and hands each request to the
10
//!   platform eyedropper: macOS's system sampler (`NSColorSampler`, no screen-recording permission
11
//!   needed), or - on X11, Windows and Wayland - a screenshot (Wayland asks the user through the
12
//!   desktop portal first; the others can read the screen freely) shown in a fullscreen loupe
13
//!   window where the user picks a pixel.
14
//!
15
//! - When the user picks or cancels, the backend parks the outcome in [`push_result`]. Every
16
//!   window's pass drains the results addressed TO IT ([`drain_results_for`]) - results are routed
17
//!   by request id, so the window whose callback asked is the window whose callbacks hear
18
//!   `EventType::ScreenColorPicked` (window-level, target = root) and read the colour with
19
//!   `CallbackInfo::get_picked_screen_color()`.
20
//!
21
//! While any pick is in flight ([`in_flight_anywhere`]) a popup must not
22
//! light-dismiss on focus loss: the loupe window (or the system sampler)
23
//! takes the focus, and the colour picker popup that asked has to still be
24
//! there when the answer comes back.
25
//!
26
//! No platform deps: `azul-layout` stays platform-free; the dll owns the
27
//! screen reading.
28

            
29
use alloc::vec::Vec;
30
use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
31

            
32
use azul_core::{
33
    dom::DomNodeId,
34
    events::{EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent},
35
    task::Instant,
36
};
37
use azul_css::props::basic::color::ColorU;
38

            
39
/// Per-window eyedropper state.
40
#[derive(Debug, Clone, Default, PartialEq, Eq)]
41
pub struct EyedropperManager {
42
    /// Request ids this window issued whose outcome is still outstanding.
43
    /// Non-empty keeps the capability pump's timer armed so the reply
44
    /// reaches callbacks in an otherwise idle app.
45
    issued: Vec<u64>,
46
    /// The outcome of the most recently completed pick: `Some(None)` =
47
    /// cancelled, `Some(Some(c))` = picked, `None` = never completed. The
48
    /// three states are the point — the nested option is deliberate.
49
    #[allow(clippy::option_option)]
50
    last_result: Option<Option<ColorU>>,
51
    /// A pick completed since the last event pass - yield the event once.
52
    pending_event: bool,
53
}
54

            
55
impl EyedropperManager {
56
    #[must_use]
57
7581
    pub fn new() -> Self {
58
7581
        Self::default()
59
7581
    }
60

            
61
    /// Allocate a request id and record it as outstanding on this window.
62
2
    pub fn begin_request(&mut self) -> u64 {
63
2
        let id = NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
64
2
        self.issued.push(id);
65
2
        IN_FLIGHT.fetch_add(1, Ordering::Relaxed);
66
2
        id
67
2
    }
68

            
69
    /// The ids this window is waiting on.
70
    #[must_use]
71
18
    pub fn issued(&self) -> &[u64] {
72
18
        &self.issued
73
18
    }
74

            
75
    /// `true` while this window waits on a pick (the pump's arming signal).
76
    #[must_use]
77
9
    pub const fn has_pending_async(&self) -> bool {
78
9
        !self.issued.is_empty()
79
9
    }
80

            
81
    /// Fold a result addressed to one of this window's requests. Returns
82
    /// whether it was ours (and therefore folded).
83
3
    pub fn fold_result(&mut self, request_id: u64, color: Option<ColorU>) -> bool {
84
3
        let Some(i) = self.issued.iter().position(|id| *id == request_id) else {
85
1
            return false;
86
        };
87
2
        self.issued.remove(i);
88
2
        IN_FLIGHT.fetch_sub(1, Ordering::Relaxed);
89
2
        self.last_result = Some(color);
90
2
        self.pending_event = true;
91
2
        true
92
3
    }
93

            
94
    /// The most recently completed pick: `None` until one completes,
95
    /// `Some(None)` when the user cancelled.
96
    #[must_use]
97
18
    pub const fn last_result(&self) -> Option<Option<ColorU>> {
98
18
        self.last_result
99
18
    }
100

            
101
    /// Move every outstanding request id out of this manager — for a window
102
    /// that is closing while a pick it asked for is still in flight. The
103
    /// global in-flight count is deliberately untouched: the ids MUST be
104
    /// handed to another window's manager ([`Self::adopt_issued`]), or the
105
    /// count leaks and popups stop light-dismissing forever.
106
    pub fn take_issued(&mut self) -> Vec<u64> {
107
        core::mem::take(&mut self.issued)
108
    }
109

            
110
    /// Adopt outstanding request ids taken from a closing window — the color
111
    /// picker popup that asked for a screen pick and died (compositor
112
    /// `popup_done`, the loupe's grab break) before the answer arrived. Results
113
    /// are routed by request id, so after adoption THIS window's pass drains
114
    /// them and its `ScreenColorPicked` fires here instead of nowhere.
115
    pub fn adopt_issued(&mut self, ids: Vec<u64>) {
116
        self.issued.extend(ids);
117
    }
118

            
119
    /// The dll clears this after the event pass collected the event.
120
    pub const fn clear_pending_event(&mut self) {
121
        self.pending_event = false;
122
    }
123
}
124

            
125
impl EventProvider for EyedropperManager {
126
    /// One window-level `ScreenColorPicked` per completed pick.
127
1
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
128
1
        if self.pending_event {
129
1
            alloc::vec![SyntheticEvent::new(
130
1
                EventType::ScreenColorPicked,
131
1
                CoreEventSource::User,
132
                DomNodeId::ROOT,
133
1
                timestamp,
134
1
                EventData::None,
135
            )]
136
        } else {
137
            Vec::new()
138
        }
139
1
    }
140
}
141

            
142
static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
143
/// Picks in flight across every window of the process.
144
static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
145

            
146
/// `true` while any window waits on a pick. Popups read this to stay open
147
/// through the focus loss the loupe / system sampler causes.
148
#[must_use]
149
2
pub fn in_flight_anywhere() -> bool {
150
2
    IN_FLIGHT.load(Ordering::Relaxed) > 0
151
2
}
152

            
153
/// A pick the platform backend has to run.
154
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155
pub struct EyedropperRequest {
156
    /// Routes the result back to the window that asked.
157
    pub request_id: u64,
158
}
159

            
160
/// A finished pick: the colour under the pointer, or `None` if cancelled.
161
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162
pub struct EyedropperResult {
163
    pub request_id: u64,
164
    pub color: Option<ColorU>,
165
}
166

            
167
static PENDING_REQUESTS: std::sync::Mutex<Vec<EyedropperRequest>> =
168
    std::sync::Mutex::new(Vec::new());
169
static PENDING_RESULTS: std::sync::Mutex<Vec<EyedropperResult>> = std::sync::Mutex::new(Vec::new());
170

            
171
/// Queue a pick for the platform backend (from a callback, any thread).
172
pub fn push_request(request: EyedropperRequest) {
173
    let mut q = PENDING_REQUESTS
174
        .lock()
175
        .unwrap_or_else(std::sync::PoisonError::into_inner);
176
    q.push(request);
177
}
178

            
179
/// Take every queued pick. The dll dispatches each to the platform.
180
pub fn drain_requests() -> Vec<EyedropperRequest> {
181
    let mut q = PENDING_REQUESTS
182
        .lock()
183
        .unwrap_or_else(std::sync::PoisonError::into_inner);
184
    core::mem::take(&mut *q)
185
}
186

            
187
/// Park a finished pick (from the platform backend - the loupe window's
188
/// click handler, or the system sampler's completion block).
189
2
pub fn push_result(result: EyedropperResult) {
190
2
    let mut q = PENDING_RESULTS
191
2
        .lock()
192
2
        .unwrap_or_else(std::sync::PoisonError::into_inner);
193
2
    q.push(result);
194
2
}
195

            
196
/// Take the parked results addressed to `ids`, leaving the others for the
197
/// window that issued them.
198
2
pub fn drain_results_for(ids: &[u64]) -> Vec<EyedropperResult> {
199
2
    let mut q = PENDING_RESULTS
200
2
        .lock()
201
2
        .unwrap_or_else(std::sync::PoisonError::into_inner);
202
2
    let (mine, others): (Vec<_>, Vec<_>) = core::mem::take(&mut *q)
203
2
        .into_iter()
204
3
        .partition(|r| ids.contains(&r.request_id));
205
2
    *q = others;
206
2
    mine
207
2
}
208

            
209
#[cfg(test)]
210
mod tests {
211
    use super::*;
212

            
213
    #[test]
214
1
    fn results_are_routed_to_the_window_that_asked() {
215
1
        let mut a = EyedropperManager::new();
216
1
        let mut b = EyedropperManager::new();
217
1
        let ra = a.begin_request();
218
1
        let rb = b.begin_request();
219
1
        assert!(in_flight_anywhere());
220
1
        push_result(EyedropperResult {
221
1
            request_id: rb,
222
1
            color: None,
223
1
        });
224
1
        push_result(EyedropperResult {
225
1
            request_id: ra,
226
1
            color: Some(ColorU {
227
1
                r: 1,
228
1
                g: 2,
229
1
                b: 3,
230
1
                a: 255,
231
1
            }),
232
1
        });
233

            
234
1
        let for_a = drain_results_for(a.issued());
235
1
        assert_eq!(for_a.len(), 1);
236
1
        assert_eq!(for_a[0].request_id, ra);
237
2
        for r in for_a {
238
1
            assert!(a.fold_result(r.request_id, r.color));
239
        }
240
1
        assert_eq!(
241
1
            a.last_result(),
242
            Some(Some(ColorU {
243
                r: 1,
244
                g: 2,
245
                b: 3,
246
                a: 255
247
            }))
248
        );
249
1
        assert!(!a.has_pending_async());
250
1
        assert_eq!(
251
1
            a.get_pending_events(Instant::Tick(azul_core::task::SystemTick {
252
1
                tick_counter: 0
253
1
            }))
254
1
            .len(),
255
            1
256
        );
257

            
258
        // b's result was left in the channel for b.
259
1
        let for_b = drain_results_for(b.issued());
260
1
        assert_eq!(for_b.len(), 1);
261
1
        assert!(b.fold_result(rb, None));
262
1
        assert_eq!(b.last_result(), Some(None), "cancelled");
263
1
        assert!(!in_flight_anywhere());
264

            
265
        // A result for nobody is not ours.
266
1
        assert!(!a.fold_result(999, None));
267
1
    }
268
}