Skip to main content

bhoo/icons/
material_system.rs

1//! Official Google Material Symbols Outlined resolution-independent MSDF system icons (68 icons).
2//!
3//! Source: https://github.com/google/material-design-icons (Apache-2.0, pinned rev `10ecc14790612ca8fd164e3f4ffe9c16fc50d5b7`)
4//! Generated by `tools/msdf-icon-gen` (`fdsm` 0.8 pure-Rust Chlumsky MSDF generator) into
5//! `codes/libs/libbhoo/assets/material-system/icons.msdf` (48x48 3-channel MSDF, `px_range = 4.0`).
6//!
7//! - On GLES (`feature = "gles"`): uploads one 48x48 MSDF per `SystemIcon` to the GPU image atlas
8//!   (68 slots total, regardless of color/opacity) and evaluates `median(r,g,b)` + `fwidth` in the
9//!   fragment shader for razor-sharp vector edges at any size or zoom factor.
10//! - On non-GLES backends (`bhoo-web` Canvas 2D / CPU): evaluates the embedded MSDF via bilinear
11//!   median reconstruction into a cached 96x96 RGBA `Image`.
12
13use crate::{Color, Frame, Image, ImageFit, Rect};
14use std::collections::HashMap;
15use std::sync::{Mutex, OnceLock};
16
17const SYS_ICON_RASTER_SIZE: u32 = 96;
18const SYS_SVG_COUNT: usize = 68;
19const SYS_MSDF_BLOB: &[u8] = include_bytes!("../../assets/material-system/icons.msdf");
20
21/// Bundled high-resolution Google Material Symbols Outlined system icons (Quick Settings, Settings, System UI).
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23pub enum SystemIcon {
24    Wifi,
25    WifiOff,
26    Bluetooth,
27    Flashlight,
28    Alarm,
29    Airplane,
30    DeviceControls,
31    AutoRotate,
32    BatterySaver,
33    DarkMode,
34    Dnd,
35    ScreenCast,
36    ScreenRecord,
37    NightLight,
38    Camera,
39    Mic,
40    Aod,
41    Hotspot,
42    Location,
43    Nfc,
44    InvertColors,
45    Sun,
46    AutoBrightness,
47    Power,
48    Restart,
49    Screenshot,
50    Emergency,
51    Vibrate,
52    Silent,
53    Ring,
54    MusicNote,
55    Bell,
56    Info,
57    SplitScreen,
58    Freeform,
59    Maximize,
60    Close,
61    Settings,
62    Widgets,
63    Palette,
64    Search,
65    Back,
66    ChevronRight,
67    ChevronLeft,
68    ChevronDown,
69    ChevronUp,
70    Edit,
71    Trash,
72    Battery,
73    Storage,
74    Sound,
75    Display,
76    Accessibility,
77    Security,
78    Privacy,
79    Accounts,
80    System,
81    PhoneInfo,
82    AppsGrid,
83    Usb,
84    History,
85    MoreVert,
86    VisibilityOff,
87    LockOpen,
88    Fingerprint,
89    Tune,
90    NotificationsActive,
91    Gesture,
92    CheckCircle,
93    Devices,
94    Language,
95}
96
97impl SystemIcon {
98    /// All distinct `SystemIcon` variants.
99    pub const ALL: &'static [Self] = &[
100        Self::Wifi, Self::WifiOff, Self::Bluetooth, Self::Flashlight, Self::Alarm, Self::Airplane,
101        Self::DeviceControls, Self::AutoRotate, Self::BatterySaver, Self::DarkMode, Self::Dnd,
102        Self::ScreenCast, Self::ScreenRecord, Self::NightLight, Self::Camera, Self::Mic, Self::Aod,
103        Self::Hotspot, Self::Location, Self::Nfc, Self::InvertColors, Self::Sun,
104        Self::AutoBrightness, Self::Power, Self::Restart, Self::Screenshot, Self::Emergency,
105        Self::Vibrate, Self::Silent, Self::Ring, Self::MusicNote, Self::Bell, Self::Info,
106        Self::SplitScreen, Self::Freeform, Self::Maximize, Self::Close, Self::Settings,
107        Self::Widgets, Self::Palette, Self::Search, Self::Back, Self::ChevronRight,
108        Self::ChevronLeft, Self::ChevronDown, Self::ChevronUp, Self::Edit, Self::Trash,
109        Self::Battery, Self::Storage, Self::Sound, Self::Display, Self::Accessibility,
110        Self::Security, Self::Privacy, Self::Accounts, Self::System, Self::PhoneInfo,
111        Self::AppsGrid, Self::Usb, Self::History, Self::MoreVert, Self::VisibilityOff,
112        Self::LockOpen, Self::Fingerprint, Self::Tune, Self::NotificationsActive,
113        Self::Gesture, Self::CheckCircle, Self::Devices, Self::Language,
114    ];
115
116    pub(crate) fn mask_index(self) -> usize {
117        match self {
118            Self::Wifi => 0,
119            Self::WifiOff => 1,
120            Self::Bluetooth => 2,
121            Self::Flashlight => 3,
122            Self::Alarm => 4,
123            Self::Airplane => 5,
124            Self::DeviceControls => 6,
125            Self::AutoRotate => 7,
126            Self::BatterySaver => 8,
127            Self::DarkMode => 9,
128            Self::Dnd => 10,
129            Self::ScreenCast => 11,
130            Self::ScreenRecord => 12,
131            Self::NightLight => 13,
132            Self::Camera => 14,
133            Self::Mic => 15,
134            Self::Aod => 16,
135            Self::Hotspot => 17,
136            Self::Location => 18,
137            Self::Nfc => 19,
138            Self::InvertColors => 20,
139            Self::Sun | Self::Display => 21,
140            Self::AutoBrightness => 22,
141            Self::Power => 23,
142            Self::Restart => 24,
143            Self::Screenshot => 25,
144            Self::Emergency => 26,
145            Self::Vibrate => 27,
146            Self::Silent => 28,
147            Self::Ring | Self::Bell => 29,
148            Self::MusicNote => 30,
149            Self::Info | Self::System => 31,
150            Self::SplitScreen => 32,
151            Self::Freeform => 33,
152            Self::Maximize => 34,
153            Self::Close => 35,
154            Self::Settings => 36,
155            Self::Widgets => 37,
156            Self::Palette => 38,
157            Self::Search => 39,
158            Self::Back => 40,
159            Self::ChevronRight => 41,
160            Self::ChevronLeft => 42,
161            Self::ChevronDown => 43,
162            Self::ChevronUp => 44,
163            Self::Edit => 45,
164            Self::Trash => 46,
165            Self::Battery => 47,
166            Self::Storage => 48,
167            Self::Sound => 49,
168            Self::Accessibility => 50,
169            Self::Security => 51,
170            Self::Privacy => 52,
171            Self::Accounts => 53,
172            Self::PhoneInfo => 54,
173            Self::AppsGrid => 55,
174            Self::Usb => 56,
175            Self::History => 57,
176            Self::MoreVert => 58,
177            Self::VisibilityOff => 59,
178            Self::LockOpen => 60,
179            Self::Fingerprint => 61,
180            Self::Tune => 62,
181            Self::NotificationsActive => 63,
182            Self::Gesture => 64,
183            Self::CheckCircle => 65,
184            Self::Devices => 66,
185            Self::Language => 67,
186        }
187    }
188}
189
190/// Decode a legacy 4-bit-value / 4-bit-run-length alpha mask into `total` bytes (`0..=255`).
191pub fn decode_rle4(rle: &[u8], total: usize) -> Vec<u8> {
192    let mut mask = Vec::with_capacity(total);
193    for &b in rle {
194        let v = (b >> 4) * 17;
195        let run = ((b & 0x0F) as usize) + 1;
196        let take = run.min(total - mask.len());
197        mask.resize(mask.len() + take, v);
198        if mask.len() >= total {
199            break;
200        }
201    }
202    mask.resize(total, 0);
203    mask
204}
205
206/// Decode a lossless 8-bit RLE byte stream into `total` bytes (`0..=255`).
207pub fn decode_rle8(rle: &[u8], total: usize) -> Vec<u8> {
208    let mut mask = Vec::with_capacity(total);
209    let mut i = 0;
210    while i < rle.len() && mask.len() < total {
211        let b = rle[i];
212        i += 1;
213        if b < 0x80 {
214            let take = ((b as usize) + 1).min(total - mask.len());
215            mask.resize(mask.len() + take, 0);
216        } else if b < 0xC0 {
217            let take = (((b - 0x80) as usize) + 1).min(total - mask.len());
218            mask.resize(mask.len() + take, 255);
219        } else {
220            let count = ((b - 0xC0) as usize) + 1;
221            let avail = count.min(rle.len().saturating_sub(i));
222            let take = avail.min(total - mask.len());
223            mask.extend_from_slice(&rle[i..i + take]);
224            i += count;
225        }
226    }
227    mask.resize(total, 0);
228    mask
229}
230
231fn decode_msdf_entry(idx: usize) -> (u32, f32, Vec<u8>) {
232    debug_assert!(SYS_MSDF_BLOB.len() >= 12 && &SYS_MSDF_BLOB[0..4] == b"MSDF");
233    let count = u16::from_le_bytes([SYS_MSDF_BLOB[4], SYS_MSDF_BLOB[5]]) as usize;
234    let size = u16::from_le_bytes([SYS_MSDF_BLOB[6], SYS_MSDF_BLOB[7]]) as u32;
235    let px_range = f32::from_le_bytes([
236        SYS_MSDF_BLOB[8],
237        SYS_MSDF_BLOB[9],
238        SYS_MSDF_BLOB[10],
239        SYS_MSDF_BLOB[11],
240    ]);
241    assert!(idx < count, "SystemIcon index {idx} out of range {count}");
242    let table_start = 12usize;
243    let payload_start = table_start + (count + 1) * 4;
244    let off0 = u32::from_le_bytes(
245        SYS_MSDF_BLOB[table_start + idx * 4..table_start + (idx + 1) * 4]
246            .try_into()
247            .unwrap(),
248    ) as usize;
249    let off1 = u32::from_le_bytes(
250        SYS_MSDF_BLOB[table_start + (idx + 1) * 4..table_start + (idx + 2) * 4]
251            .try_into()
252            .unwrap(),
253    ) as usize;
254    let plane_len = (size * size) as usize;
255    let planar = decode_rle8(&SYS_MSDF_BLOB[payload_start + off0..payload_start + off1], plane_len * 3);
256    let (r_plane, rest) = planar.split_at(plane_len);
257    let (g_plane, b_plane) = rest.split_at(plane_len);
258    let mut rgba = vec![255u8; plane_len * 4];
259    for i in 0..plane_len {
260        let o = i * 4;
261        rgba[o] = r_plane[i];
262        rgba[o + 1] = g_plane[i];
263        rgba[o + 2] = b_plane[i];
264    }
265    (size, px_range, rgba)
266}
267
268/// Return the cached resolution-independent 48x48 MSDF `Image` for `icon`.
269///
270/// Each distinct `SystemIcon` occupies only one 48x48 GPU atlas slot regardless of tint color or
271/// opacity animation; the GLES fragment shader evaluates `median(r, g, b)` analytically per pixel.
272pub fn system_icon_msdf(icon: SystemIcon) -> Image {
273    let idx = icon.mask_index();
274    static MSDF_CACHE: OnceLock<[OnceLock<Image>; SYS_SVG_COUNT]> = OnceLock::new();
275    let slots = MSDF_CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
276    slots[idx]
277        .get_or_init(|| {
278            let (size, px_range, rgba) = decode_msdf_entry(idx);
279            Image::msdf(size, size, px_range, rgba).expect("valid embedded MSDF system icon")
280        })
281        .clone()
282}
283
284#[inline]
285fn median3(r: f32, g: f32, b: f32) -> f32 {
286    r.min(g).max(r.max(g).min(b))
287}
288
289/// Decode a tinted 96x96 RGBA `Image` for `icon` by evaluating its embedded MSDF on CPU,
290/// cached by quantized alpha (used by non-GLES backends such as `bhoo-web` Canvas 2D).
291pub fn system_icon_image(icon: SystemIcon, color: Color) -> Image {
292    let idx = icon.mask_index();
293    let qa = if color.3 >= 248 {
294        255
295    } else {
296        ((color.3 as u16 + 8) / 17 * 17).min(255) as u8
297    };
298    let key = (idx as u16, color.0, color.1, color.2, qa);
299    static SYS_CACHE: OnceLock<Mutex<HashMap<(u16, u8, u8, u8, u8), Image>>> = OnceLock::new();
300    let lock = SYS_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
301    let mut map = lock.lock().expect("sys icon cache lock");
302    if let Some(existing) = map.get(&key) {
303        return existing.clone();
304    }
305    if map.len() > 280 {
306        map.clear();
307    }
308    let msdf = system_icon_msdf(icon);
309    let src_w = msdf.width() as usize;
310    let src_h = msdf.height() as usize;
311    let src = msdf.pixels();
312    let px_range = msdf.msdf_px_range();
313    let dst_size = SYS_ICON_RASTER_SIZE as usize;
314    // Match GLES atlas UV mapping: quad [0..dst_size] maps onto texel centers [0.0 .. src_w - 1.0].
315    let screen_px_range = (px_range * (dst_size as f32 / (src_w as f32 - 1.0))).max(1.0);
316    let mut rgba = vec![0u8; dst_size * dst_size * 4];
317    for dy in 0..dst_size {
318        let sy = ((dy as f32 + 0.5) / dst_size as f32) * (src_h as f32 - 1.0);
319        let y0 = (sy.floor() as usize).min(src_h - 1);
320        let y1 = (y0 + 1).min(src_h - 1);
321        let fy = sy - y0 as f32;
322        for dx in 0..dst_size {
323            let sx = ((dx as f32 + 0.5) / dst_size as f32) * (src_w as f32 - 1.0);
324            let x0 = (sx.floor() as usize).min(src_w - 1);
325            let x1 = (x0 + 1).min(src_w - 1);
326            let fx = sx - x0 as f32;
327
328            let i00 = (y0 * src_w + x0) * 4;
329            let i10 = (y0 * src_w + x1) * 4;
330            let i01 = (y1 * src_w + x0) * 4;
331            let i11 = (y1 * src_w + x1) * 4;
332            let w00 = (1.0 - fx) * (1.0 - fy);
333            let w10 = fx * (1.0 - fy);
334            let w01 = (1.0 - fx) * fy;
335            let w11 = fx * fy;
336
337            let r = (src[i00] as f32 * w00
338                + src[i10] as f32 * w10
339                + src[i01] as f32 * w01
340                + src[i11] as f32 * w11)
341                * (1.0 / 255.0);
342            let g = (src[i00 + 1] as f32 * w00
343                + src[i10 + 1] as f32 * w10
344                + src[i01 + 1] as f32 * w01
345                + src[i11 + 1] as f32 * w11)
346                * (1.0 / 255.0);
347            let b = (src[i00 + 2] as f32 * w00
348                + src[i10 + 2] as f32 * w10
349                + src[i01 + 2] as f32 * w01
350                + src[i11 + 2] as f32 * w11)
351                * (1.0 / 255.0);
352
353            let sd = median3(r, g, b) - 0.5;
354            let cov = (screen_px_range * sd + 0.5).clamp(0.0, 1.0);
355            let m = (cov * 255.0 + 0.5) as u8;
356            if m > 0 {
357                let o = (dy * dst_size + dx) * 4;
358                rgba[o] = color.0;
359                rgba[o + 1] = color.1;
360                rgba[o + 2] = color.2;
361                rgba[o + 3] = ((m as u16 * qa as u16 + 127) / 255) as u8;
362            }
363        }
364    }
365    let created = Image::rgba(SYS_ICON_RASTER_SIZE, SYS_ICON_RASTER_SIZE, rgba)
366        .expect("valid 96x96 sys icon");
367    map.insert(key, created.clone());
368    created
369}
370
371impl Frame<'_> {
372    /// Paint a bundled high-resolution Material Symbols Outlined system icon tinted to `color`.
373    ///
374    /// On GLES backends, renders directly from the embedded 48x48 MSDF texture for resolution-
375    /// independent vector sharpness at any display scale or zoom level.
376    pub fn paint_system_icon(&mut self, bounds: Rect, icon: SystemIcon, color: Color) {
377        if color.3 <= 2 || bounds.width <= 0.5 || bounds.height <= 0.5 {
378            return;
379        }
380        #[cfg(feature = "gles")]
381        {
382            let img = system_icon_msdf(icon);
383            self.paint_tinted_image(bounds, &img, ImageFit::Contain, 0.0, color);
384        }
385        #[cfg(not(feature = "gles"))]
386        {
387            let img = system_icon_image(icon, color);
388            self.paint_image(bounds, &img, ImageFit::Contain, 0.0);
389        }
390    }
391}
392
393#[cfg(test)]
394#[path = "material_system.spec.rs"]
395mod tests;