ailloli_ui_winit/capture.rs
1//! Low-level one-shot renderer hook and thread-safe declarative capture queue.
2//!
3//! Capture coordinates are physical pixels. Declarative requests are retained
4//! across wake failures and completed results remain queued until explicitly taken.
5
6use std::collections::BTreeSet;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Mutex};
9
10use ailloli_ui_core::{Color, Rect};
11use ailloli_ui_render_wgpu::capture::encode_png_rgba;
12use ailloli_ui_render_wgpu::{
13 CaptureParams, CapturedFrame, CapturedFrameFormat, LayerPass, Renderer, RendererError,
14};
15use ailloli_ui_runtime::app::{UiWake, UiWakeError};
16use ailloli_ui_runtime::DrawCmd;
17
18/// Result of a single-shot frame capture.
19///
20/// # Examples
21///
22/// ```
23/// use ailloli_ui_render_wgpu::{CapturedFrame, CapturedFrameFormat};
24/// use ailloli_ui_winit::FrameCaptureResult;
25/// let result = FrameCaptureResult { frame: CapturedFrame {
26/// width: 1, height: 1, format: CapturedFrameFormat::Rgba8,
27/// rgba: vec![0, 0, 0, 255], png_data: None,
28/// }};
29/// assert_eq!(result.frame.width, 1);
30/// ```
31#[derive(Debug)]
32pub struct FrameCaptureResult {
33 /// Complete RGBA8 frame and optional PNG payload returned by the renderer.
34 pub frame: CapturedFrame,
35}
36
37/// Thread-safe hook to request a one-shot capture on the next redraw.
38///
39/// **Recommendation:** for apps built with `ailloli_ui::App`, prefer [`CaptureHandle`] and
40/// `AppBuilder::capture(...)` (per logical window or view key, structured results).
41/// This hook suits **low-level** integrations that already own a
42/// `ailloli_ui_render_wgpu::Renderer` and call
43/// [`FrameCaptureHook::capture_if_requested`](Self::capture_if_requested) from their own
44/// `RedrawRequested` loop.
45///
46/// Intended usage:
47/// - keep a clone of this hook in tooling/tests/agent integration
48/// - call [`FrameCaptureHook::request_frame_capture_once`]
49/// - in your redraw path, call [`FrameCaptureHook::capture_if_requested`]
50///
51/// Multiple requests made before consumption coalesce into one capture. The
52/// release/acquire atomic flag is safe to share across threads.
53///
54/// # Examples
55///
56/// ```
57/// let hook = ailloli_ui_winit::FrameCaptureHook::default();
58/// assert!(!hook.is_requested());
59/// hook.request_frame_capture_once();
60/// assert!(hook.is_requested());
61/// ```
62#[derive(Clone, Debug)]
63pub struct FrameCaptureHook {
64 /// Shared one-bit request latch.
65 requested: Arc<AtomicBool>,
66}
67
68/// Creates a hook with no pending request.
69impl Default for FrameCaptureHook {
70 /// Allocates the shared atomic request flag, initially `false`.
71 fn default() -> Self {
72 Self {
73 requested: Arc::new(AtomicBool::new(false)),
74 }
75 }
76}
77
78/// Request-latch observation and capture consumption.
79impl FrameCaptureHook {
80 /// Latches a capture request for the next redraw.
81 ///
82 /// Repeated calls before capture coalesce and do not count separately.
83 ///
84 /// # Examples
85 ///
86 /// ```
87 /// let hook = ailloli_ui_winit::FrameCaptureHook::default();
88 /// hook.request_frame_capture_once();
89 /// hook.request_frame_capture_once();
90 /// assert!(hook.is_requested());
91 /// ```
92 pub fn request_frame_capture_once(&self) {
93 self.requested.store(true, Ordering::Release);
94 }
95
96 /// Observes the request latch without consuming it.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// let hook = ailloli_ui_winit::FrameCaptureHook::default();
102 /// assert!(!hook.is_requested());
103 /// ```
104 pub fn is_requested(&self) -> bool {
105 self.requested.load(Ordering::Acquire)
106 }
107
108 /// If a capture was requested, consumes the request and captures the frame.
109 ///
110 /// Returns `Ok(None)` without touching the renderer when no request is
111 /// pending. The latch is cleared before rendering, so a render failure is
112 /// still a consumed request and a concurrent new request remains pending.
113 ///
114 /// # Errors
115 ///
116 /// Propagates the renderer capture failure.
117 ///
118 /// # Examples
119 ///
120 /// ```no_run
121 /// use ailloli_ui_core::Color;
122 /// use ailloli_ui_render_wgpu::{CaptureParams, LayerPass, Renderer};
123 /// fn capture(hook: &ailloli_ui_winit::FrameCaptureHook, renderer: &mut Renderer) {
124 /// let layers: [LayerPass<'_>; 0] = [];
125 /// let result: Option<ailloli_ui_winit::FrameCaptureResult> = hook
126 /// .capture_if_requested(renderer, Color::BLACK, &layers, CaptureParams::default())
127 /// .unwrap();
128 /// let _ = result;
129 /// }
130 /// ```
131 pub fn capture_if_requested(
132 &self,
133 renderer: &mut Renderer,
134 clear: Color,
135 layers: &[LayerPass<'_>],
136 params: CaptureParams,
137 ) -> Result<Option<FrameCaptureResult>, RendererError> {
138 if self
139 .requested
140 .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
141 .is_err()
142 {
143 return Ok(None);
144 }
145
146 let frame = renderer.render_layered_capture_once(clear, layers, params)?;
147 Ok(Some(FrameCaptureResult { frame }))
148 }
149
150 /// Convenience helper for the common single-layer path (no clipping).
151 ///
152 /// It wraps `cmds` in one [`LayerPass`] and otherwise has the same latch,
153 /// error, and consumption semantics as [`Self::capture_if_requested`].
154 ///
155 /// # Errors
156 ///
157 /// Propagates the renderer capture failure.
158 ///
159 /// # Examples
160 ///
161 /// ```no_run
162 /// use ailloli_ui_core::Color;
163 /// use ailloli_ui_render_wgpu::{CaptureParams, Renderer};
164 /// fn capture(hook: &ailloli_ui_winit::FrameCaptureHook, renderer: &mut Renderer) {
165 /// let result = hook.capture_single_layer_if_requested(
166 /// renderer, Color::BLACK, &[], CaptureParams::default()).unwrap();
167 /// let _: Option<ailloli_ui_winit::FrameCaptureResult> = result;
168 /// }
169 /// ```
170 pub fn capture_single_layer_if_requested(
171 &self,
172 renderer: &mut Renderer,
173 clear: Color,
174 cmds: &[DrawCmd],
175 params: CaptureParams,
176 ) -> Result<Option<FrameCaptureResult>, RendererError> {
177 let pass = [LayerPass::new(cmds)];
178 self.capture_if_requested(renderer, clear, &pass, params)
179 }
180}
181
182/// Opaque id for a capture request.
183///
184/// IDs start at one per [`CaptureHandle`] state and use saturating increment;
185/// after `u64::MAX`, later requests retain that maximum value.
186///
187/// # Examples
188///
189/// ```
190/// let id: ailloli_ui_winit::CaptureRequestId = 1_u64;
191/// assert_eq!(id, 1);
192/// ```
193pub type CaptureRequestId = u64;
194
195/// What to capture: full window or a single element by view key.
196///
197/// Window ids and keys are opaque strings. Empty strings are retained and will
198/// ordinarily fail lookup rather than receiving special treatment.
199///
200/// # Examples
201///
202/// ```
203/// let target = ailloli_ui_winit::CaptureTarget::element("main", "toolbar.save");
204/// assert_eq!(target.window_id(), "main");
205/// ```
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub enum CaptureTarget {
208 /// Entire presentation identified by its logical window id.
209 Window {
210 /// Opaque logical window id.
211 window_id: String,
212 },
213 /// Bounds-cropped element identified by window id and retained view key.
214 Element {
215 /// Opaque logical window id.
216 window_id: String,
217 /// Opaque retained view key, which must resolve exactly once.
218 key: String,
219 },
220}
221
222/// Constructors and shared window-id access.
223impl CaptureTarget {
224 /// Creates a full-window target.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// let target = ailloli_ui_winit::CaptureTarget::window("main");
230 /// assert_eq!(target.window_id(), "main");
231 /// ```
232 pub fn window(window_id: impl Into<String>) -> Self {
233 Self::Window {
234 window_id: window_id.into(),
235 }
236 }
237
238 /// Creates an element target with an exact retained view key.
239 ///
240 /// # Examples
241 ///
242 /// ```
243 /// use ailloli_ui_winit::CaptureTarget;
244 /// let target = CaptureTarget::element("main", "editor");
245 /// assert!(matches!(target, CaptureTarget::Element { key, .. } if key == "editor"));
246 /// ```
247 pub fn element(window_id: impl Into<String>, key: impl Into<String>) -> Self {
248 Self::Element {
249 window_id: window_id.into(),
250 key: key.into(),
251 }
252 }
253
254 /// Returns the logical window id for either target kind.
255 ///
256 /// # Examples
257 ///
258 /// ```
259 /// let target = ailloli_ui_winit::CaptureTarget::window("preview");
260 /// assert_eq!(target.window_id(), "preview");
261 /// ```
262 pub fn window_id(&self) -> &str {
263 match self {
264 Self::Window { window_id } | Self::Element { window_id, .. } => window_id,
265 }
266 }
267}
268
269/// Pending capture with target and render parameters.
270///
271/// # Examples
272///
273/// ```
274/// use ailloli_ui_render_wgpu::CaptureParams;
275/// use ailloli_ui_winit::{CaptureRequest, CaptureTarget};
276/// let request = CaptureRequest { id: 7, target: CaptureTarget::window("main"),
277/// params: CaptureParams::default() };
278/// assert_eq!(request.id, 7);
279/// ```
280#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct CaptureRequest {
282 /// Handle-local request identifier.
283 pub id: CaptureRequestId,
284 /// Full-window or exactly keyed element selection.
285 pub target: CaptureTarget,
286 /// Renderer capture options, including PNG encoding policy.
287 pub params: CaptureParams,
288}
289
290/// Completed capture payload (frame + optional element bounds).
291///
292/// `bounds_px` is `None` for full-window captures and `Some` for successful
293/// element captures. The frame of an element result is already cropped.
294///
295/// # Examples
296///
297/// ```
298/// use ailloli_ui_render_wgpu::{CaptureParams, CapturedFrame, CapturedFrameFormat};
299/// use ailloli_ui_winit::{CaptureRequest, CaptureResult, CaptureTarget};
300/// let result = CaptureResult {
301/// request: CaptureRequest { id: 1, target: CaptureTarget::window("main"),
302/// params: CaptureParams::default() },
303/// frame: CapturedFrame { width: 1, height: 1, format: CapturedFrameFormat::Rgba8,
304/// rgba: vec![0; 4], png_data: None },
305/// bounds_px: None,
306/// };
307/// assert!(result.bounds_px.is_none());
308/// ```
309#[derive(Debug, Clone, PartialEq)]
310pub struct CaptureResult {
311 /// Original request, including its id and render parameters.
312 pub request: CaptureRequest,
313 /// Full or cropped RGBA8 capture.
314 pub frame: CapturedFrame,
315 /// Captured element bounds in physical pixels for element captures.
316 pub bounds_px: Option<Rect>,
317}
318
319/// Capture failure (missing window/element, crop, encode, render).
320///
321/// # Examples
322///
323/// ```
324/// let error = ailloli_ui_winit::CaptureError::WindowNotFound { window_id: "main".into() };
325/// assert!(error.to_string().contains("main"));
326/// ```
327#[derive(Debug, Clone, PartialEq)]
328pub enum CaptureError {
329 /// The requested logical window was absent when unknown requests were resolved.
330 WindowNotFound {
331 /// Requested logical window id.
332 window_id: String,
333 },
334 /// No retained element had the requested key.
335 ElementNotFound {
336 /// Logical window searched.
337 window_id: String,
338 /// Missing retained view key.
339 key: String,
340 },
341 /// More than one retained element had a key that must be unique for capture.
342 DuplicateElementKey {
343 /// Logical window searched.
344 window_id: String,
345 /// Duplicated retained view key.
346 key: String,
347 /// Number of matching elements found.
348 count: usize,
349 },
350 /// The clamped physical crop rectangle had zero width or height.
351 EmptyCrop {
352 /// Requested physical-pixel rectangle before clamp/rounding.
353 rect: Rect,
354 },
355 /// RGBA storage length was not exactly `width * height * 4` bytes.
356 InvalidFrameBuffer {
357 /// Declared physical width.
358 width: u32,
359 /// Declared physical height.
360 height: u32,
361 /// Actual byte length.
362 len: usize,
363 },
364 /// PNG encoding failed with the renderer's diagnostic message.
365 Encode(String),
366 /// Rendering or GPU readback failed with the renderer's diagnostic message.
367 Render(String),
368}
369
370/// Formats stable category text plus identifying values.
371impl std::fmt::Display for CaptureError {
372 /// Formats the stable human-readable capture failure description.
373 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374 match self {
375 Self::WindowNotFound { window_id } => {
376 write!(f, "capture window `{window_id}` was not found")
377 }
378 Self::ElementNotFound { window_id, key } => {
379 write!(
380 f,
381 "capture element `{key}` was not found in window `{window_id}`"
382 )
383 }
384 Self::DuplicateElementKey {
385 window_id,
386 key,
387 count,
388 } => write!(
389 f,
390 "capture element key `{key}` is duplicated {count} times in window `{window_id}`"
391 ),
392 Self::EmptyCrop { rect } => write!(f, "capture crop is empty: {rect:?}"),
393 Self::InvalidFrameBuffer { width, height, len } => write!(
394 f,
395 "capture frame buffer has invalid length: {width}x{height}, len={len}"
396 ),
397 Self::Encode(err) => write!(f, "capture png encode failed: {err}"),
398 Self::Render(err) => write!(f, "capture render failed: {err}"),
399 }
400 }
401}
402
403/// Marks capture failures as standard errors without a chained source.
404impl std::error::Error for CaptureError {}
405
406/// Converts renderer failures into the string-carrying render category.
407impl From<RendererError> for CaptureError {
408 /// Preserves the renderer failure as a capture renderer-error variant.
409 fn from(value: RendererError) -> Self {
410 Self::Render(value.to_string())
411 }
412}
413
414/// Thread-safe completion callback cloned before invocation outside the state mutex.
415type CompletionListener =
416 Arc<dyn Fn(CaptureRequestId, &Result<CaptureResult, CaptureError>) + Send + Sync>;
417
418#[derive(Default)]
419/// Mutex-protected request, result, listener, wake-coalescing, and exit state.
420struct CaptureState {
421 /// Saturating id counter; the first issued id is one.
422 next_id: CaptureRequestId,
423 /// FIFO requests not yet claimed by a window redraw.
424 pending: Vec<CaptureRequest>,
425 /// Completion-order results retained until taken.
426 completed: Vec<(CaptureRequestId, Result<CaptureResult, CaptureError>)>,
427 /// Saturating count distinguishing never-requested from drained.
428 issued_count: usize,
429 /// Whether a drained non-empty request set should close the application.
430 exit_after_all_captures: bool,
431 /// Callbacks invoked in registration order outside the mutex.
432 completion_listeners: Vec<CompletionListener>,
433 /// Late-bound event-loop wake target.
434 wake: Option<Arc<dyn UiWake>>,
435 /// Coalescing latch cleared at the beginning of each host service.
436 wake_pending: bool,
437 /// First non-fatal wake failure, consumed by the public accessor.
438 wake_error: Option<UiWakeError>,
439}
440
441/// Summarizes queue sizes and wake state without formatting callbacks.
442impl std::fmt::Debug for CaptureState {
443 /// Formats callback count rather than opaque closures.
444 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445 f.debug_struct("CaptureState")
446 .field("next_id", &self.next_id)
447 .field("pending", &self.pending)
448 .field("completed", &self.completed)
449 .field("issued_count", &self.issued_count)
450 .field("exit_after_all_captures", &self.exit_after_all_captures)
451 .field("completion_listeners", &self.completion_listeners.len())
452 .field("has_wake", &self.wake.is_some())
453 .field("wake_pending", &self.wake_pending)
454 .field("wake_error", &self.wake_error)
455 .finish()
456 }
457}
458
459/// Invokes a stable listener snapshot in registration order without holding the mutex.
460fn notify_listeners(
461 listeners: &[CompletionListener],
462 id: CaptureRequestId,
463 result: &Result<CaptureResult, CaptureError>,
464) {
465 for listener in listeners {
466 listener(id, result);
467 }
468}
469
470/// Thread-safe queue of window/element capture requests for [`UiApp`](crate::ui_app::UiApp).
471///
472/// When attached through [`WinitHost`](crate::host::WinitHost), a request made
473/// while the native event loop is waiting wakes the host and schedules a
474/// redraw. Requests made before the event-loop proxy exists are retained and
475/// wake it once the proxy is installed.
476///
477/// Clones share one mutex-protected queue. Requests and completion listeners may
478/// be submitted from any thread. A poisoned mutex causes read/drain helpers to
479/// return conservative empty values, while request submission treats poisoning
480/// as a programmer error and panics.
481///
482/// # Examples
483///
484/// ```
485/// let captures = ailloli_ui_winit::CaptureHandle::new();
486/// let clone = captures.clone();
487/// let id = clone.request_window("main");
488/// assert_eq!(id, 1);
489/// assert!(captures.has_pending_for_window("main"));
490/// ```
491#[derive(Clone, Debug, Default)]
492pub struct CaptureHandle {
493 /// Shared request state.
494 inner: Arc<Mutex<CaptureState>>,
495}
496
497/// Request submission, wake coordination, completion, and result drains.
498impl CaptureHandle {
499 /// Creates an empty shared capture queue.
500 ///
501 /// # Examples
502 ///
503 /// ```
504 /// let captures = ailloli_ui_winit::CaptureHandle::new();
505 /// assert!(!captures.has_pending());
506 /// assert!(!captures.is_complete());
507 /// ```
508 pub fn new() -> Self {
509 Self::default()
510 }
511
512 /// Sets whether the host should exit after all issued requests leave the pending queue.
513 ///
514 /// The flag defaults to `false`. A poisoned state mutex leaves the previous
515 /// value unchanged.
516 ///
517 /// # Examples
518 ///
519 /// ```
520 /// let captures = ailloli_ui_winit::CaptureHandle::new();
521 /// captures.set_exit_after_all_captures(true);
522 /// assert!(captures.exit_after_all_captures());
523 /// ```
524 pub fn set_exit_after_all_captures(&self, value: bool) {
525 if let Ok(mut state) = self.inner.lock() {
526 state.exit_after_all_captures = value;
527 }
528 }
529
530 /// Returns the configured automatic-exit flag.
531 ///
532 /// Returns `false` if the state mutex is poisoned.
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// let captures = ailloli_ui_winit::CaptureHandle::new();
538 /// assert!(!captures.exit_after_all_captures());
539 /// ```
540 pub fn exit_after_all_captures(&self) -> bool {
541 self.inner
542 .lock()
543 .map(|state| state.exit_after_all_captures)
544 .unwrap_or(false)
545 }
546
547 /// Enqueues a default-parameter full-window capture and returns its id.
548 ///
549 /// # Panics
550 ///
551 /// Panics if the shared capture-state mutex is poisoned.
552 ///
553 /// # Examples
554 ///
555 /// ```
556 /// let captures = ailloli_ui_winit::CaptureHandle::new();
557 /// assert_eq!(captures.request_window("main"), 1);
558 /// ```
559 pub fn request_window(&self, window_id: impl Into<String>) -> CaptureRequestId {
560 self.request(CaptureTarget::window(window_id), CaptureParams::default())
561 }
562
563 /// Enqueues a default-parameter capture of one exactly keyed element.
564 ///
565 /// # Panics
566 ///
567 /// Panics if the shared capture-state mutex is poisoned.
568 ///
569 /// # Examples
570 ///
571 /// ```
572 /// let captures = ailloli_ui_winit::CaptureHandle::new();
573 /// let id = captures.request_element("main", "editor");
574 /// assert_eq!(id, 1);
575 /// ```
576 pub fn request_element(
577 &self,
578 window_id: impl Into<String>,
579 key: impl Into<String>,
580 ) -> CaptureRequestId {
581 self.request(
582 CaptureTarget::element(window_id, key),
583 CaptureParams::default(),
584 )
585 }
586
587 /// Enqueues a capture with explicit target and renderer parameters.
588 ///
589 /// IDs and the issued counter saturate. Wake requests coalesce until the
590 /// host begins service; queued work is retained if waking fails.
591 ///
592 /// # Panics
593 ///
594 /// Panics if the shared capture-state mutex is poisoned.
595 ///
596 /// # Examples
597 ///
598 /// ```
599 /// use ailloli_ui_render_wgpu::CaptureParams;
600 /// use ailloli_ui_winit::{CaptureHandle, CaptureTarget};
601 /// let captures = CaptureHandle::new();
602 /// let id = captures.request(CaptureTarget::window("main"), CaptureParams::default());
603 /// assert_eq!(id, 1);
604 /// ```
605 pub fn request(&self, target: CaptureTarget, params: CaptureParams) -> CaptureRequestId {
606 let (id, wake) = {
607 let mut state = self.inner.lock().expect("capture state lock poisoned");
608 state.next_id = state.next_id.saturating_add(1);
609 let id = state.next_id;
610 state.pending.push(CaptureRequest { id, target, params });
611 state.issued_count = state.issued_count.saturating_add(1);
612 let wake = if state.wake_pending {
613 None
614 } else {
615 state.wake_pending = true;
616 state.wake.clone()
617 };
618 (id, wake)
619 };
620 self.invoke_wake(wake);
621 id
622 }
623
624 /// Takes the first non-fatal error raised while waking the native host.
625 ///
626 /// Capture requests remain queued when waking fails. A later host
627 /// attachment can therefore service the request without the caller
628 /// retrying it and accidentally issuing a second capture.
629 /// The first stored error is consumed; mutex poisoning returns `None`.
630 ///
631 /// # Examples
632 ///
633 /// ```
634 /// let captures = ailloli_ui_winit::CaptureHandle::new();
635 /// assert!(captures.take_wake_error().is_none());
636 /// ```
637 pub fn take_wake_error(&self) -> Option<UiWakeError> {
638 self.inner
639 .lock()
640 .ok()
641 .and_then(|mut state| state.wake_error.take())
642 }
643
644 /// Peeks at the first wake failure without consuming it.
645 ///
646 /// # Examples
647 ///
648 /// ```
649 /// // Public callers consume this slot through `take_wake_error`.
650 /// let captures = ailloli_ui_winit::CaptureHandle::new();
651 /// assert!(captures.take_wake_error().is_none());
652 /// ```
653 pub(crate) fn wake_error(&self) -> Option<UiWakeError> {
654 self.inner.lock().ok().and_then(|state| state.wake_error)
655 }
656
657 /// Installs or replaces the UI-host wake callback.
658 ///
659 /// Requests queued before the host exists are late-bound: installing the
660 /// callback immediately wakes the host once. The callback is always
661 /// invoked after releasing the capture-state mutex.
662 ///
663 /// # Errors
664 ///
665 /// Returns the wake error while also latching it for later observation.
666 ///
667 /// # Panics
668 ///
669 /// Panics if the shared state mutex is poisoned during installation.
670 ///
671 /// # Examples
672 ///
673 /// ```
674 /// // `run_winit_host` installs this late-bound callback automatically.
675 /// let captures = ailloli_ui_winit::CaptureHandle::new();
676 /// captures.request_window("main");
677 /// assert!(captures.has_pending());
678 /// ```
679 pub(crate) fn install_wake(&self, wake: Arc<dyn UiWake>) -> Result<(), UiWakeError> {
680 let should_wake = {
681 let mut state = self.inner.lock().expect("capture state lock poisoned");
682 state.wake = Some(wake.clone());
683 state.wake_pending
684 };
685 if should_wake {
686 self.invoke_wake_result(Some(wake))?;
687 }
688 Ok(())
689 }
690
691 /// Rearms capture waking at the beginning of a host callback.
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// // Host service re-arms wake coalescing before checking pending work.
697 /// let captures = ailloli_ui_winit::CaptureHandle::new();
698 /// assert!(!captures.has_pending());
699 /// ```
700 pub(crate) fn begin_host_service(&self) {
701 if let Ok(mut state) = self.inner.lock() {
702 state.wake_pending = false;
703 }
704 }
705
706 /// Performs a best-effort wake and leaves any error latched.
707 fn invoke_wake(&self, wake: Option<Arc<dyn UiWake>>) {
708 let _ = self.invoke_wake_result(wake);
709 }
710
711 /// Invokes a wake outside the mutex and stores only the first failure.
712 ///
713 /// # Errors
714 ///
715 /// Propagates [`UiWakeError`] from the installed wake callback after
716 /// best-effort latching it. An absent callback succeeds without side effects.
717 fn invoke_wake_result(&self, wake: Option<Arc<dyn UiWake>>) -> Result<(), UiWakeError> {
718 let Some(wake) = wake else {
719 return Ok(());
720 };
721 let result = wake.wake();
722 if let Err(error) = result {
723 if let Ok(mut state) = self.inner.lock() {
724 state.wake_error.get_or_insert(error);
725 }
726 return Err(error);
727 }
728 Ok(())
729 }
730
731 /// Returns whether any request remains unclaimed by a window redraw.
732 ///
733 /// Returns `false` if the mutex is poisoned.
734 ///
735 /// # Examples
736 ///
737 /// ```
738 /// let captures = ailloli_ui_winit::CaptureHandle::new();
739 /// captures.request_window("main");
740 /// assert!(captures.has_pending());
741 /// ```
742 pub fn has_pending(&self) -> bool {
743 self.inner
744 .lock()
745 .map(|state| !state.pending.is_empty())
746 .unwrap_or(false)
747 }
748
749 /// Returns sorted logical windows that still have pending capture work.
750 ///
751 /// The snapshot does not claim requests. It is used only by the host to
752 /// avoid waking unrelated presentations before per-window capture drains.
753 pub(crate) fn pending_window_ids(&self) -> Vec<String> {
754 self.inner
755 .lock()
756 .map(|state| {
757 state
758 .pending
759 .iter()
760 .map(|request| request.target.window_id().to_string())
761 .collect::<BTreeSet<_>>()
762 .into_iter()
763 .collect()
764 })
765 .unwrap_or_default()
766 }
767
768 /// Returns whether a pending request targets exactly `window_id`.
769 ///
770 /// Returns `false` if the mutex is poisoned. Element and full-window
771 /// requests use the same logical window comparison.
772 ///
773 /// # Examples
774 ///
775 /// ```
776 /// let captures = ailloli_ui_winit::CaptureHandle::new();
777 /// captures.request_element("main", "button");
778 /// assert!(captures.has_pending_for_window("main"));
779 /// assert!(!captures.has_pending_for_window("other"));
780 /// ```
781 pub fn has_pending_for_window(&self, window_id: &str) -> bool {
782 self.inner
783 .lock()
784 .map(|state| {
785 state
786 .pending
787 .iter()
788 .any(|request| request.target.window_id() == window_id)
789 })
790 .unwrap_or(false)
791 }
792
793 /// Reports that at least one request was issued and none remains pending.
794 ///
795 /// This tracks request claiming, not result consumption: a renderer may
796 /// still be producing a claimed result, and completed results may remain queued.
797 /// Mutex poisoning returns `false`.
798 ///
799 /// # Examples
800 ///
801 /// ```
802 /// let captures = ailloli_ui_winit::CaptureHandle::new();
803 /// assert!(!captures.is_complete());
804 /// ```
805 pub fn is_complete(&self) -> bool {
806 self.inner
807 .lock()
808 .map(|state| state.issued_count > 0 && state.pending.is_empty())
809 .unwrap_or(false)
810 }
811
812 /// Removes and returns the completed result with exactly `id`.
813 ///
814 /// Results with other ids retain completion order. Unknown ids and mutex
815 /// poisoning return `None`.
816 ///
817 /// # Examples
818 ///
819 /// ```
820 /// let captures = ailloli_ui_winit::CaptureHandle::new();
821 /// assert!(captures.take_result(99).is_none());
822 /// ```
823 pub fn take_result(&self, id: CaptureRequestId) -> Option<Result<CaptureResult, CaptureError>> {
824 let mut state = self.inner.lock().ok()?;
825 let idx = state
826 .completed
827 .iter()
828 .position(|(completed_id, _)| *completed_id == id)?;
829 Some(state.completed.remove(idx).1)
830 }
831
832 /// Drains all completed results in completion order, without their ids.
833 ///
834 /// Returns an empty vector when there are no results or the mutex is poisoned.
835 ///
836 /// # Examples
837 ///
838 /// ```
839 /// let captures = ailloli_ui_winit::CaptureHandle::new();
840 /// assert!(captures.take_all_results().is_empty());
841 /// ```
842 pub fn take_all_results(&self) -> Vec<Result<CaptureResult, CaptureError>> {
843 let Ok(mut state) = self.inner.lock() else {
844 return Vec::new();
845 };
846 state
847 .completed
848 .drain(..)
849 .map(|(_, result)| result)
850 .collect()
851 }
852
853 /// Registers a listener invoked on each completed or failed capture request.
854 ///
855 /// Listeners accumulate and run in registration order. Each invocation uses
856 /// a cloned listener list after releasing the mutex, so callbacks may safely
857 /// enqueue another request. Mutex poisoning silently declines registration.
858 ///
859 /// # Examples
860 ///
861 /// ```
862 /// use std::sync::Arc;
863 /// let captures = ailloli_ui_winit::CaptureHandle::new();
864 /// captures.on_complete(Arc::new(|id, result| {
865 /// let _: ailloli_ui_winit::CaptureRequestId = id;
866 /// let _succeeded: bool = result.is_ok();
867 /// }));
868 /// ```
869 pub fn on_complete(&self, listener: CompletionListener) {
870 if let Ok(mut state) = self.inner.lock() {
871 state.completion_listeners.push(listener);
872 }
873 }
874
875 /// Removes all pending requests for one logical window, preserving their order.
876 ///
877 /// Mutex poisoning returns an empty vector. Claimed requests are no longer
878 /// counted by [`Self::has_pending`] and must subsequently be completed or failed.
879 ///
880 /// # Examples
881 ///
882 /// ```
883 /// // Window redraw handling claims requests through this internal operation.
884 /// let captures = ailloli_ui_winit::CaptureHandle::new();
885 /// captures.request_window("main");
886 /// assert!(captures.has_pending_for_window("main"));
887 /// ```
888 pub(crate) fn take_pending_for_window(&self, window_id: &str) -> Vec<CaptureRequest> {
889 let Ok(mut state) = self.inner.lock() else {
890 return Vec::new();
891 };
892 let mut taken = Vec::new();
893 let mut i = 0;
894 while i < state.pending.len() {
895 if state.pending[i].target.window_id() == window_id {
896 taken.push(state.pending.remove(i));
897 } else {
898 i += 1;
899 }
900 }
901 taken
902 }
903
904 /// Stores a successful result and notifies a listener snapshot outside the mutex.
905 ///
906 /// Mutex poisoning drops the result and notification.
907 ///
908 /// # Examples
909 ///
910 /// ```
911 /// // Successful renderer results become observable through `take_result`.
912 /// let captures = ailloli_ui_winit::CaptureHandle::new();
913 /// assert!(captures.take_result(1).is_none());
914 /// ```
915 pub(crate) fn complete(&self, result: CaptureResult) {
916 let notification = if let Ok(mut state) = self.inner.lock() {
917 let id = result.request.id;
918 let outcome = Ok(result);
919 state.completed.push((id, outcome.clone()));
920 Some((state.completion_listeners.clone(), id, outcome))
921 } else {
922 None
923 };
924 if let Some((listeners, id, outcome)) = notification {
925 notify_listeners(&listeners, id, &outcome);
926 }
927 }
928
929 /// Stores a failed request and notifies a listener snapshot outside the mutex.
930 ///
931 /// Mutex poisoning drops the failure and notification.
932 ///
933 /// # Examples
934 ///
935 /// ```
936 /// // Failed renderer requests are returned through the same result queue.
937 /// let captures = ailloli_ui_winit::CaptureHandle::new();
938 /// assert!(captures.take_all_results().is_empty());
939 /// ```
940 pub(crate) fn fail(&self, request: CaptureRequest, error: CaptureError) {
941 let notification = if let Ok(mut state) = self.inner.lock() {
942 let id = request.id;
943 let outcome = Err(error);
944 state.completed.push((id, outcome.clone()));
945 Some((state.completion_listeners.clone(), id, outcome))
946 } else {
947 None
948 };
949 if let Some((listeners, id, outcome)) = notification {
950 notify_listeners(&listeners, id, &outcome);
951 }
952 }
953
954 /// Fails pending requests whose logical window id is absent from `known_window_ids`.
955 ///
956 /// Known requests retain order. Unknown requests are moved to the completion
957 /// queue in pending order and listeners run afterward without the mutex.
958 /// Mutex poisoning leaves all requests unchanged.
959 ///
960 /// # Examples
961 ///
962 /// ```
963 /// // The UI host invokes this after comparing requests with live presentations.
964 /// let captures = ailloli_ui_winit::CaptureHandle::new();
965 /// captures.request_window("missing");
966 /// assert!(captures.has_pending());
967 /// ```
968 pub(crate) fn fail_unknown_windows<'a>(
969 &self,
970 known_window_ids: impl IntoIterator<Item = &'a str>,
971 ) {
972 let known = known_window_ids
973 .into_iter()
974 .collect::<std::collections::HashSet<_>>();
975 let notification = {
976 let Ok(mut state) = self.inner.lock() else {
977 return;
978 };
979 let mut i = 0;
980 let mut failed = Vec::new();
981 while i < state.pending.len() {
982 let window_id = state.pending[i].target.window_id();
983 if known.contains(window_id) {
984 i += 1;
985 continue;
986 }
987 let request = state.pending.remove(i);
988 let window_id = request.target.window_id().to_string();
989 let id = request.id;
990 failed.push((id, Err(CaptureError::WindowNotFound { window_id })));
991 }
992 let listeners = state.completion_listeners.clone();
993 state.completed.extend(failed.iter().cloned());
994 (listeners, failed)
995 };
996 for (id, outcome) in notification.1 {
997 notify_listeners(¬ification.0, id, &outcome);
998 }
999 }
1000}
1001
1002/// Crops a full-window RGBA capture to `rect_px` (physical pixels).
1003///
1004/// The rectangle is rounded outward (`floor` left/top, `ceil` right/bottom)
1005/// and clamped to the frame. The returned format is always RGBA8. PNG data is
1006/// regenerated only when `encode_png` is `true`; existing source PNG bytes are
1007/// never reused.
1008///
1009/// # Errors
1010///
1011/// Returns [`CaptureError::InvalidFrameBuffer`] unless the source has exactly
1012/// four bytes per declared pixel, [`CaptureError::EmptyCrop`] after clamp, or
1013/// [`CaptureError::Encode`] if optional PNG encoding fails.
1014///
1015/// # Panics
1016///
1017/// With overflow checks enabled, may panic if declared dimensions overflow
1018/// `usize` RGBA-size arithmetic. Allocation failure follows Rust's allocator policy.
1019///
1020/// # Examples
1021///
1022/// ```
1023/// use ailloli_ui_core::Rect;
1024/// use ailloli_ui_render_wgpu::{CapturedFrame, CapturedFrameFormat};
1025/// let frame = CapturedFrame { width: 2, height: 1,
1026/// format: CapturedFrameFormat::Rgba8,
1027/// rgba: vec![1, 2, 3, 255, 4, 5, 6, 255], png_data: None };
1028/// let crop = ailloli_ui_winit::crop_captured_frame(
1029/// &frame, Rect::new(1.0, 0.0, 1.0, 1.0), false).unwrap();
1030/// assert_eq!((crop.width, crop.height, crop.rgba), (1, 1, vec![4, 5, 6, 255]));
1031/// ```
1032pub fn crop_captured_frame(
1033 frame: &CapturedFrame,
1034 rect_px: Rect,
1035 encode_png: bool,
1036) -> Result<CapturedFrame, CaptureError> {
1037 let expected_len = frame.width as usize * frame.height as usize * 4;
1038 if frame.rgba.len() != expected_len {
1039 return Err(CaptureError::InvalidFrameBuffer {
1040 width: frame.width,
1041 height: frame.height,
1042 len: frame.rgba.len(),
1043 });
1044 }
1045
1046 let x0 = rect_px.x.floor().max(0.0).min(frame.width as f32) as u32;
1047 let y0 = rect_px.y.floor().max(0.0).min(frame.height as f32) as u32;
1048 let x1 = rect_px.right().ceil().max(0.0).min(frame.width as f32) as u32;
1049 let y1 = rect_px.bottom().ceil().max(0.0).min(frame.height as f32) as u32;
1050
1051 let width = x1.saturating_sub(x0);
1052 let height = y1.saturating_sub(y0);
1053 if width == 0 || height == 0 {
1054 return Err(CaptureError::EmptyCrop { rect: rect_px });
1055 }
1056
1057 let mut rgba = vec![0u8; width as usize * height as usize * 4];
1058 let src_stride = frame.width as usize * 4;
1059 let dst_stride = width as usize * 4;
1060 for row in 0..height as usize {
1061 let src_start = (y0 as usize + row) * src_stride + x0 as usize * 4;
1062 let src_end = src_start + dst_stride;
1063 let dst_start = row * dst_stride;
1064 rgba[dst_start..dst_start + dst_stride].copy_from_slice(&frame.rgba[src_start..src_end]);
1065 }
1066
1067 let png_data = if encode_png {
1068 Some(encode_png_rgba(width, height, &rgba).map_err(CaptureError::Encode)?)
1069 } else {
1070 None
1071 };
1072
1073 Ok(CapturedFrame {
1074 width,
1075 height,
1076 format: CapturedFrameFormat::Rgba8,
1077 rgba,
1078 png_data,
1079 })
1080}
1081
1082/// Clears embedded PNG data when `encode_png` is false.
1083///
1084/// `true` preserves existing bytes but does not generate missing PNG data.
1085/// RGBA bytes, dimensions, and format are unchanged.
1086///
1087/// # Examples
1088///
1089/// ```
1090/// use ailloli_ui_render_wgpu::{CapturedFrame, CapturedFrameFormat};
1091/// let frame = CapturedFrame { width: 1, height: 1,
1092/// format: CapturedFrameFormat::Rgba8, rgba: vec![0; 4],
1093/// png_data: Some(vec![1, 2, 3]) };
1094/// let frame = ailloli_ui_winit::strip_png_if_disabled(frame, false);
1095/// assert!(frame.png_data.is_none());
1096/// ```
1097pub fn strip_png_if_disabled(mut frame: CapturedFrame, encode_png: bool) -> CapturedFrame {
1098 if !encode_png {
1099 frame.png_data = None;
1100 }
1101 frame
1102}
1103
1104#[cfg(test)]
1105/// Queue, listener reentrancy, wake coalescing/failure, and physical-crop scenarios.
1106mod tests {
1107 use super::*;
1108 use std::sync::atomic::{AtomicUsize, Ordering};
1109 use std::sync::Weak;
1110
1111 #[derive(Default)]
1112 /// Wake test double counting successful invocations.
1113 struct CountingWake(AtomicUsize);
1114
1115 /// Relaxed counter implementation sufficient for single-test observation.
1116 impl UiWake for CountingWake {
1117 fn wake(&self) -> Result<(), UiWakeError> {
1118 self.0.fetch_add(1, Ordering::Relaxed);
1119 Ok(())
1120 }
1121 }
1122
1123 /// Wake test double that always reports a closed target.
1124 struct FailingWake;
1125
1126 /// Deterministic wake failure used to prove requests remain queued.
1127 impl UiWake for FailingWake {
1128 fn wake(&self) -> Result<(), UiWakeError> {
1129 Err(UiWakeError::TargetClosed)
1130 }
1131 }
1132
1133 /// Wake test double that re-enters the capture handle during notification.
1134 struct ReentrantWake {
1135 /// Weak state reference avoiding a test-only ownership cycle.
1136 state: Weak<Mutex<CaptureState>>,
1137 /// Number of successful reentrant observations.
1138 calls: AtomicUsize,
1139 }
1140
1141 /// Confirms wake callbacks execute after the capture mutex is released.
1142 impl UiWake for ReentrantWake {
1143 fn wake(&self) -> Result<(), UiWakeError> {
1144 self.calls.fetch_add(1, Ordering::Relaxed);
1145 let inner = self.state.upgrade().expect("capture handle still alive");
1146 let handle = CaptureHandle { inner };
1147 assert!(handle.has_pending());
1148 Ok(())
1149 }
1150 }
1151
1152 /// Creates an RGBA8 fixture whose red/green channels encode pixel coordinates.
1153 fn test_frame(width: u32, height: u32) -> CapturedFrame {
1154 let mut rgba = Vec::new();
1155 for y in 0..height {
1156 for x in 0..width {
1157 rgba.extend_from_slice(&[x as u8, y as u8, 255, 255]);
1158 }
1159 }
1160 CapturedFrame {
1161 width,
1162 height,
1163 format: CapturedFrameFormat::Rgba8,
1164 rgba,
1165 png_data: None,
1166 }
1167 }
1168
1169 #[test]
1170 fn capture_handle_on_complete_invoked_on_success_and_failure() {
1171 let handle = CaptureHandle::new();
1172 let seen = Arc::new(Mutex::new(Vec::new()));
1173 let seen_cb = seen.clone();
1174 handle.on_complete(Arc::new(move |id, result| {
1175 seen_cb.lock().unwrap().push((id, result.is_ok()));
1176 }));
1177
1178 let id_ok = handle.request_window("main");
1179 let request = handle.take_pending_for_window("main").pop().unwrap();
1180 handle.complete(CaptureResult {
1181 request,
1182 frame: test_frame(2, 2),
1183 bounds_px: None,
1184 });
1185
1186 let id_fail = handle.request_window("missing");
1187 handle.fail_unknown_windows(["other"]);
1188
1189 let events = seen.lock().unwrap();
1190 assert_eq!(events.len(), 2);
1191 assert_eq!(events[0], (id_ok, true));
1192 assert_eq!(events[1], (id_fail, false));
1193 }
1194
1195 #[test]
1196 fn capture_listener_can_enqueue_the_next_capture_without_deadlock() {
1197 let handle = CaptureHandle::new();
1198 let callback_handle = handle.clone();
1199 handle.on_complete(Arc::new(move |_id, result| {
1200 if result.is_ok() {
1201 callback_handle.request_window("second");
1202 }
1203 }));
1204
1205 handle.request_window("first");
1206 let request = handle.take_pending_for_window("first").pop().unwrap();
1207 handle.complete(CaptureResult {
1208 request,
1209 frame: test_frame(2, 2),
1210 bounds_px: None,
1211 });
1212
1213 assert!(handle.has_pending_for_window("second"));
1214 }
1215
1216 #[test]
1217 fn pending_capture_windows_are_sorted_and_deduplicated() {
1218 let handle = CaptureHandle::new();
1219 handle.request_window("beta");
1220 handle.request_element("alpha", "first");
1221 handle.request_element("beta", "second");
1222
1223 assert_eq!(
1224 handle.pending_window_ids(),
1225 vec!["alpha".to_string(), "beta".to_string()]
1226 );
1227 }
1228
1229 #[test]
1230 fn capture_wake_is_late_bound_and_rearmed_after_idle_service() {
1231 let handle = CaptureHandle::new();
1232 handle.request_window("before-host");
1233
1234 let wake = Arc::new(CountingWake::default());
1235 handle.install_wake(wake.clone()).unwrap();
1236 assert_eq!(wake.0.load(Ordering::Relaxed), 1);
1237
1238 handle.begin_host_service();
1239 handle.request_window("after-idle");
1240 assert_eq!(wake.0.load(Ordering::Relaxed), 2);
1241 }
1242
1243 #[test]
1244 fn capture_wake_runs_without_holding_the_capture_mutex() {
1245 let handle = CaptureHandle::new();
1246 handle.request_window("before-host");
1247 let wake = Arc::new(ReentrantWake {
1248 state: Arc::downgrade(&handle.inner),
1249 calls: AtomicUsize::new(0),
1250 });
1251 handle.install_wake(wake.clone()).unwrap();
1252
1253 handle.begin_host_service();
1254 handle.request_window("after-idle");
1255
1256 assert_eq!(wake.calls.load(Ordering::Relaxed), 2);
1257 }
1258
1259 #[test]
1260 fn capture_wake_failure_is_non_fatal_and_observable() {
1261 let handle = CaptureHandle::new();
1262 handle.install_wake(Arc::new(FailingWake)).unwrap();
1263
1264 let id = handle.request_window("main");
1265
1266 assert!(handle.has_pending_for_window("main"));
1267 assert_eq!(handle.take_wake_error(), Some(UiWakeError::TargetClosed));
1268 assert_eq!(handle.take_wake_error(), None);
1269 assert_eq!(id, 1);
1270 }
1271
1272 #[test]
1273 fn capture_handle_completes_window_request() {
1274 let handle = CaptureHandle::new();
1275 handle.set_exit_after_all_captures(true);
1276 let id = handle.request_window("main");
1277 let request = handle.take_pending_for_window("main").pop().unwrap();
1278 handle.complete(CaptureResult {
1279 request,
1280 frame: test_frame(2, 2),
1281 bounds_px: None,
1282 });
1283
1284 assert!(handle.exit_after_all_captures());
1285 assert!(handle.is_complete());
1286 assert!(handle.take_result(id).unwrap().is_ok());
1287 }
1288
1289 #[test]
1290 fn capture_handle_fails_unknown_window() {
1291 let handle = CaptureHandle::new();
1292 let id = handle.request_window("missing");
1293 handle.fail_unknown_windows(["main"]);
1294 let err = handle.take_result(id).unwrap().unwrap_err();
1295 assert!(matches!(
1296 err,
1297 CaptureError::WindowNotFound { window_id } if window_id == "missing"
1298 ));
1299 }
1300
1301 #[test]
1302 fn crop_captured_frame_clips_to_frame_bounds() {
1303 let cropped =
1304 crop_captured_frame(&test_frame(4, 4), Rect::new(2.0, 1.0, 4.0, 2.0), false).unwrap();
1305 assert_eq!(cropped.width, 2);
1306 assert_eq!(cropped.height, 2);
1307 assert_eq!(&cropped.rgba[0..4], &[2, 1, 255, 255]);
1308 }
1309
1310 #[test]
1311 fn crop_captured_frame_clips_partially_outside() {
1312 let cropped =
1313 crop_captured_frame(&test_frame(4, 4), Rect::new(2.0, 2.0, 4.0, 4.0), false).unwrap();
1314 assert_eq!(cropped.width, 2);
1315 assert_eq!(cropped.height, 2);
1316 assert_eq!(&cropped.rgba[0..4], &[2, 2, 255, 255]);
1317 }
1318
1319 #[test]
1320 fn crop_captured_frame_rejects_empty_rect() {
1321 let err = crop_captured_frame(&test_frame(4, 4), Rect::new(10.0, 10.0, 1.0, 1.0), false)
1322 .unwrap_err();
1323 assert!(matches!(err, CaptureError::EmptyCrop { .. }));
1324 }
1325}