1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(clippy::float_cmp)] // exact-value assertions on hidpi scale factors
5
mod audit_tests {
6
    use super::*;
7

            
8
    #[test]
9
1
    fn hidpi_factor_guards_zero_dpi() {
10
        // dpi == 0 must not produce a 0.0 scale factor (later divide-by-zero
11
        // in to_logical); it falls back to 96 DPI (scale 1.0).
12
1
        let ws = WindowSize {
13
1
            dpi: 0,
14
1
            ..WindowSize::default()
15
1
        };
16
1
        let factor = ws.get_hidpi_factor().inner.get();
17
1
        assert_eq!(factor, 1.0);
18

            
19
1
        let ws2 = WindowSize {
20
1
            dpi: 192,
21
1
            ..WindowSize::default()
22
1
        };
23
1
        assert_eq!(ws2.get_hidpi_factor().inner.get(), 2.0);
24
1
    }
25

            
26
    #[test]
27
1
    fn virtual_keycode_from_u32_roundtrips() {
28
        // A representative spread across the enum, including first/last.
29
8
        for vk in [
30
1
            VirtualKeyCode::Key1,
31
1
            VirtualKeyCode::A,
32
1
            VirtualKeyCode::Z,
33
1
            VirtualKeyCode::Left,
34
1
            VirtualKeyCode::Back,
35
1
            VirtualKeyCode::Delete,
36
1
            VirtualKeyCode::LControl,
37
1
            VirtualKeyCode::Cut,
38
        ] {
39
8
            assert_eq!(VirtualKeyCode::from_u32(vk as u32), Some(vk));
40
        }
41
        // Out of range -> None (no UB, no panic).
42
1
        assert_eq!(VirtualKeyCode::from_u32(10_000), None);
43
1
    }
44
}
45

            
46
#[cfg(test)]
47
#[allow(clippy::float_cmp)] // exact-value assertions on saturating float->int conversions
48
mod autotest_generated {
49
    use alloc::{format, string::String, vec};
50

            
51
    use super::*;
52

            
53
    /// Highest valid `VirtualKeyCode` discriminant (`Cut`, the last declared variant).
54
    const LAST_VK: u32 = 162;
55

            
56
    /// Deterministic, `no_std`-safe hasher so hash/eq consistency can be checked
57
    /// without pulling in `std::collections::hash_map::DefaultHasher`.
58
    #[derive(Default)]
59
    struct TestHasher(u64);
60

            
61
    impl Hasher for TestHasher {
62
        fn write(&mut self, bytes: &[u8]) {
63
            for &b in bytes {
64
                self.0 = self.0.rotate_left(5) ^ u64::from(b);
65
            }
66
        }
67
        fn finish(&self) -> u64 {
68
            self.0
69
        }
70
    }
71

            
72
    fn hash_of<T: Hash>(value: &T) -> u64 {
73
        let mut h = TestHasher::default();
74
        value.hash(&mut h);
75
        h.finish()
76
    }
77

            
78
    fn keyboard_with(keys: &[VirtualKeyCode]) -> KeyboardState {
79
        KeyboardState {
80
            pressed_virtual_keycodes: keys.to_vec().into(),
81
            ..KeyboardState::default()
82
        }
83
    }
84

            
85
    fn pair(key: &str, value: &str) -> AzStringPair {
86
        AzStringPair {
87
            key: key.into(),
88
            value: value.into(),
89
        }
90
    }
91

            
92
    // ---------------------------------------------------------------------
93
    // Constructors: WindowId / IconKey (atomic counters)
94
    // ---------------------------------------------------------------------
95

            
96
    #[test]
97
    fn window_id_new_is_unique_and_monotonic() {
98
        // The counter is process-global and shared with other tests in this
99
        // binary, so only *relative* properties may be asserted.
100
        let mut ids = BTreeSet::new();
101
        let mut prev = WindowId::new();
102
        assert!(ids.insert(prev));
103
        for _ in 0..1000 {
104
            let next = WindowId::new();
105
            assert!(next.id > prev.id, "WindowId counter must strictly increase");
106
            assert!(ids.insert(next), "WindowId::new() handed out a duplicate");
107
            prev = next;
108
        }
109
        // Default delegates to new(): two defaults are never the same window.
110
        assert_ne!(WindowId::default(), WindowId::default());
111
    }
112

            
113
    #[test]
114
    fn icon_key_new_is_unique_and_monotonic() {
115
        let mut keys = BTreeSet::new();
116
        let mut prev = IconKey::new();
117
        assert!(keys.insert(prev));
118
        for _ in 0..1000 {
119
            let next = IconKey::new();
120
            assert!(
121
                next.icon_id > prev.icon_id,
122
                "IconKey counter must strictly increase"
123
            );
124
            assert!(keys.insert(next), "IconKey::new() handed out a duplicate");
125
            prev = next;
126
        }
127
        assert_ne!(IconKey::default(), IconKey::default());
128
    }
129

            
130
    // ---------------------------------------------------------------------
131
    // RendererOptions + Vsync / Srgb / HwAcceleration predicates
132
    // ---------------------------------------------------------------------
133

            
134
    #[test]
135
    fn renderer_options_new_preserves_every_combination() {
136
        let vsyncs = [Vsync::Enabled, Vsync::Disabled, Vsync::DontCare];
137
        let srgbs = [Srgb::Enabled, Srgb::Disabled, Srgb::DontCare];
138
        let accels = [
139
            HwAcceleration::Enabled,
140
            HwAcceleration::Disabled,
141
            HwAcceleration::DontCare,
142
        ];
143
        for v in vsyncs {
144
            for s in srgbs {
145
                for a in accels {
146
                    let o = RendererOptions::new(v, s, a);
147
                    assert_eq!(o.vsync, v);
148
                    assert_eq!(o.srgb, s);
149
                    assert_eq!(o.hw_accel, a);
150
                    // Constructed value must round-trip through equality/copy.
151
                    assert_eq!(o, RendererOptions::new(v, s, a));
152
                }
153
            }
154
        }
155
    }
156

            
157
    #[test]
158
    fn renderer_options_default_does_not_force_cpu_rendering() {
159
        // Regression guard: hw_accel must be DontCare (auto), NOT Disabled -
160
        // Disabled silently forced every app into CPU rendering.
161
        let d = RendererOptions::default();
162
        assert_eq!(d.hw_accel, HwAcceleration::DontCare);
163
        assert!(!d.hw_accel.is_enabled());
164
        assert!(d.vsync.is_enabled());
165
        assert!(!d.srgb.is_enabled());
166
    }
167

            
168
    #[test]
169
    fn tri_state_is_enabled_only_for_enabled_variant() {
170
        assert!(Vsync::Enabled.is_enabled());
171
        assert!(!Vsync::Disabled.is_enabled());
172
        assert!(!Vsync::DontCare.is_enabled());
173

            
174
        assert!(Srgb::Enabled.is_enabled());
175
        assert!(!Srgb::Disabled.is_enabled());
176
        assert!(!Srgb::DontCare.is_enabled());
177

            
178
        assert!(HwAcceleration::Enabled.is_enabled());
179
        assert!(!HwAcceleration::Disabled.is_enabled());
180
        assert!(!HwAcceleration::DontCare.is_enabled());
181
    }
182

            
183
    // ---------------------------------------------------------------------
184
    // KeyboardState getters / predicates
185
    // ---------------------------------------------------------------------
186

            
187
    #[test]
188
    fn keyboard_state_default_has_no_key_down() {
189
        let k = KeyboardState::default();
190
        assert!(!k.shift_down());
191
        assert!(!k.ctrl_down());
192
        assert!(!k.alt_down());
193
        assert!(!k.super_down());
194
        assert!(!k.primary_down());
195
        // Every single keycode reports "not down" on an empty state.
196
        for v in 0..=LAST_VK {
197
            let vk = VirtualKeyCode::from_u32(v).expect("discriminant in range");
198
            assert!(!k.is_key_down(vk));
199
        }
200
    }
201

            
202
    #[test]
203
    fn keyboard_state_modifiers_accept_either_side() {
204
        for (left, right, probe) in [
205
            (
206
                VirtualKeyCode::LShift,
207
                VirtualKeyCode::RShift,
208
                KeyboardState::shift_down as fn(&KeyboardState) -> bool,
209
            ),
210
            (
211
                VirtualKeyCode::LControl,
212
                VirtualKeyCode::RControl,
213
                KeyboardState::ctrl_down as fn(&KeyboardState) -> bool,
214
            ),
215
            (
216
                VirtualKeyCode::LAlt,
217
                VirtualKeyCode::RAlt,
218
                KeyboardState::alt_down as fn(&KeyboardState) -> bool,
219
            ),
220
            (
221
                VirtualKeyCode::LWin,
222
                VirtualKeyCode::RWin,
223
                KeyboardState::super_down as fn(&KeyboardState) -> bool,
224
            ),
225
        ] {
226
            assert!(probe(&keyboard_with(&[left])), "left variant must register");
227
            assert!(
228
                probe(&keyboard_with(&[right])),
229
                "right variant must register"
230
            );
231
            assert!(probe(&keyboard_with(&[left, right])));
232
            // An unrelated key must not light up a modifier.
233
            assert!(!probe(&keyboard_with(&[VirtualKeyCode::A])));
234
        }
235
    }
236

            
237
    #[test]
238
    fn keyboard_state_primary_down_follows_platform() {
239
        let ctrl = keyboard_with(&[VirtualKeyCode::LControl]);
240
        let cmd = keyboard_with(&[VirtualKeyCode::LWin]);
241
        if cfg!(target_os = "macos") {
242
            assert!(cmd.primary_down(), "Cmd (super) is PRIMARY on macOS");
243
            assert!(!ctrl.primary_down());
244
        } else {
245
            assert!(ctrl.primary_down(), "Ctrl is PRIMARY off macOS");
246
            assert!(!cmd.primary_down());
247
        }
248
        // On every platform, primary_down agrees with one of the two modifiers.
249
        for k in [&ctrl, &cmd, &KeyboardState::default()] {
250
            assert_eq!(
251
                k.primary_down(),
252
                if cfg!(target_os = "macos") {
253
                    k.super_down()
254
                } else {
255
                    k.ctrl_down()
256
                }
257
            );
258
        }
259
    }
260

            
261
    #[test]
262
    fn is_key_down_handles_duplicates_and_large_state() {
263
        // Same key pressed many times (backends can push duplicates).
264
        let dup = keyboard_with(&[VirtualKeyCode::S; 512]);
265
        assert!(dup.is_key_down(VirtualKeyCode::S));
266
        assert!(!dup.is_key_down(VirtualKeyCode::A));
267

            
268
        // Every key held down at once: no panic, all report true.
269
        let all: alloc::vec::Vec<VirtualKeyCode> = (0..=LAST_VK)
270
            .map(|v| VirtualKeyCode::from_u32(v).expect("discriminant in range"))
271
            .collect();
272
        let everything = keyboard_with(&all);
273
        for vk in &all {
274
            assert!(everything.is_key_down(*vk));
275
        }
276
        assert!(everything.shift_down() && everything.ctrl_down());
277
        assert!(everything.alt_down() && everything.super_down());
278
    }
279

            
280
    // ---------------------------------------------------------------------
281
    // AcceleratorKey / matches_accelerator
282
    // ---------------------------------------------------------------------
283

            
284
    #[test]
285
    fn empty_chord_matches_trivially() {
286
        // Documented: "An empty chord matches trivially."
287
        assert!(KeyboardState::default().matches_accelerator(&[]));
288
        assert!(keyboard_with(&[VirtualKeyCode::A]).matches_accelerator(&[]));
289
    }
290

            
291
    #[test]
292
    fn matches_accelerator_requires_every_entry() {
293
        let state = keyboard_with(&[
294
            VirtualKeyCode::LControl,
295
            VirtualKeyCode::LShift,
296
            VirtualKeyCode::S,
297
        ]);
298
        assert!(state.matches_accelerator(&[
299
            AcceleratorKey::Ctrl,
300
            AcceleratorKey::Shift,
301
            AcceleratorKey::Key(VirtualKeyCode::S),
302
        ]));
303
        // One missing entry (Alt) is enough to reject the whole chord.
304
        assert!(!state.matches_accelerator(&[
305
            AcceleratorKey::Ctrl,
306
            AcceleratorKey::Alt,
307
            AcceleratorKey::Key(VirtualKeyCode::S),
308
        ]));
309
        // Wrong key, right modifiers.
310
        assert!(!state
311
            .matches_accelerator(&[AcceleratorKey::Ctrl, AcceleratorKey::Key(VirtualKeyCode::Q),]));
312
        // Order must not matter.
313
        assert!(state.matches_accelerator(&[
314
            AcceleratorKey::Key(VirtualKeyCode::S),
315
            AcceleratorKey::Shift,
316
            AcceleratorKey::Ctrl,
317
        ]));
318
    }
319

            
320
    #[test]
321
    fn matches_accelerator_survives_huge_chord() {
322
        // A pathologically long chord must terminate (linear scan, no recursion).
323
        let state = keyboard_with(&[VirtualKeyCode::LShift]);
324
        let long_ok = vec![AcceleratorKey::Shift; 10_000];
325
        assert!(state.matches_accelerator(&long_ok));
326

            
327
        // 10k satisfiable entries with a single unsatisfiable one at the very end:
328
        // `all()` must still reach it and return false.
329
        let mut long_bad = vec![AcceleratorKey::Shift; 10_000];
330
        long_bad.push(AcceleratorKey::Ctrl);
331
        assert!(!state.matches_accelerator(&long_bad));
332
    }
333

            
334
    #[test]
335
    fn accelerator_key_matches_each_variant() {
336
        let empty = KeyboardState::default();
337
        for a in [
338
            AcceleratorKey::Ctrl,
339
            AcceleratorKey::Alt,
340
            AcceleratorKey::Shift,
341
            AcceleratorKey::Key(VirtualKeyCode::A),
342
        ] {
343
            assert!(
344
                !a.matches(&empty),
345
                "nothing matches an empty keyboard state"
346
            );
347
        }
348
        assert!(AcceleratorKey::Ctrl.matches(&keyboard_with(&[VirtualKeyCode::RControl])));
349
        assert!(AcceleratorKey::Alt.matches(&keyboard_with(&[VirtualKeyCode::RAlt])));
350
        assert!(AcceleratorKey::Shift.matches(&keyboard_with(&[VirtualKeyCode::RShift])));
351
        assert!(AcceleratorKey::Key(VirtualKeyCode::F24)
352
            .matches(&keyboard_with(&[VirtualKeyCode::F24])));
353
        // Modifier accelerators are NOT satisfied by the letter of the same name.
354
        assert!(!AcceleratorKey::Ctrl.matches(&keyboard_with(&[VirtualKeyCode::C])));
355
    }
356

            
357
    // ---------------------------------------------------------------------
358
    // MouseState / MouseButtonState
359
    // ---------------------------------------------------------------------
360

            
361
    #[test]
362
    fn mouse_state_matches_context_button() {
363
        let base = MouseState::default();
364
        assert!(!base.matches(&ContextMenuMouseButton::Left));
365
        assert!(!base.matches(&ContextMenuMouseButton::Right));
366
        assert!(!base.matches(&ContextMenuMouseButton::Middle));
367

            
368
        for (ctx, ms) in [
369
            (
370
                ContextMenuMouseButton::Left,
371
                MouseState {
372
                    left_down: true,
373
                    ..MouseState::default()
374
                },
375
            ),
376
            (
377
                ContextMenuMouseButton::Right,
378
                MouseState {
379
                    right_down: true,
380
                    ..MouseState::default()
381
                },
382
            ),
383
            (
384
                ContextMenuMouseButton::Middle,
385
                MouseState {
386
                    middle_down: true,
387
                    ..MouseState::default()
388
                },
389
            ),
390
        ] {
391
            assert!(ms.matches(&ctx), "{ctx:?} must match its own button");
392
            // ...and only its own button.
393
            let others = [
394
                ContextMenuMouseButton::Left,
395
                ContextMenuMouseButton::Right,
396
                ContextMenuMouseButton::Middle,
397
            ];
398
            for other in others {
399
                assert_eq!(ms.matches(&other), other == ctx);
400
            }
401
        }
402
    }
403

            
404
    #[test]
405
    fn mouse_down_and_button_state_agree_for_all_8_combinations() {
406
        for bits in 0u8..8 {
407
            let (l, r, m) = (bits & 1 != 0, bits & 2 != 0, bits & 4 != 0);
408
            let ms = MouseState {
409
                left_down: l,
410
                right_down: r,
411
                middle_down: m,
412
                ..MouseState::default()
413
            };
414
            assert_eq!(ms.mouse_down(), l || r || m);
415

            
416
            let snapshot = ms.button_state();
417
            assert_eq!(snapshot.left_down, l);
418
            assert_eq!(snapshot.right_down, r);
419
            assert_eq!(snapshot.middle_down, m);
420
            // any_down is exactly mouse_down, and the From impl is the same snapshot.
421
            assert_eq!(snapshot.any_down(), ms.mouse_down());
422
            assert_eq!(crate::events::MouseButtonState::from(&ms), snapshot);
423
        }
424
        // Default MouseState has no button held.
425
        assert!(!MouseState::default().mouse_down());
426
        assert!(!MouseState::default().button_state().any_down());
427
    }
428

            
429
    // ---------------------------------------------------------------------
430
    // process_system_scroll (numeric)
431
    // ---------------------------------------------------------------------
432

            
433
    #[test]
434
    fn process_system_scroll_zero_and_negative_zero_consume_nothing() {
435
        let r = process_system_scroll(LogicalPosition::zero(), false);
436
        assert_eq!(r.scrolled_nodes, 0);
437
        assert_eq!(r.remaining_delta, LogicalPosition::zero());
438
        assert!(!r.hit_scrollbar);
439

            
440
        // -0.0 == 0.0 under IEEE-754, so a negative-zero delta must also be a no-op.
441
        let neg_zero = process_system_scroll(LogicalPosition::new(-0.0, -0.0), true);
442
        assert_eq!(neg_zero.scrolled_nodes, 0);
443
        assert!(neg_zero.hit_scrollbar, "hit_scrollbar is echoed verbatim");
444
    }
445

            
446
    #[test]
447
    fn process_system_scroll_counts_any_nonzero_axis() {
448
        for delta in [
449
            LogicalPosition::new(1.0, 0.0),
450
            LogicalPosition::new(0.0, -1.0),
451
            LogicalPosition::new(-3.5, 7.25),
452
            LogicalPosition::new(f32::MIN, 0.0),
453
            LogicalPosition::new(0.0, f32::MAX),
454
            LogicalPosition::new(f32::INFINITY, f32::NEG_INFINITY),
455
            LogicalPosition::new(f32::MIN_POSITIVE, 0.0),
456
        ] {
457
            let r = process_system_scroll(delta, false);
458
            assert_eq!(r.scrolled_nodes, 1, "{delta:?} must count as consumed");
459
            // Overscroll is never reported by this helper.
460
            assert_eq!(r.remaining_delta, LogicalPosition::zero());
461
        }
462
    }
463

            
464
    #[test]
465
    fn process_system_scroll_does_not_panic_on_nan() {
466
        // NaN != 0.0 is `true`, so a NaN delta is currently treated as consumed.
467
        // The contract asserted here is only "terminates, no panic, bounded count".
468
        for delta in [
469
            LogicalPosition::new(f32::NAN, 0.0),
470
            LogicalPosition::new(0.0, f32::NAN),
471
            LogicalPosition::new(f32::NAN, f32::NAN),
472
        ] {
473
            let r = process_system_scroll(delta, true);
474
            assert!(r.scrolled_nodes <= 1);
475
            assert_eq!(r.remaining_delta, LogicalPosition::zero());
476
            assert!(r.hit_scrollbar);
477
        }
478
    }
479

            
480
    #[test]
481
    fn scroll_result_default_is_inert() {
482
        let d = ScrollResult::default();
483
        assert_eq!(d.scrolled_nodes, 0);
484
        assert_eq!(d.remaining_delta, LogicalPosition::zero());
485
        assert!(!d.hit_scrollbar);
486
    }
487

            
488
    // ---------------------------------------------------------------------
489
    // CursorPosition
490
    // ---------------------------------------------------------------------
491

            
492
    #[test]
493
    fn cursor_position_get_position_only_inside_window() {
494
        let p = LogicalPosition::new(12.0, 34.0);
495
        assert_eq!(CursorPosition::InWindow(p).get_position(), Some(p));
496
        assert_eq!(CursorPosition::OutOfWindow(p).get_position(), None);
497
        assert_eq!(CursorPosition::Uninitialized.get_position(), None);
498
        // Default (as used by MouseState::default) is Uninitialized.
499
        assert_eq!(CursorPosition::default(), CursorPosition::Uninitialized);
500
        assert_eq!(CursorPosition::default().get_position(), None);
501
    }
502

            
503
    #[test]
504
    fn cursor_position_is_inside_window_agrees_with_get_position() {
505
        for c in [
506
            CursorPosition::Uninitialized,
507
            CursorPosition::InWindow(LogicalPosition::zero()),
508
            CursorPosition::OutOfWindow(LogicalPosition::zero()),
509
            CursorPosition::InWindow(LogicalPosition::new(f32::MIN, f32::MAX)),
510
            CursorPosition::OutOfWindow(LogicalPosition::new(f32::INFINITY, f32::NAN)),
511
        ] {
512
            assert_eq!(c.is_inside_window(), c.get_position().is_some());
513
        }
514
        // Extreme / non-finite coordinates are passed through, not sanitized.
515
        let nan_pos = CursorPosition::InWindow(LogicalPosition::new(f32::NAN, f32::INFINITY));
516
        assert!(nan_pos.is_inside_window());
517
        let got = nan_pos
518
            .get_position()
519
            .expect("InWindow always yields a position");
520
        assert!(got.x.is_nan());
521
        assert!(got.y.is_infinite());
522
    }
523

            
524
    // ---------------------------------------------------------------------
525
    // MonitorId constructors
526
    // ---------------------------------------------------------------------
527

            
528
    #[test]
529
    fn monitor_id_constructors_preserve_fields_at_extremes() {
530
        assert_eq!(MonitorId::PRIMARY, MonitorId { index: 0, hash: 0 });
531
        assert_eq!(MonitorId::new(0), MonitorId::PRIMARY);
532

            
533
        for index in [0usize, 1, 42, usize::MAX] {
534
            let m = MonitorId::new(index);
535
            assert_eq!(m.index, index);
536
            assert_eq!(m.hash, 0, "new() documents hash == 0");
537

            
538
            for hash in [0u64, 1, u64::MAX] {
539
                let m = MonitorId::from_index_and_hash(index, hash);
540
                assert_eq!(m.index, index);
541
                assert_eq!(m.hash, hash);
542
            }
543
        }
544
        // index and hash are independent coordinates of identity.
545
        assert_ne!(MonitorId::new(1), MonitorId::new(2));
546
        assert_ne!(
547
            MonitorId::from_index_and_hash(1, 7),
548
            MonitorId::from_index_and_hash(1, 8)
549
        );
550
    }
551

            
552
    #[test]
553
    fn monitor_id_from_properties_is_stable_and_index_independent() {
554
        let pos = LayoutPoint::new(-1920, 0);
555
        let size = LayoutSize::new(2560, 1440);
556

            
557
        let a = MonitorId::from_properties(0, "HDMI-1", pos, size);
558
        let b = MonitorId::from_properties(0, "HDMI-1", pos, size);
559
        assert_eq!(a, b, "hash must be stable across calls (persistable)");
560

            
561
        // The hash intentionally covers only the properties, not the runtime index.
562
        let reindexed = MonitorId::from_properties(7, "HDMI-1", pos, size);
563
        assert_eq!(reindexed.hash, a.hash);
564
        assert_eq!(reindexed.index, 7);
565
        assert_ne!(reindexed, a, "index is still part of identity");
566
    }
567

            
568
    #[test]
569
    fn monitor_id_from_properties_is_sensitive_to_each_property() {
570
        let pos = LayoutPoint::new(0, 0);
571
        let size = LayoutSize::new(1920, 1080);
572
        let base = MonitorId::from_properties(0, "DP-1", pos, size);
573

            
574
        // Changing any single property must change the hash.
575
        assert_ne!(
576
            base.hash,
577
            MonitorId::from_properties(0, "DP-2", pos, size).hash
578
        );
579
        assert_ne!(
580
            base.hash,
581
            MonitorId::from_properties(0, "DP-1", LayoutPoint::new(1, 0), size).hash
582
        );
583
        assert_ne!(
584
            base.hash,
585
            MonitorId::from_properties(0, "DP-1", LayoutPoint::new(0, 1), size).hash
586
        );
587
        assert_ne!(
588
            base.hash,
589
            MonitorId::from_properties(0, "DP-1", pos, LayoutSize::new(1921, 1080)).hash
590
        );
591
        assert_ne!(
592
            base.hash,
593
            MonitorId::from_properties(0, "DP-1", pos, LayoutSize::new(1920, 1081)).hash
594
        );
595
        // A swapped width/height is a different monitor, not the same one.
596
        assert_ne!(
597
            base.hash,
598
            MonitorId::from_properties(0, "DP-1", pos, LayoutSize::new(1080, 1920)).hash
599
        );
600
    }
601

            
602
    #[test]
603
    fn monitor_id_from_properties_handles_hostile_inputs() {
604
        let size = LayoutSize::new(isize::MAX, isize::MIN);
605
        let pos = LayoutPoint::new(isize::MIN, isize::MAX);
606

            
607
        // Empty / whitespace / unicode / NUL-containing names must not panic.
608
        for name in ["", "   ", "\t\n", "\u{1F600}", "e\u{301}", "é", "a\0b"] {
609
            let m = MonitorId::from_properties(3, name, pos, size);
610
            assert_eq!(m.index, 3);
611
            // Same input -> same hash, even at isize extremes.
612
            assert_eq!(m, MonitorId::from_properties(3, name, pos, size));
613
        }
614

            
615
        // Byte-exact name comparison: combining-mark and precomposed forms differ.
616
        assert_ne!(
617
            MonitorId::from_properties(0, "e\u{301}", pos, size).hash,
618
            MonitorId::from_properties(0, "é", pos, size).hash
619
        );
620

            
621
        // A 1M-char monitor name must terminate quickly (FNV-1a is linear).
622
        let huge = "x".repeat(1_000_000);
623
        let h1 = MonitorId::from_properties(0, &huge, LayoutPoint::zero(), LayoutSize::zero());
624
        let h2 = MonitorId::from_properties(0, &huge, LayoutPoint::zero(), LayoutSize::zero());
625
        assert_eq!(h1, h2);
626
        assert_ne!(
627
            h1.hash,
628
            MonitorId::from_properties(0, "x", LayoutPoint::zero(), LayoutSize::zero()).hash
629
        );
630
    }
631

            
632
    // ---------------------------------------------------------------------
633
    // WindowFlags predicates / getters
634
    // ---------------------------------------------------------------------
635

            
636
    #[test]
637
    fn window_flags_type_predicates_are_mutually_exclusive() {
638
        for (ty, menu, tooltip, dialog) in [
639
            (WindowType::Normal, false, false, false),
640
            (WindowType::Menu, true, false, false),
641
            (WindowType::Tooltip, false, true, false),
642
            (WindowType::Dialog, false, false, true),
643
        ] {
644
            let f = WindowFlags {
645
                window_type: ty,
646
                ..WindowFlags::default()
647
            };
648
            assert_eq!(f.is_menu_window(), menu);
649
            assert_eq!(f.is_tooltip_window(), tooltip);
650
            assert_eq!(f.is_dialog_window(), dialog);
651
            // At most one classification can ever be true at once.
652
            let count = u8::from(f.is_menu_window())
653
                + u8::from(f.is_tooltip_window())
654
                + u8::from(f.is_dialog_window());
655
            assert!(count <= 1);
656
        }
657
    }
658

            
659
    #[test]
660
    fn window_flags_bool_getters_mirror_their_fields() {
661
        // Default: focused, no close request, no CSD.
662
        let d = WindowFlags::default();
663
        assert!(d.window_has_focus());
664
        assert!(!d.is_close_requested());
665
        assert!(!d.has_csd());
666
        assert_eq!(
667
            d.use_native_menus(),
668
            cfg!(any(target_os = "windows", target_os = "macos"))
669
        );
670
        assert_eq!(
671
            d.use_native_context_menus(),
672
            cfg!(any(target_os = "windows", target_os = "macos"))
673
        );
674

            
675
        // Every getter is a pure mirror of its field, in both states.
676
        for b in [false, true] {
677
            let f = WindowFlags {
678
                has_focus: b,
679
                close_requested: b,
680
                has_decorations: b,
681
                use_native_menus: b,
682
                use_native_context_menus: b,
683
                ..WindowFlags::default()
684
            };
685
            assert_eq!(f.window_has_focus(), b);
686
            assert_eq!(f.is_close_requested(), b);
687
            assert_eq!(f.has_csd(), b);
688
            assert_eq!(f.use_native_menus(), b);
689
            assert_eq!(f.use_native_context_menus(), b);
690
        }
691
    }
692

            
693
    // ---------------------------------------------------------------------
694
    // StringPairVec: get_key / get_key_mut / insert_kv
695
    // ---------------------------------------------------------------------
696

            
697
    #[test]
698
    fn get_key_on_empty_vec_is_none() {
699
        let empty = StringPairVec::new();
700
        assert!(empty.get_key("").is_none());
701
        assert!(empty.get_key("anything").is_none());
702

            
703
        let mut empty_mut = StringPairVec::new();
704
        assert!(empty_mut.get_key_mut("").is_none());
705
        assert!(empty_mut.get_key_mut("anything").is_none());
706
    }
707

            
708
    #[test]
709
    fn get_key_valid_minimal_and_missing() {
710
        let v = StringPairVec::from_vec(vec![pair("WM_CLASS", "azul")]);
711
        assert_eq!(
712
            v.get_key("WM_CLASS").map(AzString::as_str),
713
            Some("azul"),
714
            "positive control"
715
        );
716
        assert!(v.get_key("wm_class").is_none(), "lookup is case-sensitive");
717
        assert!(v.get_key("WM_CLAS").is_none());
718
        assert!(v.get_key("WM_CLASS ").is_none(), "no trimming is performed");
719
        assert!(v.get_key(" WM_CLASS").is_none());
720
        assert!(v.get_key("WM_CLASS;garbage").is_none());
721
    }
722

            
723
    #[test]
724
    fn get_key_handles_garbage_whitespace_and_boundary_numbers() {
725
        let v = StringPairVec::from_vec(vec![
726
            pair("", "empty-key"),
727
            pair("   ", "spaces"),
728
            pair("\t\n", "tabs"),
729
            pair("0", "zero"),
730
            pair("-0", "neg-zero"),
731
            pair("9223372036854775807", "i64-max"),
732
            pair("NaN", "nan"),
733
            pair("inf", "inf"),
734
        ]);
735

            
736
        // Empty and whitespace-only keys are ordinary keys - looked up verbatim.
737
        assert_eq!(v.get_key("").map(AzString::as_str), Some("empty-key"));
738
        assert_eq!(v.get_key("   ").map(AzString::as_str), Some("spaces"));
739
        assert_eq!(v.get_key("\t\n").map(AzString::as_str), Some("tabs"));
740

            
741
        // Numeric-looking keys are compared as strings: "0" and "-0" are distinct.
742
        assert_eq!(v.get_key("0").map(AzString::as_str), Some("zero"));
743
        assert_eq!(v.get_key("-0").map(AzString::as_str), Some("neg-zero"));
744
        assert_eq!(
745
            v.get_key("9223372036854775807").map(AzString::as_str),
746
            Some("i64-max")
747
        );
748
        assert_eq!(v.get_key("NaN").map(AzString::as_str), Some("nan"));
749
        assert_eq!(v.get_key("inf").map(AzString::as_str), Some("inf"));
750
        assert!(v.get_key("nan").is_none());
751

            
752
        // Random non-grammar bytes / control chars / deep bracket nesting: None, no panic.
753
        assert!(v.get_key("\u{0}\u{1}\u{7f}\\x\"';--").is_none());
754
        assert!(v.get_key(&"[".repeat(10_000)).is_none());
755
        assert!(v.get_key(&"{\"a\":".repeat(10_000)).is_none());
756
    }
757

            
758
    #[test]
759
    fn get_key_handles_unicode_without_panicking() {
760
        let v = StringPairVec::from_vec(vec![
761
            pair("\u{1F600}", "grin"),
762
            pair("é", "precomposed"),
763
            pair("日本語", "jp"),
764
        ]);
765
        assert_eq!(v.get_key("\u{1F600}").map(AzString::as_str), Some("grin"));
766
        assert_eq!(v.get_key("日本語").map(AzString::as_str), Some("jp"));
767
        // No unicode normalization: decomposed "e" + combining acute != "é".
768
        assert_eq!(v.get_key("é").map(AzString::as_str), Some("precomposed"));
769
        assert!(v.get_key("e\u{301}").is_none());
770
        // A prefix of a multi-byte key must not match (no byte-slicing bugs).
771
        assert!(v.get_key("日本").is_none());
772
    }
773

            
774
    #[test]
775
    fn get_key_handles_extremely_long_input() {
776
        let huge = "k".repeat(1_000_000);
777
        let mut v = StringPairVec::from_vec(vec![pair("short", "1")]);
778

            
779
        // Searching for a 1M-char key that is not present: linear, terminates.
780
        assert!(v.get_key(&huge).is_none());
781

            
782
        // ...and one that IS present.
783
        v.push(AzStringPair {
784
            key: huge.as_str().into(),
785
            value: "big".into(),
786
        });
787
        assert_eq!(v.get_key(&huge).map(AzString::as_str), Some("big"));
788
        // Off-by-one on a 1M-char key must not match.
789
        assert!(v.get_key(&"k".repeat(999_999)).is_none());
790
        assert!(v.get_key(&"k".repeat(1_000_001)).is_none());
791
    }
792

            
793
    #[test]
794
    fn get_key_returns_first_of_duplicate_keys() {
795
        let v = StringPairVec::from_vec(vec![
796
            pair("dup", "first"),
797
            pair("dup", "second"),
798
            pair("dup", "third"),
799
        ]);
800
        assert_eq!(v.get_key("dup").map(AzString::as_str), Some("first"));
801
    }
802

            
803
    #[test]
804
    fn get_key_mut_mutates_in_place() {
805
        let mut v = StringPairVec::from_vec(vec![pair("a", "1"), pair("b", "2")]);
806
        {
807
            let entry = v.get_key_mut("b").expect("b is present");
808
            entry.value = "changed".into();
809
        }
810
        assert_eq!(v.get_key("b").map(AzString::as_str), Some("changed"));
811
        assert_eq!(v.get_key("a").map(AzString::as_str), Some("1"));
812
        assert!(v.get_key_mut("missing").is_none());
813
        assert_eq!(v.len(), 2, "get_key_mut must not add entries");
814

            
815
        // Mutating the KEY through get_key_mut is possible and re-targets lookups.
816
        {
817
            let entry = v.get_key_mut("a").expect("a is present");
818
            entry.key = "z".into();
819
        }
820
        assert!(v.get_key("a").is_none());
821
        assert_eq!(v.get_key("z").map(AzString::as_str), Some("1"));
822
    }
823

            
824
    #[test]
825
    fn insert_kv_updates_existing_and_appends_new() {
826
        let mut v = StringPairVec::new();
827
        v.insert_kv("k", "v1");
828
        assert_eq!(v.len(), 1);
829
        assert_eq!(v.get_key("k").map(AzString::as_str), Some("v1"));
830

            
831
        // Re-inserting the same key overwrites in place instead of appending.
832
        v.insert_kv("k", "v2");
833
        assert_eq!(v.len(), 1, "insert_kv must not duplicate an existing key");
834
        assert_eq!(v.get_key("k").map(AzString::as_str), Some("v2"));
835

            
836
        // A different key appends.
837
        v.insert_kv("other", "x");
838
        assert_eq!(v.len(), 2);
839
        assert_eq!(v.get_key("k").map(AzString::as_str), Some("v2"));
840
        assert_eq!(v.get_key("other").map(AzString::as_str), Some("x"));
841

            
842
        // Repeated inserts of the same key never grow the vec.
843
        for i in 0..100 {
844
            v.insert_kv(String::from("k"), format!("gen{i}"));
845
        }
846
        assert_eq!(v.len(), 2);
847
        assert_eq!(v.get_key("k").map(AzString::as_str), Some("gen99"));
848
    }
849

            
850
    #[test]
851
    fn insert_kv_accepts_hostile_keys_and_values() {
852
        let mut v = StringPairVec::new();
853
        v.insert_kv("", "");
854
        assert_eq!(v.len(), 1);
855
        assert_eq!(v.get_key("").map(AzString::as_str), Some(""));
856

            
857
        v.insert_kv("\u{1F600}", "😀");
858
        assert_eq!(v.get_key("\u{1F600}").map(AzString::as_str), Some("😀"));
859

            
860
        v.insert_kv("   ", "\t\n");
861
        assert_eq!(v.get_key("   ").map(AzString::as_str), Some("\t\n"));
862

            
863
        // Very long key + value: no hang, and the update path still finds it.
864
        let huge_key = "K".repeat(100_000);
865
        let huge_val = "V".repeat(100_000);
866
        v.insert_kv(huge_key.clone(), huge_val.clone());
867
        let before = v.len();
868
        assert_eq!(
869
            v.get_key(&huge_key).map(AzString::as_str),
870
            Some(huge_val.as_str())
871
        );
872
        v.insert_kv(huge_key.clone(), String::from("small"));
873
        assert_eq!(v.len(), before, "long key must hit the update path");
874
        assert_eq!(v.get_key(&huge_key).map(AzString::as_str), Some("small"));
875
    }
876

            
877
    #[test]
878
    fn insert_kv_only_updates_the_first_of_pre_existing_duplicates() {
879
        // Duplicates can only arrive via push()/from_vec(); insert_kv updates the
880
        // first match (get_key_mut semantics) and leaves the shadowed one stale.
881
        let mut v = StringPairVec::from_vec(vec![pair("dup", "first"), pair("dup", "second")]);
882
        v.insert_kv("dup", "updated");
883
        assert_eq!(v.len(), 2, "no new entry is appended");
884
        assert_eq!(v.get_key("dup").map(AzString::as_str), Some("updated"));
885
        assert_eq!(
886
            v.get(1).expect("second entry still present").value.as_str(),
887
            "second",
888
            "the shadowed duplicate is left untouched"
889
        );
890
    }
891

            
892
    // ---------------------------------------------------------------------
893
    // WindowSize getters (numeric saturation)
894
    // ---------------------------------------------------------------------
895

            
896
    #[test]
897
    fn window_size_get_logical_size_is_the_identity() {
898
        for dims in [
899
            LogicalSize::zero(),
900
            LogicalSize::new(640.0, 480.0),
901
            LogicalSize::new(-1.0, -2.0),
902
            LogicalSize::new(f32::MAX, f32::MIN),
903
            LogicalSize::new(f32::INFINITY, f32::MIN_POSITIVE),
904
        ] {
905
            let ws = WindowSize {
906
                dimensions: dims,
907
                ..WindowSize::default()
908
            };
909
            assert_eq!(ws.get_logical_size(), dims);
910
        }
911
        // Default is the documented 640x480 @ 96 DPI.
912
        let d = WindowSize::default();
913
        assert_eq!(d.get_logical_size(), LogicalSize::new(640.0, 480.0));
914
        assert_eq!(d.dpi, 96);
915
    }
916

            
917
    #[test]
918
    fn window_size_get_layout_size_rounds_half_away_from_zero() {
919
        for (w, h, ew, eh) in [
920
            (0.0f32, 0.0f32, 0isize, 0isize),
921
            (640.0, 480.0, 640, 480),
922
            (640.4, 480.4, 640, 480),
923
            (640.6, 480.6, 641, 481),
924
            (640.5, 639.5, 641, 640),
925
            (-0.5, -1.5, -1, -2),
926
        ] {
927
            let ws = WindowSize {
928
                dimensions: LogicalSize::new(w, h),
929
                ..WindowSize::default()
930
            };
931
            assert_eq!(ws.get_layout_size(), LayoutSize::new(ew, eh), "{w}x{h}");
932
        }
933
    }
934

            
935
    #[test]
936
    fn window_size_get_layout_size_saturates_on_non_finite() {
937
        // `as isize` saturates: NaN -> 0, +inf -> isize::MAX, -inf -> isize::MIN.
938
        let nan = WindowSize {
939
            dimensions: LogicalSize::new(f32::NAN, f32::NAN),
940
            ..WindowSize::default()
941
        };
942
        assert_eq!(nan.get_layout_size(), LayoutSize::new(0, 0));
943

            
944
        let inf = WindowSize {
945
            dimensions: LogicalSize::new(f32::INFINITY, f32::NEG_INFINITY),
946
            ..WindowSize::default()
947
        };
948
        assert_eq!(
949
            inf.get_layout_size(),
950
            LayoutSize::new(isize::MAX, isize::MIN)
951
        );
952

            
953
        let max = WindowSize {
954
            dimensions: LogicalSize::new(f32::MAX, f32::MIN),
955
            ..WindowSize::default()
956
        };
957
        let ls = max.get_layout_size();
958
        assert!(ls.width > 0 && ls.height < 0, "sign is preserved: {ls:?}");
959
    }
960

            
961
    #[test]
962
    fn window_size_get_physical_size_saturates_instead_of_wrapping() {
963
        // Negative logical sizes clamp to 0 (u32 cast drops the sign).
964
        let neg = WindowSize {
965
            dimensions: LogicalSize::new(-100.0, -0.4),
966
            ..WindowSize::default()
967
        };
968
        assert_eq!(neg.get_physical_size(), PhysicalSize::new(0, 0));
969

            
970
        // NaN -> 0, +inf -> u32::MAX (saturating float->int cast, no UB).
971
        let nan = WindowSize {
972
            dimensions: LogicalSize::new(f32::NAN, f32::INFINITY),
973
            ..WindowSize::default()
974
        };
975
        assert_eq!(nan.get_physical_size(), PhysicalSize::new(0, u32::MAX));
976

            
977
        // f32::MAX at 4x scale overflows u32 -> saturates, never wraps to a small value.
978
        let huge = WindowSize {
979
            dimensions: LogicalSize::new(f32::MAX, f32::MAX),
980
            dpi: 384,
981
            ..WindowSize::default()
982
        };
983
        assert_eq!(
984
            huge.get_physical_size(),
985
            PhysicalSize::new(u32::MAX, u32::MAX)
986
        );
987

            
988
        // The normal path: 96 DPI is 1:1, 192 DPI doubles.
989
        let normal = WindowSize::default();
990
        assert_eq!(normal.get_physical_size(), PhysicalSize::new(640, 480));
991
        let retina = WindowSize {
992
            dpi: 192,
993
            ..WindowSize::default()
994
        };
995
        assert_eq!(retina.get_physical_size(), PhysicalSize::new(1280, 960));
996
    }
997

            
998
    #[test]
999
    fn window_size_get_hidpi_factor_is_never_zero_or_negative() {
        // A 0.0 factor would divide-by-zero in to_logical(); the getter guards dpi == 0.
        for dpi in [
            0u32,
            1,
            47,
            48,
            95,
            96,
            97,
            120,
            144,
            192,
            384,
            u32::from(u16::MAX),
            u32::MAX,
        ] {
            let ws = WindowSize {
                dpi,
                ..WindowSize::default()
            };
            let f = ws.get_hidpi_factor().inner.get();
            assert!(
                f.is_finite() && f > 0.0,
                "dpi {dpi} produced a non-positive / non-finite scale factor: {f}"
            );
        }
        // Exactly representable factors must be exact (no quantization drift).
        for (dpi, expected) in [
            (0u32, 1.0f32),
            (96, 1.0),
            (144, 1.5),
            (192, 2.0),
            (384, 4.0),
        ] {
            let ws = WindowSize {
                dpi,
                ..WindowSize::default()
            };
            assert_eq!(ws.get_hidpi_factor().inner.get(), expected, "dpi {dpi}");
        }
        // Non-representable factors stay within FloatValue's 1/1000 quantization.
        let odd = WindowSize {
            dpi: 100,
            ..WindowSize::default()
        };
        let f = odd.get_hidpi_factor().inner.get();
        assert!((f - 100.0 / 96.0).abs() < 0.002, "dpi 100 -> {f}");
    }
    // ---------------------------------------------------------------------
    // VirtualKeyCode: from_u32 / get_lowercase
    // ---------------------------------------------------------------------
    #[test]
    fn virtual_keycode_from_u32_roundtrips_every_discriminant() {
        for v in 0..=LAST_VK {
            let vk = VirtualKeyCode::from_u32(v)
                .unwrap_or_else(|| panic!("discriminant {v} is missing from the from_u32 table"));
            assert_eq!(vk as u32, v, "from_u32({v}) does not round-trip");
        }
        // First and last declared variants anchor the table.
        assert_eq!(VirtualKeyCode::Key1 as u32, 0);
        assert_eq!(VirtualKeyCode::Cut as u32, LAST_VK);
    }
    #[test]
    fn virtual_keycode_from_u32_rejects_out_of_range() {
        for v in [
            LAST_VK + 1,
            LAST_VK + 2,
            255,
            256,
            1024,
            i32::MAX as u32,
            u32::MAX - 1,
            u32::MAX,
        ] {
            assert_eq!(
                VirtualKeyCode::from_u32(v),
                None,
                "{v} must not decode to a keycode"
            );
        }
    }
    #[test]
    fn virtual_keycode_get_lowercase_never_panics_and_maps_letters_and_digits() {
        // Exhaustive: no keycode may panic, and any produced char is ASCII.
        for v in 0..=LAST_VK {
            let vk = VirtualKeyCode::from_u32(v).expect("discriminant in range");
            if let Some(c) = vk.get_lowercase() {
                assert!(c.is_ascii(), "{vk:?} produced a non-ASCII char {c:?}");
                assert!(!c.is_ascii_uppercase(), "{vk:?} must yield lowercase");
            }
        }
        // Letters A..Z are discriminants 10..=35 and map to 'a'..='z'.
        for (i, expected) in ('a'..='z').enumerate() {
            let vk = VirtualKeyCode::from_u32(10 + i as u32).expect("letter range");
            assert_eq!(vk.get_lowercase(), Some(expected));
        }
        // Digits: both the top row and the numpad map to the same char.
        for (top, pad, c) in [
            (VirtualKeyCode::Key0, VirtualKeyCode::Numpad0, '0'),
            (VirtualKeyCode::Key1, VirtualKeyCode::Numpad1, '1'),
            (VirtualKeyCode::Key5, VirtualKeyCode::Numpad5, '5'),
            (VirtualKeyCode::Key9, VirtualKeyCode::Numpad9, '9'),
        ] {
            assert_eq!(top.get_lowercase(), Some(c));
            assert_eq!(pad.get_lowercase(), Some(c));
        }
        // Punctuation that IS mapped.
        assert_eq!(VirtualKeyCode::Minus.get_lowercase(), Some('-'));
        assert_eq!(VirtualKeyCode::Period.get_lowercase(), Some('.'));
        assert_eq!(VirtualKeyCode::Slash.get_lowercase(), Some('/'));
        assert_eq!(VirtualKeyCode::Caret.get_lowercase(), Some('^'));
        // Non-character keys have no lowercase form.
        for vk in [
            VirtualKeyCode::LShift,
            VirtualKeyCode::RControl,
            VirtualKeyCode::Escape,
            VirtualKeyCode::F12,
            VirtualKeyCode::Space,
            VirtualKeyCode::Return,
            VirtualKeyCode::Back,
        ] {
            assert_eq!(vk.get_lowercase(), None, "{vk:?}");
        }
    }
    // ---------------------------------------------------------------------
    // WindowIcon::get_key + key-only Eq/Ord/Hash
    // ---------------------------------------------------------------------
    #[test]
    fn window_icon_get_key_returns_the_stored_key() {
        let small_key = IconKey::new();
        let large_key = IconKey::new();
        let small = WindowIcon::Small(SmallWindowIconBytes {
            key: small_key,
            rgba_bytes: vec![0u8; 16 * 16 * 4].into(),
        });
        let large = WindowIcon::Large(LargeWindowIconBytes {
            key: large_key,
            rgba_bytes: vec![255u8; 32 * 32 * 4].into(),
        });
        assert_eq!(small.get_key(), small_key);
        assert_eq!(large.get_key(), large_key);
        // Empty payloads are legal and must not panic.
        let empty = WindowIcon::Small(SmallWindowIconBytes {
            key: small_key,
            rgba_bytes: vec![].into(),
        });
        assert_eq!(empty.get_key(), small_key);
    }
    #[test]
    fn window_icon_identity_is_the_key_alone() {
        // The whole point of IconKey: diff the key, not the bytes. Two icons with
        // the same key compare equal even though their pixels differ.
        let key = IconKey::new();
        let a = WindowIcon::Small(SmallWindowIconBytes {
            key,
            rgba_bytes: vec![0u8; 4].into(),
        });
        let b = WindowIcon::Small(SmallWindowIconBytes {
            key,
            rgba_bytes: vec![7u8; 1024].into(),
        });
        // ...even across the Small/Large variants.
        let c = WindowIcon::Large(LargeWindowIconBytes {
            key,
            rgba_bytes: vec![9u8; 32 * 32 * 4].into(),
        });
        assert_eq!(a, b);
        assert_eq!(a, c);
        assert_eq!(a.cmp(&c), Ordering::Equal);
        assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal));
        // Hash must agree with Eq, or icons break as BTreeMap/HashMap keys.
        assert_eq!(hash_of(&a), hash_of(&b));
        assert_eq!(hash_of(&a), hash_of(&c));
        // Different keys: unequal, and ordered by key.
        let older = WindowIcon::Small(SmallWindowIconBytes {
            key,
            rgba_bytes: vec![0u8; 4].into(),
        });
        let newer = WindowIcon::Small(SmallWindowIconBytes {
            key: IconKey::new(),
            rgba_bytes: vec![0u8; 4].into(),
        });
        assert_ne!(older, newer);
        assert_eq!(older.cmp(&newer), Ordering::Less);
    }
    // ---------------------------------------------------------------------
    // UpdateFocusWarning: Display
    // ---------------------------------------------------------------------
    #[test]
    fn update_focus_warning_display_is_non_empty_for_every_variant() {
        let dom = format!("{}", UpdateFocusWarning::FocusInvalidDomId(DomId::ROOT_ID));
        assert!(dom.contains("invalid ID"), "{dom}");
        assert!(!dom.is_empty());
        let node = format!(
            "{}",
            UpdateFocusWarning::FocusInvalidNodeId(NodeHierarchyItemId::NONE)
        );
        assert!(node.contains("invalid ID"), "{node}");
        // Edge values: a zero DomId, a raw-encoded huge node id, an empty CssPath.
        let huge = format!(
            "{}",
            UpdateFocusWarning::FocusInvalidNodeId(NodeHierarchyItemId::from_raw(usize::MAX))
        );
        assert!(!huge.is_empty());
        let path = format!(
            "{}",
            UpdateFocusWarning::CouldNotFindFocusNode(CssPath::default())
        );
        assert!(
            path.starts_with("Could not find focus node for path:"),
            "{path}"
        );
    }
}