1
//! Screen-capture widget — a "dumb widget" identical in architecture to the
2
//! [`CameraWidget`](super::camera), only the source differs (a display /
3
//! window). SUPER_PLAN_2 §4 P6, widget pivot.
4
//!
5
//! `ScreenCaptureWidget::create(config).dom()` → an `<img>` a background
6
//! capture thread keeps fed; each frame goes through
7
//! [`super::capture_common::present_frame`] (GL-texture install-once /
8
//! re-upload + recomposite). The shared core lives in `capture_common`; this
9
//! widget is its config + worker. Test-pattern worker (a moving band) stands
10
//! in for the real ScreenCaptureKit / MediaProjection / PipeWire worker.
11
//!
12
//! ONE CAPTURE, MANY CONSUMERS — exactly as the camera widget: the stream is
13
//! opened at the covering size of the tile (device px, via `NodeResized`)
14
//! and every registered [`FrameConsumer`]; each frame is cut per consumer
15
//! off the main thread (`capture_common::run_capture_loop`). The request
16
//! also carries `config.source` (display index / window id) and
17
//! `config.fps`, and asks the backend to leave this app's own windows out
18
//! of the picture (`exclude_self`), so sharing the desktop that shows the
19
//! sharing app does not loop at 30 fps.
20

            
21
use alloc::vec::Vec;
22

            
23
use azul_core::{
24
    callbacks::Update,
25
    dom::{ComponentEventFilter, DatasetMergeCallbackType, Dom, EventFilter},
26
    refany::{OptionRefAny, RefAny},
27
    resources::{ImageRef, RawImageFormat},
28
    screencap::{ScreenCaptureConfig, ScreenCaptureSource},
29
    task::{ThreadId, ThreadReceiver, ThreadSendMsg},
30
    video::{FrameConsumer, FrameConsumerVec},
31
};
32
use azul_css::AzString;
33

            
34
use super::capture_common::{
35
    frame_resampler, present_captured, preview_size_for_node, run_capture_loop, screen_backend,
36
    send_capture_targets, test_pattern_vtable, CaptureRequest, CaptureSession, CaptureTargets,
37
    CapturedFrames, OnConsumerFrame, OnConsumerFrameCallback, OnVideoFrame, OnVideoFrameCallback,
38
    OptionOnConsumerFrame, OptionOnVideoFrame, TestPattern, REOPEN_COOLDOWN_MS,
39
};
40
use crate::{
41
    callbacks::{Callback, CallbackInfo, CallbackType},
42
    thread::{Thread, ThreadCallback, ThreadSender},
43
};
44

            
45
/// Init data handed to the capture worker thread.
46
struct ScreencapThreadInit {
47
    /// The request's source + fps + exclusion (size filled in per reopen).
48
    request: CaptureRequest,
49
    /// Who wants frames at mount time.
50
    targets: CaptureTargets,
51
    /// The size the capture never drops below (an `on_frame` hook expects
52
    /// frames "as configured": the default size).
53
    floor: Option<(u32, u32)>,
54
}
55

            
56
/// Default capture size for the test pattern (the real backend reports the
57
/// source's actual size).
58
const DEFAULT_W: u32 = 1280;
59
const DEFAULT_H: u32 = 720;
60

            
61
/// Live state for one screencap widget, carried across relayout by
62
/// [`merge_screencap_state`].
63
#[derive(Debug)]
64
pub struct ScreenCaptureWidgetState {
65
    /// The requested capture configuration (the control POD).
66
    pub config: ScreenCaptureConfig,
67
    /// `true` once the capture thread has been started.
68
    pub started: bool,
69
    /// The stable external GL texture id once installed.
70
    pub gl_texture_id: Option<u32>,
71
    /// Optional user hook invoked with each captured frame (effects / save /
72
    /// send). Re-set on every fresh build (see [`merge_screencap_state`]).
73
    pub on_frame: OptionOnVideoFrame,
74
    /// Every registered consumer (see [`FrameConsumer`]). Re-set on every
75
    /// fresh build; a change is pushed to the running worker.
76
    pub consumers: FrameConsumerVec,
77
    /// Optional hook receiving every consumer's cut of every frame.
78
    pub on_consumer_frame: OptionOnConsumerFrame,
79
    /// The MARKER stamped on the tile node (`Dom::with_marker`); the frame
80
    /// writeback resolves it back to the node via
81
    /// `CallbackInfo::get_node_id_by_marker`. Adopted forward on merge so the
82
    /// persistent allocation always names the CURRENT build's node.
83
    pub marker: AzString,
84
    /// The capture worker, once started (`NodeResized` messages it).
85
    pub thread_id: Option<ThreadId>,
86
    /// The main->worker sender, cloned at mount so the merge callback can
87
    /// push a changed consumer list without a `CallbackInfo`.
88
    pub control: Option<std::sync::mpsc::Sender<ThreadSendMsg>>,
89
    /// The tile's last reported device size.
90
    pub preview: Option<(u32, u32)>,
91
}
92

            
93
impl ScreenCaptureWidgetState {
94
    /// The worker's view of who wants frames, from this state.
95
    #[must_use]
96
1
    pub fn targets(&self) -> CaptureTargets {
97
1
        CaptureTargets {
98
1
            preview: self.preview,
99
1
            consumers: self.consumers.as_ref().to_vec(),
100
1
            wants_source: self.on_frame.is_some(),
101
1
        }
102
1
    }
103
}
104

            
105
/// A screen-capture widget. `create(config).dom()` yields an `<img>` the
106
/// capture thread keeps fed.
107
#[repr(C)]
108
#[derive(Debug)]
109
pub struct ScreenCaptureWidget {
110
    /// What to capture + fps + format.
111
    pub config: ScreenCaptureConfig,
112
    /// Optional per-frame user hook (effects / save / send - azul-meet).
113
    pub on_frame: OptionOnVideoFrame,
114
    /// Consumers of the captured frames beyond the on-screen tile: each gets
115
    /// its own cut of every frame at its requested size.
116
    pub consumers: FrameConsumerVec,
117
    /// Optional hook receiving each consumer's cut (see `consumers`).
118
    pub on_consumer_frame: OptionOnConsumerFrame,
119
}
120

            
121
impl ScreenCaptureWidget {
122
    /// Create a screencap widget for the given config.
123
    #[must_use]
124
66
    pub const fn create(config: ScreenCaptureConfig) -> Self {
125
66
        Self {
126
66
            config,
127
66
            on_frame: OptionOnVideoFrame::None,
128
66
            consumers: FrameConsumerVec::from_const_slice(&[]),
129
66
            on_consumer_frame: OptionOnConsumerFrame::None,
130
66
        }
131
66
    }
132

            
133
    /// Register a consumer of the captured frames (see
134
    /// `CameraWidget::add_consumer` - identical semantics: one capture at
135
    /// the covering size, one cut per consumer, same-id replaces).
136
    pub fn add_consumer(&mut self, consumer: FrameConsumer) {
137
        let mut all: Vec<FrameConsumer> = self.consumers.as_ref().to_vec();
138
        all.retain(|c| c.id != consumer.id);
139
        all.push(consumer);
140
        self.consumers = all.into();
141
    }
142

            
143
    /// Builder form of [`add_consumer`](Self::add_consumer).
144
    #[must_use]
145
    pub fn with_consumer(mut self, consumer: FrameConsumer) -> Self {
146
        self.add_consumer(consumer);
147
        self
148
    }
149

            
150
    /// Set the hook that receives every consumer's cut of every captured
151
    /// frame (route on `frame.consumer.id`).
152
    pub fn set_on_consumer_frame<C: Into<OnConsumerFrameCallback>>(
153
        &mut self,
154
        data: RefAny,
155
        on_consumer_frame: C,
156
    ) {
157
        self.on_consumer_frame = Some(OnConsumerFrame {
158
            refany: data,
159
            callback: on_consumer_frame.into(),
160
        })
161
        .into();
162
    }
163

            
164
    /// Builder form of [`set_on_consumer_frame`](Self::set_on_consumer_frame).
165
    #[must_use]
166
    pub fn with_on_consumer_frame<C: Into<OnConsumerFrameCallback>>(
167
        mut self,
168
        data: RefAny,
169
        on_consumer_frame: C,
170
    ) -> Self {
171
        self.set_on_consumer_frame(data, on_consumer_frame);
172
        self
173
    }
174

            
175
    /// Set a hook invoked with every captured frame - for live effects, saving
176
    /// frames into your data model, or sending them over the network
177
    /// (azul-meet).
178
28
    pub fn set_on_frame<C: Into<OnVideoFrameCallback>>(&mut self, data: RefAny, on_frame: C) {
179
28
        self.on_frame = Some(OnVideoFrame {
180
28
            refany: data,
181
28
            callback: on_frame.into(),
182
28
        })
183
28
        .into();
184
28
    }
185

            
186
    /// Builder form of [`set_on_frame`](Self::set_on_frame).
187
    #[must_use]
188
9
    pub fn with_on_frame<C: Into<OnVideoFrameCallback>>(
189
9
        mut self,
190
9
        data: RefAny,
191
9
        on_frame: C,
192
9
    ) -> Self {
193
9
        self.set_on_frame(data, on_frame);
194
9
        self
195
9
    }
196

            
197
    /// Build the widget's DOM: a single `<img>` node, fed by a background
198
    /// capture thread started on mount.
199
    #[must_use]
200
22
    pub fn dom(self) -> Dom {
201
22
        let marker = super::capture_common::next_capture_marker("screencap");
202
22
        let state = ScreenCaptureWidgetState {
203
22
            config: self.config,
204
22
            started: false,
205
22
            gl_texture_id: None,
206
22
            on_frame: self.on_frame,
207
22
            consumers: self.consumers,
208
22
            on_consumer_frame: self.on_consumer_frame,
209
22
            marker: marker.clone(),
210
22
            thread_id: None,
211
22
            control: None,
212
22
            preview: None,
213
22
        };
214
22
        let dataset = RefAny::new(state);
215

            
216
22
        let placeholder = ImageRef::null_image(
217
22
            DEFAULT_W as usize,
218
22
            DEFAULT_H as usize,
219
22
            RawImageFormat::BGRA8,
220
22
            b"azul-screencap-placeholder".to_vec(),
221
        );
222

            
223
22
        Dom::create_image(placeholder)
224
22
            .with_dataset(OptionRefAny::Some(dataset.clone()))
225
22
            .with_marker(Some(marker).into())
226
22
            .with_merge_callback(azul_core::dom::DatasetMergeCallback::from_ptr(merge_screencap_state))
227
22
            .with_callback(
228
22
                EventFilter::Component(ComponentEventFilter::AfterMount),
229
22
                dataset.clone(),
230
22
                Callback::from_ptr(screencap_on_after_mount),
231
            )
232
            // The tile's device size feeds the stream size + the preview cut.
233
22
            .with_callback(
234
22
                EventFilter::Component(ComponentEventFilter::NodeResized),
235
22
                dataset,
236
22
                Callback::from_ptr(screencap_on_resize),
237
            )
238
22
    }
239
}
240

            
241
/// The backend request for a config: `source` -> display index / window id,
242
/// `fps`, and this app's own windows excluded (the feedback-loop fix).
243
3
const fn capture_request(config: &ScreenCaptureConfig) -> CaptureRequest {
244
3
    let (index, window) = match config.source {
245
1
        ScreenCaptureSource::PrimaryDisplay => (0, 0),
246
1
        ScreenCaptureSource::Display(i) => (i, 0),
247
1
        ScreenCaptureSource::Window(id) => (0, id),
248
    };
249
3
    CaptureRequest {
250
3
        index,
251
3
        window,
252
3
        width: 0,
253
3
        height: 0,
254
3
        fps: config.fps,
255
3
        exclude_self: true,
256
3
    }
257
3
}
258

            
259
/// The size the stream never drops below: the default size when an
260
/// `on_frame` hook expects frames as before; otherwise the tile and the
261
/// consumers decide (a 320x180 share tile streams 320x180, not 1280x720).
262
2
const fn capture_floor(wants_source: bool) -> Option<(u32, u32)> {
263
2
    if wants_source {
264
1
        Some((DEFAULT_W, DEFAULT_H))
265
    } else {
266
1
        None
267
    }
268
2
}
269

            
270
/// `AfterMount`: start the background capture thread exactly once, telling
271
/// it who wants frames (the tile's size if layout already produced one).
272
5
extern "C" fn screencap_on_after_mount(mut data: RefAny, mut info: CallbackInfo) -> Update {
273
5
    let preview = preview_size_for_node(&info);
274
    let init = {
275
5
        let Some(mut s) = data.downcast_mut::<ScreenCaptureWidgetState>() else {
276
2
            return Update::DoNothing;
277
        };
278
3
        if s.started {
279
3
            return Update::DoNothing;
280
        }
281
        s.started = true;
282
        s.preview = preview;
283
        ScreencapThreadInit {
284
            request: capture_request(&s.config),
285
            targets: s.targets(),
286
            floor: capture_floor(s.on_frame.is_some()),
287
        }
288
    };
289
    let tid = ThreadId::unique();
290
    let thread = Thread::create(
291
        RefAny::new(init),
292
        data.clone(),
293
        ThreadCallback::new(screencap_worker),
294
    );
295
    let control = thread.clone_sender();
296
    info.add_thread(tid, thread);
297
    if let Some(mut s) = data.downcast_mut::<ScreenCaptureWidgetState>() {
298
        s.thread_id = Some(tid);
299
        s.control = control;
300
    }
301
    Update::DoNothing
302
5
}
303

            
304
/// `NodeResized`: the tile's device size changed — tell the worker (see
305
/// `camera_on_resize`). A message, not a relayout: returns `DoNothing`.
306
extern "C" fn screencap_on_resize(mut data: RefAny, info: CallbackInfo) -> Update {
307
    let Some(preview) = preview_size_for_node(&info) else {
308
        return Update::DoNothing;
309
    };
310
    let (tid, targets) = {
311
        let Some(mut s) = data.downcast_mut::<ScreenCaptureWidgetState>() else {
312
            return Update::DoNothing;
313
        };
314
        if s.preview == Some(preview) {
315
            return Update::DoNothing;
316
        }
317
        s.preview = Some(preview);
318
        (s.thread_id, s.targets())
319
    };
320
    if let Some(tid) = tid {
321
        send_capture_targets(&info, tid, targets);
322
    }
323
    Update::DoNothing
324
}
325

            
326
/// Background worker: the shared capture loop over the registered screen
327
/// backend (`ScreenCaptureKit` / `PipeWire` / X11 / DXGI), else the moving-band
328
/// test pattern — see `capture_common::run_capture_loop`.
329
1
extern "C" fn screencap_worker(
330
1
    mut init: RefAny,
331
1
    mut sender: ThreadSender,
332
1
    mut recv: ThreadReceiver,
333
1
) {
334
1
    let (targets, request, floor) = match init.downcast_ref::<ScreencapThreadInit>() {
335
        Some(i) => (i.targets.clone(), i.request, i.floor),
336
1
        None => (
337
1
            CaptureTargets::default(),
338
1
            CaptureRequest::new(0, 0, 0),
339
1
            None,
340
1
        ),
341
    };
342
1
    let session = CaptureSession {
343
1
        backend: screen_backend(),
344
1
        test_pattern: test_pattern_vtable(TestPattern::MovingBand),
345
1
        request,
346
1
        floor,
347
1
        fallback: (DEFAULT_W, DEFAULT_H),
348
1
        writeback: screencap_writeback,
349
1
        resample: frame_resampler(),
350
1
        reopen_cooldown_ms: REOPEN_COOLDOWN_MS,
351
1
    };
352
1
    run_capture_loop(session, targets, &mut sender, &mut recv);
353
1
}
354

            
355
/// Writeback (main thread): run the hooks and put the preview cut (else the
356
/// captured frame) on the node — `capture_common::present_captured`.
357
15
extern "C" fn screencap_writeback(
358
15
    mut writeback_data: RefAny,
359
15
    mut frame_data: RefAny,
360
15
    mut info: CallbackInfo,
361
15
) -> Update {
362
15
    let (on_frame, on_consumer_frame, marker) = writeback_data
363
15
        .downcast_ref::<ScreenCaptureWidgetState>()
364
15
        .map_or_else(
365
1
            || {
366
1
                (
367
1
                    OptionOnVideoFrame::None,
368
1
                    OptionOnConsumerFrame::None,
369
1
                    AzString::from_const_str(""),
370
1
                )
371
1
            },
372
14
            |s| {
373
14
                (
374
14
                    s.on_frame.clone(),
375
14
                    s.on_consumer_frame.clone(),
376
14
                    s.marker.clone(),
377
14
                )
378
14
            },
379
        );
380
15
    let Some(mut captured) = frame_data.downcast_mut::<CapturedFrames>() else {
381
1
        return Update::DoNothing;
382
    };
383
14
    present_captured(
384
14
        &mut info,
385
14
        marker,
386
14
        &on_frame,
387
14
        &on_consumer_frame,
388
14
        &mut captured,
389
    )
390
15
}
391

            
392
/// Carry live state forward across relayout.
393
6
extern "C" fn merge_screencap_state(mut new_data: RefAny, mut old_data: RefAny) -> RefAny {
394
    // Return the OLD allocation (the one live capture backends may hold a
395
    // clone of), adopting config forward — the merge_map_tile_cache rule.
396
    // Returning new_data would re-point the DOM at a fresh allocation the
397
    // running worker's writeback clone never sees.
398
6
    let merged_into_old = {
399
6
        let new_guard = new_data.downcast_ref::<ScreenCaptureWidgetState>();
400
6
        let old_guard = old_data.downcast_mut::<ScreenCaptureWidgetState>();
401
6
        if let (Some(new_g), Some(mut old_g)) = (new_guard, old_guard) {
402
3
            let worker_cares = old_g.consumers != new_g.consumers
403
3
                || old_g.on_frame.is_some() != new_g.on_frame.is_some();
404
3
            old_g.config = new_g.config;
405
3
            old_g.on_frame = new_g.on_frame.clone();
406
3
            old_g.consumers = new_g.consumers.clone();
407
3
            old_g.on_consumer_frame = new_g.on_consumer_frame.clone();
408
            // The reconciled NODE carries the NEW build's marker string, so
409
            // the surviving allocation must resolve by that string too.
410
3
            old_g.marker = new_g.marker.clone();
411
3
            if worker_cares {
412
1
                let targets = old_g.targets();
413
1
                if let Some(snd) = old_g.control.as_ref() {
414
                    drop(snd.send(ThreadSendMsg::Custom(RefAny::new(targets))));
415
1
                }
416
2
            }
417
3
            true
418
        } else {
419
            // Foreign / mismatched payloads (one side is not this widget's
420
            // state): hand back the NEW payload untouched — there is no
421
            // persistent allocation to preserve, and returning a
422
            // wrong-typed old dataset would poison the node.
423
3
            false
424
        }
425
    };
426
6
    if merged_into_old {
427
3
        old_data
428
    } else {
429
3
        new_data
430
    }
431
6
}
432

            
433
// ============================================================================
434
// Generated adversarial tests
435
// ============================================================================
436

            
437
#[cfg(test)]
438
#[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
439
mod autotest_generated {
440
    use std::{
441
        collections::BTreeMap,
442
        panic::{catch_unwind, AssertUnwindSafe},
443
        sync::{
444
            mpsc::{channel, Receiver, Sender},
445
            Arc, Mutex, PoisonError,
446
        },
447
    };
448

            
449
    use azul_core::{
450
        dom::{DomId, DomNodeId, NodeType},
451
        geom::OptionLogicalPosition,
452
        gl::OptionGlContextPtr,
453
        hit_test::ScrollPosition,
454
        resources::{DecodedImage, RendererResources},
455
        styled_dom::NodeHierarchyItemId,
456
        task::{
457
            OptionThreadSendMsg, ThreadReceiverDestructorCallback, ThreadReceiverInner,
458
            ThreadRecvCallback,
459
        },
460
        video::VideoFrame,
461
        window::{MonitorVec, RawWindowHandle},
462
    };
463
    use azul_css::system::SystemStyle;
464
    use rust_fontconfig::FcFontCache;
465

            
466
    use super::*;
467
    #[cfg(feature = "icu")]
468
    use crate::icu::IcuLocalizerHandle;
469
    use crate::{
470
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
471
        thread::{
472
            ThreadReceiveMsg, ThreadSendCallback, ThreadSenderDestructorCallback, ThreadSenderInner,
473
        },
474
        widgets::capture_common::OnVideoFrameCallbackType,
475
        window::LayoutWindow,
476
        window_state::FullWindowState,
477
    };
478

            
479
    // ------------------------------------------------------------------
480
    // Config fixtures
481
    // ------------------------------------------------------------------
482

            
483
    const fn cfg(
484
        source: ScreenCaptureSource,
485
        fps: u32,
486
        output_format: RawImageFormat,
487
    ) -> ScreenCaptureConfig {
488
        ScreenCaptureConfig {
489
            source,
490
            fps,
491
            output_format,
492
        }
493
    }
494

            
495
    /// Representative + extreme configs: both payload boundaries of each
496
    /// carrying `ScreenCaptureSource` variant, `fps` at 0 / 1 / `u32::MAX`, and
497
    /// a format that is deliberately *not* the widget's placeholder format.
498
    const ALL_CONFIGS: [ScreenCaptureConfig; 8] = [
499
        cfg(
500
            ScreenCaptureSource::PrimaryDisplay,
501
            0,
502
            RawImageFormat::BGRA8,
503
        ),
504
        cfg(
505
            ScreenCaptureSource::PrimaryDisplay,
506
            u32::MAX,
507
            RawImageFormat::RGBA8,
508
        ),
509
        cfg(ScreenCaptureSource::Display(0), 1, RawImageFormat::BGRA8),
510
        cfg(
511
            ScreenCaptureSource::Display(u32::MAX),
512
            60,
513
            RawImageFormat::R8,
514
        ),
515
        cfg(ScreenCaptureSource::Window(0), 0, RawImageFormat::BGRA8),
516
        cfg(
517
            ScreenCaptureSource::Window(u64::MAX),
518
            u32::MAX,
519
            RawImageFormat::R8,
520
        ),
521
        cfg(
522
            ScreenCaptureSource::Window(u32::MAX as u64),
523
            30,
524
            RawImageFormat::RGBA8,
525
        ),
526
        cfg(ScreenCaptureSource::Display(1), 240, RawImageFormat::BGRA8),
527
    ];
528

            
529
    const DEFAULT_CFG: ScreenCaptureConfig = ALL_CONFIGS[0];
530

            
531
    /// Compile-time proof that `create` really is a `const fn` (its `const`
532
    /// qualifier is part of the public API - a non-const `create` would make
533
    /// this fn fail to compile).
534
    const fn const_create(config: ScreenCaptureConfig) -> ScreenCaptureWidget {
535
        ScreenCaptureWidget::create(config)
536
    }
537

            
538
    // ------------------------------------------------------------------
539
    // State fixtures
540
    // ------------------------------------------------------------------
541

            
542
    /// A `ScreenCaptureWidgetState` payload with no `on_frame` hook.
543
    fn state(config: ScreenCaptureConfig, started: bool, gl_texture_id: Option<u32>) -> RefAny {
544
        RefAny::new(ScreenCaptureWidgetState {
545
            config,
546
            started,
547
            gl_texture_id,
548
            on_frame: OptionOnVideoFrame::None,
549
            consumers: FrameConsumerVec::from_const_slice(&[]),
550
            on_consumer_frame: OptionOnConsumerFrame::None,
551
            marker: "azul-screencap-test".into(),
552
            thread_id: None,
553
            control: None,
554
            preview: None,
555
        })
556
    }
557

            
558
    /// The writeback payload the worker queues for one captured `frame`.
559
    fn captured(frame: VideoFrame) -> RefAny {
560
        RefAny::new(CapturedFrames {
561
            source: Some(frame),
562
            preview: None,
563
            consumers: Vec::new(),
564
            in_flight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
565
        })
566
    }
567

            
568
    /// `(config, started, gl_texture_id, has_hook)` of a `ScreenCaptureWidgetState`.
569
    fn read_state(data: &mut RefAny) -> (ScreenCaptureConfig, bool, Option<u32>, bool) {
570
        let s = data
571
            .downcast_ref::<ScreenCaptureWidgetState>()
572
            .expect("payload must still be a ScreenCaptureWidgetState");
573
        (
574
            s.config,
575
            s.started,
576
            s.gl_texture_id,
577
            matches!(s.on_frame, OptionOnVideoFrame::Some(_)),
578
        )
579
    }
580

            
581
    /// The placeholder image behind an `<img>` `Dom` root: `(w, h, format, tag)`.
582
    fn placeholder_of(dom: &Dom) -> (usize, usize, RawImageFormat, Vec<u8>) {
583
        let NodeType::Image(image) = dom.root.get_node_type() else {
584
            panic!("ScreenCaptureWidget::dom must build an image node");
585
        };
586
        match image.get_data() {
587
            DecodedImage::NullImage {
588
                width,
589
                height,
590
                format,
591
                tag,
592
            } => (*width, *height, *format, tag.clone()),
593
            _ => panic!("the placeholder must be a NullImage (no decode, no allocation)"),
594
        }
595
    }
596

            
597
    // ---- frame hook -------------------------------------------------------
598

            
599
    /// Records every frame a widget's `on_frame` hook is handed, and replies
600
    /// with a caller-chosen `Update`.
601
    struct FrameLog {
602
        seen: Vec<(u32, u32, usize)>,
603
        reply: Update,
604
    }
605

            
606
    extern "C" fn record_frame(mut data: RefAny, _: CallbackInfo, frame: VideoFrame) -> Update {
607
        let mut reply = Update::DoNothing;
608
        if let Some(mut log) = data.downcast_mut::<FrameLog>() {
609
            log.seen
610
                .push((frame.width, frame.height, frame.bytes.as_ref().len()));
611
            reply = log.reply;
612
        }
613
        reply
614
    }
615

            
616
    extern "C" fn frame_do_nothing(_: RefAny, _: CallbackInfo, _: VideoFrame) -> Update {
617
        // A distinct body so the linker cannot fold this onto `record_frame` and
618
        // make the fn-pointer identity assertions vacuous.
619
        core::hint::black_box(Update::DoNothing)
620
    }
621

            
622
    fn frame_log(reply: Update) -> RefAny {
623
        RefAny::new(FrameLog {
624
            seen: Vec::new(),
625
            reply,
626
        })
627
    }
628

            
629
    /// The frames recorded by a `FrameLog` payload.
630
    fn logged_frames(data: &mut RefAny) -> Vec<(u32, u32, usize)> {
631
        data.downcast_ref::<FrameLog>()
632
            .expect("payload must still be a FrameLog")
633
            .seen
634
            .clone()
635
    }
636

            
637
    /// A `ScreenCaptureWidgetState` whose `on_frame` hook writes into `log`.
638
    fn state_with_hook(config: ScreenCaptureConfig, log: &RefAny) -> RefAny {
639
        RefAny::new(ScreenCaptureWidgetState {
640
            config,
641
            started: true,
642
            gl_texture_id: None,
643
            on_frame: Some(OnVideoFrame {
644
                refany: log.clone(),
645
                callback: (record_frame as OnVideoFrameCallbackType).into(),
646
            })
647
            .into(),
648
            consumers: FrameConsumerVec::from_const_slice(&[]),
649
            on_consumer_frame: OptionOnConsumerFrame::None,
650
            marker: "azul-screencap-test".into(),
651
            thread_id: None,
652
            control: None,
653
            preview: None,
654
        })
655
    }
656

            
657
    /// A tightly-packed RGBA frame (`width * height * 4` bytes).
658
    fn frame(width: u32, height: u32) -> VideoFrame {
659
        let px = (width as usize) * (height as usize);
660
        VideoFrame {
661
            width,
662
            height,
663
            bytes: vec![7u8; px * 4].into(),
664
        }
665
    }
666

            
667
    /// A frame whose declared dimensions need not match its byte count.
668
    fn frame_raw(width: u32, height: u32, bytes: Vec<u8>) -> VideoFrame {
669
        VideoFrame {
670
            width,
671
            height,
672
            bytes: bytes.into(),
673
        }
674
    }
675

            
676
    // ---- CallbackInfo harness --------------------------------------------
677

            
678
    /// Runs `f` against a real `CallbackInfo` over an empty `LayoutWindow` (no GL
679
    /// context -> the widget's CPU present path). Returns `f`'s value plus every
680
    /// `CallbackChange` the callback recorded.
681
    fn with_callback_info<R>(f: impl FnOnce(CallbackInfo) -> R) -> (R, Vec<CallbackChange>) {
682
        let layout_window =
683
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
684
        let renderer_resources = RendererResources::default();
685
        let previous_window_state: Option<FullWindowState> = None;
686
        let current_window_state = FullWindowState::default();
687
        let gl_context = OptionGlContextPtr::None;
688
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
689
            BTreeMap::new();
690
        let window_handle = RawWindowHandle::Unsupported;
691
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
692

            
693
        let ref_data = CallbackInfoRefData {
694
            layout_window: &layout_window,
695
            renderer_resources: &renderer_resources,
696
            previous_window_state: &previous_window_state,
697
            current_window_state: &current_window_state,
698
            gl_context: &gl_context,
699
            current_scroll_manager: &scroll_states,
700
            current_window_handle: &window_handle,
701
            system_callbacks: &system_callbacks,
702
            system_style: Arc::new(SystemStyle::default()),
703
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
704
            #[cfg(feature = "icu")]
705
            icu_localizer: IcuLocalizerHandle::default(),
706
            ctx: OptionRefAny::None,
707
        };
708

            
709
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
710

            
711
        let info = CallbackInfo::new(
712
            &ref_data,
713
            &changes,
714
            DomNodeId {
715
                dom: DomId::ROOT_ID,
716
                node: NodeHierarchyItemId::NONE,
717
            },
718
            OptionLogicalPosition::None,
719
            OptionLogicalPosition::None,
720
        );
721

            
722
        let out = f(info);
723
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
724
        (out, recorded)
725
    }
726

            
727
    // ---- screencap_worker harness ----------------------------------------
728

            
729
    /// One frame `screencap_worker` pushed, summarised so the (multi-megabyte)
730
    /// pixel buffer never has to be cloned into the log.
731
    #[derive(Debug, Clone, PartialEq, Eq)]
732
    struct SentFrame {
733
        width: u32,
734
        height: u32,
735
        len: usize,
736
        /// The first byte of every scanline (that row's test-pattern value).
737
        row_values: Vec<u8>,
738
        /// Every pixel of every scanline is `[v, v, v, 255]` for that row's `v`.
739
        rows_uniform_opaque: bool,
740
    }
741

            
742
    /// Everything `screencap_worker` managed to send. Guarded by `WORKER_GATE` -
743
    /// the worker's send callback is a plain C fn pointer, so it has nowhere else
744
    /// to put its result.
745
    static WORKER_LOG: Mutex<Vec<SentFrame>> = Mutex::new(Vec::new());
746
    static WORKER_GATE: Mutex<()> = Mutex::new(());
747

            
748
    /// Records the frame, then reports the send as *failed* - i.e. "the main
749
    /// thread is gone", the only signal `screencap_worker` has to stop. A worker
750
    /// that ignored it would hang this test binary forever (and grow ~3.7 MB per
751
    /// 33 ms while doing so).
752
    extern "C" fn record_and_stop(
753
        _sender: *const core::ffi::c_void,
754
        msg: ThreadReceiveMsg,
755
    ) -> bool {
756
        if let ThreadReceiveMsg::WriteBack(mut wb) = msg {
757
            if let Some(c) = wb.refany.downcast_ref::<CapturedFrames>() {
758
                let Some(f) = c.preview.as_ref().or(c.source.as_ref()) else {
759
                    return false;
760
                };
761
                let bytes = f.bytes.as_ref();
762
                let stride = (f.width as usize) * 4;
763
                let mut row_values = Vec::new();
764
                let mut rows_uniform_opaque = true;
765
                if stride > 0 {
766
                    for row in bytes.chunks_exact(stride) {
767
                        let v = row[0];
768
                        row_values.push(v);
769
                        if !row.chunks_exact(4).all(|px| px == &[v, v, v, 255][..]) {
770
                            rows_uniform_opaque = false;
771
                        }
772
                    }
773
                }
774
                WORKER_LOG
775
                    .lock()
776
                    .unwrap_or_else(PoisonError::into_inner)
777
                    .push(SentFrame {
778
                        width: f.width,
779
                        height: f.height,
780
                        len: bytes.len(),
781
                        row_values,
782
                        rows_uniform_opaque,
783
                    });
784
            }
785
        }
786
        false
787
    }
788

            
789
    extern "C" fn sender_drop_noop(_: *mut ThreadSenderInner) {}
790
    extern "C" fn receiver_drop_noop(_: *mut ThreadReceiverInner) {}
791
    extern "C" fn recv_nothing(_: *const core::ffi::c_void) -> OptionThreadSendMsg {
792
        OptionThreadSendMsg::None
793
    }
794

            
795
    /// A `ThreadSender` whose every `send` is recorded and then rejected.
796
    fn stopped_sender() -> (Receiver<ThreadReceiveMsg>, ThreadSender) {
797
        let (tx, rx) = channel::<ThreadReceiveMsg>();
798
        let sender = ThreadSender::new(ThreadSenderInner {
799
            ptr: Box::new(tx),
800
            send_fn: ThreadSendCallback {
801
                cb: record_and_stop,
802
            },
803
            destructor: ThreadSenderDestructorCallback {
804
                cb: sender_drop_noop,
805
            },
806
        });
807
        (rx, sender)
808
    }
809

            
810
    /// A `ThreadReceiver` that never delivers anything (the worker ignores it).
811
    fn silent_receiver() -> (Sender<ThreadSendMsg>, ThreadReceiver) {
812
        let (tx, rx) = channel::<ThreadSendMsg>();
813
        let receiver = ThreadReceiver::new(ThreadReceiverInner {
814
            ptr: Box::new(rx),
815
            recv_fn: ThreadRecvCallback { cb: recv_nothing },
816
            destructor: ThreadReceiverDestructorCallback {
817
                cb: receiver_drop_noop,
818
            },
819
        });
820
        (tx, receiver)
821
    }
822

            
823
    /// Runs `screencap_worker` with `init` against a sender that rejects the
824
    /// first frame, and returns everything the worker managed to send.
825
    ///
826
    /// `None` when a real platform screen backend is registered in this process
827
    /// (`capture_common`'s own tests register one into the same process-global
828
    /// `OnceLock`) - the worker is then not the test pattern these assertions
829
    /// describe. The check *after* the run is the load-bearing one: a `OnceLock`
830
    /// is monotone, so "still unset afterwards" proves it was unset throughout.
831
    fn run_worker(init: RefAny) -> Option<Vec<SentFrame>> {
832
        let _gate = WORKER_GATE.lock().unwrap_or_else(PoisonError::into_inner);
833
        if screen_backend().is_some() {
834
            return None;
835
        }
836
        WORKER_LOG
837
            .lock()
838
            .unwrap_or_else(PoisonError::into_inner)
839
            .clear();
840

            
841
        let (_rx, sender) = stopped_sender();
842
        let (_tx, receiver) = silent_receiver();
843
        screencap_worker(init, sender, receiver);
844

            
845
        if screen_backend().is_some() {
846
            return None; // registered by a parallel test mid-run
847
        }
848
        Some(
849
            WORKER_LOG
850
                .lock()
851
                .unwrap_or_else(PoisonError::into_inner)
852
                .clone(),
853
        )
854
    }
855

            
856
    // ------------------------------------------------------------------
857
    // ScreenCaptureWidget::create
858
    // ------------------------------------------------------------------
859

            
860
    #[test]
861
    fn create_stores_the_config_verbatim_and_leaves_the_hook_unset() {
862
        for config in ALL_CONFIGS {
863
            let widget = ScreenCaptureWidget::create(config);
864
            assert_eq!(
865
                widget.config, config,
866
                "create must not normalise or clamp the config"
867
            );
868
            assert!(
869
                matches!(widget.on_frame, OptionOnVideoFrame::None),
870
                "a fresh widget has no frame hook"
871
            );
872
        }
873
    }
874

            
875
    #[test]
876
    fn create_preserves_the_full_source_payload_width() {
877
        // A `as u32` anywhere in the widget would collapse a u64 window handle.
878
        let widget = ScreenCaptureWidget::create(cfg(
879
            ScreenCaptureSource::Window(u64::MAX),
880
            0,
881
            RawImageFormat::BGRA8,
882
        ));
883
        match widget.config.source {
884
            ScreenCaptureSource::Window(h) => assert_eq!(h, u64::MAX),
885
            other => panic!("expected Window(u64::MAX), got {other:?}"),
886
        }
887

            
888
        let widget = ScreenCaptureWidget::create(cfg(
889
            ScreenCaptureSource::Display(u32::MAX),
890
            u32::MAX,
891
            RawImageFormat::BGRA8,
892
        ));
893
        match widget.config.source {
894
            ScreenCaptureSource::Display(i) => assert_eq!(i, u32::MAX),
895
            other => panic!("expected Display(u32::MAX), got {other:?}"),
896
        }
897
        assert_eq!(widget.config.fps, u32::MAX, "fps must not be clamped");
898
    }
899

            
900
    #[test]
901
    fn create_is_usable_from_a_const_fn() {
902
        for config in ALL_CONFIGS {
903
            let widget = const_create(config);
904
            assert_eq!(widget.config, config);
905
            assert!(matches!(widget.on_frame, OptionOnVideoFrame::None));
906
        }
907
    }
908

            
909
    // ------------------------------------------------------------------
910
    // ScreenCaptureWidget::set_on_frame / with_on_frame
911
    // ------------------------------------------------------------------
912

            
913
    #[test]
914
    fn set_on_frame_installs_the_hook_without_touching_the_config() {
915
        for config in ALL_CONFIGS {
916
            let mut widget = ScreenCaptureWidget::create(config);
917
            widget.set_on_frame(
918
                frame_log(Update::DoNothing),
919
                record_frame as OnVideoFrameCallbackType,
920
            );
921

            
922
            assert_eq!(widget.config, config, "the hook must not alter the config");
923
            let OptionOnVideoFrame::Some(hook) = &widget.on_frame else {
924
                panic!("set_on_frame must install a hook");
925
            };
926
            assert_eq!(
927
                hook.callback.cb as usize, record_frame as OnVideoFrameCallbackType as usize,
928
                "the stored fn pointer must be exactly the one that was passed in"
929
            );
930
        }
931
    }
932

            
933
    #[test]
934
    fn set_on_frame_twice_keeps_only_the_last_hook() {
935
        let mut widget = ScreenCaptureWidget::create(DEFAULT_CFG);
936
        widget.set_on_frame(
937
            RefAny::new(0_usize),
938
            record_frame as OnVideoFrameCallbackType,
939
        );
940
        widget.set_on_frame(
941
            RefAny::new(1_usize),
942
            frame_do_nothing as OnVideoFrameCallbackType,
943
        );
944

            
945
        let OptionOnVideoFrame::Some(hook) = &widget.on_frame else {
946
            panic!("hook must still be set");
947
        };
948
        assert_eq!(
949
            hook.callback.cb as usize, frame_do_nothing as OnVideoFrameCallbackType as usize,
950
            "the second set_on_frame must replace the first, not stack"
951
        );
952
        assert_eq!(
953
            hook.refany.clone().downcast_ref::<usize>().map(|v| *v),
954
            Some(1),
955
            "the replacement's payload must come with it"
956
        );
957
    }
958

            
959
    #[test]
960
    fn set_on_frame_shares_the_users_payload_rather_than_copying_it() {
961
        // The backreference DI pattern only works if the widget holds a handle to
962
        // the *same* allocation the caller kept.
963
        let mut log = frame_log(Update::DoNothing);
964
        let mut widget = ScreenCaptureWidget::create(DEFAULT_CFG);
965
        widget.set_on_frame(log.clone(), record_frame as OnVideoFrameCallbackType);
966

            
967
        let OptionOnVideoFrame::Some(hook) = &widget.on_frame else {
968
            panic!("hook must be set");
969
        };
970
        let mut stored = hook.refany.clone();
971
        {
972
            let mut inner = stored
973
                .downcast_mut::<FrameLog>()
974
                .expect("the widget must hold a FrameLog");
975
            inner.seen.push((1, 2, 3));
976
        }
977
        assert_eq!(
978
            logged_frames(&mut log),
979
            vec![(1, 2, 3)],
980
            "the widget must share the caller's payload, not clone it"
981
        );
982
    }
983

            
984
    #[test]
985
    fn with_on_frame_is_exactly_create_plus_set_on_frame() {
986
        for config in ALL_CONFIGS {
987
            let built = ScreenCaptureWidget::create(config).with_on_frame(
988
                frame_log(Update::RefreshDom),
989
                record_frame as OnVideoFrameCallbackType,
990
            );
991
            let mut manual = ScreenCaptureWidget::create(config);
992
            manual.set_on_frame(
993
                frame_log(Update::RefreshDom),
994
                record_frame as OnVideoFrameCallbackType,
995
            );
996

            
997
            assert_eq!(
998
                built.config, config,
999
                "the builder must not touch the config"
            );
            assert_eq!(built.config, manual.config);
            let (OptionOnVideoFrame::Some(a), OptionOnVideoFrame::Some(b)) =
                (&built.on_frame, &manual.on_frame)
            else {
                panic!("both forms must install a hook");
            };
            assert_eq!(a.callback.cb as usize, b.callback.cb as usize);
        }
    }
    // ------------------------------------------------------------------
    // ScreenCaptureWidget::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_placeholder_is_always_1280x720_bgra8_whatever_the_config_asks_for() {
        // The placeholder is a fixed-size stand-in: the *real* size is whatever
        // the backend reports at runtime. So neither the requested source nor the
        // requested output format may leak into it.
        for config in ALL_CONFIGS {
            let (w, h, format, tag) = placeholder_of(&ScreenCaptureWidget::create(config).dom());
            assert_eq!(
                (w, h),
                (1280, 720),
                "the placeholder size is fixed, not derived from {config:?}"
            );
            assert_eq!(
                format,
                RawImageFormat::BGRA8,
                "output_format is a *capture* request; the placeholder stays BGRA8"
            );
            assert_eq!(tag, b"azul-screencap-placeholder".to_vec());
        }
    }
    #[test]
    fn dom_placeholder_is_a_null_image_that_allocates_no_pixels() {
        // 1280 * 720 * 4 bytes would be ~3.7 MB per widget if the placeholder were
        // a real raw image; a NullImage is only a descriptor.
        let dom = ScreenCaptureWidget::create(DEFAULT_CFG).dom();
        let NodeType::Image(image) = dom.root.get_node_type() else {
            panic!("the widget must build an image node");
        };
        assert!(
            matches!(image.get_data(), DecodedImage::NullImage { .. }),
            "the placeholder must not decode or allocate"
        );
    }
    #[test]
    fn dom_wires_exactly_one_after_mount_callback_a_dataset_and_a_merge_callback() {
        let dom = ScreenCaptureWidget::create(DEFAULT_CFG).dom();
        assert_eq!(
            dom.children.as_ref().len(),
            0,
            "the widget is a single node"
        );
        let callbacks = dom.root.get_callbacks();
        assert_eq!(
            callbacks.as_ref().len(),
            2,
            "two callbacks: the AfterMount capture-thread starter + the NodeResized re-targeter"
        );
        assert_eq!(
            callbacks.as_ref()[0].event,
            EventFilter::Component(ComponentEventFilter::AfterMount),
            "the thread must start on AfterMount, not on any input event"
        );
        assert_eq!(
            callbacks.as_ref()[0].callback.cb,
            screencap_on_after_mount as CallbackType as usize,
            "the wired callback must be screencap_on_after_mount"
        );
        let merge = dom
            .root
            .get_merge_callback()
            .expect("state must survive relayout");
        assert_eq!(
            merge.cb as usize, merge_screencap_state as DatasetMergeCallbackType as usize,
            "the merge callback must be merge_screencap_state"
        );
    }
    #[test]
    fn dom_seeds_the_dataset_with_the_config_and_a_not_yet_started_thread() {
        for config in ALL_CONFIGS {
            let dom = ScreenCaptureWidget::create(config).dom();
            let mut dataset = dom
                .root
                .get_dataset()
                .cloned()
                .expect("the node must carry its ScreenCaptureWidgetState");
            let (stored, started, texture, has_hook) = read_state(&mut dataset);
            assert_eq!(stored, config, "dom() must not rewrite the config");
            assert!(!started, "the capture thread only starts on AfterMount");
            assert_eq!(texture, None, "no texture exists before the first frame");
            assert!(!has_hook, "no hook was set on this widget");
        }
    }
    #[test]
    fn dom_moves_the_on_frame_hook_into_the_dataset() {
        let dom = ScreenCaptureWidget::create(DEFAULT_CFG)
            .with_on_frame(
                frame_log(Update::DoNothing),
                record_frame as OnVideoFrameCallbackType,
            )
            .dom();
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
        let (_, _, _, has_hook) = read_state(&mut dataset);
        assert!(has_hook, "dom() must carry the user hook into the state");
    }
    #[test]
    fn dom_gives_the_after_mount_callback_the_very_same_state_the_node_carries() {
        // `dom()` hands the callback a *clone* of the dataset. If that clone did
        // not share the payload, AfterMount would flip `started` on a copy and the
        // capture thread would be started again on every mount.
        let dom = ScreenCaptureWidget::create(DEFAULT_CFG).dom();
        let mut node_ds = dom.root.get_dataset().cloned().expect("dataset");
        let mut cb_ds = dom.root.get_callbacks().as_ref()[0].refany.clone();
        {
            let mut s = cb_ds
                .downcast_mut::<ScreenCaptureWidgetState>()
                .expect("the callback's payload must be the widget state");
            s.started = true;
            s.gl_texture_id = Some(1234);
        }
        let (_, started, texture, _) = read_state(&mut node_ds);
        assert!(
            started,
            "the callback and the node must share one state, not two copies"
        );
        assert_eq!(texture, Some(1234));
    }
    #[test]
    fn two_widgets_built_from_one_config_get_independent_state() {
        let a = ScreenCaptureWidget::create(cfg(
            ScreenCaptureSource::Display(0),
            30,
            RawImageFormat::BGRA8,
        ))
        .dom();
        let b = ScreenCaptureWidget::create(cfg(
            ScreenCaptureSource::Window(7),
            60,
            RawImageFormat::RGBA8,
        ))
        .dom();
        let mut da = a.root.get_dataset().cloned().expect("dataset a");
        let mut db = b.root.get_dataset().cloned().expect("dataset b");
        {
            let mut s = da
                .downcast_mut::<ScreenCaptureWidgetState>()
                .expect("state a");
            s.started = true;
        }
        let (config_a, started_a, _, _) = read_state(&mut da);
        let (config_b, started_b, _, _) = read_state(&mut db);
        assert!(started_a);
        assert!(
            !started_b,
            "two widgets must not share one global capture state"
        );
        assert_eq!(config_a.source, ScreenCaptureSource::Display(0));
        assert_eq!(config_b.source, ScreenCaptureSource::Window(7));
    }
    // ------------------------------------------------------------------
    // screencap_on_after_mount
    //
    // NOTE: the *first* mount (started == false) is deliberately not exercised.
    // It calls `Thread::create`, which spawns a real OS thread running
    // `screencap_worker`; nothing in a unit test drains that thread's channel, so
    // the worker would loop forever pushing ~3.7 MB frames while the `Thread`
    // destructor waits to join it. Only the guard paths below can be driven
    // safely (this mirrors the camera widget's test module).
    // ------------------------------------------------------------------
    #[test]
    fn after_mount_ignores_a_dataset_that_is_not_a_screencap_state() {
        for foreign in [RefAny::new(0_u32), RefAny::new(DEFAULT_CFG)] {
            // The second case is the plausible mistake: handing the *config* POD
            // instead of the widget state.
            let (update, changes) =
                with_callback_info(|info| screencap_on_after_mount(foreign.clone(), info));
            assert_eq!(update, Update::DoNothing);
            assert!(
                changes.is_empty(),
                "a foreign dataset must not start a capture thread: {changes:?}"
            );
        }
    }
    #[test]
    fn after_mount_is_a_no_op_once_the_thread_has_started() {
        let log = frame_log(Update::RefreshDom);
        let mut data = state_with_hook(DEFAULT_CFG, &log);
        {
            let mut s = data
                .downcast_mut::<ScreenCaptureWidgetState>()
                .expect("state");
            s.gl_texture_id = Some(3);
        }
        // Repeated mounts (relayout re-runs AfterMount) must stay inert.
        for _ in 0..3 {
            let (update, changes) =
                with_callback_info(|info| screencap_on_after_mount(data.clone(), info));
            assert_eq!(update, Update::DoNothing);
            assert!(
                changes.is_empty(),
                "AfterMount must start the capture thread at most once: {changes:?}"
            );
        }
        let (config, started, texture, has_hook) = read_state(&mut data);
        assert_eq!(
            config, DEFAULT_CFG,
            "a re-mount must not rewrite the config"
        );
        assert!(started);
        assert_eq!(texture, Some(3), "a re-mount must not drop the texture");
        assert!(has_hook, "a re-mount must not drop the user hook");
    }
    // ------------------------------------------------------------------
    // capture_request / capture_floor — the config reaches the backend
    // ------------------------------------------------------------------
    #[test]
    fn the_config_source_and_fps_reach_the_backend_request_with_self_excluded() {
        // `config.source` and `config.fps` used to be ignored: the worker
        // opened display 0 at a hard-coded size and the backend ran at a
        // hard-coded 30 fps.
        let mut cfg = ScreenCaptureConfig {
            fps: 15,
            source: ScreenCaptureSource::Display(2),
            ..ScreenCaptureConfig::default()
        };
        let r = capture_request(&cfg);
        assert_eq!((r.index, r.window, r.fps), (2, 0, 15));
        assert!(
            r.exclude_self,
            "a share never shows the sharing app to itself"
        );
        cfg.source = ScreenCaptureSource::Window(0xABCD);
        assert_eq!(capture_request(&cfg).window, 0xABCD);
        cfg.source = ScreenCaptureSource::PrimaryDisplay;
        assert_eq!(capture_request(&cfg).index, 0);
        assert_eq!(
            capture_floor(false),
            None,
            "no hook: the tile + consumers size the stream"
        );
        assert_eq!(capture_floor(true), Some((DEFAULT_W, DEFAULT_H)));
    }
    // ------------------------------------------------------------------
    // screencap_worker
    // ------------------------------------------------------------------
    #[test]
    fn worker_stops_as_soon_as_the_main_thread_stops_receiving() {
        let Some(sent) = run_worker(RefAny::new(())) else {
            return; // a platform screen backend is registered: not the test pattern
        };
        assert_eq!(
            sent.len(),
            1,
            "the worker must stop after the first rejected send, not spin"
        );
        assert_eq!(
            (sent[0].width, sent[0].height),
            (DEFAULT_W, DEFAULT_H),
            "the test pattern is emitted at the widget's default capture size"
        );
        assert_eq!(
            sent[0].len,
            (DEFAULT_W as usize) * (DEFAULT_H as usize) * 4,
            "the frame must be tightly-packed RGBA8: w * h * 4 bytes"
        );
    }
    #[test]
    fn worker_emits_the_documented_band_pattern_on_its_first_frame() {
        let Some(sent) = run_worker(RefAny::new(())) else {
            return;
        };
        let f = &sent[0];
        assert!(
            f.rows_uniform_opaque,
            "every pixel must be an opaque grey [v, v, v, 255]"
        );
        assert_eq!(
            f.row_values.len(),
            DEFAULT_H as usize,
            "one value per scanline"
        );
        // tick 0 => band == 0, so rows 0..8 are the bright band (|y - 0| < 8).
        assert!(
            f.row_values[..8].iter().all(|&v| v == 235),
            "rows 0..8 are the bright band, got {:?}",
            &f.row_values[..8]
        );
        assert!(
            f.row_values[8..].iter().all(|&v| v == 28),
            "every row below the band is dark grey"
        );
    }
    #[test]
    fn worker_ignores_its_init_payload_entirely() {
        // ADVERSARIAL: the test-pattern worker takes NO input - not the widget's
        // config, not its fps, not its source. A caller cannot influence the
        // frames by handing it a different init, and a garbage init must not
        // panic.
        let Some(unit) = run_worker(RefAny::new(())) else {
            return;
        };
        let Some(text) = run_worker(RefAny::new("not an init struct")) else {
            return;
        };
        let Some(widget_state) = run_worker(state(
            cfg(
                ScreenCaptureSource::Window(u64::MAX),
                u32::MAX,
                RawImageFormat::R8,
            ),
            true,
            Some(u32::MAX),
        )) else {
            return;
        };
        assert_eq!(unit, text, "a foreign init must not change the frames");
        assert_eq!(
            unit, widget_state,
            "even a full widget state (fps = u32::MAX, R8) must not change the test pattern - it \
             is hard-coded"
        );
    }
    // ------------------------------------------------------------------
    // screencap_writeback
    // ------------------------------------------------------------------
    #[test]
    fn writeback_invokes_the_hook_with_the_frame_and_returns_its_update() {
        for reply in [
            Update::DoNothing,
            Update::RefreshDom,
            Update::RefreshDomAllWindows,
        ] {
            let mut log = frame_log(reply);
            let mut data = state_with_hook(DEFAULT_CFG, &log);
            let frame_data = captured(frame(2, 2));
            let (update, _) = with_callback_info(|info| {
                screencap_writeback(data.clone(), frame_data.clone(), info)
            });
            assert_eq!(
                update, reply,
                "the user hook's Update must be returned as-is"
            );
            assert_eq!(logged_frames(&mut log), vec![(2, 2, 16)]);
            let (_, _, texture, _) = read_state(&mut data);
            assert_eq!(
                texture, None,
                "without a GL context no texture id is ever installed"
            );
        }
    }
    #[test]
    fn writeback_ignores_frame_data_of_the_wrong_type() {
        let mut log = frame_log(Update::RefreshDom);
        let mut data = state_with_hook(DEFAULT_CFG, &log);
        let (update, changes) =
            with_callback_info(|info| screencap_writeback(data.clone(), RefAny::new(0_u32), info));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty(), "no frame -> no image change");
        assert!(
            logged_frames(&mut log).is_empty(),
            "the user hook must not fire without a frame"
        );
    }
    #[test]
    fn writeback_survives_a_writeback_dataset_that_is_not_a_screencap_state() {
        let (update, changes) = with_callback_info(|info| {
            screencap_writeback(RefAny::new(0_u32), captured(frame(1, 1)), info)
        });
        assert_eq!(
            update,
            Update::DoNothing,
            "a foreign dataset means no hook and no texture - but no panic either"
        );
        assert!(
            changes.is_empty(),
            "no node owns that dataset, so nothing may be installed: {changes:?}"
        );
    }
    #[test]
    fn writeback_keeps_a_preexisting_texture_id_on_the_cpu_path() {
        for current in [Some(0_u32), Some(42), Some(u32::MAX)] {
            let mut data = state(DEFAULT_CFG, true, current);
            let frame_data = captured(frame(2, 2));
            let (update, _) = with_callback_info(|info| {
                screencap_writeback(data.clone(), frame_data.clone(), info)
            });
            assert_eq!(update, Update::DoNothing, "no hook -> no user update");
            let (_, _, texture, _) = read_state(&mut data);
            assert_eq!(
                texture, current,
                "the stable texture id must survive the writeback unchanged"
            );
        }
    }
    #[test]
    fn writeback_rejects_a_frame_whose_bytes_do_not_match_its_dimensions() {
        // A malformed/hostile backend frame: the image upload must fail cleanly
        // instead of indexing out of bounds or allocating ~17 GB.
        for (w, h, bytes) in [
            (u32::MAX, 1_u32, Vec::new()),
            (4, 4, vec![0_u8; 63]),
            (4, 4, vec![0_u8; 65]),
            (2, 2, Vec::new()),
        ] {
            let mut data = state(DEFAULT_CFG, true, None);
            let bogus = captured(frame_raw(w, h, bytes.clone()));
            let (update, changes) =
                with_callback_info(|info| screencap_writeback(data.clone(), bogus.clone(), info));
            assert_eq!(update, Update::DoNothing);
            assert!(
                changes.is_empty(),
                "a {w}x{h} frame with {} bytes must not touch the DOM: {changes:?}",
                bytes.len()
            );
            let (_, _, texture, _) = read_state(&mut data);
            assert_eq!(
                texture, None,
                "a rejected frame must not invent a texture id"
            );
        }
    }
    #[test]
    fn writeback_hands_even_a_rejected_frame_to_the_user_hook() {
        // FOOTGUN worth pinning: `present_frame` and `invoke_on_frame` are
        // independent. A frame the image pipeline rejects still reaches user code,
        // so `on_frame` is NOT a "this frame was valid" signal.
        let mut log = frame_log(Update::RefreshDom);
        let mut data = state_with_hook(DEFAULT_CFG, &log);
        let bogus = captured(frame_raw(u32::MAX, 1, Vec::new()));
        let (update, changes) =
            with_callback_info(|info| screencap_writeback(data.clone(), bogus.clone(), info));
        assert_eq!(update, Update::RefreshDom);
        assert!(changes.is_empty(), "the frame itself was rejected");
        assert_eq!(
            logged_frames(&mut log),
            vec![(u32::MAX, 1, 0)],
            "the hook sees the raw frame, dimensions and all, unvalidated"
        );
    }
    #[test]
    fn writeback_accepts_a_zero_sized_frame_without_panicking() {
        // 0 * 0 * 4 == 0 == len(bytes), so a 0x0 frame passes the length check and
        // is installed as a degenerate image. Pin that it stays panic-free and
        // leaves the texture id alone.
        let mut data = state(DEFAULT_CFG, true, Some(2));
        let empty = captured(frame_raw(0, 0, Vec::new()));
        let (update, _) =
            with_callback_info(|info| screencap_writeback(data.clone(), empty.clone(), info));
        assert_eq!(update, Update::DoNothing);
        let (_, _, texture, _) = read_state(&mut data);
        assert_eq!(texture, Some(2));
    }
    #[test]
    fn writeback_survives_dimensions_whose_byte_count_overflows_usize() {
        // ADVERSARIAL: a backend reporting 2^31 x 2^31 makes the CPU present path
        // compute `width * height * 4` in usize -> 2^64, which overflows. In a
        // debug build that is an arithmetic-overflow panic; in release it wraps to
        // 0 and the empty buffer is *accepted* as a valid 2^31 x 2^31 image.
        // Neither is a graceful rejection (see the autotest report) - what must
        // hold in both modes is that the widget's stored texture id is never
        // corrupted and the process is still usable afterwards.
        let mut data = state(DEFAULT_CFG, true, Some(11));
        let huge = captured(frame_raw(1_u32 << 31, 1_u32 << 31, Vec::new()));
        let (result, _) = with_callback_info(|info| {
            catch_unwind(AssertUnwindSafe(|| {
                screencap_writeback(data.clone(), huge.clone(), info)
            }))
        });
        match result {
            Ok(update) => {
                assert_eq!(update, Update::DoNothing);
                let (_, _, texture, _) = read_state(&mut data);
                assert_eq!(texture, Some(11), "the texture id must not be corrupted");
            }
            Err(_) => eprintln!(
                "NOTE: screencap_writeback panicked (usize overflow of width*height*4) for a 2^31 \
                 x 2^31 frame - a malformed capture backend can take the process down"
            ),
        }
    }
    // ------------------------------------------------------------------
    // merge_screencap_state
    // ------------------------------------------------------------------
    #[test]
    fn merge_takes_the_thread_state_from_old_and_everything_else_from_new() {
        let fresh = cfg(
            ScreenCaptureSource::Window(u64::MAX),
            60,
            RawImageFormat::RGBA8,
        );
        let log = frame_log(Update::DoNothing);
        let new_data = state_with_hook(fresh, &log);
        let old_data = state(
            cfg(ScreenCaptureSource::Display(3), 1, RawImageFormat::R8),
            true,
            Some(9),
        );
        let mut merged = merge_screencap_state(new_data, old_data);
        let (config, started, texture, has_hook) = read_state(&mut merged);
        assert_eq!(config, fresh, "the fresh build's config wins");
        assert!(has_hook, "the fresh build's hook wins");
        assert!(started, "'thread already running' must carry forward");
        assert_eq!(texture, Some(9), "the stable texture id must carry forward");
    }
    #[test]
    fn merge_lets_the_old_thread_state_overwrite_a_fresh_builds_claim() {
        // The old state is authoritative for `started` / `gl_texture_id` in BOTH
        // directions: a fresh build that (wrongly) claims to be running is reset,
        // so the thread is started exactly once per real mount.
        let new_data = RefAny::new(ScreenCaptureWidgetState {
            config: DEFAULT_CFG,
            started: true,
            gl_texture_id: Some(77),
            on_frame: OptionOnVideoFrame::None,
            consumers: FrameConsumerVec::from_const_slice(&[]),
            on_consumer_frame: OptionOnConsumerFrame::None,
            marker: "azul-screencap-test".into(),
            thread_id: None,
            control: None,
            preview: None,
        });
        let old_data = state(DEFAULT_CFG, false, None);
        let mut merged = merge_screencap_state(new_data, old_data);
        let (_, started, texture, _) = read_state(&mut merged);
        assert!(
            !started,
            "the old state wins for `started`, in both directions"
        );
        assert_eq!(texture, None, "and for the texture id too");
    }
    #[test]
    fn merge_returns_the_persistent_old_payload_not_a_copy() {
        // PIN FLIPPED (2026-07-31, deliberately): merge used to return the
        // NEW allocation, which orphaned the allocation live capture
        // backends hold a clone of (the frame writeback then wrote into a
        // dataset nobody rendered — the frozen-picture family). The rule is
        // now the map widget's: adopt config forward, return the OLD
        // (persistent) allocation.
        let old_data = state(DEFAULT_CFG, true, Some(5));
        let mut kept = old_data.clone();
        let mut merged = merge_screencap_state(state(DEFAULT_CFG, false, None), old_data);
        {
            let mut s = merged
                .downcast_mut::<ScreenCaptureWidgetState>()
                .expect("merged state");
            s.gl_texture_id = Some(1);
        }
        let (_, started, texture, _) = read_state(&mut kept);
        assert!(
            started,
            "the persistent allocation keeps its worker-facing fields"
        );
        assert_eq!(
            texture,
            Some(1),
            "merge must hand back the OLD allocation — the one live capture backends hold a clone \
             of"
        );
    }
    #[test]
    fn merge_leaves_the_new_state_alone_when_the_old_one_is_foreign() {
        let new_data = state(DEFAULT_CFG, false, None);
        let mut merged = merge_screencap_state(new_data, RefAny::new(0_u32));
        let (config, started, texture, _) = read_state(&mut merged);
        assert_eq!(config, DEFAULT_CFG);
        assert!(!started, "nothing to carry forward from a foreign payload");
        assert_eq!(texture, None);
    }
    #[test]
    fn merge_returns_a_foreign_new_dataset_untouched() {
        let old_data = state(DEFAULT_CFG, true, Some(1));
        let mut merged = merge_screencap_state(RefAny::new(77_u32), old_data);
        assert_eq!(
            merged.downcast_ref::<u32>().map(|v| *v),
            Some(77),
            "merge must hand back exactly the payload it was given"
        );
    }
    #[test]
    fn merge_of_a_dataset_with_itself_does_not_panic() {
        // The same RefAny on both sides: the mutable + shared borrow overlap, so
        // the merge is skipped rather than aliasing. Either way the state must
        // survive intact.
        let mut data = state(DEFAULT_CFG, true, Some(5));
        let mut merged = merge_screencap_state(data.clone(), data.clone());
        let (config, started, texture, _) = read_state(&mut merged);
        assert_eq!(config, DEFAULT_CFG);
        assert!(started);
        assert_eq!(texture, Some(5));
        assert_eq!(read_state(&mut data), (DEFAULT_CFG, true, Some(5), false));
    }
    /// REGRESSION (B3): a capture worker must ACKNOWLEDGE `TerminateThread`.
    ///
    /// Reported from azul-meet on macOS after using camera + screenshare — the
    /// framework printed, twice (once per capture worker):
    ///
    /// ```text
    /// [azul][thread] a background thread did not acknowledge TerminateThread
    /// within 2000ms and was DETACHED rather than joined.
    /// ```
    ///
    /// Root cause: the worker took its receiver as `_recv` and never polled it,
    /// so the terminate message was never observed. The only exit was
    /// `sender.send()` returning false, which does NOT happen at shutdown
    /// because the main thread still owns the receiving end while it waits out
    /// the grace period. Fixed by `capture_common::terminate_requested`.
    ///
    /// The budget here is the framework's own:
    /// `THREAD_TERMINATE_GRACE_STEPS (200) * 10ms = 2000ms`.
    #[test]
    fn screencap_worker_acknowledges_terminate_within_the_grace_budget() {
        use crate::thread::{Thread, ThreadCallback};
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            ThreadCallback::new(screencap_worker),
        );
        assert!(
            t.send_message(ThreadSendMsg::TerminateThread),
            "the worker holds its receiver alive, so the send must succeed"
        );
        let finished = || {
            t.ptr
                .lock()
                .expect("thread mutex must not be poisoned")
                .is_finished()
        };
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(2_000);
        while !finished() && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert!(
            finished(),
            "screencap_worker did not acknowledge TerminateThread within 2000ms — at shutdown it \
             would be DETACHED rather than joined"
        );
    }
}