1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(
5
    clippy::float_cmp,
6
    clippy::too_many_lines,
7
    clippy::cast_precision_loss,
8
    clippy::unusual_byte_groupings
9
)]
10
mod autotest_generated {
11
    use alloc::string::String;
12

            
13
    use super::*;
14
    use crate::{
15
        events::HoverEventFilter,
16
        resources::{RawImageFormat, RouteMatch},
17
        window::StringPairVec,
18
    };
19

            
20
    // ---- helpers -----------------------------------------------------------
21

            
22
    fn s(v: &str) -> AzString {
23
        AzString::from(String::from(v))
24
    }
25

            
26
    fn win(width: f32, height: f32, dpi: u32) -> WindowSize {
27
        WindowSize {
28
            dimensions: LogicalSize::new(width, height),
29
            dpi,
30
            min_dimensions: None.into(),
31
            max_dimensions: None.into(),
32
        }
33
    }
34

            
35
    /// Owns everything a `LayoutCallbackInfoRefData` borrows, so that the raw
36
    /// pointer `LayoutCallbackInfo` launders to `'static` always points at
37
    /// live memory for the duration of a test.
38
    struct Fixture {
39
        fonts: FcFontCache,
40
        images: ImageCache,
41
        style: Arc<SystemStyle>,
42
        gl: OptionGlContextPtr,
43
        route: Option<RouteMatch>,
44
    }
45

            
46
    impl Fixture {
47
        fn new() -> Self {
48
            Self {
49
                fonts: FcFontCache::default(),
50
                images: ImageCache::default(),
51
                style: Arc::new(SystemStyle::default()),
52
                gl: OptionGlContextPtr::None,
53
                route: None,
54
            }
55
        }
56

            
57
        fn with_route(route: RouteMatch) -> Self {
58
            let mut f = Self::new();
59
            f.route = Some(route);
60
            f
61
        }
62

            
63
        fn ref_data(&self) -> LayoutCallbackInfoRefData<'_> {
64
            LayoutCallbackInfoRefData {
65
                image_cache: &self.images,
66
                gl_context: &self.gl,
67
                system_fonts: &self.fonts,
68
                system_style: self.style.clone(),
69
                active_route: self.route.as_ref(),
70
                monitors: crate::window::MonitorVec::from_const_slice(&[]),
71
                safe_area: azul_css::system::SafeAreaInsets::default(),
72
            }
73
        }
74
    }
75

            
76
    /// #28 (d): `get_max_monitor_size` returns the LARGEST monitor by area
77
    /// (the safe "how much could possibly be visible" bound for first
78
    /// layout) and `None` on an empty snapshot (headless/web).
79
    #[test]
80
    fn max_monitor_size_is_largest_by_area_or_none() {
81
        use azul_css::props::basic::LayoutSize;
82

            
83
        use crate::window::{Monitor, MonitorVec};
84

            
85
        let fixture = Fixture::new();
86
        let mut rd = fixture.ref_data();
87
        rd.monitors = MonitorVec::from_vec(Vec::from([
88
            Monitor {
89
                size: LayoutSize::new(1920, 1080),
90
                ..Monitor::default()
91
            },
92
            Monitor {
93
                size: LayoutSize::new(2560, 1440),
94
                ..Monitor::default()
95
            },
96
            Monitor {
97
                size: LayoutSize::new(800, 600),
98
                ..Monitor::default()
99
            },
100
        ]));
101
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
102
        let max: Option<LayoutSize> = info.get_max_monitor_size().into();
103
        assert_eq!(max, Some(LayoutSize::new(2560, 1440)));
104
        assert_eq!(info.get_monitors().len(), 3);
105

            
106
        let rd2 = fixture.ref_data(); // empty snapshot
107
        let info2 = LayoutCallbackInfo::new(&rd2, WindowSize::default(), WindowTheme::LightMode);
108
        let none: Option<LayoutSize> = info2.get_max_monitor_size().into();
109
        assert_eq!(none, None);
110
    }
111

            
112
    /// `/user/:id` with a plain and a non-ASCII parameter.
113
    fn user_route() -> RouteMatch {
114
        RouteMatch {
115
            pattern: s("/user/:id"),
116
            params: StringPairVec::from_vec(Vec::from([
117
                AzStringPair {
118
                    key: s("id"),
119
                    value: s("42"),
120
                },
121
                AzStringPair {
122
                    key: s("\u{1F600}"),
123
                    value: s("emoji"),
124
                },
125
            ])),
126
        }
127
    }
128

            
129
    fn vv_info<'a>(
130
        fonts: &'a FcFontCache,
131
        images: &'a ImageCache,
132
        bounds: HidpiAdjustedBounds,
133
    ) -> VirtualViewCallbackInfo {
134
        VirtualViewCallbackInfo::new(
135
            VirtualViewCallbackReason::InitialRender,
136
            fonts,
137
            images,
138
            WindowTheme::LightMode,
139
            crate::window::WindowFrame::Normal,
140
            bounds,
141
            // materialized: a window at y=2 covering 100x200 of the document
142
            LogicalRect::new(
143
                LogicalPosition::new(1.0, 2.0),
144
                LogicalSize::new(100.0, 200.0),
145
            ),
146
            // virtual_rect: the whole document
147
            LogicalRect::new(LogicalPosition::zero(), LogicalSize::new(1000.0, 2000.0)),
148
            // where the user is looking
149
            LogicalPosition::new(3.0, 4.0),
150
        )
151
    }
152

            
153
    fn bounds_1x1() -> HidpiAdjustedBounds {
154
        HidpiAdjustedBounds::from_bounds(LayoutSize::new(1, 1), DpiScaleFactor::new(1.0))
155
    }
156

            
157
    // ---- Update::max_self --------------------------------------------------
158

            
159
    const ALL_UPDATES: [Update; 3] = [
160
        Update::DoNothing,
161
        Update::RefreshDom,
162
        Update::RefreshDomAllWindows,
163
    ];
164

            
165
    /// `max_self` must be exactly the `Ord`-max of the lattice, for every one
166
    /// of the 3x3 combinations (this is the whole contract, so check it
167
    /// exhaustively rather than sampling).
168
    #[test]
169
    fn update_max_self_is_exhaustively_ord_max() {
170
        for a in ALL_UPDATES {
171
            for b in ALL_UPDATES {
172
                let mut got = a;
173
                got.max_self(b);
174
                assert_eq!(
175
                    got,
176
                    core::cmp::max(a, b),
177
                    "max_self({a:?}, {b:?}) disagrees with Ord::max"
178
                );
179
            }
180
        }
181
    }
182

            
183
    #[test]
184
    fn update_max_self_is_idempotent_and_monotone() {
185
        for a in ALL_UPDATES {
186
            // idempotent: x.max(x) == x
187
            let mut got = a;
188
            got.max_self(a);
189
            assert_eq!(got, a);
190

            
191
            // absorbing top element: nothing can lower RefreshDomAllWindows
192
            let mut top = Update::RefreshDomAllWindows;
193
            top.max_self(a);
194
            assert_eq!(top, Update::RefreshDomAllWindows);
195

            
196
            // monotone: max_self never decreases self
197
            let mut m = a;
198
            m.max_self(Update::DoNothing);
199
            assert!(m >= a);
200
        }
201
    }
202

            
203
    /// Applying the same set of updates in any order must converge to the same
204
    /// value (commutativity/associativity of the fold), since callbacks fold
205
    /// their `Update`s in nondeterministic order.
206
    #[test]
207
    fn update_max_self_fold_is_order_independent() {
208
        for a in ALL_UPDATES {
209
            for b in ALL_UPDATES {
210
                for c in ALL_UPDATES {
211
                    let mut fwd = a;
212
                    fwd.max_self(b);
213
                    fwd.max_self(c);
214

            
215
                    let mut rev = c;
216
                    rev.max_self(b);
217
                    rev.max_self(a);
218

            
219
                    assert_eq!(fwd, rev, "fold of {a:?},{b:?},{c:?} is order-dependent");
220
                }
221
            }
222
        }
223
    }
224

            
225
    // ---- LayoutCallback / default_layout_callback ---------------------------
226

            
227
    static ALT_LAYOUT_CALLS: AtomicUsize = AtomicUsize::new(0);
228

            
229
    // NOTE: the body must differ from `default_layout_callback`'s, otherwise
230
    // identical-code-folding may merge the two symbols and the pointer
231
    // inequality assertion below would compare equal addresses.
232
    extern "C" fn alt_layout_callback(_: RefAny, _: LayoutCallbackInfo) -> Dom {
233
        ALT_LAYOUT_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
234
        Dom::create_body()
235
    }
236

            
237
    #[test]
238
    fn default_layout_callback_returns_body_and_does_not_panic() {
239
        let fx = Fixture::new();
240
        let rd = fx.ref_data();
241
        let info = LayoutCallbackInfo::new(&rd, win(0.0, 0.0, 0), WindowTheme::DarkMode);
242

            
243
        // extreme arg: zero-sized window, zero DPI, empty caches
244
        let dom = default_layout_callback(RefAny::new(0u32), info);
245
        assert_eq!(dom, Dom::create_body());
246
    }
247

            
248
    #[test]
249
    fn layout_callback_create_stores_the_given_fn_and_null_ctx() {
250
        let from_default = LayoutCallback::create(default_layout_callback as LayoutCallbackType);
251
        assert!(
252
            from_default.ctx.is_none(),
253
            "native-Rust create() must leave the FFI ctx empty"
254
        );
255
        assert_eq!(from_default, LayoutCallback::default());
256

            
257
        // create() must actually store its argument, not silently fall back
258
        // to the default callback.
259
        let from_alt = LayoutCallback::create(alt_layout_callback as LayoutCallbackType);
260
        assert!(from_alt.ctx.is_none());
261
        assert_ne!(
262
            from_alt, from_default,
263
            "create() ignored its argument (or the two fns were ICF-folded)"
264
        );
265

            
266
        // the stored pointer is callable and is the one we passed in
267
        let fx = Fixture::new();
268
        let rd = fx.ref_data();
269
        let before = ALT_LAYOUT_CALLS.load(AtomicOrdering::SeqCst);
270
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
271
        let _ = (from_alt.cb)(RefAny::new(()), info);
272
        assert_eq!(ALT_LAYOUT_CALLS.load(AtomicOrdering::SeqCst), before + 1);
273
    }
274

            
275
    // ---- VirtualViewCallback ------------------------------------------------
276

            
277
    extern "C" fn vv_keep_current_cb(
278
        _: RefAny,
279
        info: VirtualViewCallbackInfo,
280
    ) -> VirtualViewReturn {
281
        VirtualViewReturn::keep_current(info.materialized, info.virtual_rect)
282
    }
283

            
284
    #[test]
285
    fn virtual_view_callback_create_round_trips_through_the_fn_ptr() {
286
        let cb = VirtualViewCallback::create(vv_keep_current_cb as VirtualViewCallbackType);
287
        assert!(cb.ctx.is_none());
288

            
289
        let fonts = FcFontCache::default();
290
        let images = ImageCache::default();
291
        let info = vv_info(&fonts, &images, bounds_1x1());
292

            
293
        let ret = (cb.cb)(RefAny::new(0u8), info);
294
        assert!(ret.dom.is_none());
295
        assert_eq!(ret.materialized.size, LogicalSize::new(100.0, 200.0));
296
        assert_eq!(ret.materialized.origin, LogicalPosition::new(1.0, 2.0));
297
        assert_eq!(ret.virtual_rect.size, LogicalSize::new(1000.0, 2000.0));
298
        assert_eq!(ret.virtual_rect.origin, LogicalPosition::zero());
299
    }
300

            
301
    // ---- VirtualViewCallbackInfo -------------------------------------------
302

            
303
    #[test]
304
    fn virtual_view_callback_info_new_holds_its_fields() {
305
        let fonts = FcFontCache::default();
306
        let images = ImageCache::default();
307
        let bounds =
308
            HidpiAdjustedBounds::from_bounds(LayoutSize::new(800, 600), DpiScaleFactor::new(2.0));
309
        let info = vv_info(&fonts, &images, bounds);
310

            
311
        assert_eq!(info.reason, VirtualViewCallbackReason::InitialRender);
312
        assert_eq!(info.window_theme, WindowTheme::LightMode);
313
        assert_eq!(
314
            info.get_bounds().get_logical_size(),
315
            LogicalSize::new(800.0, 600.0)
316
        );
317
        assert_eq!(
318
            info.get_bounds().get_hidpi_factor(),
319
            DpiScaleFactor::new(2.0)
320
        );
321
        assert_eq!(info.materialized.size, LogicalSize::new(100.0, 200.0));
322

            
323
        // the raw pointers must alias the borrows we handed in
324
        assert!(core::ptr::eq(info.internal_get_system_fonts(), &fonts));
325
        assert!(core::ptr::eq(info.internal_get_image_cache(), &images));
326

            
327
        // FFI ctx starts empty and the measure hook starts absent
328
        assert!(info.get_ctx().is_none());
329
        assert_eq!(
330
            info.measure_dom(Dom::create_body(), LogicalSize::new(10.0, 10.0)),
331
            LogicalSize::zero()
332
        );
333

            
334
        // clone must not disturb any of that
335
        let cloned = info;
336
        assert_eq!(cloned.reason, info.reason);
337
        assert!(core::ptr::eq(cloned.internal_get_system_fonts(), &fonts));
338
        assert!(cloned.get_ctx().is_none());
339
    }
340

            
341
    #[test]
342
    fn virtual_view_callback_info_new_survives_nan_and_infinite_geometry() {
343
        let fonts = FcFontCache::default();
344
        let images = ImageCache::default();
345
        let info = VirtualViewCallbackInfo::new(
346
            VirtualViewCallbackReason::EdgeScrolled(EdgeType::Bottom),
347
            &fonts,
348
            &images,
349
            WindowTheme::DarkMode,
350
            crate::window::WindowFrame::Normal,
351
            HidpiAdjustedBounds::from_bounds(
352
                LayoutSize::new(isize::MAX, isize::MIN),
353
                DpiScaleFactor::new(f32::NAN),
354
            ),
355
            LogicalRect::new(
356
                LogicalPosition::new(f32::NEG_INFINITY, f32::MAX),
357
                LogicalSize::new(f32::NAN, f32::INFINITY),
358
            ),
359
            LogicalRect::new(
360
                LogicalPosition::new(-0.0, f32::EPSILON),
361
                LogicalSize::new(f32::MIN, 0.0),
362
            ),
363
            LogicalPosition::new(-0.0, f32::EPSILON),
364
        );
365

            
366
        // extreme values are stored verbatim, not silently clamped
367
        assert!(info.materialized.size.width.is_nan());
368
        assert!(info.materialized.size.height.is_infinite());
369
        assert!(
370
            info.materialized.origin.x.is_infinite()
371
                && info.materialized.origin.x.is_sign_negative()
372
        );
373
        assert_eq!(info.virtual_rect.size.width, f32::MIN);
374
        assert_eq!(
375
            info.reason,
376
            VirtualViewCallbackReason::EdgeScrolled(EdgeType::Bottom)
377
        );
378

            
379
        // and none of the getters panic on that instance
380
        assert!(info.get_ctx().is_none());
381
        assert!(info.get_bounds().get_logical_size().width > 0.0);
382
    }
383

            
384
    #[test]
385
    fn virtual_view_callback_info_get_ctx_clones_without_double_free() {
386
        let fonts = FcFontCache::default();
387
        let images = ImageCache::default();
388
        let mut info = vv_info(&fonts, &images, bounds_1x1());
389

            
390
        // null callable_ptr -> None (the native-Rust path)
391
        assert!(info.get_ctx().is_none());
392

            
393
        let callable = OptionRefAny::Some(RefAny::new(0xDEAD_BEEF_u32));
394
        info.set_callable_ptr(&callable);
395

            
396
        // repeated get_ctx() must hand out independent clones; dropping them
397
        // all must not corrupt the original RefAny's refcount.
398
        for _ in 0..64 {
399
            let got = info.get_ctx();
400
            assert!(got.is_some());
401
            drop(got);
402
        }
403

            
404
        let mut got = info.get_ctx();
405
        match got {
406
            OptionRefAny::Some(ref mut r) => {
407
                let inner = r.downcast_ref::<u32>().expect("ctx should hold a u32");
408
                assert_eq!(*inner, 0xDEAD_BEEF_u32);
409
            }
410
            OptionRefAny::None => panic!("callable_ptr was set, get_ctx() returned None"),
411
        }
412
        drop(got);
413

            
414
        // the original is still alive and intact after all those clones dropped
415
        let mut orig = callable;
416
        match orig {
417
            OptionRefAny::Some(ref mut r) => {
418
                assert_eq!(*r.downcast_ref::<u32>().unwrap(), 0xDEAD_BEEF_u32);
419
            }
420
            OptionRefAny::None => panic!("original callable was consumed"),
421
        }
422
    }
423

            
424
    // ---- measure_dom --------------------------------------------------------
425

            
426
    static MEASURE_CALLS: AtomicUsize = AtomicUsize::new(0);
427
    /// The `MeasureDomMode` the trampoline saw last (0 = Extent, 1 = ShrinkToFit).
428
    static LAST_MEASURE_MODE: AtomicUsize = AtomicUsize::new(usize::MAX);
429

            
430
    /// Test trampoline. Per the `MeasureDomFn` contract the `Dom` is passed by
431
    /// pointer and **consumed** (moved out) here.
432
    extern "C" fn test_measure_dom_fn(
433
        ctx: *mut c_void,
434
        dom: *mut Dom,
435
        available: LogicalSize,
436
        mode: MeasureDomMode,
437
    ) -> LogicalSize {
438
        MEASURE_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
439
        LAST_MEASURE_MODE.store(
440
            match mode {
441
                MeasureDomMode::Extent => 0,
442
                MeasureDomMode::ShrinkToFit => 1,
443
            },
444
            AtomicOrdering::SeqCst,
445
        );
446
        // SAFETY: `measure_dom` always passes a valid, owned-but-ManuallyDrop
447
        // Dom; taking it by value here is exactly the documented contract.
448
        let dom = unsafe { core::ptr::read(dom) };
449
        drop(dom);
450
        if !ctx.is_null() {
451
            // SAFETY: the only caller below passes a `&mut u32`.
452
            unsafe {
453
                *ctx.cast::<u32>() = 0xABCD;
454
            }
455
        }
456
        LogicalSize::new(available.width * 2.0, available.height / 2.0)
457
    }
458

            
459
    #[test]
460
    fn measure_dom_without_hook_returns_zero_for_every_input() {
461
        let fonts = FcFontCache::default();
462
        let images = ImageCache::default();
463
        let info = vv_info(&fonts, &images, bounds_1x1());
464

            
465
        // zero / negative / NaN / infinite / huge available sizes must all take
466
        // the null-hook early-out without panicking (and must drop the Dom).
467
        for available in [
468
            LogicalSize::zero(),
469
            LogicalSize::new(-1.0, -1.0),
470
            LogicalSize::new(f32::NAN, f32::NAN),
471
            LogicalSize::new(f32::INFINITY, f32::NEG_INFINITY),
472
            LogicalSize::new(f32::MAX, f32::MIN),
473
            LogicalSize::new(1.0, 1_000_000.0),
474
        ] {
475
            assert_eq!(
476
                info.measure_dom(Dom::create_body(), available),
477
                LogicalSize::zero()
478
            );
479
        }
480
    }
481

            
482
    #[test]
483
    fn measure_dom_with_hook_forwards_ctx_and_available_and_consumes_the_dom() {
484
        let fonts = FcFontCache::default();
485
        let images = ImageCache::default();
486
        let mut info = vv_info(&fonts, &images, bounds_1x1());
487

            
488
        let mut ctx_val: u32 = 0;
489
        info.set_measure_dom_fn(
490
            test_measure_dom_fn,
491
            core::ptr::from_mut(&mut ctx_val).cast::<c_void>(),
492
        );
493

            
494
        // NOTE: `>` not `== before + 1` - other tests share this static and
495
        // run in parallel, so only monotonicity is safe to assert here.
496
        let before = MEASURE_CALLS.load(AtomicOrdering::SeqCst);
497
        let out = info.measure_dom(Dom::create_body(), LogicalSize::new(100.0, 40.0));
498

            
499
        assert!(MEASURE_CALLS.load(AtomicOrdering::SeqCst) > before);
500
        assert_eq!(out, LogicalSize::new(200.0, 20.0));
501
        assert_eq!(ctx_val, 0xABCD, "measure ctx pointer was not forwarded");
502

            
503
        // the documented virtual-scroll sizing idiom: measure at a huge height
504
        let natural = info.measure_dom(Dom::create_body(), LogicalSize::new(320.0, 1_000_000.0));
505
        assert_eq!(natural, LogicalSize::new(640.0, 500_000.0));
506

            
507
        // NaN / infinite constraints reach the hook unmodified and come back
508
        // as NaN/inf rather than panicking or being clamped
509
        let nan = info.measure_dom(Dom::create_body(), LogicalSize::new(f32::NAN, 4.0));
510
        assert!(nan.width.is_nan());
511
        assert_eq!(nan.height, 2.0);
512

            
513
        let inf = info.measure_dom(Dom::create_body(), LogicalSize::new(f32::INFINITY, 4.0));
514
        assert!(inf.width.is_infinite());
515
    }
516

            
517
    #[test]
518
    fn measure_dom_shrink_to_fit_reaches_the_same_hook_in_its_own_mode() {
519
        let fonts = FcFontCache::default();
520
        let images = ImageCache::default();
521
        let mut info = vv_info(&fonts, &images, bounds_1x1());
522

            
523
        // No hook: zero, like `measure_dom`.
524
        assert_eq!(
525
            info.measure_dom_shrink_to_fit(Dom::create_body(), LogicalSize::new(50.0, 50.0)),
526
            LogicalSize::zero()
527
        );
528

            
529
        info.set_measure_dom_fn(test_measure_dom_fn, core::ptr::null_mut());
530
        // The two entry points share one hook and differ only in the mode
531
        // they pass; a mode-blind trampoline would answer both the same way.
532
        // (Other tests share the statics, so each assertion reads its own
533
        // store back immediately.)
534
        let fit = info.measure_dom_shrink_to_fit(Dom::create_body(), LogicalSize::new(3.0, 8.0));
535
        assert_eq!(fit, LogicalSize::new(6.0, 4.0));
536
        assert_eq!(LAST_MEASURE_MODE.load(AtomicOrdering::SeqCst), 1);
537
        let extent = info.measure_dom(Dom::create_body(), LogicalSize::new(3.0, 8.0));
538
        assert_eq!(extent, fit);
539
        assert_eq!(LAST_MEASURE_MODE.load(AtomicOrdering::SeqCst), 0);
540
    }
541

            
542
    #[test]
543
    fn measure_dom_hook_can_be_replaced_and_last_writer_wins() {
544
        let fonts = FcFontCache::default();
545
        let images = ImageCache::default();
546
        let mut info = vv_info(&fonts, &images, bounds_1x1());
547

            
548
        info.set_measure_dom_fn(test_measure_dom_fn, core::ptr::null_mut());
549
        // null ctx must be tolerated by the trampoline contract
550
        let first = info.measure_dom(Dom::create_body(), LogicalSize::new(2.0, 8.0));
551
        assert_eq!(first, LogicalSize::new(4.0, 4.0));
552

            
553
        let mut ctx_val: u32 = 0;
554
        info.set_measure_dom_fn(
555
            test_measure_dom_fn,
556
            core::ptr::from_mut(&mut ctx_val).cast::<c_void>(),
557
        );
558
        let second = info.measure_dom(Dom::create_body(), LogicalSize::new(2.0, 8.0));
559
        assert_eq!(second, first);
560
        assert_eq!(ctx_val, 0xABCD);
561
    }
562

            
563
    // ---- VirtualViewReturn --------------------------------------------------
564

            
565
    #[test]
566
    fn virtual_view_return_with_dom_and_keep_current_hold_their_fields() {
567
        // the window the callback rendered: 30px tall, sitting 300px down the document
568
        let mat = LogicalRect::new(
569
            LogicalPosition::new(0.0, 300.0),
570
            LogicalSize::new(600.0, 30.0),
571
        );
572
        // the whole document estimate
573
        let virt = LogicalRect::new(LogicalPosition::zero(), LogicalSize::new(600.0, 30_000.0));
574

            
575
        let with = VirtualViewReturn::with_dom(Dom::create_body(), mat, virt);
576
        assert!(with.dom.is_some(), "with_dom must produce OptionDom::Some");
577
        assert_eq!(with.materialized, mat);
578
        assert_eq!(with.virtual_rect, virt);
579
        assert_eq!(with.dom, OptionDom::Some(Dom::create_body()));
580

            
581
        let keep = VirtualViewReturn::keep_current(mat, virt);
582
        assert!(
583
            keep.dom.is_none(),
584
            "keep_current must produce OptionDom::None"
585
        );
586
        assert_eq!(keep.materialized, mat);
587
        assert_eq!(keep.virtual_rect, virt);
588

            
589
        // the two constructors differ *only* in the dom field
590
        assert_ne!(with, keep);
591

            
592
        // default is the "keep everything, render nothing" zero value
593
        let d = VirtualViewReturn::default();
594
        assert_eq!(
595
            d,
596
            VirtualViewReturn::keep_current(LogicalRect::zero(), LogicalRect::zero())
597
        );
598
    }
599

            
600
    #[test]
601
    fn virtual_view_return_keep_current_passes_extreme_values_through_unclamped() {
602
        // zero
603
        let z = VirtualViewReturn::keep_current(LogicalRect::zero(), LogicalRect::zero());
604
        assert_eq!(z.materialized.size, LogicalSize::zero());
605
        assert_eq!(z.virtual_rect.size, LogicalSize::zero());
606

            
607
        // negative + f32 limits: stored verbatim (no saturation, no panic)
608
        let n = VirtualViewReturn::keep_current(
609
            LogicalRect::new(
610
                LogicalPosition::new(f32::MIN, f32::MAX),
611
                LogicalSize::new(-1.0, -0.0),
612
            ),
613
            LogicalRect::new(
614
                LogicalPosition::new(-f32::EPSILON, 0.0),
615
                LogicalSize::new(f32::MAX, f32::MIN_POSITIVE),
616
            ),
617
        );
618
        assert_eq!(n.materialized.size.width, -1.0);
619
        assert_eq!(n.materialized.origin.x, f32::MIN);
620
        assert_eq!(n.materialized.origin.y, f32::MAX);
621
        assert_eq!(n.virtual_rect.size.width, f32::MAX);
622
        assert_eq!(n.virtual_rect.size.height, f32::MIN_POSITIVE);
623

            
624
        // NaN / inf: stored verbatim; NaN makes the struct unequal to itself
625
        // under PartialEq, so probe the fields directly.
626
        let x = VirtualViewReturn::keep_current(
627
            LogicalRect::new(
628
                LogicalPosition::new(f32::NEG_INFINITY, f32::NAN),
629
                LogicalSize::new(f32::NAN, f32::INFINITY),
630
            ),
631
            LogicalRect::new(
632
                LogicalPosition::new(f32::NAN, f32::NEG_INFINITY),
633
                LogicalSize::new(f32::INFINITY, f32::NAN),
634
            ),
635
        );
636
        assert!(x.materialized.size.width.is_nan());
637
        assert!(
638
            x.materialized.size.height.is_infinite()
639
                && x.materialized.size.height.is_sign_positive()
640
        );
641
        assert!(
642
            x.materialized.origin.x.is_infinite() && x.materialized.origin.x.is_sign_negative()
643
        );
644
        assert!(x.materialized.origin.y.is_nan());
645
        assert!(x.virtual_rect.origin.y.is_infinite());
646
        assert!(x.dom.is_none());
647
    }
648

            
649
    // ---- TimerCallbackReturn ------------------------------------------------
650

            
651
    #[test]
652
    fn timer_callback_return_constructors_match_their_documented_flags() {
653
        let c = TimerCallbackReturn::continue_unchanged();
654
        assert_eq!(c.should_update, Update::DoNothing);
655
        assert_eq!(c.should_terminate, TerminateTimer::Continue);
656

            
657
        let cr = TimerCallbackReturn::continue_and_refresh_dom();
658
        assert_eq!(cr.should_update, Update::RefreshDom);
659
        assert_eq!(cr.should_terminate, TerminateTimer::Continue);
660

            
661
        let t = TimerCallbackReturn::terminate_unchanged();
662
        assert_eq!(t.should_update, Update::DoNothing);
663
        assert_eq!(t.should_terminate, TerminateTimer::Terminate);
664

            
665
        let tr = TimerCallbackReturn::terminate_and_refresh_dom();
666
        assert_eq!(tr.should_update, Update::RefreshDom);
667
        assert_eq!(tr.should_terminate, TerminateTimer::Terminate);
668

            
669
        // all four are distinct - no constructor is a copy-paste of another
670
        let all = [c, cr, t, tr];
671
        for (i, a) in all.iter().enumerate() {
672
            for (j, b) in all.iter().enumerate() {
673
                assert_eq!(i == j, a == b, "constructors {i} and {j} collide");
674
            }
675
        }
676

            
677
        // Default is documented as "continue, no update"
678
        assert_eq!(TimerCallbackReturn::default(), c);
679
    }
680

            
681
    #[test]
682
    fn timer_callback_return_create_round_trips_every_flag_combination() {
683
        for u in ALL_UPDATES {
684
            for t in [TerminateTimer::Continue, TerminateTimer::Terminate] {
685
                let r = TimerCallbackReturn::create(u, t);
686
                assert_eq!(r.should_update, u);
687
                assert_eq!(r.should_terminate, t);
688
            }
689
        }
690

            
691
        // the named constructors agree with the generic one
692
        assert_eq!(
693
            TimerCallbackReturn::create(Update::DoNothing, TerminateTimer::Continue),
694
            TimerCallbackReturn::continue_unchanged()
695
        );
696
        assert_eq!(
697
            TimerCallbackReturn::create(Update::RefreshDom, TerminateTimer::Terminate),
698
            TimerCallbackReturn::terminate_and_refresh_dom()
699
        );
700

            
701
        // RefreshDomAllWindows is reachable through create() even though no
702
        // named constructor exposes it
703
        let all_windows =
704
            TimerCallbackReturn::create(Update::RefreshDomAllWindows, TerminateTimer::Terminate);
705
        assert_eq!(all_windows.should_update, Update::RefreshDomAllWindows);
706
    }
707

            
708
    // ---- LayoutCallbackInfo: construction + getters --------------------------
709

            
710
    #[test]
711
    fn layout_callback_info_new_defaults_to_initial_reason_and_holds_fields() {
712
        let fx = Fixture::new();
713
        let rd = fx.ref_data();
714
        let info = LayoutCallbackInfo::new(&rd, win(1280.0, 720.0, 192), WindowTheme::DarkMode);
715

            
716
        assert_eq!(info.relayout_reason(), RelayoutReason::Initial);
717
        assert_eq!(info.theme, WindowTheme::DarkMode);
718
        assert_eq!(info.get_window_width(), 1280.0);
719
        assert_eq!(info.get_window_height(), 720.0);
720
        assert_eq!(info.get_dpi_factor(), 2.0);
721
        assert!(info.get_ctx().is_none());
722

            
723
        // the borrowed resources are reachable through the laundered pointer
724
        assert!(core::ptr::eq(info.internal_get_image_cache(), &fx.images));
725
        assert!(core::ptr::eq(info.internal_get_system_fonts(), &fx.fonts));
726
        assert!(core::ptr::eq(info.internal_get_gl_context(), &fx.gl));
727
        assert!(info.get_gl_context().is_none());
728
    }
729

            
730
    #[test]
731
    fn layout_callback_info_new_with_reason_round_trips_every_reason() {
732
        let fx = Fixture::new();
733
        let rd = fx.ref_data();
734

            
735
        for reason in [
736
            RelayoutReason::Initial,
737
            RelayoutReason::RefreshDom,
738
            RelayoutReason::Resize,
739
            RelayoutReason::ThemeChange,
740
            RelayoutReason::RouteChange,
741
            RelayoutReason::Other,
742
        ] {
743
            let info = LayoutCallbackInfo::new_with_reason(
744
                &rd,
745
                WindowSize::default(),
746
                WindowTheme::LightMode,
747
                reason,
748
            );
749
            assert_eq!(info.relayout_reason(), reason);
750
            // clone must preserve it
751
            assert_eq!(info.clone().relayout_reason(), reason);
752
        }
753

            
754
        assert_eq!(RelayoutReason::default(), RelayoutReason::Initial);
755
    }
756

            
757
    #[test]
758
    fn layout_callback_info_get_system_style_shares_the_arc() {
759
        let fx = Fixture::new();
760
        let rd = fx.ref_data();
761
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
762

            
763
        let a = info.get_system_style();
764
        let b = info.get_system_style();
765
        // it is a clone of the *same* Arc, not a fresh deep copy
766
        assert!(Arc::ptr_eq(&a, &b));
767
        assert!(Arc::ptr_eq(&a, &fx.style));
768

            
769
        // repeated cloning must not leak/underflow the refcount
770
        let before = Arc::strong_count(&fx.style);
771
        for _ in 0..128 {
772
            drop(info.get_system_style());
773
        }
774
        assert_eq!(Arc::strong_count(&fx.style), before);
775
    }
776

            
777
    #[test]
778
    fn layout_callback_info_get_ctx_is_none_until_set_then_clones_safely() {
779
        let fx = Fixture::new();
780
        let rd = fx.ref_data();
781
        let mut info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
782

            
783
        assert!(info.get_ctx().is_none(), "native path must have a null ctx");
784

            
785
        let callable = OptionRefAny::Some(RefAny::new(7u64));
786
        info.set_callable_ptr(&callable);
787

            
788
        for _ in 0..64 {
789
            assert!(info.get_ctx().is_some());
790
        }
791

            
792
        let mut got = info.get_ctx();
793
        match got {
794
            OptionRefAny::Some(ref mut r) => assert_eq!(*r.downcast_ref::<u64>().unwrap(), 7),
795
            OptionRefAny::None => panic!("get_ctx() lost the callable"),
796
        }
797
        drop(got);
798

            
799
        // a clone of the info keeps pointing at the same callable
800
        let cloned = info;
801
        assert!(cloned.get_ctx().is_some());
802
    }
803

            
804
    #[test]
805
    fn layout_callback_info_get_system_fonts_is_empty_for_an_empty_cache() {
806
        let fx = Fixture::new();
807
        let rd = fx.ref_data();
808
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
809

            
810
        // an empty FcFontCache must yield an empty list, not panic
811
        let fonts: Vec<AzStringPair> = info.get_system_fonts();
812
        assert!(fonts.is_empty());
813
        // and be stable across calls
814
        assert_eq!(info.get_system_fonts().len(), fonts.len());
815
    }
816

            
817
    // ---- LayoutCallbackInfo::get_image --------------------------------------
818

            
819
    #[test]
820
    fn get_image_returns_none_for_missing_empty_and_hostile_ids() {
821
        let fx = Fixture::new();
822
        let rd = fx.ref_data();
823
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
824

            
825
        assert!(info.get_image(&s("")).is_none());
826
        assert!(info.get_image(&s("   ")).is_none());
827
        assert!(info.get_image(&s("nope")).is_none());
828
        assert!(info.get_image(&s("\u{1F600}\u{0301}")).is_none());
829
        assert!(info.get_image(&s("\0")).is_none());
830
        assert!(info.get_image(&s(&"x".repeat(100_000))).is_none());
831
    }
832

            
833
    #[test]
834
    fn get_image_finds_an_inserted_id_and_is_exact_match() {
835
        let mut fx = Fixture::new();
836
        fx.images.add_css_image_id(
837
            s("logo"),
838
            ImageRef::null_image(2, 2, RawImageFormat::RGBA8, Vec::new()),
839
        );
840
        let rd = fx.ref_data();
841
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
842

            
843
        assert!(info.get_image(&s("logo")).is_some(), "positive control");
844

            
845
        // lookup is exact: no trimming, no case folding, no prefix matching
846
        assert!(info.get_image(&s("Logo")).is_none());
847
        assert!(info.get_image(&s(" logo")).is_none());
848
        assert!(info.get_image(&s("logo ")).is_none());
849
        assert!(info.get_image(&s("log")).is_none());
850
        assert!(info.get_image(&s("logos")).is_none());
851
    }
852

            
853
    // ---- LayoutCallbackInfo::get_active_route / get_route_param -------------
854

            
855
    #[test]
856
    fn get_route_param_returns_none_when_no_route_is_active() {
857
        let fx = Fixture::new();
858
        let rd = fx.ref_data();
859
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
860

            
861
        assert!(info.get_active_route().is_none());
862

            
863
        // every hostile key must take the `?` early-out, never panic
864
        for key in ["", " ", "\t\n", "id", "\u{1F600}", "\0", "../../etc/passwd"] {
865
            assert!(info.get_route_param(key).is_none(), "key {key:?}");
866
        }
867
    }
868

            
869
    #[test]
870
    fn get_route_param_valid_minimal_and_unicode_positive_controls() {
871
        let fx = Fixture::with_route(user_route());
872
        let rd = fx.ref_data();
873
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
874

            
875
        let route = info.get_active_route().expect("route was configured");
876
        assert_eq!(route.pattern.as_str(), "/user/:id");
877

            
878
        // positive control
879
        assert_eq!(info.get_route_param("id").map(AzString::as_str), Some("42"));
880
        // multibyte key round-trips
881
        assert_eq!(
882
            info.get_route_param("\u{1F600}").map(AzString::as_str),
883
            Some("emoji")
884
        );
885
    }
886

            
887
    #[test]
888
    fn get_route_param_rejects_malformed_keys_without_trimming_or_folding() {
889
        let fx = Fixture::with_route(user_route());
890
        let rd = fx.ref_data();
891
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
892

            
893
        // empty / whitespace-only
894
        assert!(info.get_route_param("").is_none());
895
        assert!(info.get_route_param("   ").is_none());
896
        assert!(info.get_route_param("\t\n").is_none());
897

            
898
        // leading/trailing junk is NOT trimmed, and lookup is case-sensitive
899
        assert!(info.get_route_param(" id").is_none());
900
        assert!(info.get_route_param("id ").is_none());
901
        assert!(info.get_route_param("  id  ").is_none());
902
        assert!(info.get_route_param("id;garbage").is_none());
903
        assert!(info.get_route_param("ID").is_none());
904
        assert!(info.get_route_param("Id").is_none());
905

            
906
        // no prefix / substring matching
907
        assert!(info.get_route_param("i").is_none());
908
        assert!(info.get_route_param("idd").is_none());
909

            
910
        // garbage bytes, NUL, control chars
911
        assert!(info.get_route_param("\0").is_none());
912
        assert!(info.get_route_param("id\0").is_none());
913
        assert!(info.get_route_param("\u{7F}\u{1}\u{2}").is_none());
914

            
915
        // boundary numeric strings
916
        for key in [
917
            "0",
918
            "-0",
919
            "9223372036854775807",
920
            "-9223372036854775808",
921
            "18446744073709551616",
922
            "NaN",
923
            "inf",
924
            "-inf",
925
            "1e400",
926
            "0.0000000000000000001",
927
        ] {
928
            assert!(info.get_route_param(key).is_none(), "key {key:?}");
929
        }
930

            
931
        // non-ASCII that is *not* a param, incl. combining marks
932
        assert!(info.get_route_param("i\u{0301}d").is_none());
933
        assert!(info.get_route_param("\u{1F600}\u{1F600}").is_none());
934
    }
935

            
936
    #[test]
937
    fn get_route_param_handles_pathological_key_sizes_and_nesting() {
938
        let fx = Fixture::with_route(user_route());
939
        let rd = fx.ref_data();
940
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
941

            
942
        // extremely long key: must return None quickly, not hang or overflow
943
        let huge = "x".repeat(1_000_000);
944
        assert!(info.get_route_param(&huge).is_none());
945

            
946
        // a long key that *shares a prefix* with a real param
947
        let long_id = alloc::format!("id{}", "0".repeat(1_000_000));
948
        assert!(info.get_route_param(&long_id).is_none());
949

            
950
        // deeply nested brackets: the lookup is a flat scan, so this must not
951
        // recurse or stack-overflow
952
        let nested = "[".repeat(10_000) + &"]".repeat(10_000);
953
        assert!(info.get_route_param(&nested).is_none());
954
    }
955

            
956
    #[test]
957
    fn get_route_param_preserves_huge_and_unicode_values() {
958
        let big = "v".repeat(200_000);
959
        let route = RouteMatch {
960
            pattern: s("/blob/:data"),
961
            params: StringPairVec::from_vec(Vec::from([AzStringPair {
962
                key: s("data"),
963
                value: s(&big),
964
            }])),
965
        };
966
        let fx = Fixture::with_route(route);
967
        let rd = fx.ref_data();
968
        let info = LayoutCallbackInfo::new(&rd, WindowSize::default(), WindowTheme::LightMode);
969

            
970
        let got = info.get_route_param("data").expect("param exists");
971
        assert_eq!(got.as_str().len(), 200_000);
972
    }
973

            
974
    // ---- LayoutCallbackInfo: responsive predicates ---------------------------
975

            
976
    #[test]
977
    fn window_predicates_obey_trichotomy_and_the_between_identity() {
978
        let fx = Fixture::new();
979
        let rd = fx.ref_data();
980

            
981
        let probes = [
982
            0.0f32,
983
            -0.0,
984
            1.0,
985
            -1.0,
986
            640.0,
987
            f32::MIN,
988
            f32::MAX,
989
            f32::MIN_POSITIVE,
990
            f32::INFINITY,
991
            f32::NEG_INFINITY,
992
        ];
993

            
994
        for &dim in &probes {
995
            let info = LayoutCallbackInfo::new(&rd, win(dim, dim, 96), WindowTheme::LightMode);
996

            
997
            for &px in &probes {
998
                let lt = info.window_width_less_than(px);
999
                let gt = info.window_width_greater_than(px);
                let eq = info.get_window_width() == px;
                // exactly one of <, >, == holds for non-NaN operands
                assert_eq!(
                    u8::from(lt) + u8::from(gt) + u8::from(eq),
                    1,
                    "trichotomy broken for width {dim} vs {px}"
                );
                // height predicates mirror the width ones on a square window
                assert_eq!(info.window_height_less_than(px), lt);
                assert_eq!(info.window_height_greater_than(px), gt);
                for &px2 in &probes {
                    // between(a, b) == !(w < a) && !(w > b)
                    assert_eq!(
                        info.window_width_between(px, px2),
                        !info.window_width_less_than(px) && !info.window_width_greater_than(px2),
                        "between identity broken for width {dim} in [{px}, {px2}]"
                    );
                    assert_eq!(
                        info.window_height_between(px, px2),
                        info.window_width_between(px, px2)
                    );
                }
            }
        }
    }
    #[test]
    fn window_predicates_with_inverted_and_degenerate_ranges() {
        let fx = Fixture::new();
        let rd = fx.ref_data();
        let info = LayoutCallbackInfo::new(&rd, win(640.0, 480.0, 96), WindowTheme::LightMode);
        // inverted range is always empty
        assert!(!info.window_width_between(1000.0, 100.0));
        assert!(!info.window_height_between(1000.0, 100.0));
        // degenerate (min == max) range is inclusive on both ends
        assert!(info.window_width_between(640.0, 640.0));
        assert!(info.window_height_between(480.0, 480.0));
        assert!(!info.window_width_between(639.9, 639.95));
        // inclusive boundaries
        assert!(info.window_width_between(640.0, 1000.0));
        assert!(info.window_width_between(0.0, 640.0));
        // strictness at the exact boundary
        assert!(!info.window_width_less_than(640.0));
        assert!(!info.window_width_greater_than(640.0));
        assert!(info.window_width_less_than(640.001));
        assert!(info.window_width_greater_than(639.999));
        // the widest possible range contains a finite width
        assert!(info.window_width_between(f32::NEG_INFINITY, f32::INFINITY));
    }
    #[test]
    fn window_predicates_are_all_false_for_nan_probes() {
        let fx = Fixture::new();
        let rd = fx.ref_data();
        let info = LayoutCallbackInfo::new(&rd, win(640.0, 480.0, 96), WindowTheme::LightMode);
        // every comparison against NaN is false - no panic, no accidental `true`
        assert!(!info.window_width_less_than(f32::NAN));
        assert!(!info.window_width_greater_than(f32::NAN));
        assert!(!info.window_width_between(f32::NAN, f32::NAN));
        assert!(!info.window_width_between(f32::NAN, 10_000.0));
        assert!(!info.window_width_between(0.0, f32::NAN));
        assert!(!info.window_height_less_than(f32::NAN));
        assert!(!info.window_height_greater_than(f32::NAN));
        assert!(!info.window_height_between(f32::NAN, f32::NAN));
        assert!(!info.window_height_between(f32::NAN, 10_000.0));
        assert!(!info.window_height_between(0.0, f32::NAN));
    }
    #[test]
    fn window_predicates_are_all_false_for_a_nan_sized_window() {
        let fx = Fixture::new();
        let rd = fx.ref_data();
        let info =
            LayoutCallbackInfo::new(&rd, win(f32::NAN, f32::NAN, 96), WindowTheme::LightMode);
        assert!(info.get_window_width().is_nan());
        assert!(info.get_window_height().is_nan());
        // a NaN window is neither smaller, larger, nor within any range
        for px in [0.0f32, 640.0, f32::MAX, f32::INFINITY, f32::NEG_INFINITY] {
            assert!(!info.window_width_less_than(px));
            assert!(!info.window_width_greater_than(px));
            assert!(!info.window_height_less_than(px));
            assert!(!info.window_height_greater_than(px));
            assert!(!info.window_width_between(f32::NEG_INFINITY, px));
            assert!(!info.window_height_between(px, f32::INFINITY));
        }
    }
    #[test]
    fn get_dpi_factor_at_zero_and_u32_limits() {
        let fx = Fixture::new();
        let rd = fx.ref_data();
        // 96 DPI is the 1.0 baseline
        let base = LayoutCallbackInfo::new(&rd, win(1.0, 1.0, 96), WindowTheme::LightMode);
        assert_eq!(base.get_dpi_factor(), 1.0);
        let hidpi = LayoutCallbackInfo::new(&rd, win(1.0, 1.0, 192), WindowTheme::LightMode);
        assert_eq!(hidpi.get_dpi_factor(), 2.0);
        // dpi = 0 must not divide-by-zero-panic; it yields 0.0
        let zero = LayoutCallbackInfo::new(&rd, win(1.0, 1.0, 0), WindowTheme::LightMode);
        assert_eq!(zero.get_dpi_factor(), 0.0);
        // u32::MAX must not overflow the f32 cast - it stays finite
        let max = LayoutCallbackInfo::new(&rd, win(1.0, 1.0, u32::MAX), WindowTheme::LightMode);
        let f = max.get_dpi_factor();
        assert!(f.is_finite() && f > 0.0, "dpi factor {f} is not finite");
        assert_eq!(f, (u32::MAX as f32) / 96.0);
        // dpi = 1 rounds to a tiny-but-positive factor rather than 0
        let one = LayoutCallbackInfo::new(&rd, win(1.0, 1.0, 1), WindowTheme::LightMode);
        assert!(one.get_dpi_factor() > 0.0);
    }
    // ---- HidpiAdjustedBounds -------------------------------------------------
    #[test]
    fn hidpi_adjusted_bounds_from_bounds_holds_its_fields() {
        let b =
            HidpiAdjustedBounds::from_bounds(LayoutSize::new(800, 600), DpiScaleFactor::new(1.5));
        assert_eq!(b.get_logical_size(), LogicalSize::new(800.0, 600.0));
        assert_eq!(b.get_hidpi_factor(), DpiScaleFactor::new(1.5));
        assert_eq!(b.logical_size, b.get_logical_size());
        assert_eq!(b.hidpi_factor, b.get_hidpi_factor());
        let p = b.get_physical_size();
        assert_eq!(p.width, 1200);
        assert_eq!(p.height, 900);
    }
    #[test]
    fn hidpi_adjusted_bounds_at_zero() {
        let b = HidpiAdjustedBounds::from_bounds(LayoutSize::new(0, 0), DpiScaleFactor::new(1.0));
        assert_eq!(b.get_logical_size(), LogicalSize::zero());
        let p = b.get_physical_size();
        assert_eq!(p.width, 0);
        assert_eq!(p.height, 0);
        // a zero scale factor collapses any size to 0x0 without panicking
        let z =
            HidpiAdjustedBounds::from_bounds(LayoutSize::new(1920, 1080), DpiScaleFactor::new(0.0));
        let zp = z.get_physical_size();
        assert_eq!(zp.width, 0);
        assert_eq!(zp.height, 0);
    }
    /// `get_physical_size` funnels through `roundf(x) as u32`, which is a
    /// *saturating* float->int cast in Rust: negatives clamp to 0, huge values
    /// clamp to u32::MAX, NaN becomes 0. Pin that down so a future refactor to
    /// an unchecked cast (UB) or a panicking one is caught.
    #[test]
    fn hidpi_adjusted_bounds_physical_size_saturates_on_negative_input() {
        let b =
            HidpiAdjustedBounds::from_bounds(LayoutSize::new(-100, -50), DpiScaleFactor::new(1.0));
        assert_eq!(b.get_logical_size(), LogicalSize::new(-100.0, -50.0));
        let p = b.get_physical_size();
        assert_eq!(
            p.width, 0,
            "negative logical width must clamp to 0, not wrap"
        );
        assert_eq!(
            p.height, 0,
            "negative logical height must clamp to 0, not wrap"
        );
        // negative scale factor on a positive size clamps the same way
        let neg_scale =
            HidpiAdjustedBounds::from_bounds(LayoutSize::new(100, 100), DpiScaleFactor::new(-2.0));
        let np = neg_scale.get_physical_size();
        assert_eq!(np.width, 0);
        assert_eq!(np.height, 0);
    }
    #[test]
    fn hidpi_adjusted_bounds_physical_size_saturates_at_the_upper_limit() {
        // isize::MAX logical px * 1.0 overflows u32 -> must saturate, not wrap
        let b = HidpiAdjustedBounds::from_bounds(
            LayoutSize::new(isize::MAX, isize::MAX),
            DpiScaleFactor::new(1.0),
        );
        let p = b.get_physical_size();
        assert_eq!(p.width, u32::MAX);
        assert_eq!(p.height, u32::MAX);
        // isize::MIN saturates downwards to 0
        let min = HidpiAdjustedBounds::from_bounds(
            LayoutSize::new(isize::MIN, isize::MIN),
            DpiScaleFactor::new(1.0),
        );
        let mp = min.get_physical_size();
        assert_eq!(mp.width, 0);
        assert_eq!(mp.height, 0);
        // a huge scale factor on a modest size also saturates
        let huge_scale = HidpiAdjustedBounds::from_bounds(
            LayoutSize::new(1000, 1000),
            DpiScaleFactor::new(f32::MAX),
        );
        let hp = huge_scale.get_physical_size();
        assert_eq!(hp.width, u32::MAX);
        assert_eq!(hp.height, u32::MAX);
    }
    /// `DpiScaleFactor` stores its f32 in a fixed-point `isize` (x1000), so
    /// NaN quantizes to 0 and +/-inf quantize to the isize limits. Assert the
    /// *observable* consequence rather than a panic.
    #[test]
    fn hidpi_adjusted_bounds_physical_size_with_nan_and_infinite_scale() {
        let nan = HidpiAdjustedBounds::from_bounds(
            LayoutSize::new(100, 100),
            DpiScaleFactor::new(f32::NAN),
        );
        // NaN -> fixed-point 0 -> 0.0 scale -> 0x0 physical
        assert_eq!(nan.get_hidpi_factor().inner.get(), 0.0);
        let np = nan.get_physical_size();
        assert_eq!(np.width, 0);
        assert_eq!(np.height, 0);
        let inf = HidpiAdjustedBounds::from_bounds(
            LayoutSize::new(100, 100),
            DpiScaleFactor::new(f32::INFINITY),
        );
        // +inf -> saturated fixed-point -> huge (but finite) scale
        assert!(inf.get_hidpi_factor().inner.get().is_finite());
        let ip = inf.get_physical_size();
        assert_eq!(ip.width, u32::MAX);
        assert_eq!(ip.height, u32::MAX);
        let neg_inf = HidpiAdjustedBounds::from_bounds(
            LayoutSize::new(100, 100),
            DpiScaleFactor::new(f32::NEG_INFINITY),
        );
        let nip = neg_inf.get_physical_size();
        assert_eq!(nip.width, 0);
        assert_eq!(nip.height, 0);
    }
    #[test]
    fn hidpi_adjusted_bounds_physical_size_rounds_to_nearest() {
        // 0.5px rounds away from zero (libm::roundf), not truncates
        let b = HidpiAdjustedBounds::from_bounds(LayoutSize::new(3, 3), DpiScaleFactor::new(1.5));
        let p = b.get_physical_size();
        assert_eq!(p.width, 5, "3 * 1.5 = 4.5 must round to 5");
        assert_eq!(p.height, 5);
        // idempotent: repeated calls give the same answer
        let p2 = b.get_physical_size();
        assert_eq!(p.width, p2.width);
        assert_eq!(p.height, p2.height);
    }
    // ---- CoreCallbackDataVec -------------------------------------------------
    fn cb_data(cb: usize) -> CoreCallbackData {
        CoreCallbackData {
            event: EventFilter::Hover(HoverEventFilter::MouseOver),
            callback: CoreCallback::from(cb),
            refany: RefAny::new(cb),
        }
    }
    #[test]
    fn core_callback_data_vec_as_container_on_empty_vecs_does_not_panic() {
        // both the const-empty and the heap-empty representation must produce
        // a valid (length-0) container - a null-ptr slice here would be UB
        let empty = CoreCallbackDataVec::new();
        assert_eq!(empty.as_container().len(), 0);
        assert!(empty.as_container().internal.is_empty());
        let from_empty_vec = CoreCallbackDataVec::from_vec(Vec::new());
        assert_eq!(from_empty_vec.as_container().len(), 0);
        let mut mut_empty = CoreCallbackDataVec::from_vec(Vec::new());
        assert!(mut_empty.as_container_mut().internal.is_empty());
    }
    #[test]
    fn core_callback_data_vec_as_container_matches_the_backing_vec() {
        let v = CoreCallbackDataVec::from_vec(Vec::from([cb_data(1), cb_data(2), cb_data(3)]));
        let c = v.as_container();
        assert_eq!(c.len(), 3);
        assert_eq!(c.len(), v.len());
        assert_eq!(c.internal[0].callback.cb, 1);
        assert_eq!(c.internal[2].callback.cb, 3);
        // the container borrows - it does not copy
        assert!(core::ptr::eq(c.internal.as_ptr(), v.as_slice().as_ptr()));
    }
    #[test]
    fn core_callback_data_vec_as_container_mut_writes_through() {
        let mut v = CoreCallbackDataVec::from_vec(Vec::from([cb_data(1), cb_data(2)]));
        {
            let mut c = v.as_container_mut();
            assert_eq!(c.internal.len(), 2);
            c.internal[0].callback.cb = 99;
            c.internal[1].event = EventFilter::Hover(HoverEventFilter::MouseDown);
        }
        // mutations are visible through the immutable container
        let c = v.as_container();
        assert_eq!(c.internal[0].callback.cb, 99);
        assert_eq!(
            c.internal[1].event,
            EventFilter::Hover(HoverEventFilter::MouseDown)
        );
        assert_eq!(c.len(), 2);
    }
}
/// Tests for the recorded window-size queries — the responsive helpers
/// (`window_width_less_than` & co.) every `layout()` should branch on, and the
/// mechanism that lets a resize skip `layout()` when no recorded answer flips.
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod size_query_tests {
    use super::*;
    use crate::geom::LogicalSize;
5
    fn win(width: f32, height: f32) -> WindowSize {
5
        WindowSize {
5
            dimensions: LogicalSize::new(width, height),
5
            ..WindowSize::default()
5
        }
5
    }
5
    fn info_at(rd: &LayoutCallbackInfoRefData<'_>, w: f32, h: f32) -> LayoutCallbackInfo {
5
        LayoutCallbackInfo::new(rd, win(w, h), WindowTheme::LightMode)
5
    }
12
    fn drain() -> (alloc::vec::Vec<SizeQuery>, bool) {
12
        take_recorded_size_queries()
12
    }
    /// Build the minimal ref-data a `LayoutCallbackInfo` needs. The queries
    /// only read `window_size`, so everything else can be empty.
    struct Rd {
        image_cache: crate::resources::ImageCache,
        gl: crate::gl::OptionGlContextPtr,
        fonts: rust_fontconfig::FcFontCache,
        style: alloc::sync::Arc<azul_css::system::SystemStyle>,
    }
    impl Rd {
5
        fn new() -> Self {
5
            Self {
5
                image_cache: crate::resources::ImageCache::default(),
5
                gl: crate::gl::OptionGlContextPtr::None,
5
                fonts: rust_fontconfig::FcFontCache::default(),
5
                style: alloc::sync::Arc::new(azul_css::system::SystemStyle::default()),
5
            }
5
        }
5
        fn ref_data(&self) -> LayoutCallbackInfoRefData<'_> {
5
            LayoutCallbackInfoRefData {
5
                image_cache: &self.image_cache,
5
                gl_context: &self.gl,
5
                system_fonts: &self.fonts,
5
                system_style: self.style.clone(),
5
                active_route: None,
5
                monitors: crate::window::MonitorVec::from_const_slice(&[]),
5
                safe_area: azul_css::system::SafeAreaInsets::default(),
5
            }
5
        }
    }
    #[test]
1
    fn every_responsive_helper_records_with_its_exact_operator() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = drain();
1
        let info = info_at(&rd, 800.0, 600.0);
1
        assert!(
1
            !info.window_width_less_than(800.0),
            "strict <: boundary is false"
        );
1
        assert!(
1
            !info.window_width_greater_than(800.0),
            "strict >: boundary is false"
        );
1
        assert!(
1
            info.window_width_between(800.0, 1024.0),
            "between is inclusive"
        );
1
        assert!(info.window_height_less_than(601.0));
1
        assert!(!info.window_height_greater_than(600.0));
1
        assert!(info.window_height_between(0.0, 600.0));
1
        let (recorded, overflowed) = drain();
        // between records BOTH of its bounds, so 4 single-bound calls + 2
        // between calls = 8 queries.
1
        assert_eq!(
1
            recorded.len(),
            8,
            "every call recorded; between records two bounds"
        );
1
        assert!(!overflowed);
1
        assert_eq!(recorded[0].op, SizeQueryOp::LessThan);
1
        assert_eq!(recorded[1].op, SizeQueryOp::GreaterThan);
1
        assert_eq!(recorded[2].op, SizeQueryOp::GreaterOrEqual);
1
        assert_eq!(recorded[3].op, SizeQueryOp::LessOrEqual);
1
    }
    #[test]
1
    fn flips_at_detects_exactly_the_crossings() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = drain();
1
        let info = info_at(&rd, 800.0, 600.0);
1
        let mobile = info.window_width_less_than(640.0); // false at 800
1
        assert!(!mobile);
1
        let (recorded, _) = drain();
1
        let q = recorded[0];
        // Shrinking within the desktop range does not flip…
1
        assert!(!q.flips_at(LogicalSize::new(700.0, 600.0)));
1
        assert!(
1
            !q.flips_at(LogicalSize::new(640.0, 600.0)),
            "strict <: 640 is still false"
        );
        // …crossing the queried threshold does…
1
        assert!(q.flips_at(LogicalSize::new(639.9, 600.0)));
1
        assert!(q.flips_at(LogicalSize::new(320.0, 600.0)));
        // …and the other axis is irrelevant to a width query.
1
        assert!(!q.flips_at(LogicalSize::new(700.0, 10.0)));
1
    }
    /// `between` must flip on BOTH of its bounds, inclusively — the reason
    /// [`SizeQueryOp`] has four exact operators instead of a bool.
    #[test]
1
    fn between_flips_on_either_bound_with_inclusive_semantics() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = drain();
1
        let info = info_at(&rd, 800.0, 600.0);
1
        assert!(info.window_width_between(768.0, 1024.0));
1
        let (recorded, _) = drain();
1
        let lower = recorded[0];
1
        let upper = recorded[1];
1
        assert!(
1
            !lower.flips_at(LogicalSize::new(768.0, 600.0)),
            ">= 768: boundary holds"
        );
1
        assert!(lower.flips_at(LogicalSize::new(767.9, 600.0)));
1
        assert!(
1
            !upper.flips_at(LogicalSize::new(1024.0, 600.0)),
            "<= 1024: boundary holds"
        );
1
        assert!(upper.flips_at(LogicalSize::new(1024.1, 600.0)));
1
    }
    #[test]
1
    fn drain_resets_the_recording() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = drain();
1
        let info = info_at(&rd, 1024.0, 768.0);
1
        let _ = info.window_width_greater_than(640.0);
1
        let (first, _) = drain();
1
        assert_eq!(first.len(), 1);
1
        let (second, overflowed) = drain();
1
        assert!(second.is_empty(), "drain must reset");
1
        assert!(!overflowed);
1
    }
    #[test]
1
    fn overflow_latches_and_reports_rather_than_dropping_silently() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = drain();
1
        let info = info_at(&rd, 1024.0, 768.0);
266
        for i in 0..(size_query_recorder::SIZE_QUERY_CAP + 10) {
266
            let _ = info.window_width_greater_than(i as f32);
266
        }
1
        let (recorded, overflowed) = drain();
1
        assert_eq!(recorded.len(), size_query_recorder::SIZE_QUERY_CAP);
1
        assert!(
1
            overflowed,
            "past the cap the drain MUST say the list is incomplete — silence here is a resize \
             skipping a layout() that would have branched"
        );
        // And the latch itself resets with the drain.
1
        let (_, overflowed2) = drain();
1
        assert!(!overflowed2);
1
    }
}
/// Tests for the declared system-style dependencies — the seam that decides
/// whether an appearance change costs the app a full `Update::RefreshDom` or
/// only a restyle.
#[cfg(test)]
mod system_style_dependency_tests {
    use azul_css::{
        props::basic::color::ColorU,
        system::{SystemStyle, Theme},
    };
    use super::*;
    use crate::geom::LogicalSize;
12
    fn style() -> SystemStyle {
12
        SystemStyle::default()
12
    }
3
    fn c(r: u8, g: u8, b: u8) -> azul_css::props::basic::color::OptionColorU {
3
        Some(ColorU { r, g, b, a: 255 }).into()
3
    }
    struct Rd {
        image_cache: crate::resources::ImageCache,
        gl: crate::gl::OptionGlContextPtr,
        fonts: rust_fontconfig::FcFontCache,
        style: alloc::sync::Arc<SystemStyle>,
    }
    impl Rd {
3
        fn new() -> Self {
3
            Self {
3
                image_cache: crate::resources::ImageCache::default(),
3
                gl: crate::gl::OptionGlContextPtr::None,
3
                fonts: rust_fontconfig::FcFontCache::default(),
3
                style: alloc::sync::Arc::new(style()),
3
            }
3
        }
3
        fn ref_data(&self) -> LayoutCallbackInfoRefData<'_> {
3
            LayoutCallbackInfoRefData {
3
                image_cache: &self.image_cache,
3
                gl_context: &self.gl,
3
                system_fonts: &self.fonts,
3
                system_style: alloc::sync::Arc::clone(&self.style),
3
                active_route: None,
3
                monitors: crate::window::MonitorVec::from_const_slice(&[]),
3
                safe_area: azul_css::system::SafeAreaInsets::default(),
3
            }
3
        }
    }
3
    fn info(rd: &LayoutCallbackInfoRefData<'_>) -> LayoutCallbackInfo {
3
        LayoutCallbackInfo::new(
3
            rd,
3
            WindowSize {
3
                dimensions: LogicalSize::new(800.0, 600.0),
3
                ..WindowSize::default()
3
            },
3
            WindowTheme::LightMode,
        )
3
    }
    /// The whole point: a callback that only mirrors light/dark keeps its DOM
    /// across a change that leaves the polarity alone, and loses it when the
    /// polarity flips. Both directions asserted — a `dom_depends_on_change`
    /// hardwired to `false` would pass the first half alone.
    #[test]
1
    fn a_theme_only_dependency_ignores_a_palette_move_but_not_a_polarity_flip() {
1
        let mut deps = SystemStyleDependencies::empty();
1
        deps.insert(SystemStyleDependency::Theme);
1
        let old = style();
        // Same polarity, different accent: this app cannot have built a
        // different DOM, so it must not be rebuilt.
1
        let mut recoloured = style();
1
        recoloured.colors.accent = c(61, 174, 233);
1
        assert_ne!(old.colors, recoloured.colors, "the fixture must differ");
1
        assert!(!deps.dom_depends_on_change(&old, &recoloured));
        // Polarity flip: rebuild.
1
        let mut dark = style();
1
        dark.theme = Theme::Dark;
1
        assert!(deps.dom_depends_on_change(&old, &dark));
1
    }
    /// An app that paints its own controls from the OS palette IS invalidated
    /// by a light-to-light accent change — the case the theme-only app is not.
    #[test]
1
    fn a_colors_dependency_catches_a_light_to_light_accent_change() {
1
        let mut deps = SystemStyleDependencies::empty();
1
        deps.insert(SystemStyleDependency::Colors);
1
        let old = style();
1
        let mut recoloured = style();
1
        recoloured.colors.accent = c(61, 174, 233);
1
        assert!(deps.dom_depends_on_change(&old, &recoloured));
        // ... and is NOT invalidated by something outside the palette.
1
        let mut louder = style();
1
        louder.audio.event_sounds_enabled = !louder.audio.event_sounds_enabled;
1
        assert_ne!(old.audio, louder.audio, "the fixture must differ");
1
        assert!(!deps.dom_depends_on_change(&old, &louder));
1
    }
    /// Declaring NOTHING is not declaring independence: every callback written
    /// before this API existed lands here, and silently skipping its rebuild
    /// would leave the old palette baked into its DOM.
    #[test]
1
    fn an_undeclared_callback_is_rebuilt_on_any_change_and_only_on_a_change() {
1
        let deps = SystemStyleDependencies::empty();
1
        let old = style();
1
        let mut moved = style();
1
        moved.colors.accent = c(61, 174, 233);
1
        assert!(deps.dom_depends_on_change(&old, &moved));
        // But an EQUAL style is still not a change — a settings broadcast that
        // carries nothing new must stay free.
1
        assert!(!deps.dom_depends_on_change(&old, &style()));
1
    }
    /// `Everything` subsumes every facet, which is what makes one widget's
    /// whole-struct read conservative for the entire tree.
    #[test]
1
    fn everything_contains_every_facet() {
1
        let mut deps = SystemStyleDependencies::empty();
1
        deps.insert(SystemStyleDependency::Everything);
6
        for dep in [
1
            SystemStyleDependency::Theme,
1
            SystemStyleDependency::Colors,
1
            SystemStyleDependency::Fonts,
1
            SystemStyleDependency::Metrics,
1
            SystemStyleDependency::Icons,
1
            SystemStyleDependency::Accessibility,
        ] {
6
            assert!(deps.contains(dep), "{dep:?} must be covered by Everything");
        }
        // And a narrow declaration does NOT claim its neighbours.
1
        let mut narrow = SystemStyleDependencies::empty();
1
        narrow.insert(SystemStyleDependency::Theme);
1
        assert!(narrow.contains(SystemStyleDependency::Theme));
1
        assert!(!narrow.contains(SystemStyleDependency::Colors));
1
    }
    /// The recorder unions what the callback declared, and the drain empties
    /// it — a leak across two `layout()` calls would make the second one
    /// inherit the first's dependencies.
    #[test]
1
    fn declarations_union_and_the_drain_empties_the_recording() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = take_recorded_style_dependencies();
1
        let info = info(&rd);
1
        assert!(
1
            take_recorded_style_dependencies().is_empty(),
            "constructing the info declares nothing"
        );
1
        info.depends_on_system_style(SystemStyleDependency::Theme);
1
        info.depends_on_system_style(SystemStyleDependency::Fonts);
1
        let declared = take_recorded_style_dependencies();
1
        assert!(declared.contains(SystemStyleDependency::Theme));
1
        assert!(declared.contains(SystemStyleDependency::Fonts));
1
        assert!(!declared.contains(SystemStyleDependency::Colors));
1
        assert!(
1
            take_recorded_style_dependencies().is_empty(),
            "the drain must reset — the next layout() starts from nothing"
        );
1
    }
    /// `get_theme()` is the tracked way to read the polarity; the bare `theme`
    /// FIELD declares nothing, exactly like reading `window_size` directly.
    #[test]
1
    fn get_theme_declares_the_polarity_and_the_bare_field_declares_nothing() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = take_recorded_style_dependencies();
1
        let info = info(&rd);
1
        let _ = info.theme;
1
        assert!(take_recorded_style_dependencies().is_empty());
1
        assert_eq!(info.get_theme(), WindowTheme::LightMode);
1
        let declared = take_recorded_style_dependencies();
1
        assert!(declared.contains(SystemStyleDependency::Theme));
1
        assert!(!declared.contains(SystemStyleDependency::Colors));
1
    }
    /// Handing out the whole struct is opaque, so it declares everything —
    /// while the untracked accessor (engine-internal readers, and callbacks
    /// that already said what they read) declares nothing.
    #[test]
1
    fn get_system_style_declares_everything_and_the_untracked_one_declares_nothing() {
1
        let rd = Rd::new();
1
        let rd = rd.ref_data();
1
        let _ = take_recorded_style_dependencies();
1
        let info = info(&rd);
1
        let _ = info.get_system_style_untracked();
1
        assert!(take_recorded_style_dependencies().is_empty());
1
        let _ = info.get_system_style();
1
        let declared = take_recorded_style_dependencies();
1
        assert!(declared.contains(SystemStyleDependency::Everything));
1
        assert!(declared.contains(SystemStyleDependency::Colors));
1
    }
}