1
//! Generic icon provider system for Azul
2
//!
3
//! This module defines a generic, callback-based icon resolution infrastructure.
4
//! The actual parsing/loading implementations live in `azul-layout`.
5
//!
6
//! # Architecture
7
//!
8
//! The icon system is fully generic using RefAny:
9
//!
10
//! 1. `IconProviderHandle` - stores icons in nested map: pack_name → (icon_name → RefAny)
11
//! 2. The resolver callback turns (icon_data, original_dom) into a StyledDom
12
//! 3. Differentiation between Image/Font/SVG/etc. is via RefAny::downcast
13
//! 4. Supports any icon source: images, fonts, SVGs, animated icons, etc.
14
//!
15
//! # Resolution Flow
16
//!
17
//! 1. User creates Icon nodes: `Dom::create_icon("home")`
18
//! 2. Before layout, `resolve_icons_in_styled_dom()` is called
19
//! 3. Each Icon node is looked up across all packs (first match wins)
20
//! 4. The resolver callback is invoked with the found RefAny data + original DOM
21
//! 5. The callback returns a StyledDom subtree that replaces the icon node
22
//!
23
//! # Caching
24
//!
25
//! Resolution results are CACHED on the [`SharedIconProvider`], keyed by
26
//! (icon spec, the original icon node's full `NodeData`, its `StyledNode`),
27
//! and flushed when the `SystemStyle` changes. The engine calls
28
//! `resolve_icons_in_styled_dom` on EVERY DOM regeneration — during a Wayland
29
//! drag-resize that is one call per pixel of mouse movement (373 in a measured
30
//! 5-second drag), and each un-cached resolution runs `StyledDom::create`'s
31
//! full single-node cascade whose output is then thrown away by the host's
32
//! own cascade recompute. ~66 ribbon icons × 373 regenerations ≈ 24 600
33
//! throwaway cascades per drag, all yielding bit-identical results
34
//!.
35
//!
36
//! The cache stores the resolver's output DECONSTRUCTED into exactly the
37
//! fields the replacement consumes (node type, inline style, accessibility,
38
//! styled node), so a hit is four field clones — no `Dom`, no `StyledDom`,
39
//! no cascade, no `CssPropertyCache`, not even the single-node extraction of
40
//! the original.
41
//!
42
//! Correctness notes:
43
//! - The KEY includes the whole original `NodeData` + `StyledNode`, because a custom resolver may
44
//!   read anything from `original_icon_dom` (the default one copies inline styles and accessibility
45
//!   info). Same name with different inline styles → separate entries; a hover-state flip on the
46
//!   node → different `StyledNode` → re-resolve.
47
//! - The icon SET and the resolver are frozen once the provider is shared (`App::run` consumes the
48
//!   handle; `SharedIconProvider` exposes no registration), so registration invalidation cannot be
49
//!   needed post-share.
50
//! - "Animated icons" remain compatible: animation is carried by the DATA the resolver returns
51
//!   (e.g. an image-callback node that animates per frame), not by re-resolving per frame —
52
//!   re-resolution only ever happened on DOM regeneration anyway.
53
//!
54
//! # Custom Resolvers
55
//!
56
//! Users can provide custom C callbacks for complete control:
57
//!
58
//! ```c
59
//! AzStyledDom my_resolver(
60
//!     AzRefAny* icon_data,           // NULL if icon not found
61
//!     AzStyledDom* original_icon_dom, // Contains icon_name, styles, a11y
62
//!     AzSystemStyle* system_style
63
//! ) {
64
//!     // Custom resolution logic - icon_data contains your registered data
65
//!     return create_my_icon_dom(...);
66
//! }
67
//! ```
68

            
69
use alloc::{
70
    boxed::Box,
71
    collections::BTreeMap,
72
    string::{String, ToString},
73
    sync::Arc,
74
    vec::Vec,
75
};
76
use core::{fmt, mem::ManuallyDrop};
77
#[cfg(feature = "std")]
78
use std::sync::Mutex;
79

            
80
#[cfg(not(feature = "std"))]
81
use self::nostd_lock::Mutex;
82

            
83
/// Minimal `no_std` spinlock that mirrors the slice of the `std::sync::Mutex`
84
/// API actually used by this module (`new` + `lock` returning a `Result`).
85
#[cfg(not(feature = "std"))]
86
mod nostd_lock {
87
    use core::{
88
        cell::UnsafeCell,
89
        ops::{Deref, DerefMut},
90
        sync::atomic::{AtomicBool, Ordering},
91
    };
92

            
93
    pub struct Mutex<T> {
94
        locked: AtomicBool,
95
        data: UnsafeCell<T>,
96
    }
97

            
98
    unsafe impl<T: Send> Send for Mutex<T> {}
99
    unsafe impl<T: Send> Sync for Mutex<T> {}
100

            
101
    pub struct MutexGuard<'a, T> {
102
        lock: &'a Mutex<T>,
103
    }
104

            
105
    impl<T> Mutex<T> {
106
        pub fn new(data: T) -> Self {
107
            Mutex {
108
                locked: AtomicBool::new(false),
109
                data: UnsafeCell::new(data),
110
            }
111
        }
112

            
113
        /// Returns `Ok(guard)` to mirror `std::sync::Mutex::lock`. Never poisons.
114
        pub fn lock(&self) -> Result<MutexGuard<'_, T>, core::convert::Infallible> {
115
            while self
116
                .locked
117
                .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
118
                .is_err()
119
            {
120
                core::hint::spin_loop();
121
            }
122
            Ok(MutexGuard { lock: self })
123
        }
124
    }
125

            
126
    impl<'a, T> Deref for MutexGuard<'a, T> {
127
        type Target = T;
128
        fn deref(&self) -> &T {
129
            unsafe { &*self.lock.data.get() }
130
        }
131
    }
132

            
133
    impl<'a, T> DerefMut for MutexGuard<'a, T> {
134
        fn deref_mut(&mut self) -> &mut T {
135
            unsafe { &mut *self.lock.data.get() }
136
        }
137
    }
138

            
139
    impl<'a, T> Drop for MutexGuard<'a, T> {
140
        fn drop(&mut self) {
141
            self.lock.locked.store(false, Ordering::Release);
142
        }
143
    }
144

            
145
    // Mirror `std::sync::Mutex: Debug` so containers can derive Debug. Does not
146
    // lock (the spinlock has no `try_lock`, and locking in `fmt` could deadlock).
147
    impl<T> core::fmt::Debug for Mutex<T> {
148
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
149
            f.debug_struct("Mutex").finish_non_exhaustive()
150
        }
151
    }
152
}
153

            
154
use azul_css::{system::SystemStyle, AzString};
155

            
156
use crate::{
157
    dom::{Dom, NodeData, NodeType},
158
    refany::{OptionRefAny, RefAny},
159
    styled_dom::StyledDom,
160
};
161

            
162
// Type name constants for RefAny-based icon type detection in debug output
163
const IMAGE_ICON_DATA_TYPE_NAME: &str = "ImageIconData";
164
const FONT_ICON_DATA_TYPE_NAME: &str = "FontIconData";
165

            
166
// Icon Resolver Callback
167

            
168
/// Callback type for resolving icon data to a `StyledDom`.
169
///
170
/// Parameters:
171
/// - `icon_data`: The `RefAny` data from the icon pack (cloned, or None if not found)
172
/// - `original_icon_dom`: The original icon node's `StyledDom` (contains inline styles, a11y info,
173
///   `icon_name`)
174
/// - `system_style`: Current system style (theme, colors, etc.)
175
///
176
/// Returns: A `StyledDom` that will replace the icon node.
177
/// The resolver should copy relevant styles from `original_icon_dom` to the result.
178
/// Return an empty `StyledDom` to show a placeholder or nothing.
179
///
180
/// Note: `icon_name` is accessible via `original_icon_dom.node_data[0].get_node_type()` →
181
/// `NodeType::Icon(name)`
182
pub type IconResolverCallbackType = extern "C" fn(
183
    icon_data: OptionRefAny,
184
    original_icon_node: &NodeData,
185
    system_style: &SystemStyle,
186
) -> Dom;
187

            
188
/// Default resolver: an empty div, i.e. the icon renders as nothing.
189
#[must_use]
190
3
pub extern "C" fn default_icon_resolver(
191
3
    _icon_data: OptionRefAny,
192
3
    _original_icon_node: &NodeData,
193
3
    _system_style: &SystemStyle,
194
3
) -> Dom {
195
3
    Dom::create_div()
196
3
}
197

            
198
// Icon Provider Inner (single mutex)
199

            
200
/// Inner data for `IconProviderHandle` - all fields behind single mutex
201
#[derive(Debug, Clone)]
202
pub struct IconProviderInner {
203
    /// Nested map: `pack_name` → (`icon_name` → `RefAny`)
204
    /// Differentiation between Image/Font/SVG is via `RefAny::downcast`
205
    pub icons: BTreeMap<String, BTreeMap<String, RefAny>>,
206
    /// The resolver callback
207
    pub resolver: IconResolverCallbackType,
208
}
209

            
210
impl Default for IconProviderInner {
211
    fn default() -> Self {
212
        Self {
213
            icons: BTreeMap::new(),
214
            resolver: default_icon_resolver,
215
        }
216
    }
217
}
218

            
219
// Icon Provider Handle
220

            
221
/// Icon provider stored in `AppConfig`.
222
///
223
/// This is a Box<IconProviderInner> for C FFI compatibility.
224
/// When `App::run()` is called, it gets converted to Arc<Mutex<IconProviderInner>>
225
/// and cloned to each window.
226
///
227
/// Icons are stored in a nested map: `pack_name` → (`icon_name` → `RefAny`)
228
/// This allows:
229
/// - Multiple packs with different sources (app-images, material-icons, etc.)
230
/// - Easy unregistration of entire packs
231
/// - First-match-wins lookup across all packs
232
#[repr(C)]
233
pub struct IconProviderHandle {
234
    /// Boxed inner data - Box<T> is repr(C) compatible (single pointer).
235
    /// `ManuallyDrop` so the Box is freed ONLY by our `Drop` (gated on
236
    /// `run_destructor`), never by drop-glue. The codegen Az wrapper nests an
237
    /// `AzIconProviderHandle` field (in `AzAppConfig`) whose own `Drop` re-runs
238
    /// `_delete` -> `drop_in_place::<IconProviderHandle>` on the SAME bytes; with
239
    /// a bare `Box` the glue freed it a second time -> double free. Same
240
    /// convention as `GlContextPtr` / `CssPropertyCachePtr`.
241
    pub inner: ManuallyDrop<Box<IconProviderInner>>,
242
    pub run_destructor: bool,
243
}
244

            
245
impl Clone for IconProviderHandle {
246
101
    fn clone(&self) -> Self {
247
101
        Self {
248
101
            inner: ManuallyDrop::new(Box::new((**self.inner).clone())),
249
101
            run_destructor: true,
250
101
        }
251
101
    }
252
}
253

            
254
impl Drop for IconProviderHandle {
255
698
    fn drop(&mut self) {
256
        // First drop (run_destructor still true) frees the Box and clears the flag
257
        // in the shared bytes; the codegen's redundant second drop sees false -> no-op.
258
698
        if self.run_destructor {
259
533
            self.run_destructor = false;
260
533
            unsafe {
261
533
                ManuallyDrop::drop(&mut self.inner);
262
533
            }
263
165
        }
264
698
    }
265
}
266

            
267
impl fmt::Debug for IconProviderHandle {
268
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269
        let pack_count = self.inner.icons.len();
270
        let icon_count: usize = self.inner.icons.values().map(BTreeMap::len).sum();
271

            
272
        f.debug_struct("IconProviderHandle")
273
            .field("pack_count", &pack_count)
274
            .field("icon_count", &icon_count)
275
            .finish_non_exhaustive()
276
    }
277
}
278

            
279
impl Default for IconProviderHandle {
280
1
    fn default() -> Self {
281
1
        Self::new()
282
1
    }
283
}
284

            
285
impl IconProviderInner {
286
    /// Resolves an icon SPEC to registered icon data.
287
    ///
288
    /// A spec is a comma-separated fallback list of entries, each either a
289
    /// bare icon name (`"content_copy"`, searched across all packs in
290
    /// registration order, first match wins) or a pack-qualified name
291
    /// (`"material-icons:save"`, searched only in that pack). The first
292
    /// entry that resolves wins, so markup can express per-platform
293
    /// fallbacks: `<icon>ios:open_menu,kde:three-lines,menu</icon>`.
294
    /// Icon names are case-insensitive; pack names are case-sensitive.
295
    #[must_use]
296
3789
    pub fn lookup_spec(&self, spec: &str) -> Option<RefAny> {
297
        // Verbatim first: a registered name is always found as-is (names may
298
        // legally contain ':', ',' or whitespace). The spec syntax below only
299
        // applies when nothing is registered under the literal name.
300
3789
        let verbatim = spec.to_lowercase();
301
3789
        if let Some(data) = self.icons.values().find_map(|pack| pack.get(&verbatim)) {
302
2336
            return Some(data.clone());
303
1453
        }
304

            
305
1465
        for entry in spec.split(',') {
306
1465
            let entry = entry.trim();
307
1465
            if entry.is_empty() {
308
28
                continue;
309
1437
            }
310
1437
            let (pack, name) = match entry.split_once(':') {
311
66
                Some((p, n)) => (Some(p.trim()), n.trim()),
312
1371
                None => (None, entry),
313
            };
314
1437
            let name_lower = name.to_lowercase();
315
1437
            let found = pack.map_or_else(
316
1371
                || self.icons.values().find_map(|pack| pack.get(&name_lower)),
317
66
                |p| self.icons.get(p).and_then(|pack| pack.get(&name_lower)),
318
            );
319
1437
            if let Some(data) = found {
320
30
                return Some(data.clone());
321
1407
            }
322
        }
323
1423
        None
324
3789
    }
325
}
326

            
327
impl IconProviderHandle {
328
    /// Create a new empty icon provider with the default (no-op) resolver.
329
    ///
330
    /// Note: The default resolver in core crate returns an empty `StyledDom`.
331
    /// Use `set_resolver()` to set a proper resolver from the layout crate,
332
    /// or use `with_resolver()` to create with a custom resolver.
333
    #[must_use]
334
198
    pub fn new() -> Self {
335
198
        Self {
336
198
            inner: ManuallyDrop::new(Box::new(IconProviderInner {
337
198
                icons: BTreeMap::new(),
338
198
                resolver: default_icon_resolver,
339
198
            })),
340
198
            run_destructor: true,
341
198
        }
342
198
    }
343

            
344
    /// Create with a custom resolver callback
345
399
    pub fn with_resolver(resolver: IconResolverCallbackType) -> Self {
346
399
        Self {
347
399
            inner: ManuallyDrop::new(Box::new(IconProviderInner {
348
399
                icons: BTreeMap::new(),
349
399
                resolver,
350
399
            })),
351
399
            run_destructor: true,
352
399
        }
353
399
    }
354

            
355
    /// Convert this handle into an Arc<Mutex<IconProviderInner>> for use in windows.
356
    ///
357
    /// This consumes the Box and creates an Arc. Called by `App::run()` to create
358
    /// the shared icon provider that gets cloned to each window.
359
165
    pub(crate) fn into_shared(mut self) -> Arc<Mutex<IconProviderInner>> {
360
        // Take the Box out and disarm our Drop so it doesn't free the moved-out
361
        // allocation (ManuallyDrop::take leaves `inner` logically uninitialized).
362
165
        let inner = unsafe { ManuallyDrop::take(&mut self.inner) };
363
165
        self.run_destructor = false;
364
165
        Arc::new(Mutex::new(*inner))
365
165
    }
366

            
367
    /// Set the resolver callback
368
2
    pub fn set_resolver(&mut self, resolver: IconResolverCallbackType) {
369
2
        self.inner.resolver = resolver;
370
2
    }
371

            
372
    /// Register a single icon in a pack (creates pack if needed).
373
    ///
374
    /// Note: `pack_name` is case-sensitive, while `icon_name` is normalized to lowercase.
375
27453
    pub fn register_icon(&mut self, pack_name: &str, icon_name: &str, data: RefAny) {
376
27453
        let pack = self.inner.icons.entry(pack_name.to_string()).or_default();
377
27453
        pack.insert(icon_name.to_lowercase(), data);
378
27453
    }
379

            
380
    /// Unregister a single icon from a pack
381
58
    pub fn unregister_icon(&mut self, pack_name: &str, icon_name: &str) {
382
58
        if let Some(pack) = self.inner.icons.get_mut(pack_name) {
383
56
            pack.remove(&icon_name.to_lowercase());
384
56
            if pack.is_empty() {
385
53
                self.inner.icons.remove(pack_name);
386
53
            }
387
2
        }
388
58
    }
389

            
390
    /// Unregister an entire icon pack
391
23
    pub fn unregister_pack(&mut self, pack_name: &str) {
392
23
        self.inner.icons.remove(pack_name);
393
23
    }
394

            
395
    /// Look up an icon across all packs, returning the pack name and data reference (first match
396
    /// wins)
397
35
    fn lookup_with_pack(&self, icon_name: &str) -> Option<(&str, &RefAny)> {
398
35
        let icon_name_lower = icon_name.to_lowercase();
399
35
        for (pack_name, pack) in &self.inner.icons {
400
30
            if let Some(data) = pack.get(&icon_name_lower) {
401
27
                return Some((pack_name.as_str(), data));
402
3
            }
403
        }
404
8
        None
405
35
    }
406

            
407
    /// Look up an icon by spec (bare name, `pack:name`, or a comma-separated
408
    /// fallback list of either form; first match wins).
409
    #[must_use]
410
250
    pub fn lookup(&self, icon_name: &str) -> Option<RefAny> {
411
250
        self.inner.lookup_spec(icon_name)
412
250
    }
413

            
414
    /// Check if an icon spec resolves in any pack
415
    #[must_use]
416
388
    pub fn has_icon(&self, icon_name: &str) -> bool {
417
388
        self.inner.lookup_spec(icon_name).is_some()
418
388
    }
419

            
420
    /// List all pack names
421
    #[must_use]
422
256
    pub fn list_packs(&self) -> Vec<String> {
423
256
        self.inner.icons.keys().cloned().collect()
424
256
    }
425

            
426
    /// List all icon names in a specific pack
427
    #[must_use]
428
58
    pub fn list_icons_in_pack(&self, pack_name: &str) -> Vec<String> {
429
58
        self.inner
430
58
            .icons
431
58
            .get(pack_name)
432
58
            .map(|pack| pack.keys().cloned().collect())
433
58
            .unwrap_or_default()
434
58
    }
435

            
436
    /// Debug lookup: returns detailed info about an icon's `RefAny` contents
437
    #[allow(clippy::used_underscore_binding)] // intentional `_`-prefix (FFI/api.json pub field, or cfg-gated binding); access is deliberate
438
    #[must_use]
439
30
    pub fn debug_lookup(&self, icon_name: &str) -> AzString {
440
        use core::fmt::Write;
441

            
442
30
        let icon_name_lower = icon_name.to_lowercase();
443

            
444
30
        let mut result =
445
30
            format!("Debug lookup for icon '{icon_name}' (normalized: '{icon_name_lower}'):\n");
446

            
447
        // Report registered packs
448
30
        let _ = writeln!(result, "  Total packs: {}", self.inner.icons.len());
449
30
        for (pack_name, pack) in &self.inner.icons {
450
26
            let _ = writeln!(result, "    Pack '{}': {} icons", pack_name, pack.len());
451
472
            for name in pack.keys() {
452
472
                let _ = writeln!(result, "      - {name}");
453
472
            }
454
        }
455

            
456
        // Find the icon using shared lookup helper
457
30
        match self.lookup_with_pack(icon_name) {
458
24
            Some((pack, data)) => {
459
24
                let _ = writeln!(result, "\n  FOUND in pack '{pack}'");
460
24
                let type_name = data.get_type_name();
461
24
                let _ = writeln!(result, "  RefAny type_name: '{}'", type_name.as_str());
462

            
463
24
                let debug_info = data.sharing_info.debug_get_refcount_copied();
464
24
                let _ = writeln!(
465
24
                    result,
466
24
                    "  RefAny size: {} bytes",
467
                    debug_info._internal_layout_size
468
                );
469

            
470
24
                let type_str = type_name.as_str();
471
24
                if type_str.contains(IMAGE_ICON_DATA_TYPE_NAME) {
472
1
                    result.push_str("  RefAny type: ImageIconData (image-based icon)\n");
473
23
                } else if type_str.contains(FONT_ICON_DATA_TYPE_NAME) {
474
1
                    result.push_str("  RefAny type: FontIconData (font-based icon)\n");
475
22
                } else {
476
22
                    let _ = writeln!(result, "  RefAny type: UNKNOWN ('{type_str}')");
477
22
                }
478
            }
479
6
            None => {
480
6
                result.push_str("\n  NOT FOUND in any pack\n");
481
6
            }
482
        }
483

            
484
30
        AzString::from(result)
485
30
    }
486
}
487

            
488
/// Thread-safe icon provider for use in windows.
489
///
490
/// This is created from `IconProviderHandle::into_shared()` in `App::run()`
491
/// and cloned to each window.
492
#[derive(Debug, Clone)]
493
pub struct SharedIconProvider {
494
    inner: Arc<Mutex<IconProviderInner>>,
495
    /// Resolution cache — see the module-level `# Caching` section. Shared by
496
    /// every clone of this provider (all windows), like `inner`.
497
    cache: Arc<Mutex<IconResolutionCache>>,
498
}
499

            
500
/// Hard cap on cached resolutions. A frame's live icon set is typically a few
501
/// dozen; the cap only matters when specs vary without bound (adversarial or
502
/// generated names). Policy on overflow is FLUSH-ALL: the next frame re-fills
503
/// with the live set, so a pathological producer degrades to today's uncached
504
/// behaviour instead of growing without limit.
505
const ICON_CACHE_CAP: usize = 512;
506

            
507
/// One cached resolution. `original`/`original_styled` are the KEY (together
508
/// with the spec, the map key one level up); `resolution` is the value.
509
#[derive(Debug)]
510
struct IconCacheEntry {
511
    /// The icon node as it was BEFORE resolution. Two `<icon>` nodes with the
512
    /// same spec but different inline styles resolve differently, so the node
513
    /// itself is part of the key.
514
    original: NodeData,
515
    /// The resolved replacement, spliced in whole. A `Dom` rather than a
516
    /// flattened single node: an icon may be an arbitrary styled subtree.
517
    resolution: Dom,
518
}
519

            
520
/// See the module-level `# Caching` section.
521
#[derive(Debug, Default)]
522
struct IconResolutionCache {
523
    /// The `SystemStyle` every entry was resolved under. A mismatch flushes:
524
    /// resolvers read the style (theme, tint, grayscale), so entries from
525
    /// another style are wrong, not merely stale.
526
    system_style: Option<SystemStyle>,
527
    /// spec → entries with that spec (usually exactly one; more when the same
528
    /// icon name appears with different inline styles).
529
    entries: BTreeMap<String, Vec<IconCacheEntry>>,
530
    /// Total entry count across all specs (the map holds vecs, so `len()` of
531
    /// the map alone cannot enforce [`ICON_CACHE_CAP`]).
532
    total: usize,
533
}
534

            
535
impl SharedIconProvider {
536
    /// Create from an `IconProviderHandle` (consumes the handle)
537
    #[must_use]
538
165
    pub fn from_handle(handle: IconProviderHandle) -> Self {
539
165
        Self {
540
165
            inner: handle.into_shared(),
541
165
            cache: Arc::new(Mutex::new(IconResolutionCache::default())),
542
165
        }
543
165
    }
544

            
545
    /// Register (or REPLACE) one icon on a live shared provider.
546
    ///
547
    /// The registration path that exists after startup. `IconProviderHandle`
548
    /// is consumed by [`Self::from_handle`], so a pack built once at
549
    /// `App::create` could never be refreshed - and it has to be: a pack whose
550
    /// artwork depends on the OS theme (the desktop's own icons, tinted with
551
    /// the palette) is WRONG the moment the theme flips, and re-reading it is
552
    /// the only way to get the dark variant.
553
    ///
554
    /// Flushes the resolution cache: entries there hold the Dom the OLD
555
    /// artwork resolved to, and serving those back would make the
556
    /// re-registration invisible.
557
    pub fn register_icon(&self, pack_name: &str, icon_name: &str, data: RefAny) {
558
        if let Ok(mut inner) = self.inner.lock() {
559
            let pack = inner.icons.entry(pack_name.to_string()).or_default();
560
            pack.insert(icon_name.to_lowercase(), data);
561
        }
562
        if let Ok(mut cache) = self.cache.lock() {
563
            cache.entries.clear();
564
            cache.total = 0;
565
            // The next batch re-validates against whatever style it carries.
566
            cache.system_style = None;
567
        }
568
    }
569

            
570
    /// Flush the cache if `system_style` differs from the one its entries
571
    /// were resolved under. Called ONCE per `resolve_icons_in_styled_dom`
572
    /// batch, not per icon, so the `SystemStyle` comparison is per-frame.
573
225
    fn validate_cache_for_style(&self, system_style: &SystemStyle) {
574
225
        let Ok(mut cache) = self.cache.lock() else {
575
            return;
576
        };
577
225
        match &cache.system_style {
578
92
            Some(cached) if cached == system_style => {}
579
135
            _ => {
580
135
                cache.entries.clear();
581
135
                cache.total = 0;
582
135
                cache.system_style = Some(system_style.clone());
583
135
            }
584
        }
585
225
    }
586

            
587
    /// Cache hit test. `None` = miss (resolve for real, then
588
    /// [`Self::store_resolution`]).
589
1368
    fn cached_resolution(&self, spec: &str, node: &NodeData) -> Option<Dom> {
590
1368
        let cache = self.cache.lock().ok()?;
591
1368
        cache
592
1368
            .entries
593
1368
            .get(spec)?
594
74
            .iter()
595
75
            .find_map(|e| (e.original == *node).then(|| e.resolution.clone()))
596
1368
    }
597

            
598
    /// Insert a freshly-resolved entry, flushing everything first if the cap
599
    /// is reached (see [`ICON_CACHE_CAP`]).
600
1295
    fn store_resolution(&self, spec: &str, node: &NodeData, resolution: &Dom) {
601
1295
        let Ok(mut cache) = self.cache.lock() else {
602
            return;
603
        };
604
1295
        if cache.total >= ICON_CACHE_CAP {
605
1
            cache.entries.clear();
606
1
            cache.total = 0;
607
1294
        }
608
1295
        cache
609
1295
            .entries
610
1295
            .entry(spec.to_string())
611
1295
            .or_default()
612
1295
            .push(IconCacheEntry {
613
1295
                original: node.clone(),
614
1295
                resolution: resolution.clone(),
615
1295
            });
616
1295
        cache.total += 1;
617
1295
    }
618

            
619
    /// Resolve an icon to a `StyledDom` using the registered callback
620
    #[must_use]
621
1301
    pub fn resolve(
622
1301
        &self,
623
1301
        original_icon_node: &NodeData,
624
1301
        icon_name: &str,
625
1301
        system_style: &SystemStyle,
626
1301
    ) -> Dom {
627
1301
        let (resolver, lookup_result) = {
628
1301
            let Ok(guard) = self.inner.lock() else {
629
                return Dom::create_div();
630
            };
631

            
632
1301
            let resolver = guard.resolver;
633
1301
            let lookup_result = guard.lookup_spec(icon_name);
634

            
635
1301
            (resolver, lookup_result)
636
        };
637

            
638
1301
        resolver(lookup_result.into(), original_icon_node, system_style)
639
1301
    }
640

            
641
    /// [`Self::resolve`], memoised on `(spec, icon node)`.
642
    ///
643
    /// The system style is not part of the key: a change to it clears the whole
644
    /// cache once per pass (`validate_cache_for_style`), which is cheaper than
645
    /// carrying it in every entry.
646
    #[must_use]
647
1368
    fn resolve_cached(
648
1368
        &self,
649
1368
        original_icon_node: &NodeData,
650
1368
        icon_name: &str,
651
1368
        system_style: &SystemStyle,
652
1368
    ) -> Dom {
653
1368
        if let Some(hit) = self.cached_resolution(icon_name, original_icon_node) {
654
73
            return hit;
655
1295
        }
656
1295
        let resolved = self.resolve(original_icon_node, icon_name, system_style);
657
1295
        self.store_resolution(icon_name, original_icon_node, &resolved);
658
1295
        resolved
659
1368
    }
660

            
661
    /// Look up an icon by spec (bare name, `pack:name`, or a comma-separated
662
    /// fallback list of either form; first match wins)
663
    #[must_use]
664
960
    pub fn lookup(&self, icon_name: &str) -> Option<RefAny> {
665
960
        self.inner
666
960
            .lock()
667
960
            .ok()
668
960
            .and_then(|guard| guard.lookup_spec(icon_name))
669
960
    }
670

            
671
    /// Check if an icon spec resolves
672
    #[must_use]
673
890
    pub fn has_icon(&self, icon_name: &str) -> bool {
674
890
        self.inner
675
890
            .lock()
676
890
            .map(|guard| guard.lookup_spec(icon_name).is_some())
677
890
            .unwrap_or(false)
678
890
    }
679
}
680

            
681
// Icon Resolution in the Dom tree
682

            
683
/// How many times an icon may resolve to another icon before we stop.
684
///
685
/// Chains are legitimate - restyling an existing icon by registering a `Dom`
686
/// that contains it is the obvious way to do it - but a resolver is user code,
687
/// so a cycle has to terminate. Direct self-reference is caught exactly; this
688
/// bounds everything longer.
689
const MAX_ICON_INDIRECTION: usize = 8;
690

            
691
/// Replace every `NodeType::Icon` node in `dom` with whatever the registered
692
/// resolver returns for it.
693
///
694
/// # Why this runs on a `Dom`, BEFORE the cascade
695
///
696
/// This used to run on a `StyledDom`, after the cascade, and it is worth
697
/// recording why that was wrong - the shape of the old code is still visible in
698
/// the git history and in several comments elsewhere.
699
///
700
/// A `StyledDom` is a FLAT ARENA in DFS order: a node's first child is the next
701
/// index. So a replacement's children could not be attached to the icon node
702
/// after the fact without inserting mid-arena and shifting every index after
703
/// them. The old code therefore flattened every replacement down to its ROOT
704
/// node's `node_type` / `style` / `accessibility` plus a single glyph character
705
/// threaded into a text leaf, and threw the rest away - including the whole
706
/// `CssPropertyCache` that the resolver's own cascade had just built. Its own
707
/// comment said so: "everything else in the returned `StyledDom` ... was always
708
/// discarded".
709
///
710
/// That cost three things:
711
///
712
/// * **A wasted cascade per icon**, whose result was discarded.
713
/// * **Any icon that is not one node was impossible.** Registering a styled `Dom` as an icon could
714
///   not work, because only the root survived.
715
/// * **A stale property cache.** Rewriting a node's inline `style` after the cascade left the
716
///   precomputed per-node arrays describing the PRE-resolution node. For a font icon that hid
717
///   `font-family: StyleFontFamily::Ref(face)` - the only place that face is named - from font
718
///   collection, so shaping fell back to a face with no glyph at the icon's private-use codepoint
719
///   and drew `.notdef`. It needed an explicit cache rebuild to paper over.
720
///
721
/// Running on the `Dom` removes all three by construction. A `Dom` is a real
722
/// tree (`root` + `children` + its own `css`), so a replacement is spliced whole;
723
/// nothing is cascaded twice because the cascade has not happened yet; and there
724
/// is no property cache to invalidate. An icon is now free to be an arbitrary
725
/// styled subtree, which is what makes "register a `Dom` as an icon" work -
726
/// including the colour it should be, which travels with the icon rather than
727
/// having to be threaded through every call site as a tint parameter.
728
225
pub fn resolve_icons_in_dom(
729
225
    dom: &mut Dom,
730
225
    provider: &SharedIconProvider,
731
225
    system_style: &SystemStyle,
732
225
) {
733
    // A SystemStyle change (theme flip, tint, grayscale) invalidates every
734
    // cached resolution. Checked once per pass, not once per icon.
735
225
    provider.validate_cache_for_style(system_style);
736
225
    resolve_icons_in_dom_inner(dom, provider, system_style);
737
225
}
738

            
739
/// Resolve every `<icon>` in a user `Dom` and cascade it - the two halves of
740
/// "a `Dom` the application handed us becomes a `StyledDom`", as one call.
741
///
742
/// The halves were separate, and that is exactly how a path came to skip one:
743
/// three call sites ran `resolve_icons_in_dom` and then
744
/// `StyledDom::create_from_dom`, while a fourth - the DOM a `VirtualView`
745
/// callback returns - ran only the cascade. An `<icon>` inside a virtual view
746
/// therefore never resolved, and nothing downstream would ever resolve it
747
/// later, so it stayed an empty node for the life of the view.
748
///
749
/// The order is not interchangeable and is not obvious from either name:
750
/// resolution MUST precede the cascade, because a replacement is a SUBTREE and
751
/// `StyledDom` is a flat arena in DFS order - splicing one in afterwards would
752
/// mean inserting mid-arena and shifting every index after it, which is what
753
/// used to flatten every icon down to its root node. Giving the pair a single
754
/// name is what stops the next caller from re-deriving that.
755
#[must_use]
756
12
pub fn styled_dom_resolving_icons(
757
12
    dom: Dom,
758
12
    provider: &SharedIconProvider,
759
12
    system_style: &SystemStyle,
760
12
) -> StyledDom {
761
12
    styled_dom_resolving_icons_with_context(dom, provider, system_style, None)
762
12
}
763

            
764
/// [`styled_dom_resolving_icons`], cascading under a known window context.
765
///
766
/// The context reaches the first cascade (`StyledDom::create_with_context`),
767
/// so the funnel's later context offer is a no-op rather than a re-cascade.
768
#[must_use]
769
180
pub fn styled_dom_resolving_icons_with_context(
770
180
    mut dom: Dom,
771
180
    provider: &SharedIconProvider,
772
180
    system_style: &SystemStyle,
773
180
    context: Option<azul_css::dynamic_selector::DynamicSelectorContext>,
774
180
) -> StyledDom {
775
180
    resolve_icons_in_dom(&mut dom, provider, system_style);
776
180
    StyledDom::create_from_dom_with_context(dom, context)
777
180
}
778

            
779
/// The private dataset behind [`Dom::create_icon_view`]: the spec that view
780
/// renders right now. Public because the swap API downcasts it - see
781
/// `CallbackInfo::set_icon`.
782
#[derive(Debug, Clone, PartialEq, Eq)]
783
pub struct IconViewState {
784
    /// An icon spec, i.e. a comma-separated fallback chain exactly as
785
    /// `Dom::create_icon` takes ("system:titlebar-close,close").
786
    pub spec: AzString,
787
}
788

            
789
/// The body of [`Dom::create_icon_view`], which is where this is documented.
790
///
791
/// Not public itself: the constructor is the API, and two spellings of one
792
/// thing is how they drift.
793
#[must_use]
794
7
pub(crate) fn icon_view(spec: impl Into<AzString>) -> Dom {
795
7
    let dataset = RefAny::new(IconViewState { spec: spec.into() });
796
7
    Dom::create_virtual_view(
797
7
        dataset.clone(),
798
7
        crate::callbacks::VirtualViewCallback::create(render_icon_view),
799
    )
800
    // The SAME `RefAny` as the view's own payload, on the node: the swap API
801
    // reaches it through `CallbackInfo::get_dataset`, and a clone points at
802
    // the same data, so rewriting the spec here is what the callback reads
803
    // there. (The progress bar's fast path is built the same way.)
804
7
    .with_dataset(OptionRefAny::Some(dataset))
805
    // Lays out like the icon node it stands in for. A `VirtualView` defaults
806
    // to `display: block` (it exists to virtualize scrollable content) and to
807
    // `overflow: auto` with it - but an icon is INLINE content, and one that
808
    // grows a scrollbar is absurd. The view also reports the icon's MEASURED
809
    // size, which can exceed a box the caller sized itself (a 40px icon asked
810
    // to sit in a 24px button), and `auto` would answer that with a bar.
811
    //
812
    // A caller's own `with_css` is appended after this and so wins on anything
813
    // it states; this only fills in what the caller has no reason to think
814
    // about.
815
7
    .with_css("display: inline-block; overflow: hidden;")
816
7
}
817

            
818
/// [`icon_view`]'s callback: render the spec the dataset currently holds.
819
60
extern "C" fn render_icon_view(
820
60
    mut data: RefAny,
821
60
    info: crate::callbacks::VirtualViewCallbackInfo,
822
60
) -> crate::callbacks::VirtualViewReturn {
823
    use crate::geom::{LogicalPosition, LogicalRect, LogicalSize};
824

            
825
60
    let spec = match data.downcast_ref::<IconViewState>() {
826
        // Foreign payload: render nothing rather than lie about bounds.
827
        None => return crate::callbacks::VirtualViewReturn::default(),
828
60
        Some(state) => state.spec.clone(),
829
    };
830
60
    let dom = Dom::create_icon(spec);
831

            
832
    // How big the icon actually is. `measure_dom` styles through the window,
833
    // which resolves the icon first - so this measures the ARTWORK, not the
834
    // empty `<icon>` node.
835
    //
836
    // Measured against the view's own box, which is what a replaced element's
837
    // content is laid out in. An auto-sized view's box is the replaced-element
838
    // default (300x150) on the first pass and the icon's own size afterwards;
839
    // either is a box an icon fits in, so the measurement is the icon's
840
    // natural size in both. A box of ZERO is the degenerate case - a view in a
841
    // collapsed parent - where a real constraint would measure the icon to
842
    // nothing.
843
60
    let bounds = info.bounds.get_logical_size();
844
60
    let available = if bounds.width > 0.0 && bounds.height > 0.0 {
845
60
        bounds
846
    } else {
847
        LogicalSize::new(UNCONSTRAINED, UNCONSTRAINED)
848
    };
849
60
    let measured = info.measure_dom(dom.clone(), available);
850
    // A measurement of zero means there was no measure hook (or nothing to
851
    // draw); reporting it would collapse an auto-sized view to nothing.
852
60
    let size = if measured.width > 0.0 && measured.height > 0.0 {
853
60
        measured
854
    } else {
855
        bounds
856
    };
857

            
858
60
    let rect = LogicalRect::new(LogicalPosition::zero(), size);
859
    // An icon does not scroll, so all three rects are the same box.
860
60
    crate::callbacks::VirtualViewReturn::with_dom(dom, rect, rect)
861
60
}
862

            
863
/// The "no constraint" box an auto-sized icon is measured in. Large enough
864
/// that no icon is wrapped or clipped by it, finite so a bug cannot turn into
865
/// a NaN geometry.
866
const UNCONSTRAINED: f32 = 4096.0;
867

            
868
/// The recursive half of [`resolve_icons_in_dom`].
869
1864
fn resolve_icons_in_dom_inner(
870
1864
    dom: &mut Dom,
871
1864
    provider: &SharedIconProvider,
872
1864
    system_style: &SystemStyle,
873
1864
) {
874
    // An icon may resolve TO another icon - registering
875
    // `Dom::create_icon("favorite").with_css("color: red")` under another name
876
    // is the natural way to restyle an existing icon - so this iterates rather
877
    // than resolving once.
878
    //
879
    // Bounded two ways, because a resolver is user code and can trivially cycle:
880
    // a resolution that yields the SAME spec is a self-reference and stops
881
    // immediately, and any longer cycle stops at `MAX_ICON_INDIRECTION`. In both
882
    // cases the node is left as-is rather than looping forever.
883
1864
    let mut seen = 0;
884
3232
    while let Some(spec) = icon_spec_of(dom) {
885
1368
        if seen >= MAX_ICON_INDIRECTION {
886
            break;
887
1368
        }
888
1368
        let replacement = provider.resolve_cached(&dom.root, spec.as_str(), system_style);
889
1368
        if icon_spec_of(&replacement).as_ref().map(AzString::as_str) == Some(spec.as_str()) {
890
            // Resolves to itself: replacing would spin.
891
            break;
892
1368
        }
893
        // The whole node is replaced, children included: an `<icon>name</icon>`
894
        // carries its spec as a text child, and leaving it would render the raw
895
        // spec next to the resolved icon.
896
        //
897
        // Its STYLESHEETS are carried forward, though. `Dom::with_css` attaches
898
        // a scoped stylesheet to `Dom::css` rather than inline properties, so
899
        // `Dom::create_icon("favorite").with_css("color: red")` - the natural
900
        // way to register a recoloured icon - keeps the colour in `css`, not on
901
        // the node. Dropping it with the node made the replacement render in the
902
        // default colour and silently ignore the caller's styling.
903
        //
904
        // The replaced node's sheets go FIRST so the replacement's own
905
        // declarations still win on conflict.
906
1368
        let mut css = dom.css.clone().into_library_owned_vec();
907
1368
        let mut replacement = replacement;
908
1368
        css.extend(replacement.css.clone().into_library_owned_vec());
909
1368
        replacement.css = css.into();
910
1368
        *dom = replacement;
911
1368
        seen += 1;
912
    }
913

            
914
1864
    for child in dom.children.as_mut() {
915
1639
        resolve_icons_in_dom_inner(child, provider, system_style);
916
1639
    }
917
1864
}
918

            
919
/// The icon spec for a node, or `None` if it is not an icon node.
920
///
921
/// An icon with an explicit non-empty name (`Dom::create_icon("x")`) uses it
922
/// directly. One with an EMPTY name - the markup form `<icon>content_copy</icon>`,
923
/// where the tag carries no name - derives the spec from its direct text
924
/// children, exactly like a ligature icon font turns glyph text into an icon.
925
4600
fn icon_spec_of(dom: &Dom) -> Option<AzString> {
926
4600
    let NodeType::Icon(name) = dom.root.get_node_type() else {
927
3232
        return None;
928
    };
929
1368
    let name = name.as_str();
930
1368
    if !name.is_empty() {
931
1332
        return Some(AzString::from(name));
932
36
    }
933

            
934
36
    let mut derived = alloc::string::String::new();
935
36
    for child in dom.children.as_ref() {
936
36
        if let NodeType::Text(t) = child.root.get_node_type() {
937
36
            derived.push_str(t.as_str());
938
36
        }
939
    }
940
36
    let derived = derived.trim();
941
36
    if derived.is_empty() {
942
        None
943
    } else {
944
36
        Some(AzString::from(derived))
945
    }
946
4600
}
947

            
948
// FFI Option Types
949

            
950
impl_option!(IconProviderHandle, OptionIconProviderHandle, [Clone]);
951

            
952
#[cfg(test)]
953
#[path = "icon_test.rs"]
954
mod icon_test;