1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(clippy::float_cmp, clippy::too_many_lines)]
5
mod autotest_generated {
6
    use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};
7

            
8
    use super::*;
9
    use crate::{dom::NodeDataVec, styled_dom::StyledNodeVec};
10

            
11
    // Test payloads. The names `ImageIconData` / `FontIconData` are load-bearing:
12
    // `debug_lookup` sniffs `RefAny::get_type_name()` (i.e. `core::any::type_name`)
13
    // for those substrings.
14
    #[derive(Debug, Clone, PartialEq)]
15
    struct TestIconData {
16
        id: u32,
17
    }
18
    #[derive(Debug)]
19
    struct ImageIconData {
20
        _w: u32,
21
    }
22
    #[derive(Debug)]
23
    struct FontIconData {
24
        _codepoint: u32,
25
    }
26

            
27
    /// Empty / control / unicode / huge names, all of which are legal icon names
28
    /// (the API places no constraints on them).
29
    fn adversarial_names() -> Vec<String> {
30
        vec![
31
            String::new(),
32
            String::from(" "),
33
            String::from("   "),
34
            String::from("\t\n\r"),
35
            String::from("\0"),
36
            String::from("a\0b"),
37
            String::from("\u{1b}[0m"),
38
            String::from("../../etc/passwd"),
39
            String::from("home;garbage"),
40
            String::from("{\"json\":true}"),
41
            String::from("-0"),
42
            String::from("NaN"),
43
            String::from("inf"),
44
            String::from("9223372036854775807"),
45
            String::from("\u{1F600}"),           // emoji
46
            String::from("e\u{0301}\u{0301}"),   // combining marks
47
            String::from("\u{202e}RTL\u{202d}"), // bidi override
48
            String::from("\u{130}"),             // LATIN CAPITAL I WITH DOT ABOVE
49
            String::from("\u{FFFD}\u{10FFFF}"),  // replacement + max scalar
50
            "[".repeat(10_000),                  // deeply "nested" junk
51
            "x".repeat(100_000),                 // huge
52
        ]
53
    }
54

            
55
    // Resolvers
56

            
57
    extern "C" fn div_resolver(
58
        _icon_data: OptionRefAny,
59
        _original_icon_node: &NodeData,
60
        _system_style: &SystemStyle,
61
    ) -> Dom {
62
        Dom::create_div()
63
    }
64

            
65
    // Statics for `shared_resolve_receives_icon_data_and_original_dom` ONLY.
66
    // (`extern "C" fn` cannot capture, and tests run in parallel — never share
67
    // one recording resolver between two tests.)
68
    static REC_CALLS: AtomicUsize = AtomicUsize::new(0);
69
    static REC_SAW_DATA: AtomicBool = AtomicBool::new(false);
70
    static REC_SAW_ICON_NODE: AtomicBool = AtomicBool::new(false);
71
    static REC_NAME_LEN: AtomicUsize = AtomicUsize::new(0);
72

            
73
    extern "C" fn recording_resolver(
74
        icon_data: OptionRefAny,
75
        original_icon_node: &NodeData,
76
        _system_style: &SystemStyle,
77
    ) -> Dom {
78
        REC_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
79
        if matches!(icon_data, OptionRefAny::Some(_)) {
80
            REC_SAW_DATA.store(true, AtomicOrdering::SeqCst);
81
        }
82
        if let NodeType::Icon(name) = original_icon_node.get_node_type() {
83
            REC_SAW_ICON_NODE.store(true, AtomicOrdering::SeqCst);
84
            REC_NAME_LEN.store(name.as_ref().as_str().len(), AtomicOrdering::SeqCst);
85
        }
86
        Dom::create_div()
87
    }
88

            
89
    // Mutex (the no_std spinlock under `no_std`, `std::sync::Mutex` otherwise)
90

            
91
    #[test]
92
    fn mutex_new_then_lock_roundtrips_the_value() {
93
        let m = Mutex::new(42u32);
94
        assert_eq!(*m.lock().unwrap(), 42);
95
        *m.lock().unwrap() = u32::MAX;
96
        assert_eq!(*m.lock().unwrap(), u32::MAX);
97
    }
98

            
99
    #[test]
100
    fn mutex_lock_on_empty_and_large_payloads() {
101
        let empty: Mutex<Vec<u8>> = Mutex::new(Vec::new());
102
        assert!(empty.lock().unwrap().is_empty());
103

            
104
        let big = Mutex::new(vec![0u8; 1_000_000]);
105
        assert_eq!(big.lock().unwrap().len(), 1_000_000);
106

            
107
        // Sequential re-lock must not deadlock (guard dropped at end of statement).
108
        for _ in 0..1_000 {
109
            assert!(big.lock().is_ok());
110
        }
111
    }
112

            
113
    // default_icon_resolver
114

            
115
    #[test]
116
    fn default_resolver_returns_a_single_empty_div_for_none_and_some() {
117
        let orig = Dom::create_div().root;
118
        let style = SystemStyle::default();
119

            
120
        // The core default resolver renders nothing; azul-layout installs the
121
        // real one that understands image / font / Dom icon data.
122
        let none = default_icon_resolver(OptionRefAny::None, &orig, &style);
123
        assert!(matches!(none.root.get_node_type(), NodeType::Div));
124
        assert!(none.children.as_ref().is_empty());
125

            
126
        let some = default_icon_resolver(
127
            OptionRefAny::Some(RefAny::new(TestIconData { id: 1 })),
128
            &orig,
129
            &style,
130
        );
131
        assert!(matches!(some.root.get_node_type(), NodeType::Div));
132
        assert!(some.children.as_ref().is_empty());
133
    }
134

            
135
    // IconProviderHandle: construction / invariants
136

            
137
    #[test]
138
    fn new_handle_is_empty_and_all_queries_are_negative() {
139
        let h = IconProviderHandle::new();
140
        assert!(h.list_packs().is_empty());
141
        assert!(h.list_icons_in_pack("anything").is_empty());
142
        assert!(!h.has_icon("home"));
143
        assert!(h.lookup("home").is_none());
144
        assert!(h.lookup_with_pack("home").is_none());
145
        assert!(h.debug_lookup("home").as_str().contains("Total packs: 0"));
146
    }
147

            
148
    #[test]
149
    fn default_handle_matches_new_handle() {
150
        let a = IconProviderHandle::default();
151
        let b = IconProviderHandle::new();
152
        assert_eq!(a.list_packs(), b.list_packs());
153
        assert_eq!(a.has_icon(""), b.has_icon(""));
154
    }
155

            
156
    #[test]
157
    fn with_resolver_installs_the_callback() {
158
        let mut h = IconProviderHandle::with_resolver(div_resolver);
159
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
160
        let shared = SharedIconProvider::from_handle(h);
161
        let out = shared.resolve(&Dom::create_div().root, "home", &SystemStyle::default());
162
        assert!(matches!(out.root.get_node_type(), NodeType::Div));
163
    }
164

            
165
    #[test]
166
    fn set_resolver_overrides_the_default_resolver() {
167
        let mut h = IconProviderHandle::new();
168
        h.set_resolver(div_resolver);
169
        let shared = SharedIconProvider::from_handle(h);
170
        // Unregistered icon: resolver still runs, just with `None` data.
171
        let out = shared.resolve(&Dom::create_div().root, "missing", &SystemStyle::default());
172
        assert!(matches!(out.root.get_node_type(), NodeType::Div));
173
    }
174

            
175
    #[test]
176
    fn clone_of_handle_is_deep() {
177
        let mut a = IconProviderHandle::new();
178
        a.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
179

            
180
        let mut b = a.clone();
181
        b.register_icon("p", "settings", RefAny::new(TestIconData { id: 2 }));
182
        b.unregister_icon("p", "home");
183

            
184
        assert!(a.has_icon("home"));
185
        assert!(!a.has_icon("settings"));
186
        assert!(b.has_icon("settings"));
187
        assert!(!b.has_icon("home"));
188
    }
189

            
190
    #[test]
191
    fn drop_of_clones_and_originals_is_safe() {
192
        // Guards the ManuallyDrop / run_destructor convention (see the type's docs).
193
        let mut a = IconProviderHandle::new();
194
        a.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
195
        for _ in 0..100 {
196
            let c = a.clone();
197
            drop(c);
198
        }
199
        assert!(a.has_icon("home"));
200
        drop(a);
201
    }
202

            
203
    // register / unregister
204

            
205
    #[test]
206
    fn register_icon_lowercases_icon_name_but_not_pack_name() {
207
        let mut h = IconProviderHandle::new();
208
        h.register_icon("MyPack", "HoMe", RefAny::new(TestIconData { id: 1 }));
209

            
210
        assert_eq!(h.list_packs(), vec![String::from("MyPack")]);
211
        assert!(h
212
            .list_icons_in_pack("MyPack")
213
            .contains(&String::from("home")));
214
        // Pack name is case-sensitive:
215
        assert!(h.list_icons_in_pack("mypack").is_empty());
216
        // Icon name is not:
217
        assert!(h.has_icon("HOME"));
218
        assert!(h.has_icon("home"));
219
        assert!(h.has_icon("hOmE"));
220
    }
221

            
222
    #[test]
223
    fn registering_the_same_icon_twice_overwrites_instead_of_duplicating() {
224
        let mut h = IconProviderHandle::new();
225
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
226
        h.register_icon("p", "HOME", RefAny::new(TestIconData { id: 2 }));
227

            
228
        assert_eq!(h.list_icons_in_pack("p").len(), 1);
229
        let mut data = h.lookup("home").expect("icon must exist");
230
        assert_eq!(data.downcast_ref::<TestIconData>().unwrap().id, 2);
231
    }
232

            
233
    #[test]
234
    fn unregister_icon_drops_the_pack_once_it_is_empty() {
235
        let mut h = IconProviderHandle::new();
236
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
237
        h.register_icon("p", "settings", RefAny::new(TestIconData { id: 2 }));
238

            
239
        h.unregister_icon("p", "HOME"); // case-insensitive on the icon name
240
        assert_eq!(h.list_packs(), vec![String::from("p")]);
241
        assert!(!h.has_icon("home"));
242

            
243
        h.unregister_icon("p", "settings");
244
        assert!(h.list_packs().is_empty(), "pack must be pruned when empty");
245
    }
246

            
247
    #[test]
248
    fn unregister_of_unknown_pack_or_icon_is_a_no_op() {
249
        let mut h = IconProviderHandle::new();
250
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
251

            
252
        h.unregister_icon("nonexistent-pack", "home");
253
        h.unregister_icon("p", "nonexistent-icon");
254
        h.unregister_pack("nonexistent-pack");
255
        h.unregister_pack("");
256
        h.unregister_icon("", "");
257

            
258
        assert!(h.has_icon("home"));
259
        assert_eq!(h.list_packs().len(), 1);
260
    }
261

            
262
    #[test]
263
    fn unregister_pack_removes_all_of_its_icons() {
264
        let mut h = IconProviderHandle::new();
265
        h.register_icon("p", "a", RefAny::new(TestIconData { id: 1 }));
266
        h.register_icon("p", "b", RefAny::new(TestIconData { id: 2 }));
267
        h.register_icon("q", "a", RefAny::new(TestIconData { id: 3 }));
268

            
269
        h.unregister_pack("p");
270
        assert_eq!(h.list_packs(), vec![String::from("q")]);
271
        // "a" still resolvable via the other pack.
272
        assert!(h.has_icon("a"));
273
        assert!(!h.has_icon("b"));
274
    }
275

            
276
    #[test]
277
    fn adversarial_names_roundtrip_through_register_lookup_unregister() {
278
        for (i, name) in adversarial_names().iter().enumerate() {
279
            let mut h = IconProviderHandle::new();
280
            h.register_icon("p", name, RefAny::new(TestIconData { id: i as u32 }));
281

            
282
            assert!(h.has_icon(name), "has_icon failed for name #{i}");
283
            let mut data = h
284
                .lookup(name)
285
                .unwrap_or_else(|| panic!("lookup failed for name #{i}"));
286
            assert_eq!(data.downcast_ref::<TestIconData>().unwrap().id, i as u32);
287

            
288
            h.unregister_icon("p", name);
289
            assert!(!h.has_icon(name), "unregister failed for name #{i}");
290
            assert!(h.list_packs().is_empty());
291
        }
292
    }
293

            
294
    #[test]
295
    fn empty_pack_name_and_empty_icon_name_are_legal_keys() {
296
        let mut h = IconProviderHandle::new();
297
        h.register_icon("", "", RefAny::new(TestIconData { id: 9 }));
298

            
299
        assert_eq!(h.list_packs(), vec![String::new()]);
300
        assert_eq!(h.list_icons_in_pack(""), vec![String::new()]);
301
        assert!(h.has_icon(""));
302
        let (pack, _) = h.lookup_with_pack("").expect("empty key must be found");
303
        assert_eq!(pack, "");
304
    }
305

            
306
    // lookup / lookup_with_pack (parser-shaped adversarial cases)
307

            
308
    #[test]
309
    fn lookup_empty_input_returns_none() {
310
        let mut h = IconProviderHandle::new();
311
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
312
        assert!(h.lookup("").is_none());
313
        assert!(h.lookup_with_pack("").is_none());
314
        assert!(!h.has_icon(""));
315
    }
316

            
317
    #[test]
318
    fn lookup_whitespace_only_is_not_trimmed() {
319
        let mut h = IconProviderHandle::new();
320
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
321
        for ws in ["   ", "\t\n", "\r", "\u{a0}"] {
322
            assert!(h.lookup(ws).is_none(), "{ws:?} must not match");
323
        }
324
        // ...and a whitespace-only *registered* name matches only itself, verbatim.
325
        h.register_icon("p", "   ", RefAny::new(TestIconData { id: 2 }));
326
        assert!(h.lookup("   ").is_some());
327
        assert!(h.lookup(" ").is_none());
328
        assert!(h.lookup("").is_none());
329
    }
330

            
331
    #[test]
332
    fn lookup_garbage_returns_none_but_spec_whitespace_is_tolerated() {
333
        let mut h = IconProviderHandle::new();
334
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
335

            
336
        // Genuine garbage must never match 'home'.
337
        for junk in [
338
            "home;garbage",
339
            "home\0",
340
            "\0home",
341
            "ho\nme",
342
            "home/../../etc/passwd",
343
            "\u{1b}[31mhome\u{1b}[0m",
344
            "{\"icon\":\"home\"}",
345
        ] {
346
            assert!(h.lookup(junk).is_none(), "{junk:?} must not match 'home'");
347
            assert!(!h.has_icon(junk));
348
        }
349

            
350
        // Spec normalization: surrounding whitespace is trimmed per entry —
351
        // `<icon> home </icon>` markup must resolve (ligature-font model).
352
        for spec in [" home ", "home ", " home"] {
353
            assert!(
354
                h.lookup(spec).is_some(),
355
                "{spec:?} must resolve via spec trim"
356
            );
357
            assert!(h.has_icon(spec));
358
        }
359
        assert!(h.lookup("home").is_some(), "positive control");
360
    }
361

            
362
    #[test]
363
    fn lookup_of_extremely_long_name_terminates_and_matches_exactly() {
364
        let mut h = IconProviderHandle::new();
365
        let long = "x".repeat(1_000_000);
366
        h.register_icon("p", &long, RefAny::new(TestIconData { id: 7 }));
367

            
368
        assert!(h.lookup(&long).is_some());
369
        assert!(h.has_icon(&long));
370
        // One char shorter -> no match, still no panic/hang.
371
        assert!(h.lookup(&"x".repeat(999_999)).is_none());
372
        // A 1M-char miss against a small map.
373
        let mut h2 = IconProviderHandle::new();
374
        h2.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
375
        assert!(h2.lookup(&long).is_none());
376
    }
377

            
378
    #[test]
379
    fn lookup_of_boundary_numeric_strings_is_deterministic() {
380
        let mut h = IconProviderHandle::new();
381
        for (i, n) in [
382
            "0",
383
            "-0",
384
            "9223372036854775807",
385
            "-9223372036854775808",
386
            "nan",
387
            "inf",
388
        ]
389
        .iter()
390
        .enumerate()
391
        {
392
            h.register_icon("p", n, RefAny::new(TestIconData { id: i as u32 }));
393
        }
394
        // Numeric-looking names are plain string keys: no numeric parsing, no coercion.
395
        assert!(h.lookup("0").is_some());
396
        assert!(h.lookup("-0").is_some());
397
        assert!(h.lookup("0.0").is_none());
398
        assert!(h.lookup("00").is_none());
399
        assert!(h.lookup("+0").is_none());
400
        assert!(h.lookup("9223372036854775808").is_none()); // i64::MAX + 1
401
                                                            // ...but case folding still applies.
402
        assert!(h.lookup("NaN").is_some());
403
        assert!(h.lookup("INF").is_some());
404
    }
405

            
406
    #[test]
407
    fn lookup_of_unicode_names_folds_case_without_panicking() {
408
        let mut h = IconProviderHandle::new();
409
        h.register_icon("p", "\u{1F600}", RefAny::new(TestIconData { id: 1 }));
410
        h.register_icon("p", "\u{C4}", RefAny::new(TestIconData { id: 2 })); // Ä
411
        h.register_icon("p", "I", RefAny::new(TestIconData { id: 3 }));
412

            
413
        assert!(h.lookup("\u{1F600}").is_some(), "emoji key must round-trip");
414
        assert!(h.lookup("\u{E4}").is_some(), "ä must match registered Ä");
415
        assert!(h.lookup("i").is_some(), "I folds to i");
416

            
417
        // `str::to_lowercase` is full-Unicode: "İ" (U+0130) folds to TWO scalars
418
        // ("i" + U+0307), so the *stored key is not the registered string*.
419
        let mut h2 = IconProviderHandle::new();
420
        h2.register_icon("p", "\u{130}", RefAny::new(TestIconData { id: 4 }));
421
        assert!(
422
            h2.lookup("\u{130}").is_some(),
423
            "self-lookup must still work"
424
        );
425
        let keys = h2.list_icons_in_pack("p");
426
        assert_eq!(keys, vec![String::from("\u{130}").to_lowercase()]);
427
        assert!(
428
            !keys.contains(&String::from("\u{130}")),
429
            "key is stored folded, not verbatim"
430
        );
431
        assert!(
432
            h2.lookup("i").is_none(),
433
            "the bare ASCII 'i' must not match İ"
434
        );
435
    }
436

            
437
    #[test]
438
    fn lookup_of_deeply_nested_input_does_not_stack_overflow() {
439
        let h = IconProviderHandle::new();
440
        // Lookup is a map probe, not a recursive-descent parse: depth is irrelevant,
441
        // but assert it explicitly so a future parsing implementation stays flat.
442
        for depth in [1_000usize, 10_000, 100_000] {
443
            let nested = "[".repeat(depth);
444
            assert!(h.lookup(&nested).is_none());
445
            assert!(!h.has_icon(&nested));
446
            assert!(h.debug_lookup(&nested).as_str().contains("NOT FOUND"));
447
        }
448
    }
449

            
450
    #[test]
451
    fn lookup_valid_minimal_positive_control_roundtrips_the_payload() {
452
        let mut h = IconProviderHandle::new();
453
        h.register_icon("p", "a", RefAny::new(TestIconData { id: 123 }));
454

            
455
        let mut data = h.lookup("a").expect("registered icon must be found");
456
        assert_eq!(
457
            *data.downcast_ref::<TestIconData>().unwrap(),
458
            TestIconData { id: 123 }
459
        );
460
        // Wrong-type downcast must fail rather than reinterpret the bytes.
461
        assert!(data.downcast_ref::<u64>().is_none());
462
    }
463

            
464
    #[test]
465
    fn lookup_with_pack_first_match_is_the_lexicographically_first_pack() {
466
        let mut h = IconProviderHandle::new();
467
        // Register in reverse-alphabetical order: insertion order must NOT decide.
468
        h.register_icon("zzz", "home", RefAny::new(TestIconData { id: 26 }));
469
        h.register_icon("mmm", "home", RefAny::new(TestIconData { id: 13 }));
470
        h.register_icon("aaa", "home", RefAny::new(TestIconData { id: 1 }));
471

            
472
        let (pack, _) = h.lookup_with_pack("HOME").expect("must be found");
473
        assert_eq!(
474
            pack, "aaa",
475
            "BTreeMap order => first match is the first pack by name"
476
        );
477

            
478
        let mut data = h.lookup("home").unwrap();
479
        assert_eq!(data.downcast_ref::<TestIconData>().unwrap().id, 1);
480

            
481
        // Removing the winner promotes the next pack in order.
482
        h.unregister_pack("aaa");
483
        let (pack, _) = h.lookup_with_pack("home").unwrap();
484
        assert_eq!(pack, "mmm");
485
    }
486

            
487
    // has_icon
488

            
489
    #[test]
490
    fn has_icon_true_false_and_edge_inputs() {
491
        let mut h = IconProviderHandle::new();
492
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
493

            
494
        assert!(h.has_icon("home"));
495
        assert!(!h.has_icon("definitely-not-registered"));
496

            
497
        for name in adversarial_names() {
498
            // Deterministic bool, no panic: none of these were registered.
499
            assert!(!h.has_icon(&name));
500
        }
501
        assert!(h.has_icon("home"), "state unchanged by the queries above");
502
    }
503

            
504
    // getters: list_packs / list_icons_in_pack
505

            
506
    #[test]
507
    fn list_packs_is_sorted_and_case_sensitive() {
508
        let mut h = IconProviderHandle::new();
509
        for p in ["zeta", "alpha", "Alpha", "mid", ""] {
510
            h.register_icon(p, "home", RefAny::new(TestIconData { id: 0 }));
511
        }
512
        // BTreeMap => byte-order sorted; "Alpha" != "alpha" (case-sensitive).
513
        assert_eq!(
514
            h.list_packs(),
515
            vec![
516
                String::new(),
517
                String::from("Alpha"),
518
                String::from("alpha"),
519
                String::from("mid"),
520
                String::from("zeta"),
521
            ]
522
        );
523
    }
524

            
525
    #[test]
526
    fn list_icons_in_pack_returns_folded_keys_and_empty_for_unknown_packs() {
527
        let mut h = IconProviderHandle::new();
528
        h.register_icon("p", "Zoom", RefAny::new(TestIconData { id: 1 }));
529
        h.register_icon("p", "HOME", RefAny::new(TestIconData { id: 2 }));
530

            
531
        assert_eq!(
532
            h.list_icons_in_pack("p"),
533
            vec![String::from("home"), String::from("zoom")]
534
        );
535
        assert!(h.list_icons_in_pack("P").is_empty());
536
        assert!(h.list_icons_in_pack("").is_empty());
537
        assert!(h.list_icons_in_pack(&"x".repeat(100_000)).is_empty());
538
    }
539

            
540
    // debug_lookup
541

            
542
    #[test]
543
    fn debug_lookup_reports_not_found_for_missing_icons() {
544
        let mut h = IconProviderHandle::new();
545
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
546

            
547
        let out = h.debug_lookup("settings");
548
        let s = out.as_str();
549
        assert!(s.contains("NOT FOUND in any pack"));
550
        assert!(s.contains("Total packs: 1"));
551
        assert!(s.contains("Pack 'p': 1 icons"));
552
    }
553

            
554
    #[test]
555
    fn debug_lookup_classifies_image_font_and_unknown_refany_types() {
556
        let mut h = IconProviderHandle::new();
557
        h.register_icon("p", "img", RefAny::new(ImageIconData { _w: 16 }));
558
        h.register_icon("p", "fnt", RefAny::new(FontIconData { _codepoint: 0xF015 }));
559
        h.register_icon("p", "other", RefAny::new(TestIconData { id: 1 }));
560

            
561
        let img = h.debug_lookup("img");
562
        assert!(img.as_str().contains("FOUND in pack 'p'"));
563
        assert!(img.as_str().contains("RefAny type: ImageIconData"));
564

            
565
        let fnt = h.debug_lookup("FNT"); // case-folded lookup path
566
        assert!(fnt.as_str().contains("RefAny type: FontIconData"));
567

            
568
        let other = h.debug_lookup("other");
569
        assert!(other.as_str().contains("RefAny type: UNKNOWN"));
570
    }
571

            
572
    #[test]
573
    fn debug_lookup_survives_adversarial_names() {
574
        let mut h = IconProviderHandle::new();
575
        for (i, name) in adversarial_names().iter().enumerate() {
576
            h.register_icon("p", name, RefAny::new(TestIconData { id: i as u32 }));
577
        }
578
        for name in adversarial_names() {
579
            let out = h.debug_lookup(&name);
580
            assert!(
581
                out.as_str().contains("FOUND in pack 'p'"),
582
                "must find {name:?}"
583
            );
584
        }
585
        assert!(h
586
            .debug_lookup("never-registered")
587
            .as_str()
588
            .contains("NOT FOUND"));
589
    }
590

            
591
    // SharedIconProvider
592

            
593
    #[test]
594
    fn from_handle_preserves_every_registered_icon() {
595
        let mut h = IconProviderHandle::new();
596
        for i in 0..64u32 {
597
            h.register_icon(
598
                "p",
599
                &format!("icon{i}"),
600
                RefAny::new(TestIconData { id: i }),
601
            );
602
        }
603
        let shared = SharedIconProvider::from_handle(h);
604

            
605
        for i in 0..64u32 {
606
            let name = format!("ICON{i}");
607
            assert!(shared.has_icon(&name));
608
            let mut data = shared.lookup(&name).expect("must survive into_shared()");
609
            assert_eq!(data.downcast_ref::<TestIconData>().unwrap().id, i);
610
        }
611
        assert!(!shared.has_icon("icon64"));
612
        assert!(shared.lookup("").is_none());
613
    }
614

            
615
    #[test]
616
    fn shared_provider_lookup_and_has_icon_agree_on_adversarial_input() {
617
        let mut h = IconProviderHandle::new();
618
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
619
        let shared = SharedIconProvider::from_handle(h);
620

            
621
        for name in adversarial_names() {
622
            assert_eq!(
623
                shared.has_icon(&name),
624
                shared.lookup(&name).is_some(),
625
                "has_icon/lookup disagree for {name:?}"
626
            );
627
        }
628
        assert!(shared.has_icon("HoMe") && shared.lookup("HoMe").is_some());
629
    }
630

            
631
    #[test]
632
    fn shared_provider_clone_shares_the_same_icon_table() {
633
        let mut h = IconProviderHandle::new();
634
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
635
        let a = SharedIconProvider::from_handle(h);
636
        let b = a.clone();
637

            
638
        assert!(b.has_icon("home"));
639
        drop(a);
640
        assert!(b.has_icon("home"), "clone must keep the Arc alive");
641
        let mut data = b.lookup("home").unwrap();
642
        assert_eq!(data.downcast_ref::<TestIconData>().unwrap().id, 1);
643
    }
644

            
645
    #[test]
646
    fn shared_resolve_receives_icon_data_and_original_dom() {
647
        let mut h = IconProviderHandle::with_resolver(recording_resolver);
648
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
649
        let shared = SharedIconProvider::from_handle(h);
650

            
651
        // The resolver is handed the ICON NODE itself now, not a one-node
652
        // StyledDom carved out of the tree.
653
        let icon_node = Dom::create_icon("home").root;
654

            
655
        let out = shared.resolve(&icon_node, "HOME", &SystemStyle::default());
656

            
657
        assert!(REC_CALLS.load(AtomicOrdering::SeqCst) >= 1);
658
        assert!(
659
            REC_SAW_DATA.load(AtomicOrdering::SeqCst),
660
            "case-folded lookup must pass Some(data)"
661
        );
662
        assert!(
663
            REC_SAW_ICON_NODE.load(AtomicOrdering::SeqCst),
664
            "the resolver must receive the Icon node"
665
        );
666
        assert_eq!(REC_NAME_LEN.load(AtomicOrdering::SeqCst), "home".len());
667
        assert!(matches!(out.root.get_node_type(), NodeType::Div));
668
    }
669

            
670
    #[test]
671
    fn shared_resolve_runs_the_resolver_even_when_the_icon_is_missing() {
672
        let h = IconProviderHandle::with_resolver(div_resolver);
673
        let shared = SharedIconProvider::from_handle(h);
674
        // Empty name, huge name, unicode name: resolver still returns its DOM.
675
        let huge = "x".repeat(100_000);
676
        for name in ["", "\u{1F600}", huge.as_str()] {
677
            let out = shared.resolve(&Dom::create_div().root, name, &SystemStyle::default());
678
            assert!(matches!(out.root.get_node_type(), NodeType::Div));
679
        }
680
    }
681

            
682
    #[cfg(feature = "std")]
683
    #[test]
684
    fn shared_provider_survives_concurrent_lookups() {
685
        let mut h = IconProviderHandle::new();
686
        for i in 0..16u32 {
687
            h.register_icon(
688
                "p",
689
                &format!("icon{i}"),
690
                RefAny::new(TestIconData { id: i }),
691
            );
692
        }
693
        let shared = SharedIconProvider::from_handle(h);
694

            
695
        let mut threads = Vec::new();
696
        for _ in 0..4 {
697
            let s = shared.clone();
698
            threads.push(std::thread::spawn(move || {
699
                let mut hits = 0usize;
700
                for i in 0..200u32 {
701
                    let name = format!("icon{}", i % 16);
702
                    if s.has_icon(&name) {
703
                        hits += 1;
704
                    }
705
                    let mut data = s.lookup(&name).expect("registered icon");
706
                    assert_eq!(data.downcast_ref::<TestIconData>().unwrap().id, i % 16);
707
                }
708
                hits
709
            }));
710
        }
711
        for t in threads {
712
            assert_eq!(t.join().unwrap(), 200);
713
        }
714
        assert!(shared.has_icon("icon0"), "table intact after contention");
715
    }
716

            
717
    // resolve_icons_in_dom (end to end)
718

            
719
    /// Every icon node in the tree, by the path of child indices that reaches it.
720
    fn icon_paths(dom: &Dom) -> Vec<Vec<usize>> {
721
        fn walk(d: &Dom, path: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
722
            if matches!(d.root.get_node_type(), NodeType::Icon(_)) {
723
                out.push(path.clone());
724
            }
725
            for (i, c) in d.children.as_ref().iter().enumerate() {
726
                path.push(i);
727
                walk(c, path, out);
728
                path.pop();
729
            }
730
        }
731
        let mut out = Vec::new();
732
        walk(dom, &mut Vec::new(), &mut out);
733
        out
734
    }
735

            
736
    /// The node at a child path.
737
    fn node_at<'a>(dom: &'a Dom, path: &[usize]) -> &'a Dom {
738
        let mut cur = dom;
739
        for &i in path {
740
            cur = &cur.children.as_ref()[i];
741
        }
742
        cur
743
    }
744

            
745
    fn dom_with_icons(names: &[&str]) -> Dom {
746
        let mut body = Dom::create_body();
747
        for n in names {
748
            body = body.with_child(Dom::create_icon(AzString::from(*n)));
749
        }
750
        body
751
    }
752

            
753
    #[test]
754
    fn resolve_icons_in_dom_is_a_no_op_without_icons() {
755
        let shared =
756
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(div_resolver));
757
        let mut dom = Dom::create_body().with_child(
758
            Dom::create_text_do_not_use_without_block_level_wrapper("hi"),
759
        );
760
        let before = dom.clone();
761

            
762
        resolve_icons_in_dom(&mut dom, &shared, &SystemStyle::default());
763

            
764
        assert_eq!(dom.children.as_ref().len(), before.children.as_ref().len());
765
        assert_eq!(dom.root.get_node_type(), before.root.get_node_type());
766
    }
767

            
768
    #[test]
769
    fn resolve_icons_in_dom_replaces_every_icon_case_insensitively() {
770
        let mut h = IconProviderHandle::with_resolver(div_resolver);
771
        h.register_icon("p", "home", RefAny::new(TestIconData { id: 1 }));
772
        let shared = SharedIconProvider::from_handle(h);
773

            
774
        // Mixed case in the DOM, lowercase in the pack, plus one unregistered icon.
775
        let mut dom = dom_with_icons(&["HOME", "unregistered", "HoMe"]);
776
        let paths = icon_paths(&dom);
777
        assert_eq!(paths.len(), 3);
778

            
779
        resolve_icons_in_dom(&mut dom, &shared, &SystemStyle::default());
780

            
781
        assert!(
782
            icon_paths(&dom).is_empty(),
783
            "no Icon node may survive resolution"
784
        );
785
        for p in paths {
786
            assert!(matches!(
787
                node_at(&dom, &p).root.get_node_type(),
788
                NodeType::Div
789
            ));
790
        }
791
    }
792

            
793
    #[test]
794
    fn resolve_icons_in_dom_with_the_default_resolver_removes_the_icon_nodes() {
795
        // The default resolver returns an empty div, so an icon with no
796
        // registered data becomes that rather than staying an Icon node.
797
        let shared = SharedIconProvider::from_handle(IconProviderHandle::new());
798
        let mut dom = dom_with_icons(&["home"]);
799

            
800
        resolve_icons_in_dom(&mut dom, &shared, &SystemStyle::default());
801

            
802
        assert!(icon_paths(&dom).is_empty());
803
    }
804

            
805
    /// The whole point of resolving on the tree: a replacement may be MORE than
806
    /// one node, and all of it survives. The old StyledDom splice flattened
807
    /// every replacement to its root plus a single glyph character, which is
808
    /// why registering a `Dom` as an icon was impossible.
809
    #[test]
810
    fn a_multi_node_replacement_is_spliced_in_whole() {
811
        extern "C" fn subtree_resolver(_d: OptionRefAny, _n: &NodeData, _s: &SystemStyle) -> Dom {
812
            Dom::create_div()
813
                .with_child(Dom::create_div())
814
                .with_child(Dom::create_div())
815
        }
816

            
817
        let shared =
818
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(subtree_resolver));
819
        let mut dom = dom_with_icons(&["home"]);
820
        let path = icon_paths(&dom)[0].clone();
821

            
822
        resolve_icons_in_dom(&mut dom, &shared, &SystemStyle::default());
823

            
824
        let replaced = node_at(&dom, &path);
825
        assert!(matches!(replaced.root.get_node_type(), NodeType::Div));
826
        assert_eq!(
827
            replaced.children.as_ref().len(),
828
            2,
829
            "both children of the replacement must survive the splice"
830
        );
831
    }
832

            
833
    /// REGRESSION: an icon that resolves to ANOTHER icon must keep the
834
    /// stylesheets attached along the way.
835
    ///
836
    /// `Dom::with_css` attaches a scoped stylesheet to `Dom::css`, NOT inline
837
    /// properties - so `Dom::create_icon("favorite").with_css("color: red")`,
838
    /// the natural way to register a recoloured icon, carries the colour in
839
    /// `css`. Replacing the node wholesale dropped it, and the icon rendered in
840
    /// the default colour while every step reported success.
841
    ///
842
    /// This is the mechanism that lets an icon carry its own appearance instead
843
    /// of every call site threading a tint parameter down to the renderer.
844
    #[test]
845
    fn stylesheets_survive_an_icon_resolving_to_another_icon() {
846
        extern "C" fn to_div(_d: OptionRefAny, _n: &NodeData, _s: &SystemStyle) -> Dom {
847
            Dom::create_div()
848
        }
849

            
850
        let shared = SharedIconProvider::from_handle(IconProviderHandle::with_resolver(to_div));
851
        let mut dom =
852
            Dom::create_body().with_child(Dom::create_icon("outer").with_css("color: #d7263d;"));
853

            
854
        resolve_icons_in_dom(&mut dom, &shared, &SystemStyle::default());
855

            
856
        let resolved = &dom.children.as_ref()[0];
857
        assert!(matches!(resolved.root.get_node_type(), NodeType::Div));
858
        assert!(
859
            !resolved.css.as_ref().is_empty(),
860
            "the icon's own stylesheet must survive resolution; losing it is how a styled icon \
861
             silently renders unstyled"
862
        );
863
    }
864

            
865
    #[test]
866
    fn resolve_icons_in_dom_scales_to_many_icons() {
867
        let shared =
868
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(div_resolver));
869
        let names: Vec<String> = (0..500).map(|i| format!("icon{i}")).collect();
870
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
871
        let mut dom = dom_with_icons(&refs);
872
        let before_children = dom.children.as_ref().len();
873

            
874
        resolve_icons_in_dom(&mut dom, &shared, &SystemStyle::default());
875

            
876
        assert_eq!(dom.children.as_ref().len(), before_children);
877
        assert!(icon_paths(&dom).is_empty());
878
    }
879
}
880

            
881
/// Tests for the resolution CACHE — the reproduction of the per-regeneration
882
/// waste (RSS_MAP_2026_08_07.md §36c) and the properties of the fix.
883
///
884
/// The engine calls `resolve_icons_in_styled_dom` once per DOM regeneration on
885
/// a FRESH StyledDom each time (the layout callback rebuilds it), so "two
886
/// frames" here means two identically-built DOMs — exactly what a drag-resize
887
/// produces 373 times in five seconds.
888
#[cfg(test)]
889
#[allow(clippy::float_cmp)]
890
mod icon_cache_tests {
891
    use core::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
892

            
893
    use super::*;
894
    use crate::refany::RefAny;
895

            
896
    #[derive(Debug, Clone, PartialEq)]
897
    struct CacheTestIconData {
898
        id: u32,
899
    }
900

            
901
    /// A body whose direct children are the named icons, so child index N is
902
    /// icon N both before and after resolution.
903
13
    fn dom_with_icons(names: &[&str]) -> Dom {
904
13
        let mut body = Dom::create_body();
905
643
        for n in names {
906
630
            body.add_child(Dom::create_icon(*n));
907
630
        }
908
13
        body
909
13
    }
910

            
911
    // Per-test statics: `extern "C" fn` cannot capture, and tests run in
912
    // parallel — never share one counter between two tests (same convention
913
    // as `autotest_generated::REC_*`).
914

            
915
    static FRAME_CALLS: AtomicUsize = AtomicUsize::new(0);
916
1
    extern "C" fn frame_counting_resolver(
917
1
        _icon_data: OptionRefAny,
918
1
        _original: &NodeData,
919
1
        _style: &SystemStyle,
920
1
    ) -> Dom {
921
1
        FRAME_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
922
1
        Dom::create_div()
923
1
    }
924

            
925
    /// THE REPRODUCTION. Before the cache, this counted one resolver call per
926
    /// icon per frame — 3 icons × 2 frames = 6 calls for six bit-identical
927
    /// results (scaled up in production: 66 icons × 373 regenerations in one
928
    /// measured drag ≈ 24 600 calls, each running a full throwaway single-node
929
    /// cascade). With the cache: ONE call, ever, for identical inputs.
930
    #[test]
931
1
    fn identical_icons_across_frames_resolve_exactly_once() {
932
1
        let mut h = IconProviderHandle::with_resolver(frame_counting_resolver);
933
1
        h.register_icon("p", "home", RefAny::new(CacheTestIconData { id: 1 }));
934
1
        let shared = SharedIconProvider::from_handle(h);
935
1
        let style = SystemStyle::default();
936

            
937
4
        for frame in 0..3 {
938
3
            let mut sd = dom_with_icons(&["home", "home", "home"]);
939
3
            resolve_icons_in_dom(&mut sd, &shared, &style);
940
9
            for child in sd.children.as_ref() {
941
9
                assert!(
942
9
                    matches!(child.root.get_node_type(), NodeType::Div),
943
                    "frame {frame}: icon must be resolved on the cached path too"
944
                );
945
            }
946
        }
947

            
948
1
        assert_eq!(
949
1
            FRAME_CALLS.load(AtomicOrdering::SeqCst),
950
            1,
951
            "identical (spec, node, styled-state) must hit the cache — both across frames AND \
952
             across duplicates within one frame"
953
        );
954
1
    }
955

            
956
    static STYLE_VARIANT_CALLS: AtomicUsize = AtomicUsize::new(0);
957
2
    extern "C" fn style_variant_resolver(
958
2
        _icon_data: OptionRefAny,
959
2
        _original: &NodeData,
960
2
        _style: &SystemStyle,
961
2
    ) -> Dom {
962
2
        STYLE_VARIANT_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
963
2
        Dom::create_div()
964
2
    }
965

            
966
    /// The resolver copies inline styles off the original node, so the same
967
    /// icon NAME with different inline styles is a different resolution and
968
    /// must occupy a different cache entry.
969
    #[test]
970
1
    fn distinct_inline_styles_are_distinct_cache_entries() {
971
        use azul_css::{
972
            dynamic_selector::CssPropertyWithConditions,
973
            props::{layout::dimensions::LayoutWidth, property::CssProperty},
974
        };
975

            
976
1
        let shared = SharedIconProvider::from_handle(IconProviderHandle::with_resolver(
977
1
            style_variant_resolver,
978
        ));
979
1
        let style = SystemStyle::default();
980

            
981
2
        let build = || {
982
2
            let mut body = Dom::create_body();
983
2
            body.add_child(Dom::create_icon("home"));
984
2
            body.add_child(
985
2
                Dom::create_icon("home").with_css_props(
986
2
                    vec![CssPropertyWithConditions::simple(CssProperty::width(
987
2
                        LayoutWidth::px(24.0),
988
                    ))]
989
2
                    .into(),
990
                ),
991
            );
992
2
            body
993
2
        };
994

            
995
1
        let mut frame1 = build();
996
1
        resolve_icons_in_dom(&mut frame1, &shared, &style);
997
1
        assert_eq!(
998
1
            STYLE_VARIANT_CALLS.load(AtomicOrdering::SeqCst),
999
            2,
            "same name, different inline style => two resolutions"
        );
1
        let mut frame2 = build();
1
        resolve_icons_in_dom(&mut frame2, &shared, &style);
1
        assert_eq!(
1
            STYLE_VARIANT_CALLS.load(AtomicOrdering::SeqCst),
            2,
            "both variants must be cache hits on the second frame"
        );
1
    }
    static SYS_STYLE_CALLS: AtomicUsize = AtomicUsize::new(0);
3
    extern "C" fn sys_style_resolver(
3
        _icon_data: OptionRefAny,
3
        _original: &NodeData,
3
        _style: &SystemStyle,
3
    ) -> Dom {
3
        SYS_STYLE_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
3
        Dom::create_div()
3
    }
    /// Resolvers read the SystemStyle (theme, tint, grayscale), so a style
    /// change must flush. The policy is flush-on-change, not per-style keying:
    /// flipping BACK re-resolves too. That trade is deliberate — a style flip
    /// is a rare, user-visible event; keying every entry by style would bloat
    /// every comparison for it.
    #[test]
1
    fn system_style_change_flushes_the_cache() {
1
        let shared =
1
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(sys_style_resolver));
1
        let style_a = SystemStyle::default();
1
        let mut style_b = SystemStyle::default();
1
        style_b.language = azul_css::AzString::from("xx-ZZ");
1
        assert_ne!(style_a, style_b);
1
        let mut sd = dom_with_icons(&["home"]);
1
        resolve_icons_in_dom(&mut sd, &shared, &style_a);
1
        assert_eq!(SYS_STYLE_CALLS.load(AtomicOrdering::SeqCst), 1);
1
        let mut sd = dom_with_icons(&["home"]);
1
        resolve_icons_in_dom(&mut sd, &shared, &style_b);
1
        assert_eq!(
1
            SYS_STYLE_CALLS.load(AtomicOrdering::SeqCst),
            2,
            "style change => re-resolve"
        );
1
        let mut sd = dom_with_icons(&["home"]);
1
        resolve_icons_in_dom(&mut sd, &shared, &style_a);
1
        assert_eq!(
1
            SYS_STYLE_CALLS.load(AtomicOrdering::SeqCst),
            3,
            "flush-on-change: flipping back re-resolves (documented policy)"
        );
1
    }
    static PARITY_CALLS: AtomicUsize = AtomicUsize::new(0);
1
    extern "C" fn parity_resolver(
1
        _icon_data: OptionRefAny,
1
        original: &NodeData,
1
        _style: &SystemStyle,
1
    ) -> Dom {
        use azul_css::{
            dynamic_selector::CssPropertyWithConditions,
            props::{layout::dimensions::LayoutWidth, property::CssProperty},
        };
1
        PARITY_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
        // A realistic replacement: styled text (what a font-icon resolver
        // produces), reading nothing but producing node type + props + a11y.
1
        let mut dom = Dom::create_text_do_not_use_without_block_level_wrapper("\u{e88a}");
1
        dom.root.set_css_props(
1
            vec![CssPropertyWithConditions::simple(CssProperty::width(
1
                LayoutWidth::px(16.0),
            ))]
1
            .into(),
        );
1
        if let Some(a11y) = original.get_accessibility_info() {
            dom = dom.with_accessibility_info(a11y.clone());
1
        }
1
        dom
1
    }
    /// A cache hit must produce a node BIT-IDENTICAL to what the fresh
    /// resolver produced on frame 1 — node type, inline style, the lot.
    #[test]
1
    fn cached_hit_produces_an_identical_node() {
1
        let shared =
1
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(parity_resolver));
1
        let style = SystemStyle::default();
1
        let mut frame1 = dom_with_icons(&["save"]);
1
        resolve_icons_in_dom(&mut frame1, &shared, &style);
1
        assert_eq!(PARITY_CALLS.load(AtomicOrdering::SeqCst), 1);
1
        let mut frame2 = dom_with_icons(&["save"]);
1
        resolve_icons_in_dom(&mut frame2, &shared, &style);
1
        assert_eq!(
1
            PARITY_CALLS.load(AtomicOrdering::SeqCst),
            1,
            "frame 2 must be a hit"
        );
1
        assert_eq!(
1
            frame1.children.as_ref()[0].root,
1
            frame2.children.as_ref()[0].root,
            "cached and freshly-resolved node must be indistinguishable"
        );
1
    }
    static EMPTY_CALLS: AtomicUsize = AtomicUsize::new(0);
1
    extern "C" fn empty_resolver(
1
        _icon_data: OptionRefAny,
1
        _original: &NodeData,
1
        _style: &SystemStyle,
1
    ) -> Dom {
1
        EMPTY_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
1
        Dom::create_div()
1
    }
    /// "Icon not found → empty div" is also a resolution and is also cached.
    #[test]
1
    fn empty_resolutions_are_cached_too() {
1
        let shared =
1
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(empty_resolver));
1
        let style = SystemStyle::default();
3
        for _ in 0..2 {
2
            let mut sd = dom_with_icons(&["missing"]);
2
            resolve_icons_in_dom(&mut sd, &shared, &style);
2
            assert!(matches!(
2
                sd.children.as_ref()[0].root.get_node_type(),
                NodeType::Div
            ));
        }
1
        assert_eq!(EMPTY_CALLS.load(AtomicOrdering::SeqCst), 1);
1
    }
    static SUBTREE_CALLS: AtomicUsize = AtomicUsize::new(0);
1
    extern "C" fn subtree_resolver(
1
        _icon_data: OptionRefAny,
1
        _original: &NodeData,
1
        _style: &SystemStyle,
1
    ) -> Dom {
1
        SUBTREE_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
1
        Dom::create_body()
1
            .with_child(Dom::create_div())
1
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("x"))
1
    }
    /// Multi-node replacements go through the same cache, stored as a whole
    /// `Dom` and cloned per hit - and, unlike the old arena splice, they are
    /// spliced in ENTIRELY, children and all.
    #[test]
1
    fn subtree_resolutions_are_cached() {
1
        let shared =
1
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(subtree_resolver));
1
        let style = SystemStyle::default();
1
        let mut first_type = None;
3
        for _ in 0..2 {
2
            let mut sd = dom_with_icons(&["multi"]);
2
            resolve_icons_in_dom(&mut sd, &shared, &style);
2
            let replaced = &sd.children.as_ref()[0];
2
            assert_eq!(
2
                replaced.children.as_ref().len(),
                2,
                "the cached subtree keeps BOTH children, not just its root"
            );
2
            let t = replaced.root.get_node_type().clone();
2
            match &first_type {
1
                None => first_type = Some(t),
1
                Some(prev) => assert_eq!(prev, &t, "cached subtree must apply identically"),
            }
        }
1
        assert_eq!(SUBTREE_CALLS.load(AtomicOrdering::SeqCst), 1);
1
    }
    static CAP_CALLS: AtomicUsize = AtomicUsize::new(0);
612
    extern "C" fn cap_resolver(
612
        _icon_data: OptionRefAny,
612
        _original: &NodeData,
612
        _style: &SystemStyle,
612
    ) -> Dom {
612
        CAP_CALLS.fetch_add(1, AtomicOrdering::SeqCst);
612
        Dom::create_div()
612
    }
    /// Unbounded distinct specs must not grow the cache without limit; the
    /// flush-all overflow policy degrades to uncached behaviour, never to
    /// unbounded memory.
    #[test]
1
    fn cache_is_capped_and_correct_past_the_cap() {
1
        let shared =
1
            SharedIconProvider::from_handle(IconProviderHandle::with_resolver(cap_resolver));
1
        let style = SystemStyle::default();
1
        let names: Vec<String> = (0..(ICON_CACHE_CAP + 100))
612
            .map(|i| format!("icon{i}"))
1
            .collect();
1
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1
        let mut sd = dom_with_icons(&refs);
1
        resolve_icons_in_dom(&mut sd, &shared, &style);
1
        assert_eq!(CAP_CALLS.load(AtomicOrdering::SeqCst), ICON_CACHE_CAP + 100);
1
        assert!(
1
            sd.children
1
                .as_ref()
1
                .iter()
612
                .all(|c| !matches!(c.root.get_node_type(), NodeType::Icon(_))),
            "every icon still resolved"
        );
1
        let cache = shared.cache.lock().unwrap();
1
        assert!(
1
            cache.total <= ICON_CACHE_CAP,
            "cap must hold: total={} cap={}",
            cache.total,
            ICON_CACHE_CAP
        );
1
    }
}
/// Tests for the SWAPPABLE icon - `Dom::create_icon_view`. The shape of the
/// node is the whole contract: `CallbackInfo::set_icon` finds the view's spec
/// through the node's DATASET, so a view that does not carry one (or carries
/// something else) cannot be swapped, and the failure would only show up as
/// "the icon never changes" in a running app.
#[cfg(test)]
mod icon_view_tests {
    use super::*;
    use crate::dom::Dom;
    #[test]
1
    fn an_icon_view_is_a_virtual_view_carrying_its_spec_as_a_dataset() {
1
        let view = Dom::create_icon_view("system:window-maximize,maximize");
1
        assert!(
1
            matches!(view.root.get_node_type(), NodeType::VirtualView),
            "the swap works by re-rendering a view, so the node has to BE one"
        );
1
        let mut dataset = view
1
            .root
1
            .get_dataset()
1
            .cloned()
1
            .expect("set_icon reaches the spec through the node's dataset");
1
        let state = dataset
1
            .downcast_mut::<IconViewState>()
1
            .expect("and that dataset is what set_icon downcasts");
1
        assert_eq!(state.spec.as_str(), "system:window-maximize,maximize");
1
    }
    #[test]
1
    fn the_node_dataset_and_the_callbacks_payload_are_the_same_data() {
        // Not merely equal - the SAME `RefAny`. `set_icon` mutates the one on
        // the node; the callback reads the one the view was constructed with.
        // Two separate allocations would make every swap silently do nothing,
        // and nothing else in the system would notice.
1
        let mut view = Dom::create_icon_view("home");
1
        let mut from_node = view.root.get_dataset().cloned().expect("dataset");
1
        {
1
            let mut state = from_node.downcast_mut::<IconViewState>().expect("state");
1
            state.spec = "settings".into();
1
        }
1
        let mut payload = view
1
            .root
1
            .get_virtual_view_node()
1
            .map(|n| n.refany.clone())
1
            .expect("a virtual view node carries its callback payload");
1
        let seen = payload
1
            .downcast_ref::<IconViewState>()
1
            .expect("the payload is the same IconViewState")
1
            .spec
1
            .clone();
1
        assert_eq!(
1
            seen.as_str(),
            "settings",
            "writing through the node's dataset must be visible to the callback"
        );
1
    }
    #[test]
1
    fn an_icon_view_declares_its_own_overflow() {
        // The view reports the icon's MEASURED size, which can exceed a box the
        // caller sized itself (a 40px icon asked to sit in a 24px button).
        // Without this the view machinery would answer that with a scrollbar,
        // on an icon.
1
        let view = Dom::create_icon_view("home");
1
        let overflow_decls = view
1
            .css
1
            .as_ref()
1
            .iter()
1
            .flat_map(|c| c.rules.as_ref().iter())
1
            .flat_map(|r| r.declarations.as_ref().iter())
            // `CssPropertyType`'s Debug is the CSS spelling ("overflow-x"), and
            // the shorthand expands at parse time, so this matches whichever
            // form the parser produces.
3
            .filter(|d| format!("{:?}", d.get_type()).contains("overflow"))
1
            .count();
1
        assert!(
1
            overflow_decls >= 1,
            "the view has to state its own overflow, got {overflow_decls} declarations"
        );
1
    }
}