1
//! Rendering an icon-registry entry to RGBA pixels, at any size.
2
//!
3
//! This exists for the system tray, which is the one consumer that needs an
4
//! icon as *pixels* rather than as part of a DOM: Windows hands RGBA to
5
//! `CreateIconIndirect`, macOS to `NSBitmapImageRep`, and Linux to SNI's
6
//! `IconPixmap` (`a(iiay)`).
7
//!
8
//! # Why it goes through the DOM
9
//!
10
//! The obvious implementation — look up the icon, notice it is a font glyph,
11
//! rasterize the glyph — would work for Material Icons and nothing else. The
12
//! registry holds `ImageIconData` (image packs loaded from a ZIP) and
13
//! `FontIconData` (Material Icons) today, and whatever a custom resolver
14
//! returns tomorrow.
15
//!
16
//! So instead this does what an `<icon>` node does: build a one-node icon DOM,
17
//! run the SAME icon-resolution pass, and render the resulting
18
//! `StyledDom` with the CPU renderer. Every icon kind is handled because none
19
//! of them is special-cased — and anything a future resolver can express as a
20
//! DOM (an SVG, an emoji, a styled `<div>`) becomes a usable tray icon for
21
//! free, with no change here.
22
//!
23
//! It also means a tray icon and an in-DOM `<icon>` of the same spec can never
24
//! disagree: they are literally the same code path up to rasterization.
25

            
26
use alloc::{string::String, vec::Vec};
27

            
28
use azul_core::{
29
    dom::Dom,
30
    icon::{styled_dom_resolving_icons, SharedIconProvider},
31
    styled_dom::StyledDom,
32
};
33
use azul_css::{
34
    css::{Css, CssPropertyValue},
35
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
36
    props::{
37
        basic::{ColorU, StyleFontSize},
38
        layout::{LayoutHeight, LayoutWidth},
39
        property::CssProperty,
40
        style::text::StyleTextColor,
41
    },
42
    system::SystemStyle,
43
};
44

            
45
/// A rendered icon: device-pixel dimensions plus straight RGBA8, top row first.
46
#[derive(Debug, Clone, PartialEq, Eq)]
47
pub struct RenderedIcon {
48
    pub width: u32,
49
    pub height: u32,
50
    /// `width * height * 4` bytes, non-premultiplied RGBA8.
51
    pub rgba: Vec<u8>,
52
}
53

            
54
/// Render an icon spec to an RGBA bitmap of `size_px` square.
55
///
56
/// `spec` is exactly what an `<icon>` node takes: a bare name (`"settings"`),
57
/// a pack-qualified name (`"mypack:logo"`), or a comma-separated fallback list.
58
/// Parsing it is the registry's job — this passes it through untouched so that
59
/// a tray icon and an `<icon>` can never resolve differently.
60
///
61
/// The background is fully transparent, which is what all three tray backends
62
/// want. Note the consequence for **Material Icons specifically**: they resolve
63
/// to a text node whose colour comes from the cascade, and the default is
64
/// opaque black. That is correct for a light menu bar / taskbar and invisible
65
/// on a dark one. Callers that know the tray's background — macOS, where a
66
/// template image is tinted by `AppKit` anyway — should pass `tint`.
67
///
68
/// Returns `None` if the spec resolves to nothing (an unregistered icon), or if
69
/// the renderer fails.
70
#[must_use]
71
pub fn render_icon_to_rgba(
72
    spec: &str,
73
    size_px: u32,
74
    provider: &SharedIconProvider,
75
    system_style: &SystemStyle,
76
    tint: Option<ColorU>,
77
    font_manager: &crate::font_traits::FontManager<azul_css::props::basic::FontRef>,
78
) -> Option<RenderedIcon> {
79
    use crate::cpurender::{render_component_preview, ComponentPreviewOptions};
80

            
81
    if size_px == 0 || spec.is_empty() {
82
        return None;
83
    }
84

            
85
    // Cheap reject before doing any layout work: an unregistered spec would
86
    // otherwise resolve to an empty div and render a fully transparent square,
87
    // which the caller cannot distinguish from a legitimately blank icon.
88
    if !spec_resolves(spec, provider) {
89
        return None;
90
    }
91

            
92
    #[allow(clippy::cast_precision_loss)] // icon sizes are small
93
    let size = size_px as f32;
94

            
95
    let mut props = alloc::vec![
96
        CssPropertyWithConditions::simple(CssProperty::Width(CssPropertyValue::Exact(
97
            LayoutWidth::px(size)
98
        ))),
99
        CssPropertyWithConditions::simple(CssProperty::Height(CssPropertyValue::Exact(
100
            LayoutHeight::px(size)
101
        ))),
102
        // A font icon resolves to TEXT, and a glyph is sized by font-size, not
103
        // by its box — without this the box would be size_px and the glyph
104
        // whatever the cascade's default font-size happens to be.
105
        CssPropertyWithConditions::simple(CssProperty::FontSize(CssPropertyValue::Exact(
106
            StyleFontSize::px(size)
107
        ))),
108
    ];
109
    if let Some(c) = tint {
110
        props.push(CssPropertyWithConditions::simple(CssProperty::TextColor(
111
            CssPropertyValue::Exact(StyleTextColor { inner: c }),
112
        )));
113
    }
114

            
115
    let dom = Dom::create_icon(String::from(spec))
116
        .with_css_props(CssPropertyWithConditionsVec::from_vec(props));
117

            
118
    // Both halves in one call - the same one every other Dom-to-StyledDom path
119
    // uses. Icons resolve on the `Dom`, BEFORE the cascade, so the replacement
120
    // is spliced in whole and cascaded exactly once with everything else; doing
121
    // it the other way round - cascade, then splice into the flat StyledDom
122
    // arena - is what used to flatten every icon to a single node and leave the
123
    // property cache describing the pre-resolution node.
124
    //
125
    // And the cascade is `create_from_dom`, NOT `create(&mut dom, Css::empty())`:
126
    // the former also runs `fixup_children_estimated` + `scope_inline_css` and
127
    // collects the tree's inline CSS, which is what the engine's own layout path
128
    // (`regenerate_layout`) uses. Building the StyledDom the other way produces
129
    // a subtly different property cache and the icon does not resolve the same.
130
    let styled = styled_dom_resolving_icons(dom, provider, system_style);
131

            
132
    // The caller's FontManager, NOT a fresh one.
133
    //
134
    // Building one here (`FontManager::new(build_font_cache())`) creates a
135
    // second, disconnected font universe: a `FontManager` shapes from TWO pools
136
    // — `parsed_fonts` (resolved by family NAME out of the system font cache)
137
    // and `embedded_fonts` (handed over directly as `StyleFontFamily::Ref`) —
138
    // and Material Icons live in the SECOND, because
139
    // `create_font_icon_from_original` styles the glyph with
140
    // `StyleFontFamily::Ref(font)` rather than a family name. A fresh manager
141
    // has that pool empty, so every icon shaped to `.notdef` and the tray got a
142
    // tofu box, with every intermediate step reporting success. Same shape as
143
    // the 0.2.0 CPU-renderer failure documented on
144
    // `FontManager::resolve_font_by_hash`.
145
    //
146
    // Registering the DOM's embedded fonts is still needed for a manager that
147
    // has not seen this particular icon font yet; it is idempotent.
148
    crate::solver3::getters::register_embedded_fonts_from_styled_dom(
149
        &styled,
150
        font_manager,
151
        &system_style.platform,
152
    );
153

            
154
    let result = render_component_preview(
155
        &styled,
156
        font_manager,
157
        ComponentPreviewOptions {
158
            width: Some(size),
159
            height: Some(size),
160
            dpi_factor: 1.0,
161
            // Transparent, NOT the white the preview renderer defaults to — a
162
            // tray icon composited over a white square is a white square.
163
            background_color: ColorU {
164
                r: 0,
165
                g: 0,
166
                b: 0,
167
                a: 0,
168
            },
169
        },
170
        None,
171
    )
172
    .ok()?;
173

            
174
    // A wrong-looking tray icon is otherwise almost impossible to diagnose: it
175
    // is a 36px image inside the menu bar, and every intermediate step reports
176
    // success. `AZ_TRAY_ICON_DUMP=<dir>` writes the exact bitmap we hand the OS.
177
    if let Ok(dir) = std::env::var("AZ_TRAY_ICON_DUMP") {
178
        let path = format!("{dir}/tray-icon-{size_px}.png");
179
        // Diagnostic dump only: a write failure here must never affect the
180
        // icon actually being handed to the OS.
181
        drop(std::fs::write(&path, &result.png_data));
182
    }
183

            
184
    if result.rgba.is_empty() || result.pixel_width == 0 || result.pixel_height == 0 {
185
        return None;
186
    }
187

            
188
    Some(RenderedIcon {
189
        width: result.pixel_width,
190
        height: result.pixel_height,
191
        rgba: result.rgba,
192
    })
193
}
194

            
195
/// Does any pack hold this spec? Mirrors the registry's own lookup, including
196
/// the comma-separated fallback list, so a spec that `<icon>` would resolve is
197
/// never rejected here.
198
7
fn spec_resolves(spec: &str, provider: &SharedIconProvider) -> bool {
199
9
    spec.split(',').any(|alt| {
200
9
        let alt = alt.trim();
201
9
        !alt.is_empty() && provider.lookup(alt).is_some()
202
9
    })
203
7
}
204

            
205
#[cfg(test)]
206
mod tests {
207
    use azul_core::icon::{IconProviderHandle, SharedIconProvider};
208

            
209
    use super::*;
210

            
211
    // `render_icon_to_rgba` itself is not unit-tested: it needs a real
212
    // `FontManager`, and building one scans the system font directories, which
213
    // makes the test slow and machine-dependent. Its pure precondition —
214
    // "does this spec resolve at all" — is what actually decides whether the
215
    // caller gets an icon or a silently-blank square, so that is what is
216
    // pinned here. The rendering itself is exercised by the `tray` example
217
    // plus `AZ_TRAY_ICON_DUMP`.
218

            
219
    #[test]
220
1
    fn spec_resolution_honours_the_fallback_list() {
221
        use azul_core::refany::RefAny;
222
1
        let mut h = IconProviderHandle::new();
223
1
        h.register_icon("testpack", "logo", RefAny::new(1u8));
224
1
        let p = SharedIconProvider::from_handle(h);
225

            
226
1
        assert!(spec_resolves("logo", &p));
227
1
        assert!(spec_resolves("testpack:logo", &p));
228
        // First alternative missing, second present - must still resolve.
229
1
        assert!(spec_resolves("missing:x, logo", &p));
230
1
        assert!(!spec_resolves("missing:x", &p));
231
1
        assert!(!spec_resolves("", &p));
232
1
        assert!(!spec_resolves(" , ", &p));
233
1
    }
234

            
235
    /// REGRESSION (tray icons rendered as `.notdef` tofu boxes).
236
    ///
237
    /// `resolve_icons_in_dom` rewrites a font icon's inline style to
238
    /// carry `font-family: StyleFontFamily::Ref(face)` — the only place that
239
    /// face is ever named. But the compact CSS cache is precomputed at cascade
240
    /// time, so before the fix it still described the pre-resolution `<icon>`
241
    /// node. `collect_font_stacks_from_styled_dom` reads that cache, so it
242
    /// never saw the `Ref`, never registered the face as an embedded font, and
243
    /// shaping silently fell back to a system face with no glyph at the icon's
244
    /// private-use codepoint.
245
    ///
246
    /// The invariant this pins: **after resolving a font-backed icon, the face
247
    /// is visible to font-stack collection.** Everything downstream — embedded
248
    /// registration, shaping, rasterisation — depends on it, and every one of
249
    /// those steps reported success while producing a tofu box, so this is the
250
    /// only place the failure is cheap to catch.
251
    #[test]
252
1
    fn resolving_a_font_icon_leaves_its_face_visible_to_font_collection() {
253
        use azul_core::{
254
            dom::Dom, icon::IconProviderHandle, refany::RefAny, styled_dom::StyledDom,
255
        };
256
        use azul_css::{css::Css, props::basic::FontRef};
257

            
258
        // A FontRef needs no real font data here: collection only reports which
259
        // faces are referenced, it does not parse them.
260
        static DUMMY: u8 = 0;
261
1
        extern "C" fn noop(_: *mut core::ffi::c_void) {}
262
1
        let face = FontRef::new(core::ptr::addr_of!(DUMMY).cast::<core::ffi::c_void>(), noop);
263

            
264
1
        let mut handle = IconProviderHandle::with_resolver(crate::icon::default_icon_resolver);
265
1
        handle.register_icon(
266
1
            "testpack",
267
1
            "gear",
268
1
            RefAny::new(crate::icon::FontIconData {
269
1
                font: face.clone(),
270
1
                icon_char: "\u{e8b8}".into(),
271
1
            }),
272
        );
273
1
        let provider = SharedIconProvider::from_handle(handle);
274

            
275
1
        let mut dom = Dom::create_icon(String::from("gear"));
276
1
        azul_core::icon::resolve_icons_in_dom(&mut dom, &provider, &SystemStyle::default());
277
1
        let styled = StyledDom::create_from_dom(dom);
278

            
279
1
        let collected = crate::solver3::getters::collect_font_stacks_from_styled_dom(
280
1
            &styled,
281
1
            &SystemStyle::default().platform,
282
        );
283
1
        assert!(
284
1
            !collected.font_refs.is_empty(),
285
            "the resolved icon's FontRef must reach font-stack collection; an empty set is the \
286
             tofu-box bug (stale compact cache)"
287
        );
288
1
    }
289

            
290
    #[test]
291
1
    fn an_unregistered_spec_does_not_resolve() {
292
        // This is what stops a blank bitmap reaching the tray: resolution turns
293
        // an unknown icon into an empty div, which renders as a fully
294
        // TRANSPARENT square - indistinguishable from a working icon once it is
295
        // 18pt in a menu bar.
296
1
        let p = SharedIconProvider::from_handle(IconProviderHandle::new());
297
1
        assert!(!spec_resolves("definitely_not_registered", &p));
298
1
    }
299
}