Skip to main content

sui_platform/
debug_capture.rs

1//! Debug captures requested by the running app.
2//!
3//! An app asks for a capture of a window with
4//! [`request_window_debug_capture`]. After its next redraw the platform
5//! renders the window's last frame again offscreen at the requested stage
6//! and starts copying it back. Native platforms wait for the copy; browsers,
7//! which cannot wait, collect it on a later redraw. Either way the artifact
8//! is kept for the app to collect with [`take_window_debug_capture`], and if
9//! the request carried an [`AsyncWakeToken`], the widget that registered it
10//! is woken then.
11//!
12//! The platforms here do the capturing. A host that drives its own event
13//! loop redraws while [`has_pending_window_debug_captures`] and calls
14//! [`service_window_debug_captures`] after each redraw.
15
16use std::{
17    collections::HashMap,
18    sync::{
19        Mutex, MutexGuard, OnceLock, PoisonError,
20        atomic::{AtomicU64, Ordering},
21    },
22};
23
24use sui_core::{AsyncWakeToken, Result, WindowId};
25use sui_render_wgpu::{DebugCaptureArtifact, DebugCaptureId, DebugCaptureRequest, WgpuRenderer};
26
27/// Identifies a requested capture until its result is collected.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub struct DebugCaptureTicket(u64);
30
31struct PendingCapture {
32    ticket: DebugCaptureTicket,
33    request: DebugCaptureRequest,
34    wake: Option<AsyncWakeToken>,
35}
36
37/// A capture the renderer began and is copying back.
38struct InFlightCapture {
39    ticket: DebugCaptureTicket,
40    wake: Option<AsyncWakeToken>,
41}
42
43#[derive(Default)]
44struct CaptureStore {
45    pending: HashMap<WindowId, Vec<PendingCapture>>,
46    in_flight: HashMap<(WindowId, DebugCaptureId), InFlightCapture>,
47    results: HashMap<DebugCaptureTicket, Result<DebugCaptureArtifact>>,
48}
49
50static NEXT_TICKET: AtomicU64 = AtomicU64::new(1);
51
52fn store() -> &'static Mutex<CaptureStore> {
53    static STORE: OnceLock<Mutex<CaptureStore>> = OnceLock::new();
54    STORE.get_or_init(Mutex::default)
55}
56
57fn recover_lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
58    mutex.lock().unwrap_or_else(PoisonError::into_inner)
59}
60
61/// Ask for a capture of `window_id` after its next redraw. When it is done,
62/// `wake` (if any) is delivered to the widget that registered it; collect the
63/// artifact with [`take_window_debug_capture`].
64pub fn request_window_debug_capture(
65    window_id: WindowId,
66    request: DebugCaptureRequest,
67    wake: Option<AsyncWakeToken>,
68) -> DebugCaptureTicket {
69    let ticket = DebugCaptureTicket(NEXT_TICKET.fetch_add(1, Ordering::Relaxed));
70    recover_lock(store())
71        .pending
72        .entry(window_id)
73        .or_default()
74        .push(PendingCapture {
75            ticket,
76            request,
77            wake,
78        });
79    ticket
80}
81
82/// The capture for `ticket`, once the platform has made it. Returns `None`
83/// while it is pending; each result is handed out once.
84pub fn take_window_debug_capture(
85    ticket: DebugCaptureTicket,
86) -> Option<Result<DebugCaptureArtifact>> {
87    recover_lock(store()).results.remove(&ticket)
88}
89
90/// Whether `window_id` has captures waiting for a redraw or being copied
91/// back.
92pub fn has_pending_window_debug_captures(window_id: WindowId) -> bool {
93    let store = recover_lock(store());
94    store
95        .pending
96        .get(&window_id)
97        .is_some_and(|pending| !pending.is_empty())
98        || store
99            .in_flight
100            .keys()
101            .any(|(window, _)| *window == window_id)
102}
103
104/// Begin every capture waiting for `window_id` from the frame `renderer` last
105/// drew for it, collect the ones that are back, and return the wake tokens to
106/// deliver with `Runtime::wake_async`.
107pub fn service_window_debug_captures(
108    renderer: &mut WgpuRenderer,
109    window_id: WindowId,
110) -> Vec<AsyncWakeToken> {
111    service_with(renderer, window_id)
112}
113
114/// What makes captures: the renderer, or a stand-in in tests.
115trait CaptureSource {
116    fn begin(
117        &mut self,
118        window_id: WindowId,
119        request: DebugCaptureRequest,
120    ) -> Result<DebugCaptureId>;
121
122    /// The captures of `window_id` that are back.
123    fn finished(
124        &mut self,
125        window_id: WindowId,
126    ) -> Vec<(DebugCaptureId, Result<DebugCaptureArtifact>)>;
127}
128
129impl CaptureSource for WgpuRenderer {
130    fn begin(
131        &mut self,
132        window_id: WindowId,
133        request: DebugCaptureRequest,
134    ) -> Result<DebugCaptureId> {
135        self.begin_debug_capture(window_id, request)
136    }
137
138    fn finished(
139        &mut self,
140        window_id: WindowId,
141    ) -> Vec<(DebugCaptureId, Result<DebugCaptureArtifact>)> {
142        // Native devices can wait for the copies. Browsers cannot, so their
143        // captures come back on a later redraw, as they do here if waiting
144        // fails.
145        #[cfg(not(target_arch = "wasm32"))]
146        if self.has_debug_captures_in_flight(window_id) {
147            let _ = self.wait_for_debug_captures();
148        }
149        self.take_finished_debug_captures(window_id)
150    }
151}
152
153/// Begin every capture waiting for `window_id` with `source`, keep the
154/// results that are back, and return the wake tokens to deliver.
155fn service_with(source: &mut impl CaptureSource, window_id: WindowId) -> Vec<AsyncWakeToken> {
156    let pending = recover_lock(store())
157        .pending
158        .remove(&window_id)
159        .unwrap_or_default();
160    let mut finished = Vec::new();
161    let mut began = Vec::new();
162    for pending in pending {
163        match source.begin(window_id, pending.request) {
164            Ok(id) => began.push((
165                id,
166                InFlightCapture {
167                    ticket: pending.ticket,
168                    wake: pending.wake,
169                },
170            )),
171            Err(error) => finished.push((pending.ticket, Err(error), pending.wake)),
172        }
173    }
174    let in_flight = {
175        let mut store = recover_lock(store());
176        for (id, capture) in began {
177            store.in_flight.insert((window_id, id), capture);
178        }
179        store
180            .in_flight
181            .keys()
182            .any(|(window, _)| *window == window_id)
183    };
184    let back = if in_flight {
185        source.finished(window_id)
186    } else {
187        Vec::new()
188    };
189
190    let mut store = recover_lock(store());
191    for (id, result) in back {
192        if let Some(capture) = store.in_flight.remove(&(window_id, id)) {
193            finished.push((capture.ticket, result, capture.wake));
194        }
195    }
196    finished
197        .into_iter()
198        .filter_map(|(ticket, result, wake)| {
199            store.results.insert(ticket, result);
200            wake
201        })
202        .collect()
203}
204
205/// Forget captures for a window that closed.
206pub(crate) fn clear_window_debug_captures(window_id: WindowId) {
207    let mut store = recover_lock(store());
208    store.pending.remove(&window_id);
209    store
210        .in_flight
211        .retain(|(window, _), _| *window != window_id);
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use sui_core::Error;
218    use sui_render_wgpu::RgbaImage;
219
220    /// Makes captures that come back after `delay` services, the first
221    /// succeeding and the rest failing.
222    #[derive(Default)]
223    struct StandIn {
224        delay: usize,
225        began: Vec<(DebugCaptureId, usize)>,
226        services: usize,
227    }
228
229    impl CaptureSource for StandIn {
230        fn begin(
231            &mut self,
232            _window_id: WindowId,
233            _request: DebugCaptureRequest,
234        ) -> Result<DebugCaptureId> {
235            let id = DebugCaptureId::new(self.began.len() as u64 + 1);
236            self.began.push((id, self.services));
237            Ok(id)
238        }
239
240        fn finished(
241            &mut self,
242            _window_id: WindowId,
243        ) -> Vec<(DebugCaptureId, Result<DebugCaptureArtifact>)> {
244            self.services += 1;
245            let (ready, waiting) = std::mem::take(&mut self.began)
246                .into_iter()
247                .partition::<Vec<_>, _>(|(_, began)| self.services - began > self.delay);
248            self.began = waiting;
249            ready
250                .into_iter()
251                .map(|(id, _)| {
252                    let artifact = if id.get() == 1 {
253                        RgbaImage::new(1, 1, vec![0, 0, 0, 255]).map(DebugCaptureArtifact::SdrRgba8)
254                    } else {
255                        Err(Error::new("no frame yet"))
256                    };
257                    (id, artifact)
258                })
259                .collect()
260        }
261    }
262
263    #[test]
264    fn captures_wait_for_a_redraw_and_are_handed_out_once() {
265        let window = WindowId::new(90_001);
266        let other = WindowId::new(90_002);
267        let wake = AsyncWakeToken::new(7);
268        let first =
269            request_window_debug_capture(window, DebugCaptureRequest::default(), Some(wake));
270        let second = request_window_debug_capture(window, DebugCaptureRequest::default(), None);
271        assert!(has_pending_window_debug_captures(window));
272        assert!(take_window_debug_capture(first).is_none());
273
274        let mut source = StandIn::default();
275        assert!(service_with(&mut source, other).is_empty());
276        let wakes = service_with(&mut source, window);
277        assert_eq!(wakes, vec![wake]);
278        assert!(!has_pending_window_debug_captures(window));
279
280        assert!(matches!(
281            take_window_debug_capture(first),
282            Some(Ok(DebugCaptureArtifact::SdrRgba8(_)))
283        ));
284        assert!(take_window_debug_capture(first).is_none());
285        assert!(matches!(take_window_debug_capture(second), Some(Err(_))));
286    }
287
288    #[test]
289    fn captures_copied_back_later_stay_pending_until_they_are_back() {
290        let window = WindowId::new(90_003);
291        let wake = AsyncWakeToken::new(8);
292        let ticket =
293            request_window_debug_capture(window, DebugCaptureRequest::default(), Some(wake));
294
295        // Like a browser: the copy is not back on the redraw that began it.
296        let mut source = StandIn {
297            delay: 1,
298            ..StandIn::default()
299        };
300        assert!(service_with(&mut source, window).is_empty());
301        assert!(has_pending_window_debug_captures(window));
302        assert!(take_window_debug_capture(ticket).is_none());
303
304        assert_eq!(service_with(&mut source, window), vec![wake]);
305        assert!(!has_pending_window_debug_captures(window));
306        assert!(matches!(
307            take_window_debug_capture(ticket),
308            Some(Ok(DebugCaptureArtifact::SdrRgba8(_)))
309        ));
310    }
311}