1
//! Default icon resolver implementations for Azul
2
//!
3
//! This module provides the standard callback implementations for icon resolution.
4
//! The core types and resolution infrastructure are in `azul_core::icon`.
5
//!
6
//! # Usage
7
//!
8
//! ```rust,ignore
9
//! use azul_core::icon::IconProviderHandle;
10
//! use azul_layout::icon::{default_icon_resolver, ImageIconData, FontIconData};
11
//!
12
//! // Create provider with the default resolver
13
//! let provider = IconProviderHandle::with_resolver(default_icon_resolver);
14
//!
15
//! // Register an image icon
16
//! provider.register_icon("app-images", "logo", RefAny::new(ImageIconData {
17
//!     image: image_ref, width: 32.0, height: 32.0
18
//! }));
19
//!
20
//! // Register a font icon
21
//! provider.register_icon("material-icons", "home", RefAny::new(FontIconData {
22
//!     font: font_ref, icon_char: "\u{e88a}".to_string()
23
//! }));
24
//! ```
25

            
26
use alloc::{
27
    string::{String, ToString},
28
    vec::Vec,
29
};
30

            
31
use azul_core::{
32
    dom::{Dom, NodeData},
33
    icon::IconProviderHandle,
34
    refany::{OptionRefAny, RefAny},
35
    resources::ImageRef,
36
    styled_dom::StyledDom,
37
};
38
use azul_css::{
39
    css::{Css, CssPropertyValue},
40
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
41
    props::{
42
        basic::{length::FloatValue, FontRef, StyleFontFamily, StyleFontFamilyVec},
43
        layout::{LayoutHeight, LayoutWidth},
44
        property::CssProperty,
45
        style::{
46
            filter::{StyleColorMatrix, StyleFilter, StyleFilterVec},
47
            text::StyleTextColor,
48
        },
49
    },
50
    system::SystemStyle,
51
};
52

            
53
// ============================================================================
54
// Icon Data Marker Structs (for RefAny::downcast)
55
// ============================================================================
56

            
57
/// Image-based icon data stored in `RefAny` for the icon resolver.
58
///
59
/// Pass to `register_image_icon` or wrap in `RefAny::new(...)` and register
60
/// directly via `IconProviderHandle::register_icon`.
61
#[derive(Debug)]
62
pub struct ImageIconData {
63
    pub image: ImageRef,
64
    /// The icon's NATURAL WIDTH in logical px - the size it is drawn at, not
65
    /// the width of the bitmap behind it.
66
    ///
67
    /// The two differ whenever the bitmap is oversampled: a 16px indicator
68
    /// rasterised from an SVG at 32x32 so it stays crisp on a 2x display is
69
    /// still a 16px indicator, and laying it out at 32 makes it twice the
70
    /// size the desktop draws it (this is exactly how a window-close button
71
    /// once came out as a giant X). [`register_image_icon`] takes the bitmap's
72
    /// own size, which is right for a 1:1 bitmap; an oversampled one must say
73
    /// its natural size with [`register_image_icon_sized`].
74
    pub width: f32,
75
    /// The icon's natural HEIGHT in logical px - see [`Self::width`].
76
    pub height: f32,
77
}
78

            
79
/// Font-based icon data stored in `RefAny` for the icon resolver.
80
///
81
/// Pass to `register_font_icon` or wrap in `RefAny::new(...)` and register
82
/// directly via `IconProviderHandle::register_icon`.
83
#[derive(Debug)]
84
pub struct FontIconData {
85
    pub font: FontRef,
86
    /// The character/codepoint for this specific icon (e.g., "\u{e88a}" for home)
87
    pub icon_char: String,
88
}
89

            
90
/// An icon that IS a `Dom` - the general case, of which image and font icons
91
/// are special cases.
92
///
93
/// Register any DOM as an icon and refer to it by name everywhere an icon spec
94
/// is taken (`<icon>my-logo</icon>`, a tray icon, an app icon). Because the DOM
95
/// carries its own inline styles AND its own stylesheets (`Dom::css`), the icon
96
/// decides what it looks like - colour included - instead of every call site
97
/// having to thread a tint parameter down to the renderer.
98
///
99
/// The whole subtree is spliced in before the cascade, so a DOM icon can be any
100
/// number of nodes with any styling, not just a single glyph.
101
#[derive(Debug, Clone)]
102
pub struct DomIconData {
103
    pub dom: Dom,
104
}
105

            
106
impl DomIconData {
107
    #[must_use]
108
    pub const fn new(dom: Dom) -> Self {
109
        Self { dom }
110
    }
111
}
112

            
113
// ============================================================================
114
// Default Icon Resolver
115
// ============================================================================
116

            
117
/// Default icon resolver that handles both image and font icons.
118
///
119
/// Resolution logic:
120
/// 1. If `icon_data` is None -> return empty div (icon not found)
121
/// 2. If `icon_data` contains `ImageIconData` -> render as image
122
/// 3. If `icon_data` contains `FontIconData` -> render as text with font
123
/// 4. Unknown data type -> return empty div
124
///
125
/// Styles from the original icon DOM are copied to the result,
126
/// filtered based on `SystemStyle` preferences.
127
#[must_use]
128
47
pub extern "C" fn default_icon_resolver(
129
47
    icon_data: OptionRefAny,
130
47
    original_icon_node: &NodeData,
131
47
    system_style: &SystemStyle,
132
47
) -> Dom {
133
    // No icon found -> empty div
134
47
    let Some(mut data) = icon_data.into_option() else {
135
3
        return Dom::create_div();
136
    };
137

            
138
    // A registered Dom: the icon IS a DOM, spliced in whole. This is what lets
139
    // an icon carry its own styling - colour above all - instead of every call
140
    // site having to pass a tint down. Checked FIRST because it is the most
141
    // specific: a caller who registered a whole DOM meant that DOM.
142
44
    if let Some(dom_icon) = data.downcast_ref::<DomIconData>() {
143
        return create_dom_icon_from_original(&dom_icon, original_icon_node);
144
44
    }
145

            
146
    // Try ImageIconData
147
44
    if let Some(img) = data.downcast_ref::<ImageIconData>() {
148
19
        return create_image_icon_from_original(&img, original_icon_node, system_style);
149
25
    }
150

            
151
    // Try FontIconData
152
25
    if let Some(font_icon) = data.downcast_ref::<FontIconData>() {
153
24
        return create_font_icon_from_original(&font_icon, original_icon_node, system_style);
154
1
    }
155

            
156
    // Unknown data type -> empty div
157
1
    Dom::create_div()
158
47
}
159

            
160
/// An icon that IS a `Dom`: whatever the caller registered, spliced in whole.
161
///
162
/// The call site's styles are applied FIRST and the registered DOM's own styles
163
/// second, so the icon wins on anything it specifies (colour, background,
164
/// borders) while still inheriting what it does not (the size the tray or the
165
/// surrounding text asked for). That ordering is the point: an icon knows what
166
/// it should look like, a call site knows how big it should be.
167
fn create_dom_icon_from_original(icon: &DomIconData, original: &NodeData) -> Dom {
168
    let mut dom = icon.dom.clone();
169

            
170
    let mut props = copy_appropriate_styles_vec(original);
171
    if props.is_empty() {
172
        return dom;
173
    }
174
    // The registered DOM's own declarations go last so they override.
175
    props.extend(copy_appropriate_styles_vec(&dom.root));
176
    dom.root
177
        .set_css_props(CssPropertyWithConditionsVec::from_vec(props));
178
    dom
179
}
180

            
181
// Icon DOM Creation (from original)
182

            
183
/// Create a `StyledDom` for an image-based icon, copying styles from original.
184
///
185
/// Applies SystemStyle-aware modifications:
186
/// - Grayscale filter if `prefer_grayscale` is true
187
/// - Tint color overlay if `tint_color` is set
188
19
fn create_image_icon_from_original(
189
19
    img: &ImageIconData,
190
19
    original: &NodeData,
191
19
    system_style: &SystemStyle,
192
19
) -> Dom {
193
19
    let mut dom = Dom::create_image(img.image.clone());
194

            
195
    // Copy appropriate styles from original
196
    {
197
19
        let original_node = original;
198
19
        let mut props_vec = copy_appropriate_styles_vec(original_node);
199

            
200
        // Add default dimensions if not specified in original styles
201
19
        let has_width = props_vec
202
19
            .iter()
203
19
            .any(|p| matches!(&p.property, CssProperty::Width(_)));
204
19
        let has_height = props_vec
205
19
            .iter()
206
19
            .any(|p| matches!(&p.property, CssProperty::Height(_)));
207

            
208
19
        if !has_width {
209
18
            props_vec.push(CssPropertyWithConditions::simple(CssProperty::width(
210
18
                LayoutWidth::px(img.width),
211
18
            )));
212
18
        }
213
19
        if !has_height {
214
18
            props_vec.push(CssPropertyWithConditions::simple(CssProperty::height(
215
18
                LayoutHeight::px(img.height),
216
18
            )));
217
18
        }
218

            
219
        // Apply SystemStyle-aware filters
220
19
        apply_icon_style_filters(&mut props_vec, system_style);
221

            
222
19
        dom.root
223
19
            .set_css_props(CssPropertyWithConditionsVec::from_vec(props_vec));
224

            
225
        // Copy accessibility info
226
19
        if let Some(a11y) = original_node.get_accessibility_info() {
227
1
            dom = dom.with_accessibility_info(a11y.clone());
228
18
        }
229
    }
230

            
231
19
    dom
232
19
}
233

            
234
/// Create a `StyledDom` for a font-based icon, copying styles from original.
235
///
236
/// Applies SystemStyle-aware modifications:
237
/// - Text color override if `inherit_text_color` is true
238
/// - Tint color if `tint_color` is set
239
24
fn create_font_icon_from_original(
240
24
    font_icon: &FontIconData,
241
24
    original: &NodeData,
242
24
    system_style: &SystemStyle,
243
24
) -> Dom {
244
    // A SPAN, not a bare text node and not a <p>.
245
    //
246
    // The glyph carries css (font-family, colour, tint) and frequently sits as
247
    // a direct item of a flex or inline-flex container — the engine warned about
248
    // exactly that: "text node ... is one of 2 items in a InlineFlex container".
249
    // A bare text run has no box, so the css is INERT and the glyph competes as
250
    // a flex item with nothing to size. A <p> would give it a box and get the
251
    // flow wrong: an icon belongs INLINE inside its label, not as a block
252
    // paragraph beside it. `span` is the one that is both boxed and inline.
253
24
    let mut dom = Dom::create_span_with_text(font_icon.icon_char.clone());
254

            
255
    // Add font family
256
24
    let font_prop = CssPropertyWithConditions::simple(CssProperty::font_family(
257
24
        StyleFontFamilyVec::from_vec(vec![StyleFontFamily::Ref(font_icon.font.clone())]),
258
    ));
259

            
260
    {
261
24
        let original_node = original;
262
24
        let mut props_vec = copy_appropriate_styles_vec(original_node);
263
24
        props_vec.push(font_prop);
264

            
265
        // Apply SystemStyle-aware color modifications for font icons
266
24
        apply_font_icon_color(&mut props_vec, system_style);
267

            
268
24
        dom.root
269
24
            .set_css_props(CssPropertyWithConditionsVec::from_vec(props_vec));
270

            
271
        // Copy accessibility info
272
24
        if let Some(a11y) = original_node.get_accessibility_info() {
273
            dom = dom.with_accessibility_info(a11y.clone());
274
24
        }
275
    }
276

            
277
24
    dom
278
24
}
279

            
280
/// Copy styles from original node
281
/// Returns a Vec for easier manipulation
282
46
fn copy_appropriate_styles_vec(original_node: &NodeData) -> Vec<CssPropertyWithConditions> {
283
    // Reconstruct the legacy flat list from the unified Css store.
284
46
    original_node
285
46
        .get_style()
286
46
        .iter_inline_properties()
287
46
        .map(|(prop, conds)| CssPropertyWithConditions {
288
516
            property: prop.clone(),
289
516
            apply_if: conds.clone(),
290
516
        })
291
46
        .collect()
292
46
}
293

            
294
/// Apply SystemStyle-aware filters to icon properties.
295
///
296
/// This adds CSS filters based on accessibility and theming settings:
297
/// - Grayscale filter if `prefer_grayscale` is true
298
24
fn apply_icon_style_filters(
299
24
    props_vec: &mut Vec<CssPropertyWithConditions>,
300
24
    system_style: &SystemStyle,
301
24
) {
302
24
    let icon_style = &system_style.icon_style;
303

            
304
    // Collect filters to apply
305
24
    let mut filters = Vec::new();
306

            
307
    // Grayscale filter: Uses a color matrix that converts to grayscale
308
    // Standard luminance weights: R*0.2126 + G*0.7152 + B*0.0722
309
24
    if icon_style.prefer_grayscale {
310
4
        // Grayscale color matrix (4x5):
311
4
        // [0.2126, 0.7152, 0.0722, 0, 0]  <- R output
312
4
        // [0.2126, 0.7152, 0.0722, 0, 0]  <- G output
313
4
        // [0.2126, 0.7152, 0.0722, 0, 0]  <- B output
314
4
        // [0,      0,      0,      1, 0]  <- A output
315
4
        let grayscale_matrix = StyleColorMatrix {
316
4
            m0: FloatValue::new(0.2126),
317
4
            m1: FloatValue::new(0.7152),
318
4
            m2: FloatValue::new(0.0722),
319
4
            m3: FloatValue::new(0.0),
320
4
            m4: FloatValue::new(0.0),
321
4
            m5: FloatValue::new(0.2126),
322
4
            m6: FloatValue::new(0.7152),
323
4
            m7: FloatValue::new(0.0722),
324
4
            m8: FloatValue::new(0.0),
325
4
            m9: FloatValue::new(0.0),
326
4
            m10: FloatValue::new(0.2126),
327
4
            m11: FloatValue::new(0.7152),
328
4
            m12: FloatValue::new(0.0722),
329
4
            m13: FloatValue::new(0.0),
330
4
            m14: FloatValue::new(0.0),
331
4
            m15: FloatValue::new(0.0),
332
4
            m16: FloatValue::new(0.0),
333
4
            m17: FloatValue::new(0.0),
334
4
            m18: FloatValue::new(1.0),
335
4
            m19: FloatValue::new(0.0),
336
4
        };
337
4
        filters.push(StyleFilter::ColorMatrix(grayscale_matrix));
338
20
    }
339

            
340
    // Apply tint color as a flood filter if specified
341
24
    if let azul_css::props::basic::color::OptionColorU::Some(tint) = &icon_style.tint_color {
342
2
        filters.push(StyleFilter::Flood(*tint));
343
22
    }
344

            
345
    // Add filters if any were collected
346
24
    if !filters.is_empty() {
347
5
        props_vec.push(CssPropertyWithConditions::simple(CssProperty::Filter(
348
5
            CssPropertyValue::Exact(StyleFilterVec::from_vec(filters)),
349
5
        )));
350
19
    }
351
24
}
352

            
353
/// Apply SystemStyle-aware color modifications for font icons.
354
///
355
/// Font icons can use text color directly, so we can:
356
/// - Apply tint color as text color
357
/// - Inherit text color from parent
358
28
fn apply_font_icon_color(
359
28
    props_vec: &mut Vec<CssPropertyWithConditions>,
360
28
    system_style: &SystemStyle,
361
28
) {
362
28
    let icon_style = &system_style.icon_style;
363

            
364
    // If tint color is specified, use it as the text color
365
28
    if let azul_css::props::basic::color::OptionColorU::Some(tint) = &icon_style.tint_color {
366
2
        props_vec.push(CssPropertyWithConditions::simple(CssProperty::TextColor(
367
2
            CssPropertyValue::Exact(StyleTextColor { inner: *tint }),
368
2
        )));
369
26
    }
370
    // Note: inherit_text_color doesn't need explicit handling - text color
371
    // is inherited by default in CSS. We only need to NOT override it.
372
28
}
373

            
374
// IconProviderHandle Helper Functions
375

            
376
/// Register an image icon in a pack
377
7
pub fn register_image_icon(
378
7
    provider: &mut IconProviderHandle,
379
7
    pack_name: &str,
380
7
    icon_name: &str,
381
7
    image: ImageRef,
382
7
) {
383
    // The bitmap's own size IS the natural size for a 1:1 bitmap. An
384
    // OVERSAMPLED one (an SVG rasterised at 2x for a HiDPI display) must use
385
    // `register_image_icon_sized` instead, or it lays out at twice the size
386
    // it is drawn at.
387
7
    let size = image.get_size();
388
7
    register_image_icon_sized(
389
7
        provider,
390
7
        pack_name,
391
7
        icon_name,
392
7
        image,
393
7
        size.width,
394
7
        size.height,
395
    );
396
7
}
397

            
398
/// Register an image icon whose NATURAL SIZE differs from its bitmap's.
399
///
400
/// `width`/`height` are the logical px the icon occupies in layout; the
401
/// bitmap may be larger (an SVG rasterised at 2x or 3x so it stays crisp when
402
/// the display or the zoom scales it up). This is the difference between
403
/// "how big is this picture" and "how big is this icon", and only the caller
404
/// that rasterised it knows the second: a freedesktop theme states it in the
405
/// directory the file came from (`actions/16`, `actions/22`, ...), and a
406
/// `scalable` icon has whatever size its consumer intends.
407
///
408
/// A non-finite or non-positive size is IGNORED in favour of the bitmap's own
409
/// - a zero-sized icon is invisible, which is a worse failure than a
410
/// wrong-sized one, and NaN would poison layout.
411
12
pub fn register_image_icon_sized(
412
12
    provider: &mut IconProviderHandle,
413
12
    pack_name: &str,
414
12
    icon_name: &str,
415
12
    image: ImageRef,
416
12
    width: f32,
417
12
    height: f32,
418
12
) {
419
12
    let bitmap = image.get_size();
420
24
    let sane = |asked: f32, fallback: f32| {
421
24
        if asked.is_finite() && asked > 0.0 {
422
16
            asked
423
        } else {
424
8
            fallback
425
        }
426
24
    };
427
12
    let data = ImageIconData {
428
12
        width: sane(width, bitmap.width),
429
12
        height: sane(height, bitmap.height),
430
12
        image,
431
12
    };
432
12
    provider.register_icon(pack_name, icon_name, RefAny::new(data));
433
12
}
434

            
435
/// Register icons from a ZIP file (file names become icon names)
436
#[cfg(feature = "zip")]
437
4
pub fn register_icons_from_zip(
438
4
    provider: &mut IconProviderHandle,
439
4
    pack_name: &str,
440
4
    zip_bytes: &[u8],
441
4
) {
442
4
    for (icon_name, image, width, height) in load_images_from_zip(zip_bytes) {
443
        let data = ImageIconData {
444
            image,
445
            width,
446
            height,
447
        };
448
        provider.register_icon(pack_name, &icon_name, RefAny::new(data));
449
    }
450
4
}
451

            
452
#[cfg(not(feature = "zip"))]
453
pub fn register_icons_from_zip(
454
    _provider: &mut IconProviderHandle,
455
    _pack_name: &str,
456
    _zip_bytes: &[u8],
457
) {
458
    // ZIP support not enabled — the caller explicitly handed us an icon pack
459
    // and NOTHING got registered; every later lookup will just miss. Say so
460
    // once (this gate is hit by DEFAULT builds: `zip` is not a default
461
    // feature of azul-layout).
462
    static ANNOUNCE: std::sync::Once = std::sync::Once::new();
463
    ANNOUNCE.call_once(|| {
464
        eprintln!(
465
            "[azul][icons] register_icons_from_zip called, but this build has no `zip` feature — \
466
             NO icons were registered from the pack. Rebuild azul-layout with the `zip` (+ \
467
             `image_decoding`) features"
468
        );
469
    });
470
}
471

            
472
/// Register a font icon in a pack
473
/// Register an arbitrary `Dom` as an icon.
474
///
475
/// The general case: an icon is just a DOM, and image / font icons are special
476
/// cases of it. Whatever you register is spliced in wherever that icon name is
477
/// used - an `<icon>` node, a tray icon, an app icon - and it keeps its own
478
/// styling, because the DOM carries both inline properties and its own
479
/// stylesheets (`Dom::css`).
480
///
481
/// That is what makes colour work without a tint parameter: an icon that should
482
/// be red says so itself, once, instead of every call site having to thread a
483
/// colour down to the renderer. Sizing still comes from the call site, since the
484
/// caller is the one who knows how big the icon has to be.
485
pub fn register_dom_icon(
486
    provider: &mut IconProviderHandle,
487
    pack_name: &str,
488
    icon_name: &str,
489
    dom: Dom,
490
) {
491
    provider.register_icon(pack_name, icon_name, RefAny::new(DomIconData::new(dom)));
492
}
493

            
494
13
pub fn register_font_icon(
495
13
    provider: &mut IconProviderHandle,
496
13
    pack_name: &str,
497
13
    icon_name: &str,
498
13
    font: FontRef,
499
13
    icon_char: &str,
500
13
) {
501
13
    let data = FontIconData {
502
13
        font,
503
13
        icon_char: icon_char.to_string(),
504
13
    };
505
13
    provider.register_icon(pack_name, icon_name, RefAny::new(data));
506
13
}
507

            
508
// ============================================================================
509
// ZIP Support
510
// ============================================================================
511

            
512
/// Load all images from a ZIP file, returning (`icon_name`, `ImageRef`, width, height)
513
#[cfg(all(feature = "zip", feature = "image_decoding"))]
514
#[allow(clippy::cast_precision_loss)] // bounded graphics/coord/counter/fixed-point cast
515
9
fn load_images_from_zip(zip_bytes: &[u8]) -> Vec<(String, ImageRef, f32, f32)> {
516
    use std::path::Path;
517

            
518
    use crate::{
519
        image::decode::{decode_raw_image_from_any_bytes, ResultRawImageDecodeImageError},
520
        zip::{ZipFile, ZipReadConfig},
521
    };
522

            
523
9
    let mut result = Vec::new();
524
9
    let config = ZipReadConfig::default();
525
9
    let Ok(entries) = ZipFile::list(zip_bytes, &config) else {
526
9
        return result;
527
    };
528

            
529
    for entry in &entries {
530
        if entry.path.ends_with('/') {
531
            continue;
532
        } // Skip directories
533

            
534
        let Ok(Some(file_bytes)) = ZipFile::get_single_file(zip_bytes, entry, &config) else {
535
            continue;
536
        };
537

            
538
        // Decode as image
539
        if let ResultRawImageDecodeImageError::Ok(raw_image) =
540
            decode_raw_image_from_any_bytes(&file_bytes)
541
        {
542
            // Icon name = filename without extension
543
            let path = Path::new(&entry.path);
544
            let icon_name = path
545
                .file_stem()
546
                .and_then(|s| s.to_str())
547
                .unwrap_or("")
548
                .to_string();
549

            
550
            let width = raw_image.width as f32;
551
            let height = raw_image.height as f32;
552

            
553
            if let Some(image) = ImageRef::new_rawimage(raw_image) {
554
                result.push((icon_name, image, width, height));
555
            }
556
        }
557
    }
558

            
559
    result
560
9
}
561

            
562
#[cfg(not(all(feature = "zip", feature = "image_decoding")))]
563
fn load_images_from_zip(_zip_bytes: &[u8]) -> Vec<(String, ImageRef, f32, f32)> {
564
    // Only reachable when `zip` is on but `image_decoding` is off (the
565
    // zip-off case never calls this) — same silent-empty trap, so say so.
566
    static ANNOUNCE: std::sync::Once = std::sync::Once::new();
567
    ANNOUNCE.call_once(|| {
568
        eprintln!(
569
            "[azul][icons] icon ZIP was readable but this build has no `image_decoding` feature — \
570
             0 images decoded, NO icons registered"
571
        );
572
    });
573
    Vec::new()
574
}
575

            
576
// ============================================================================
577
// Material Icons Registration
578
// ============================================================================
579

            
580
/// Register all Material Icons in the provider.
581
///
582
/// This registers all 2234 Material Icons from the `material-icons` crate.
583
/// Each icon is registered under the "material-icons" pack with its HTML name
584
/// (e.g., "home", "settings", "`arrow_back`", etc.).
585
///
586
/// Requires the "icons" feature with material-icons crate.
587
#[cfg(feature = "icons")]
588
1
pub fn register_material_icons(provider: &mut IconProviderHandle, font: &FontRef) {
589
    use material_icons::{icon_to_char, icon_to_html_name, ALL_ICONS};
590

            
591
    // Register all Material Icons with their Unicode codepoints
592
2235
    for icon in &ALL_ICONS {
593
2234
        let icon_char = icon_to_char(*icon);
594
2234
        let name = icon_to_html_name(icon);
595
2234

            
596
2234
        let data = FontIconData {
597
2234
            font: font.clone(),
598
2234
            icon_char: icon_char.to_string(),
599
2234
        };
600
2234
        provider.register_icon("material-icons", name, RefAny::new(data));
601
2234
    }
602
1
}
603

            
604
#[cfg(not(feature = "icons"))]
605
pub fn register_material_icons(_provider: &mut IconProviderHandle, _font: FontRef) {
606
    // Icons feature not enabled — the caller asked for 2234 Material Icons
607
    // and got zero, silently. Say so once.
608
    static ANNOUNCE: std::sync::Once = std::sync::Once::new();
609
    ANNOUNCE.call_once(|| {
610
        eprintln!(
611
            "[azul][icons] register_material_icons called, but this build has no `icons` feature \
612
             — NO Material Icons were registered"
613
        );
614
    });
615
}
616

            
617
/// Load the embedded Material Icons font and register all standard icons.
618
///
619
/// This uses the `material-icons` crate which embeds the Material Icons TTF font.
620
/// The font is Apache 2.0 licensed by Google.
621
///
622
/// Returns true if registration was successful.
623
/// Register all Material Icons from caller-supplied TTF bytes.
624
///
625
/// The font bytes are NOT embedded here. `azul-doc codegen all` generates
626
/// `target/codegen/material_icons.ttf.br`, and `azul-doc` builds (depends
627
/// on) `azul-layout` — so `include!`ing that generated artifact in this
628
/// crate is a build cycle (it bit us on `cargo clean`). The `include!` +
629
/// brotli-decompression live in `azul-dll` (downstream of codegen), which
630
/// passes the decompressed TTF in here.
631
#[cfg(all(feature = "icons", feature = "text_layout"))]
632
4
pub fn register_embedded_material_icons(
633
4
    provider: &mut IconProviderHandle,
634
4
    font_bytes: &[u8],
635
4
) -> bool {
636
    use crate::{font::parsed::ParsedFont, parsed_font_to_font_ref};
637

            
638
4
    let mut warnings = Vec::new();
639
4
    let Some(parsed_font) = ParsedFont::from_bytes(font_bytes, 0, &mut warnings) else {
640
4
        return false;
641
    };
642

            
643
    let font_ref = parsed_font_to_font_ref(parsed_font);
644
    register_material_icons(provider, &font_ref);
645

            
646
    true
647
4
}
648

            
649
#[cfg(not(all(feature = "icons", feature = "text_layout")))]
650
pub fn register_embedded_material_icons(
651
    _provider: &mut IconProviderHandle,
652
    _font_bytes: &[u8],
653
) -> bool {
654
    // Icons or text_layout feature not enabled. Returning false is a weak
655
    // signal callers routinely ignore — name the gate once.
656
    static ANNOUNCE: std::sync::Once = std::sync::Once::new();
657
    ANNOUNCE.call_once(|| {
658
        eprintln!(
659
            "[azul][icons] register_embedded_material_icons called, but this build lacks the \
660
             `icons` and/or `text_layout` feature — NO icons registered (returning false)"
661
        );
662
    });
663
    false
664
}
665

            
666
// ============================================================================
667
// Convenience Functions
668
// ============================================================================
669

            
670
/// Create an `IconProviderHandle` with the default resolver.
671
23
pub fn create_default_icon_provider() -> IconProviderHandle {
672
23
    IconProviderHandle::with_resolver(default_icon_resolver)
673
23
}
674

            
675
// The embedded Material Icons font bytes (the `include!` of the
676
// codegen-generated `target/codegen/material_icons.ttf.br` + brotli
677
// decompression) deliberately live in `azul-dll`, not here — see
678
// `register_embedded_material_icons` above for why (build-cycle: azul-doc
679
// builds azul-layout to generate that artifact).
680

            
681
// ============================================================================
682
// Tests
683
// ============================================================================
684

            
685
#[cfg(test)]
686
mod tests {
687
    use super::*;
688

            
689
    #[test]
690
1
    fn test_default_resolver_no_data() {
691
1
        let style = SystemStyle::default();
692
1
        let original = Dom::create_div().root;
693

            
694
1
        let result = default_icon_resolver(OptionRefAny::None, &original, &style);
695

            
696
        // Without data, should return empty div StyledDom
697
1
        assert_eq!(result.children.as_ref().len(), 0);
698
1
    }
699

            
700
    #[test]
701
1
    fn test_create_default_provider() {
702
1
        let provider = create_default_icon_provider();
703
1
        assert!(provider.list_packs().is_empty());
704
1
    }
705
}
706

            
707
#[cfg(test)]
708
#[allow(
709
    clippy::float_cmp,
710
    clippy::items_after_statements,
711
    clippy::redundant_clone,
712
    clippy::cast_possible_truncation,
713
    clippy::cast_precision_loss,
714
    clippy::cast_sign_loss,
715
    clippy::cast_lossless,
716
    clippy::unreadable_literal,
717
    clippy::too_many_lines,
718
    clippy::many_single_char_names,
719
    clippy::similar_names,
720
    unused_qualifications,
721
    unreachable_pub,
722
    private_interfaces
723
)] // pedantic lints are noise in adversarial test code
724
mod autotest_generated {
725
    use azul_core::{a11y::SmallAriaInfo, dom::NodeType, resources::RawImageFormat};
726
    use azul_css::props::basic::color::{ColorU, OptionColorU};
727

            
728
    use super::*;
729

            
730
    // ---------------------------------------------------------------------
731
    // helpers
732
    // ---------------------------------------------------------------------
733

            
734
    /// A `FontRef` whose `parsed` pointer addresses a `'static` byte and whose
735
    /// destructor is a no-op, so nothing is freed on drop. Sound here because
736
    /// nothing on the icon-resolution path ever dereferences `parsed` (only
737
    /// `cpurender::raster` does, and that is not reached from `StyledDom::create`).
738
    fn dummy_font_ref() -> FontRef {
739
        static DUMMY_FONT_DATA: u8 = 0;
740
        extern "C" fn dummy_destructor(_: *mut core::ffi::c_void) {}
741
        FontRef::new(
742
            core::ptr::addr_of!(DUMMY_FONT_DATA).cast::<core::ffi::c_void>(),
743
            dummy_destructor,
744
        )
745
    }
746

            
747
    /// A null (non-decoded) `ImageRef` of the given pixel size — `get_size()`
748
    /// reports exactly `width` / `height`, with no allocation.
749
    fn null_img(width: usize, height: usize) -> ImageRef {
750
        ImageRef::null_image(width, height, RawImageFormat::RGBA8, Vec::new())
751
    }
752

            
753
    /// `ImageIconData` with explicitly-chosen (possibly hostile) f32 dimensions.
754
    fn image_icon(width: f32, height: f32) -> ImageIconData {
755
        ImageIconData {
756
            image: null_img(1, 1),
757
            width,
758
            height,
759
        }
760
    }
761

            
762
    fn font_icon(icon_char: &str) -> FontIconData {
763
        FontIconData {
764
            font: dummy_font_ref(),
765
            icon_char: icon_char.to_string(),
766
        }
767
    }
768

            
769
    fn grayscale_style() -> SystemStyle {
770
        let mut s = SystemStyle::default();
771
        s.icon_style.prefer_grayscale = true;
772
        s
773
    }
774

            
775
    fn tint_style(color: ColorU) -> SystemStyle {
776
        let mut s = SystemStyle::default();
777
        s.icon_style.tint_color = OptionColorU::Some(color);
778
        s
779
    }
780

            
781
    /// A "normal" original icon node: a single div carrying `props` as inline style.
782
    fn original_with(props: Vec<CssPropertyWithConditions>) -> NodeData {
783
        let mut dom = Dom::create_div();
784
        dom.root
785
            .set_css_props(CssPropertyWithConditionsVec::from_vec(props));
786
        dom.root
787
    }
788

            
789
    /// An original icon node with NO inline styles. The resolver takes a
790
    /// `NodeData` now, so "no node at all" is no longer representable - and no
791
    /// longer needs to be: the old `else` branch it drove existed only because
792
    /// a `StyledDom` could be empty.
793
    fn original_without_nodes() -> NodeData {
794
        Dom::create_div().root
795
    }
796

            
797
    /// Every inline property on every node of the result, in document order.
798
    /// (Collected across all nodes rather than `node_data[0]` so the assertions
799
    /// survive any future anonymous-node insertion in `StyledDom::create`.)
800
    fn all_props(dom: &Dom) -> Vec<CssPropertyWithConditions> {
801
        all_nodes(dom)
802
            .iter()
803
            .flat_map(|nd| {
804
                nd.get_style()
805
                    .iter_inline_properties()
806
                    .map(|(property, apply_if)| CssPropertyWithConditions {
807
                        property: property.clone(),
808
                        apply_if: apply_if.clone(),
809
                    })
810
                    .collect::<Vec<_>>()
811
            })
812
            .collect()
813
    }
814

            
815
    fn width_px(dom: &Dom) -> Option<f32> {
816
        all_props(dom).into_iter().find_map(|p| match p.property {
817
            CssProperty::Width(CssPropertyValue::Exact(LayoutWidth::Px(px))) => {
818
                Some(px.number.get())
819
            }
820
            _ => None,
821
        })
822
    }
823

            
824
    fn height_px(dom: &Dom) -> Option<f32> {
825
        all_props(dom).into_iter().find_map(|p| match p.property {
826
            CssProperty::Height(CssPropertyValue::Exact(LayoutHeight::Px(px))) => {
827
                Some(px.number.get())
828
            }
829
            _ => None,
830
        })
831
    }
832

            
833
    fn count_widths(dom: &Dom) -> usize {
834
        all_props(dom)
835
            .iter()
836
            .filter(|p| matches!(p.property, CssProperty::Width(_)))
837
            .count()
838
    }
839

            
840
    /// Every node of a `Dom` tree, in document order.
841
    fn all_nodes(dom: &Dom) -> Vec<NodeData> {
842
        let mut out = Vec::new();
843
        fn walk(d: &Dom, out: &mut Vec<NodeData>) {
844
            out.push(d.root.clone());
845
            for c in d.children.as_ref() {
846
                walk(c, out);
847
            }
848
        }
849
        walk(dom, &mut out);
850
        out
851
    }
852

            
853
    fn text_of(dom: &Dom) -> Option<String> {
854
        all_nodes(dom)
855
            .iter()
856
            .find_map(|nd| match nd.get_node_type() {
857
                NodeType::Text(t) => Some(t.as_str().to_string()),
858
                _ => None,
859
            })
860
    }
861

            
862
    fn has_image_node(dom: &Dom) -> bool {
863
        all_nodes(dom)
864
            .iter()
865
            .any(|nd| matches!(nd.get_node_type(), NodeType::Image(_)))
866
    }
867

            
868
    /// All `StyleFilter`s across every `filter:` property in the list.
869
    fn filters_of(props: &[CssPropertyWithConditions]) -> Vec<StyleFilter> {
870
        props
871
            .iter()
872
            .filter_map(|p| match &p.property {
873
                CssProperty::Filter(CssPropertyValue::Exact(v)) => Some(v.as_ref().to_vec()),
874
                _ => None,
875
            })
876
            .flatten()
877
            .collect()
878
    }
879

            
880
    fn text_color_of(props: &[CssPropertyWithConditions]) -> Option<ColorU> {
881
        props.iter().find_map(|p| match &p.property {
882
            CssProperty::TextColor(CssPropertyValue::Exact(c)) => Some(c.inner),
883
            _ => None,
884
        })
885
    }
886

            
887
    fn resolve(data: RefAny, original: &NodeData, style: &SystemStyle) -> Dom {
888
        default_icon_resolver(OptionRefAny::Some(data), original, style)
889
    }
890

            
891
    // ---------------------------------------------------------------------
892
    // default_icon_resolver — dispatch
893
    // ---------------------------------------------------------------------
894

            
895
    #[test]
896
    fn resolver_none_yields_single_unstyled_div() {
897
        let out = default_icon_resolver(
898
            OptionRefAny::None,
899
            &Dom::create_div().root,
900
            &SystemStyle::default(),
901
        );
902
        assert_eq!(all_nodes(&out).len(), 1);
903
        assert!(matches!(out.root.get_node_type(), NodeType::Div));
904
        // The "not found" placeholder must carry no styling at all — in particular
905
        // it must not inherit the original's width/height.
906
        assert!(all_props(&out).is_empty());
907
    }
908

            
909
    #[test]
910
    fn resolver_unknown_refany_type_yields_empty_div() {
911
        // A RefAny holding neither ImageIconData nor FontIconData must fall through
912
        // to the placeholder rather than panicking on a bad downcast.
913
        struct NotAnIconAtAll {
914
            _payload: [u64; 4],
915
        }
916
        let data = RefAny::new(NotAnIconAtAll { _payload: [7; 4] });
917
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
918

            
919
        assert_eq!(all_nodes(&out).len(), 1);
920
        assert!(matches!(out.root.get_node_type(), NodeType::Div));
921
        assert!(!has_image_node(&out));
922
        assert!(text_of(&out).is_none());
923
    }
924

            
925
    #[test]
926
    fn resolver_image_icon_yields_image_node_with_default_dimensions() {
927
        let out = resolve(
928
            RefAny::new(image_icon(32.0, 24.0)),
929
            &Dom::create_div().root,
930
            &SystemStyle::default(),
931
        );
932
        assert!(has_image_node(&out));
933
        assert_eq!(width_px(&out), Some(32.0));
934
        assert_eq!(height_px(&out), Some(24.0));
935
    }
936

            
937
    #[test]
938
    fn resolver_font_icon_yields_text_node_with_font_family() {
939
        let font = dummy_font_ref();
940
        let data = RefAny::new(FontIconData {
941
            font: font.clone(),
942
            icon_char: "\u{e88a}".to_string(),
943
        });
944
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
945

            
946
        // TWO nodes: the <span> and its text leaf. It was one when the glyph
947
        // was a BARE text node — which is what made its css inert and left it
948
        // competing as a flex item with no box ("text node ... is one of 2
949
        // items in a InlineFlex container"). The span is the box; the glyph
950
        // still reads through it.
951
        assert_eq!(all_nodes(&out).len(), 2);
952
        assert_eq!(text_of(&out).as_deref(), Some("\u{e88a}"));
953
        assert!(
954
            matches!(out.root.get_node_type(), azul_core::dom::NodeType::Span),
955
            "the icon must be wrapped in a span — inline, and boxed"
956
        );
957

            
958
        // The registered font must be the one that ends up in `font-family`.
959
        let has_font = all_props(&out).iter().any(|p| match &p.property {
960
            CssProperty::FontFamily(CssPropertyValue::Exact(families)) => families
961
                .as_ref()
962
                .iter()
963
                .any(|f| matches!(f, StyleFontFamily::Ref(fr) if *fr == font)),
964
            _ => false,
965
        });
966
        assert!(has_font, "font-family with the icon's FontRef must be set");
967
    }
968

            
969
    // ---------------------------------------------------------------------
970
    // default_icon_resolver — degenerate originals
971
    // ---------------------------------------------------------------------
972

            
973
    #[test]
974
    fn image_icon_with_node_less_original_still_gets_dimensions() {
975
        // `original.node_data.first()` is None -> the fallback branch must still
976
        // produce a fully-sized image instead of panicking / emitting no style.
977
        let original = original_without_nodes();
978
        let out = resolve(
979
            RefAny::new(image_icon(16.0, 16.0)),
980
            &original,
981
            &SystemStyle::default(),
982
        );
983
        assert!(has_image_node(&out));
984
        assert_eq!(width_px(&out), Some(16.0));
985
        assert_eq!(height_px(&out), Some(16.0));
986
    }
987

            
988
    #[test]
989
    fn font_icon_with_node_less_original_still_gets_font() {
990
        let original = original_without_nodes();
991
        let out = resolve(
992
            RefAny::new(font_icon("A")),
993
            &original,
994
            &SystemStyle::default(),
995
        );
996
        assert_eq!(text_of(&out).as_deref(), Some("A"));
997
        assert!(all_props(&out)
998
            .iter()
999
            .any(|p| matches!(p.property, CssProperty::FontFamily(_))));
    }
    // ---------------------------------------------------------------------
    // numeric limits: the icon dimensions are attacker-controlled f32s
    // ---------------------------------------------------------------------
    #[test]
    fn image_icon_nan_dimensions_saturate_to_zero_without_panicking() {
        // FloatValue stores `(v * 1000.0) as isize`; `NaN as isize` saturates to 0,
        // so a NaN-sized icon degrades to a 0x0 box rather than poisoning layout.
        let out = resolve(
            RefAny::new(image_icon(f32::NAN, f32::NAN)),
            &Dom::create_div().root,
            &SystemStyle::default(),
        );
        let (w, h) = (
            width_px(&out).expect("width emitted"),
            height_px(&out).expect("height emitted"),
        );
        assert!(
            w.is_finite() && h.is_finite(),
            "NaN must not survive into CSS"
        );
        assert_eq!(w, 0.0);
        assert_eq!(h, 0.0);
    }
    #[test]
    fn image_icon_infinite_dimensions_saturate_to_finite_values() {
        let out = resolve(
            RefAny::new(image_icon(f32::INFINITY, f32::NEG_INFINITY)),
            &Dom::create_div().root,
            &SystemStyle::default(),
        );
        let w = width_px(&out).expect("width emitted");
        let h = height_px(&out).expect("height emitted");
        assert!(w.is_finite(), "+inf must saturate, got {w}");
        assert!(h.is_finite(), "-inf must saturate, got {h}");
        assert!(w > 0.0 && h < 0.0, "saturation must keep the sign");
    }
    #[test]
    fn image_icon_negative_dimensions_are_passed_through_unclamped() {
        // Documents current behaviour: the resolver does NOT reject negative sizes,
        // it forwards them verbatim into `width` / `height`.
        let out = resolve(
            RefAny::new(image_icon(-32.0, -1.5)),
            &Dom::create_div().root,
            &SystemStyle::default(),
        );
        assert_eq!(width_px(&out), Some(-32.0));
        assert_eq!(height_px(&out), Some(-1.5));
    }
    /// THE bug this exists for: an oversampled bitmap is not a bigger icon.
    /// A 16px window control rasterised at 32x32 for a 2x display laid out at
    /// 32px and came out as a giant X next to the title.
    #[test]
    fn an_oversampled_icon_lays_out_at_its_natural_size_not_its_bitmap_size() {
        let mut provider = create_default_icon_provider();
        register_image_icon_sized(
            &mut provider,
            "system",
            "close",
            null_img(32, 32),
            16.0,
            16.0,
        );
        let data = provider.lookup("close").expect("icon registered");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        assert_eq!(width_px(&out), Some(16.0));
        assert_eq!(height_px(&out), Some(16.0));
        // The negative control: the plain constructor still takes the bitmap's
        // size, which is correct for a 1:1 bitmap.
        let mut provider = create_default_icon_provider();
        register_image_icon(&mut provider, "system", "close", null_img(32, 32));
        let data = provider.lookup("close").expect("icon registered");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        assert_eq!(width_px(&out), Some(32.0));
    }
    /// A nonsense natural size must not make the icon invisible: an unusable
    /// answer falls back to the bitmap, which is at least drawable.
    #[test]
    fn a_nonsense_natural_size_falls_back_to_the_bitmap() {
        for bad in [0.0, -8.0, f32::NAN, f32::INFINITY] {
            let mut provider = create_default_icon_provider();
            register_image_icon_sized(&mut provider, "system", "x", null_img(24, 24), bad, bad);
            let data = provider.lookup("x").expect("icon registered");
            let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
            assert_eq!(
                width_px(&out),
                Some(24.0),
                "natural size {bad} must be ignored"
            );
            assert_eq!(height_px(&out), Some(24.0));
        }
    }
    #[test]
    fn register_image_icon_with_usize_max_size_saturates() {
        // `ImageRef::get_size()` casts usize -> f32 (1.8e19); FloatValue then scales
        // by 1000 and casts to isize, which must saturate rather than wrap/panic.
        let mut provider = create_default_icon_provider();
        register_image_icon(
            &mut provider,
            "huge",
            "big",
            null_img(usize::MAX, usize::MAX),
        );
        let data = provider.lookup("big").expect("icon registered");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        let w = width_px(&out).expect("width emitted");
        assert!(
            w.is_finite() && w > 0.0,
            "usize::MAX size must saturate finitely, got {w}"
        );
    }
    #[test]
    fn image_icon_zero_size_is_preserved() {
        let out = resolve(
            RefAny::new(image_icon(0.0, 0.0)),
            &Dom::create_div().root,
            &SystemStyle::default(),
        );
        assert_eq!(width_px(&out), Some(0.0));
        assert_eq!(height_px(&out), Some(0.0));
    }
    // ---------------------------------------------------------------------
    // style copying / precedence
    // ---------------------------------------------------------------------
    #[test]
    fn original_dimensions_win_over_image_defaults() {
        let original = original_with(vec![
            CssPropertyWithConditions::simple(CssProperty::width(LayoutWidth::px(999.0))),
            CssPropertyWithConditions::simple(CssProperty::height(LayoutHeight::px(888.0))),
        ]);
        let out = resolve(
            RefAny::new(image_icon(32.0, 32.0)),
            &original,
            &SystemStyle::default(),
        );
        assert_eq!(width_px(&out), Some(999.0));
        assert_eq!(height_px(&out), Some(888.0));
        // ...and the 32px default must not be appended as a *second* width.
        assert_eq!(count_widths(&out), 1);
    }
    #[test]
    fn copy_appropriate_styles_vec_round_trips_exactly() {
        // encode (set_css_props -> Css) == decode (copy_appropriate_styles_vec)
        let props = vec![
            CssPropertyWithConditions::simple(CssProperty::width(LayoutWidth::px(12.5))),
            CssPropertyWithConditions::simple(CssProperty::height(LayoutHeight::px(7.0))),
        ];
        let mut nd = NodeData::create_div();
        nd.set_css_props(CssPropertyWithConditionsVec::from_vec(props.clone()));
        assert_eq!(copy_appropriate_styles_vec(&nd), props);
    }
    #[test]
    fn copy_appropriate_styles_vec_of_unstyled_node_is_empty() {
        let nd = NodeData::create_div();
        assert!(copy_appropriate_styles_vec(&nd).is_empty());
    }
    #[test]
    fn copy_appropriate_styles_vec_preserves_order_of_many_props() {
        // 512 same-typed declarations: nothing may be deduplicated or reordered,
        // otherwise the last-wins cascade of the copied icon style would flip.
        let props: Vec<CssPropertyWithConditions> = (0..512u32)
            .map(|i| {
                CssPropertyWithConditions::simple(CssProperty::width(LayoutWidth::px(i as f32)))
            })
            .collect();
        let mut nd = NodeData::create_div();
        nd.set_css_props(CssPropertyWithConditionsVec::from_vec(props.clone()));
        let copied = copy_appropriate_styles_vec(&nd);
        assert_eq!(copied.len(), 512);
        assert_eq!(copied, props);
    }
    #[test]
    fn accessibility_info_is_copied_onto_the_resolved_icon() {
        let original = Dom::create_div()
            .with_accessibility_info(SmallAriaInfo::label("Save").to_full_info())
            .root;
        let out = resolve(
            RefAny::new(image_icon(8.0, 8.0)),
            &original,
            &SystemStyle::default(),
        );
        let nodes = all_nodes(&out);
        let a11y = nodes
            .iter()
            .find_map(NodeData::get_accessibility_info)
            .expect("a11y info must survive icon resolution");
        assert_eq!(
            a11y.accessibility_name.as_ref().map(|s| s.as_str()),
            Some("Save")
        );
    }
    // ---------------------------------------------------------------------
    // apply_icon_style_filters
    // ---------------------------------------------------------------------
    #[test]
    fn icon_filters_default_style_adds_nothing() {
        let mut props = Vec::new();
        apply_icon_style_filters(&mut props, &SystemStyle::default());
        assert!(
            props.is_empty(),
            "default SystemStyle must not synthesise a filter"
        );
    }
    #[test]
    fn icon_filters_grayscale_uses_quantised_luminance_matrix() {
        let mut props = Vec::new();
        apply_icon_style_filters(&mut props, &grayscale_style());
        let filters = filters_of(&props);
        assert_eq!(filters.len(), 1);
        let StyleFilter::ColorMatrix(m) = &filters[0] else {
            panic!(
                "prefer_grayscale must emit a ColorMatrix filter, got {:?}",
                filters[0]
            );
        };
        // Rec.709 luminance weights, rounded through FloatValue's 1/1000 fixed point.
        for r in [m.m0, m.m5, m.m10] {
            assert!((r.get() - 0.2126).abs() < 0.001, "R weight {}", r.get());
        }
        for g in [m.m1, m.m6, m.m11] {
            assert!((g.get() - 0.7152).abs() < 0.001, "G weight {}", g.get());
        }
        for b in [m.m2, m.m7, m.m12] {
            assert!((b.get() - 0.0722).abs() < 0.001, "B weight {}", b.get());
        }
        // Alpha row must be pass-through, or grayscale icons would turn opaque/invisible.
        assert_eq!(m.m18.get(), 1.0);
        assert_eq!(m.m15.get(), 0.0);
        assert_eq!(m.m19.get(), 0.0);
        // FloatValue truncates at 3 decimals: the 4th digit of 0.2126 is lost.
        assert_ne!(m.m0.get(), 0.2126);
    }
    #[test]
    fn icon_filters_tint_emits_flood_even_when_fully_transparent() {
        // a == 0 is still forwarded — the resolver does not treat it as "no tint".
        let transparent = ColorU {
            r: 1,
            g: 2,
            b: 3,
            a: 0,
        };
        let mut props = Vec::new();
        apply_icon_style_filters(&mut props, &tint_style(transparent));
        let filters = filters_of(&props);
        assert_eq!(filters.len(), 1);
        assert!(matches!(filters[0], StyleFilter::Flood(c) if c == transparent));
    }
    #[test]
    fn icon_filters_grayscale_and_tint_are_ordered_matrix_then_flood() {
        let tint = ColorU {
            r: 255,
            g: 0,
            b: 128,
            a: 255,
        };
        let mut style = grayscale_style();
        style.icon_style.tint_color = OptionColorU::Some(tint);
        let mut props = Vec::new();
        apply_icon_style_filters(&mut props, &style);
        // Both filters must live in ONE `filter:` declaration (a second declaration
        // would overwrite the first in the cascade, silently dropping the grayscale).
        let filter_decls = props
            .iter()
            .filter(|p| matches!(p.property, CssProperty::Filter(_)))
            .count();
        assert_eq!(filter_decls, 1);
        let filters = filters_of(&props);
        assert_eq!(filters.len(), 2);
        assert!(matches!(filters[0], StyleFilter::ColorMatrix(_)));
        assert!(matches!(filters[1], StyleFilter::Flood(c) if c == tint));
    }
    #[test]
    fn icon_filters_preserve_pre_existing_properties() {
        let mut props = vec![CssPropertyWithConditions::simple(CssProperty::width(
            LayoutWidth::px(4.0),
        ))];
        apply_icon_style_filters(&mut props, &grayscale_style());
        assert_eq!(props.len(), 2);
        assert!(
            matches!(props[0].property, CssProperty::Width(_)),
            "existing props must not be clobbered"
        );
        assert!(matches!(props[1].property, CssProperty::Filter(_)));
    }
    #[test]
    fn image_icon_grayscale_reaches_the_resolved_dom() {
        let out = resolve(
            RefAny::new(image_icon(10.0, 10.0)),
            &Dom::create_div().root,
            &grayscale_style(),
        );
        let filters = filters_of(&all_props(&out));
        assert_eq!(filters.len(), 1);
        assert!(matches!(filters[0], StyleFilter::ColorMatrix(_)));
    }
    // ---------------------------------------------------------------------
    // apply_font_icon_color
    // ---------------------------------------------------------------------
    #[test]
    fn font_icon_color_default_style_adds_nothing() {
        let mut props = Vec::new();
        apply_font_icon_color(&mut props, &SystemStyle::default());
        assert!(props.is_empty());
    }
    #[test]
    fn font_icon_color_inherit_text_color_alone_is_a_noop() {
        // Documented: inheritance is CSS's default, so `inherit_text_color` must
        // *not* synthesise a `color:` declaration (that would break inheritance).
        let mut style = SystemStyle::default();
        style.icon_style.inherit_text_color = true;
        let mut props = Vec::new();
        apply_font_icon_color(&mut props, &style);
        assert!(props.is_empty());
    }
    #[test]
    fn font_icon_color_tint_becomes_text_color() {
        let tint = ColorU {
            r: 9,
            g: 8,
            b: 7,
            a: 6,
        };
        let mut props = Vec::new();
        apply_font_icon_color(&mut props, &tint_style(tint));
        assert_eq!(props.len(), 1);
        assert_eq!(text_color_of(&props), Some(tint));
    }
    #[test]
    fn font_icon_color_tint_wins_over_inherit_text_color() {
        let tint = ColorU {
            r: 1,
            g: 1,
            b: 1,
            a: 255,
        };
        let mut style = tint_style(tint);
        style.icon_style.inherit_text_color = true;
        let mut props = Vec::new();
        apply_font_icon_color(&mut props, &style);
        assert_eq!(text_color_of(&props), Some(tint));
    }
    #[test]
    fn font_icons_never_get_a_grayscale_filter() {
        // Font icons take the color path, not the filter path — a ColorMatrix here
        // would double-apply on top of the (inherited) text color.
        let out = resolve(
            RefAny::new(font_icon("\u{e88a}")),
            &Dom::create_div().root,
            &grayscale_style(),
        );
        assert!(filters_of(&all_props(&out)).is_empty());
    }
    // ---------------------------------------------------------------------
    // unicode / huge strings in the icon char
    // ---------------------------------------------------------------------
    #[test]
    fn font_icon_empty_char_yields_empty_text_node() {
        let out = resolve(
            RefAny::new(font_icon("")),
            &Dom::create_div().root,
            &SystemStyle::default(),
        );
        assert_eq!(text_of(&out).as_deref(), Some(""));
    }
    #[test]
    fn font_icon_hostile_unicode_round_trips_verbatim() {
        // ZWJ emoji sequence, RTL override, combining marks, an embedded NUL and a
        // lone PUA codepoint: none may be normalised, truncated or panicked on.
        for s in [
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}",
            "\u{202E}gnippilf\u{202C}",
            "e\u{0301}\u{0327}\u{0328}",
            "a\0b",
            "\u{F8FF}",
            "\u{FFFD}",
        ] {
            let out = resolve(
                RefAny::new(font_icon(s)),
                &Dom::create_div().root,
                &SystemStyle::default(),
            );
            assert_eq!(
                text_of(&out).as_deref(),
                Some(s),
                "icon_char {s:?} was altered"
            );
        }
    }
    #[test]
    fn font_icon_huge_char_string_does_not_panic() {
        let huge = "\u{e88a}".repeat(65_536);
        let out = resolve(
            RefAny::new(font_icon(&huge)),
            &Dom::create_div().root,
            &SystemStyle::default(),
        );
        assert_eq!(text_of(&out).map(|s| s.chars().count()), Some(65_536));
    }
    // ---------------------------------------------------------------------
    // registration helpers
    // ---------------------------------------------------------------------
    #[test]
    fn register_image_icon_lowercases_the_name_and_reads_size_from_the_imageref() {
        let mut provider = create_default_icon_provider();
        register_image_icon(&mut provider, "App-Images", "HOME", null_img(64, 32));
        // pack names are case-sensitive, icon names are normalised to lowercase
        assert_eq!(provider.list_packs(), vec![String::from("App-Images")]);
        assert_eq!(
            provider.list_icons_in_pack("App-Images"),
            vec![String::from("home")]
        );
        assert!(provider.list_icons_in_pack("app-images").is_empty());
        assert!(provider.has_icon("hOmE"));
        let data = provider.lookup("HOME").expect("case-insensitive lookup");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        assert_eq!(width_px(&out), Some(64.0));
        assert_eq!(height_px(&out), Some(32.0));
    }
    #[test]
    fn register_font_icon_accepts_empty_pack_and_icon_names() {
        let mut provider = create_default_icon_provider();
        register_font_icon(&mut provider, "", "", dummy_font_ref(), "");
        assert_eq!(provider.list_packs(), vec![String::new()]);
        assert!(provider.has_icon(""));
        let data = provider
            .lookup("")
            .expect("empty-named icon is still addressable");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        assert_eq!(text_of(&out).as_deref(), Some(""));
    }
    #[test]
    fn register_icon_handles_oversized_and_unicode_names() {
        let mut provider = create_default_icon_provider();
        let long_name = "n".repeat(10_000);
        register_font_icon(&mut provider, "p", &long_name, dummy_font_ref(), "x");
        assert!(provider.has_icon(&long_name));
        // "İ" (U+0130) lowercases to TWO chars (i + U+0307); the key is the
        // lowercased form, so the dotless "i" must NOT match.
        register_font_icon(&mut provider, "p", "\u{130}", dummy_font_ref(), "y");
        let folded = "\u{130}".to_lowercase();
        assert!(provider.has_icon("\u{130}"));
        assert!(provider.has_icon(&folded));
        assert!(!provider.has_icon("i"));
    }
    #[test]
    fn duplicate_icon_across_packs_resolves_to_the_alphabetically_first_pack() {
        // "First match wins" iterates a BTreeMap => pack *name* order, NOT the
        // registration order. Registering into "zzz" first must not shadow "aaa".
        let mut provider = create_default_icon_provider();
        register_image_icon(&mut provider, "zzz", "dup", null_img(1, 1));
        register_image_icon(&mut provider, "aaa", "dup", null_img(2, 2));
        let data = provider.lookup("dup").expect("icon registered");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        assert_eq!(
            width_px(&out),
            Some(2.0),
            "lookup must return the alphabetically-first pack's icon"
        );
    }
    #[test]
    fn re_registering_an_icon_replaces_it_and_unregistering_drops_the_empty_pack() {
        let mut provider = create_default_icon_provider();
        register_image_icon(&mut provider, "p", "icon", null_img(1, 1));
        register_image_icon(&mut provider, "p", "ICON", null_img(5, 5));
        assert_eq!(provider.list_icons_in_pack("p").len(), 1);
        let data = provider.lookup("icon").expect("icon registered");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        assert_eq!(width_px(&out), Some(5.0));
        provider.unregister_icon("p", "IcOn");
        assert!(!provider.has_icon("icon"));
        assert!(
            provider.list_packs().is_empty(),
            "empty pack must be removed"
        );
    }
    #[test]
    fn create_default_icon_provider_starts_empty_and_misses_resolve_to_a_placeholder() {
        let provider = create_default_icon_provider();
        assert!(provider.list_packs().is_empty());
        assert!(provider.lookup("nope").is_none());
        assert!(!provider.has_icon("nope"));
        let out = default_icon_resolver(
            OptionRefAny::from(provider.lookup("nope")),
            &Dom::create_div().root,
            &SystemStyle::default(),
        );
        assert_eq!(all_nodes(&out).len(), 1);
        assert!(all_props(&out).is_empty());
    }
    // ---------------------------------------------------------------------
    // ZIP / font-bytes entry points (both cfg variants share these signatures)
    // ---------------------------------------------------------------------
    #[test]
    fn load_images_from_zip_rejects_malformed_archives() {
        assert!(load_images_from_zip(&[]).is_empty());
        assert!(load_images_from_zip(b"definitely not a zip file").is_empty());
        // valid local-file-header magic, truncated body
        assert!(load_images_from_zip(b"PK\x03\x04\x00\x00\x00\x00").is_empty());
        // End-of-central-directory magic claiming 0xFFFF entries that don't exist
        assert!(load_images_from_zip(b"PK\x05\x06\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF").is_empty());
        assert!(load_images_from_zip(&[0xFFu8; 4096]).is_empty());
    }
    #[test]
    fn register_icons_from_zip_registers_nothing_for_garbage_bytes() {
        for bytes in [
            &b""[..],
            &b"not a zip"[..],
            &b"PK\x03\x04\x00\x00\x00\x00"[..],
            &[0x00u8; 512][..],
        ] {
            let mut provider = create_default_icon_provider();
            register_icons_from_zip(&mut provider, "pack", bytes);
            assert!(
                provider.list_packs().is_empty(),
                "a malformed ZIP must not create a pack"
            );
        }
    }
    #[test]
    fn register_embedded_material_icons_rejects_non_font_bytes() {
        for bytes in [
            &b""[..],
            &b"this is not a TTF"[..],
            // sfnt version tag + nothing else
            &b"\x00\x01\x00\x00"[..],
            &[0xFFu8; 256][..],
        ] {
            let mut provider = create_default_icon_provider();
            let ok = register_embedded_material_icons(&mut provider, bytes);
            assert!(!ok, "corrupt font bytes must not report success");
            assert!(provider.list_packs().is_empty());
        }
    }
    #[cfg(feature = "icons")]
    #[test]
    fn register_material_icons_fills_a_single_lowercase_pack() {
        let mut provider = create_default_icon_provider();
        let font = dummy_font_ref();
        register_material_icons(&mut provider, &font);
        assert_eq!(provider.list_packs(), vec![String::from("material-icons")]);
        let names = provider.list_icons_in_pack("material-icons");
        assert!(
            names.len() > 1000,
            "expected the full icon set, got {}",
            names.len()
        );
        assert!(
            names.iter().all(|n| *n == n.to_lowercase()),
            "every registered icon name must be normalised to lowercase"
        );
        assert!(provider.has_icon("home"));
        assert!(provider.has_icon("HOME"));
        let data = provider.lookup("home").expect("material 'home' icon");
        let out = resolve(data, &Dom::create_div().root, &SystemStyle::default());
        assert!(
            text_of(&out).is_some(),
            "a material icon must resolve to a text node"
        );
    }
}