Skip to main content

native_gui_core/
artprov.rs

1//! Stock art/icon provider.
2//!
3//! The provider resolves **roles** (new/open/save/warning/…) into concrete
4//! icon rasters with two independent axes:
5//!
6//! - **DPI variants** — [`IconSize::Small`] (16 logical px) and
7//!   [`IconSize::Large`] (32 logical px), rasterized at an integer `scale`
8//!   factor so the same request can serve a 1x or 2x/3x display.
9//! - **Theme modes** — the glyph palette is resolved from the active
10//!   [`Theme`], so light and dark mode produce different pixels from the same
11//!   role (severity roles use `warning`/`error`, actions use `accent`,
12//!   structure uses `text`, and cut-outs use `surface`).
13//!
14//! The portable renderer in this module is library-owned art: it is
15//! deterministic, dependency-free, and available on **every** backend through
16//! [`crate::Ui::stock_icon`] / [`crate::Ui::stock_icon_at_scale`].
17//!
18//! The optional **native tier** ([`crate::Ui::native_stock_icon`]) asks the
19//! lane for an OS-provided stock icon and is the place where platforms
20//! genuinely differ: Win32 maps the severity roles to system icons, GTK
21//! looks the role up in the icon theme, and Cocoa maps a subset to
22//! `NSImageName*` assets. A lane without a native mapping returns the typed
23//! [`GuiError::UnsupportedCapability`] instead of fabricating art, and
24//! reports what it can really do through [`ArtCapabilities`]. See
25//! `docs/widget-expansion-roadmap.md` ("Theming and art provider")
26//! for the design and evidence rules.
27//!
28//! Icons can be materialized for [`crate::WidgetKind::Image`] with
29//! [`StockIcon::to_bmp`] until typed image resources accept pixels directly.
30
31use crate::error::{GuiError, GuiResult};
32use crate::theme::{Theme, ThemeMode};
33use crate::widgets::Color;
34
35/// A portable stock-art role.
36///
37/// The set is deliberately bounded: every role has a deterministic portable
38/// glyph, a stable identifier, and a freedesktop icon name for lanes that
39/// resolve themes natively.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum IconRole {
42    New,
43    Open,
44    Save,
45    Close,
46    Delete,
47    Copy,
48    Paste,
49    Undo,
50    Redo,
51    Refresh,
52    Search,
53    Preferences,
54    Home,
55    Folder,
56    File,
57    Information,
58    Warning,
59    Error,
60    Question,
61    Help,
62    Play,
63    Stop,
64    NavigateBack,
65    NavigateForward,
66    NavigateUp,
67    Application,
68    FormatBold,
69    FormatItalic,
70    FormatStrikethrough,
71    FormatCode,
72    FormatHeading,
73    ListBulleted,
74    ListNumbered,
75    ListTask,
76    Quote,
77    InsertLink,
78    InsertImage,
79    InsertTable,
80    InsertRule,
81    ThemeToggle,
82}
83
84impl IconRole {
85    /// Every portable role, in declaration order.
86    pub const ALL: [IconRole; 40] = [
87        IconRole::New,
88        IconRole::Open,
89        IconRole::Save,
90        IconRole::Close,
91        IconRole::Delete,
92        IconRole::Copy,
93        IconRole::Paste,
94        IconRole::Undo,
95        IconRole::Redo,
96        IconRole::Refresh,
97        IconRole::Search,
98        IconRole::Preferences,
99        IconRole::Home,
100        IconRole::Folder,
101        IconRole::File,
102        IconRole::Information,
103        IconRole::Warning,
104        IconRole::Error,
105        IconRole::Question,
106        IconRole::Help,
107        IconRole::Play,
108        IconRole::Stop,
109        IconRole::NavigateBack,
110        IconRole::NavigateForward,
111        IconRole::NavigateUp,
112        IconRole::Application,
113        IconRole::FormatBold,
114        IconRole::FormatItalic,
115        IconRole::FormatStrikethrough,
116        IconRole::FormatCode,
117        IconRole::FormatHeading,
118        IconRole::ListBulleted,
119        IconRole::ListNumbered,
120        IconRole::ListTask,
121        IconRole::Quote,
122        IconRole::InsertLink,
123        IconRole::InsertImage,
124        IconRole::InsertTable,
125        IconRole::InsertRule,
126        IconRole::ThemeToggle,
127    ];
128
129    /// Stable lowercase identifier used by tests, diagnostics, and file names.
130    pub fn as_str(self) -> &'static str {
131        match self {
132            Self::New => "new",
133            Self::Open => "open",
134            Self::Save => "save",
135            Self::Close => "close",
136            Self::Delete => "delete",
137            Self::Copy => "copy",
138            Self::Paste => "paste",
139            Self::Undo => "undo",
140            Self::Redo => "redo",
141            Self::Refresh => "refresh",
142            Self::Search => "search",
143            Self::Preferences => "preferences",
144            Self::Home => "home",
145            Self::Folder => "folder",
146            Self::File => "file",
147            Self::Information => "information",
148            Self::Warning => "warning",
149            Self::Error => "error",
150            Self::Question => "question",
151            Self::Help => "help",
152            Self::Play => "play",
153            Self::Stop => "stop",
154            Self::NavigateBack => "navigate-back",
155            Self::NavigateForward => "navigate-forward",
156            Self::NavigateUp => "navigate-up",
157            Self::Application => "application",
158            Self::FormatBold => "format-bold",
159            Self::FormatItalic => "format-italic",
160            Self::FormatStrikethrough => "format-strikethrough",
161            Self::FormatCode => "format-code",
162            Self::FormatHeading => "format-heading",
163            Self::ListBulleted => "list-bulleted",
164            Self::ListNumbered => "list-numbered",
165            Self::ListTask => "list-task",
166            Self::Quote => "quote",
167            Self::InsertLink => "insert-link",
168            Self::InsertImage => "insert-image",
169            Self::InsertTable => "insert-table",
170            Self::InsertRule => "insert-rule",
171            Self::ThemeToggle => "theme-toggle",
172        }
173    }
174
175    /// Freedesktop icon name, used by the GTK native tier.
176    pub fn xdg_name(self) -> &'static str {
177        match self {
178            Self::New => "document-new",
179            Self::Open => "document-open",
180            Self::Save => "document-save",
181            Self::Close => "window-close",
182            Self::Delete => "edit-delete",
183            Self::Copy => "edit-copy",
184            Self::Paste => "edit-paste",
185            Self::Undo => "edit-undo",
186            Self::Redo => "edit-redo",
187            Self::Refresh => "view-refresh",
188            Self::Search => "edit-find",
189            Self::Preferences => "preferences-system",
190            Self::Home => "go-home",
191            Self::Folder => "folder",
192            Self::File => "text-x-generic",
193            Self::Information => "dialog-information",
194            Self::Warning => "dialog-warning",
195            Self::Error => "dialog-error",
196            Self::Question => "dialog-question",
197            Self::Help => "help-browser",
198            Self::Play => "media-playback-start",
199            Self::Stop => "media-playback-stop",
200            Self::NavigateBack => "go-previous",
201            Self::NavigateForward => "go-next",
202            Self::NavigateUp => "go-up",
203            Self::Application => "application-x-executable",
204            Self::FormatBold => "format-text-bold",
205            Self::FormatItalic => "format-text-italic",
206            Self::FormatStrikethrough => "format-text-strikethrough",
207            Self::FormatCode => "format-text-code",
208            Self::FormatHeading => "format-text-heading",
209            Self::ListBulleted => "format-list-unordered",
210            Self::ListNumbered => "format-list-ordered",
211            Self::ListTask => "format-list-checkbox",
212            Self::Quote => "format-text-blockquote",
213            Self::InsertLink => "insert-link",
214            Self::InsertImage => "insert-image",
215            Self::InsertTable => "insert-table",
216            Self::InsertRule => "insert-horizontal-rule",
217            Self::ThemeToggle => "night-light",
218        }
219    }
220
221    /// SF Symbols name, used by the Cocoa native tier on macOS 11+.
222    pub fn sf_symbol_name(self) -> Option<&'static str> {
223        match self {
224            Self::New => Some("doc.badge.plus"),
225            Self::Open => Some("folder"),
226            Self::Save => Some("square.and.arrow.down"),
227            Self::Close => Some("xmark"),
228            Self::Delete => Some("trash"),
229            Self::Copy => Some("doc.on.doc"),
230            Self::Paste => Some("doc.on.clipboard"),
231            Self::Undo => Some("arrow.uturn.backward"),
232            Self::Redo => Some("arrow.uturn.forward"),
233            Self::Refresh => Some("arrow.clockwise"),
234            Self::Search => Some("magnifyingglass"),
235            Self::Preferences => Some("gearshape"),
236            Self::Home => Some("house"),
237            Self::Folder => Some("folder"),
238            Self::File => Some("doc"),
239            Self::Information => Some("info.circle"),
240            Self::Warning => Some("exclamationmark.triangle"),
241            Self::Error => Some("xmark.octagon"),
242            Self::Question => Some("questionmark.circle"),
243            Self::Help => Some("questionmark.circle"),
244            Self::Play => Some("play.fill"),
245            Self::Stop => Some("stop.fill"),
246            Self::NavigateBack => Some("chevron.backward"),
247            Self::NavigateForward => Some("chevron.forward"),
248            Self::NavigateUp => Some("arrow.up"),
249            Self::Application => Some("app"),
250            Self::FormatBold => Some("bold"),
251            Self::FormatItalic => Some("italic"),
252            Self::FormatStrikethrough => Some("strikethrough"),
253            Self::FormatCode => Some("chevron.left.forwardslash.chevron.right"),
254            Self::FormatHeading => Some("textformat.size"),
255            Self::ListBulleted => Some("list.bullet"),
256            Self::ListNumbered => Some("list.number"),
257            Self::ListTask => Some("checklist"),
258            Self::Quote => Some("quote.opening"),
259            Self::InsertLink => Some("link"),
260            Self::InsertImage => Some("photo"),
261            Self::InsertTable => Some("tablecells"),
262            Self::InsertRule => Some("minus"),
263            Self::ThemeToggle => Some("circle.lefthalf.filled"),
264        }
265    }
266}
267
268/// DPI variant of a stock icon (wx-style small/large art).
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
270pub enum IconSize {
271    /// Small variant: 16 logical pixels (menus, toolbars).
272    Small,
273    /// Large variant: 32 logical pixels (dialogs, large buttons).
274    Large,
275}
276
277impl IconSize {
278    /// Every portable DPI variant.
279    pub const ALL: [IconSize; 2] = [IconSize::Small, IconSize::Large];
280
281    /// Base raster edge in logical pixels (before the `scale` factor).
282    pub fn pixels(self) -> u32 {
283        match self {
284            Self::Small => 16,
285            Self::Large => 32,
286        }
287    }
288
289    /// Stable lowercase identifier used by tests and file names.
290    pub fn as_str(self) -> &'static str {
291        match self {
292            Self::Small => "small",
293            Self::Large => "large",
294        }
295    }
296}
297
298/// Which tier produced a [`StockIcon`].
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
300pub enum IconSource {
301    /// Library-owned deterministic art ([`crate::Ui::stock_icon`]).
302    Portable,
303    /// An OS-provided icon ([`crate::Ui::native_stock_icon`]).
304    Native,
305}
306
307impl IconSource {
308    /// Stable lowercase identifier.
309    pub fn as_str(self) -> &'static str {
310        match self {
311            Self::Portable => "portable",
312            Self::Native => "native",
313        }
314    }
315}
316
317/// What a lane's **native** stock-art tier provides.
318///
319/// The portable renderer is library-owned art and always available, so it is
320/// not gated here; these flags describe the optional OS-native lookup served
321/// by [`crate::Backend::native_stock_icon`], which is where lanes genuinely
322/// differ.
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
324pub struct ArtCapabilities {
325    /// The lane resolves OS-provided stock icons for at least the severity
326    /// roles (Information/Warning/Error/Question).
327    pub native_icons: bool,
328    /// The native tier serves both [`IconSize`] variants.
329    pub dpi_variants: bool,
330    /// Native icons follow the application's [`ThemeMode`]. System art is
331    /// fixed today, so this is `false` where only portable art themes.
332    pub theme_aware: bool,
333}
334
335impl ArtCapabilities {
336    /// No native art: portable rendering only.
337    pub const fn none() -> Self {
338        Self {
339            native_icons: false,
340            dpi_variants: false,
341            theme_aware: false,
342        }
343    }
344
345    /// Native art is available with the given variant support.
346    pub const fn native(dpi_variants: bool, theme_aware: bool) -> Self {
347        Self {
348            native_icons: true,
349            dpi_variants,
350            theme_aware,
351        }
352    }
353}
354
355/// A resolved icon raster (RGBA8, row-major, straight alpha).
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct StockIcon {
358    /// Role this icon resolved from.
359    pub role: IconRole,
360    /// Requested DPI variant.
361    pub size: IconSize,
362    /// Theme mode the palette was resolved for.
363    pub mode: ThemeMode,
364    /// Requested DPI scale factor (1 = 96 dpi baseline), clamped to 1..=4.
365    pub scale: u32,
366    /// Tier that produced the raster.
367    pub source: IconSource,
368    /// Raster width in device pixels (`size.pixels() * scale`, or the
369    /// rounded fractional edge from [`render_stock_icon_for_scale`]).
370    pub width: u32,
371    /// Raster height in device pixels (same rule as `width`).
372    pub height: u32,
373    /// RGBA8 pixels, `width * height * 4` bytes, straight (un-premultiplied)
374    /// alpha.
375    pub pixels: Vec<u8>,
376}
377
378impl StockIcon {
379    /// Returns the RGBA pixel at `(x, y)`, or `None` when out of bounds.
380    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
381        if x >= self.width || y >= self.height {
382            return None;
383        }
384        let offset = ((y * self.width + x) * 4) as usize;
385        Some([
386            self.pixels[offset],
387            self.pixels[offset + 1],
388            self.pixels[offset + 2],
389            self.pixels[offset + 3],
390        ])
391    }
392
393    /// Whether the raster contains at least one visible (non-zero alpha)
394    /// pixel. A fully transparent raster is a rendering bug, never valid art.
395    pub fn has_visible_pixels(&self) -> bool {
396        self.pixels.as_chunks::<4>().0.iter().any(|px| px[3] != 0)
397    }
398
399    /// Encodes the icon as a 24-bit bottom-up BMP, compositing straight alpha
400    /// over `background`.
401    ///
402    /// This is the bridge to `Image` widgets (`Ui::set_image_source`) on every
403    /// lane, which decode BMP natively today.
404    pub fn to_bmp(&self, background: Color) -> Vec<u8> {
405        let width = self.width as usize;
406        let height = self.height as usize;
407        let row_stride = (width * 3 + 3) & !3;
408        let pixel_bytes = row_stride * height;
409        let mut out = Vec::with_capacity(54 + pixel_bytes);
410
411        let file_size = (54 + pixel_bytes) as u32;
412        out.extend_from_slice(b"BM");
413        out.extend_from_slice(&file_size.to_le_bytes());
414        out.extend_from_slice(&[0, 0, 0, 0]); // reserved
415        out.extend_from_slice(&54u32.to_le_bytes()); // pixel data offset
416
417        out.extend_from_slice(&40u32.to_le_bytes()); // BITMAPINFOHEADER
418        out.extend_from_slice(&(width as i32).to_le_bytes());
419        out.extend_from_slice(&(height as i32).to_le_bytes());
420        out.extend_from_slice(&1u16.to_le_bytes()); // planes
421        out.extend_from_slice(&24u16.to_le_bytes()); // bits per pixel
422        out.extend_from_slice(&0u32.to_le_bytes()); // BI_RGB
423        out.extend_from_slice(&(pixel_bytes as u32).to_le_bytes());
424        out.extend_from_slice(&2835i32.to_le_bytes()); // 72 dpi
425        out.extend_from_slice(&2835i32.to_le_bytes());
426        out.extend_from_slice(&0u32.to_le_bytes()); // palette
427        out.extend_from_slice(&0u32.to_le_bytes()); // important colors
428
429        // BMP rows are stored bottom-up.
430        for y in (0..height).rev() {
431            let row_start = out.len();
432            for x in 0..width {
433                let [r, g, b, a] = self.pixel(x as u32, y as u32).expect("in bounds");
434                let alpha = a as u32;
435                let blend = |channel: u8, bg: u8| -> u8 {
436                    (((channel as u32 * alpha) + (bg as u32 * (255 - alpha)) + 127) / 255) as u8
437                };
438                out.push(blend(b, background.b));
439                out.push(blend(g, background.g));
440                out.push(blend(r, background.r));
441            }
442            out.resize(row_start + row_stride, 0);
443        }
444
445        out
446    }
447}
448
449/// Builds the typed capability error for a role/size a lane's native tier
450/// cannot serve, so every backend reports the same error shape.
451pub fn unsupported_native_icon(role: IconRole, size: IconSize, detail: &str) -> GuiError {
452    GuiError::UnsupportedCapability(format!(
453        "native stock icon ({} / {}): {}",
454        role.as_str(),
455        size.as_str(),
456        detail
457    ))
458}
459
460/// Box-filters a straight-alpha RGBA raster to an exact target size,
461/// averaging in premultiplied space so transparent edges do not darken.
462pub fn resample_rgba(
463    source: &[u8],
464    source_width: u32,
465    source_height: u32,
466    target_width: u32,
467    target_height: u32,
468) -> GuiResult<(u32, u32, Vec<u8>)> {
469    if source_width == 0
470        || source_height == 0
471        || target_width == 0
472        || target_height == 0
473        || source.len() != (source_width * source_height * 4) as usize
474    {
475        return Err(GuiError::Backend(
476            "icon resample received a mismatched raster".to_owned(),
477        ));
478    }
479
480    let mut out = vec![0u8; (target_width * target_height * 4) as usize];
481    for ty in 0..target_height {
482        let y0 = (ty * source_height) / target_height;
483        let y1 = (((ty + 1) * source_height) / target_height)
484            .max(y0 + 1)
485            .min(source_height);
486        for tx in 0..target_width {
487            let x0 = (tx * source_width) / target_width;
488            let x1 = (((tx + 1) * source_width) / target_width)
489                .max(x0 + 1)
490                .min(source_width);
491            let mut sums = [0.0f32; 4];
492            let mut count = 0.0f32;
493            for sy in y0..y1 {
494                for sx in x0..x1 {
495                    let offset = ((sy * source_width + sx) * 4) as usize;
496                    let alpha = source[offset + 3] as f32 / 255.0;
497                    sums[0] += source[offset] as f32 * alpha;
498                    sums[1] += source[offset + 1] as f32 * alpha;
499                    sums[2] += source[offset + 2] as f32 * alpha;
500                    sums[3] += alpha;
501                    count += 1.0;
502                }
503            }
504            let offset = ((ty * target_width + tx) * 4) as usize;
505            let average_alpha = sums[3] / count;
506            if sums[3] > 0.0 {
507                out[offset] = (sums[0] / sums[3] + 0.5) as u8;
508                out[offset + 1] = (sums[1] / sums[3] + 0.5) as u8;
509                out[offset + 2] = (sums[2] / sums[3] + 0.5) as u8;
510            }
511            out[offset + 3] = (average_alpha * 255.0 + 0.5) as u8;
512        }
513    }
514
515    Ok((target_width, target_height, out))
516}
517
518/// Scales a straight-alpha RGBA raster to fit a transparent `edge`-sized
519/// square, preserving the aspect ratio and centering the result. Native icons
520/// are square in practice; this keeps non-square assets well-formed.
521///
522/// Public because the native backend crates (GTK, Win32, Cocoa) share it.
523pub fn resample_rgba_centered(
524    source: &[u8],
525    source_width: u32,
526    source_height: u32,
527    edge: u32,
528) -> GuiResult<(u32, u32, Vec<u8>)> {
529    if source_width == 0 || source_height == 0 || edge == 0 {
530        return Err(GuiError::Backend(
531            "icon resample received an empty raster".to_owned(),
532        ));
533    }
534    if source_width == edge && source_height == edge {
535        if source.len() != (edge * edge * 4) as usize {
536            return Err(GuiError::Backend(
537                "icon resample received a mismatched raster".to_owned(),
538            ));
539        }
540        return Ok((edge, edge, source.to_vec()));
541    }
542
543    let scale = (edge as f32 / source_width as f32).min(edge as f32 / source_height as f32);
544    let target_width = ((source_width as f32 * scale).round() as u32).clamp(1, edge);
545    let target_height = ((source_height as f32 * scale).round() as u32).clamp(1, edge);
546    let (_, _, scaled) = resample_rgba(
547        source,
548        source_width,
549        source_height,
550        target_width,
551        target_height,
552    )?;
553
554    let mut out = vec![0u8; (edge * edge * 4) as usize];
555    let x_offset = (edge - target_width) / 2;
556    let y_offset = (edge - target_height) / 2;
557    for y in 0..target_height {
558        for x in 0..target_width {
559            let source_offset = ((y * target_width + x) * 4) as usize;
560            let target_offset = (((y + y_offset) * edge + x + x_offset) * 4) as usize;
561            out[target_offset..target_offset + 4]
562                .copy_from_slice(&scaled[source_offset..source_offset + 4]);
563        }
564    }
565
566    Ok((edge, edge, out))
567}
568
569/// Renders a portable stock icon for `role`, `size`, `mode`, and DPI `scale`.
570///
571/// Deterministic: identical requests produce byte-identical rasters. `scale`
572/// is clamped to `1..=4`; the raster edge is `size.pixels() * scale`.
573///
574/// The raster is produced on demand and is not cached; a caller that resolves
575/// the same icon repeatedly (for example in a paint loop) should keep the
576/// returned [`StockIcon`] instead of calling this again.
577pub fn render_stock_icon(role: IconRole, size: IconSize, mode: ThemeMode, scale: u32) -> StockIcon {
578    let scale = scale.clamp(1, 4);
579    render_stock_icon_at_extent(role, size, mode, scale, size.pixels() * scale)
580}
581
582/// Raster edge in device pixels for `size` on a display with a fractional
583/// scale factor (1.0 = 96 dpi, 1.5 = 150 %, ...): `size.pixels() * scale`,
584/// rounded, kept within one to four times the baseline.
585pub fn stock_icon_edge_for_scale(size: IconSize, scale: f64) -> u32 {
586    let base = size.pixels();
587    let scale = if scale.is_finite() { scale } else { 1.0 };
588    ((f64::from(base) * scale).round() as u32).clamp(base, base * 4)
589}
590
591/// Renders a portable stock icon for a fractional display scale, such as
592/// 1.25 or 1.5. The glyphs are vector shapes, so a 150 % display gets a sharp
593/// 24 px raster for a 16 px icon instead of the 16 px one stretched or left
594/// small. The raster edge is [`stock_icon_edge_for_scale`]; `scale` on the
595/// returned icon is the factor rounded to the nearest whole number. Integer
596/// factors give the same pixels as [`render_stock_icon`].
597pub fn render_stock_icon_for_scale(
598    role: IconRole,
599    size: IconSize,
600    mode: ThemeMode,
601    scale: f64,
602) -> StockIcon {
603    let extent = stock_icon_edge_for_scale(size, scale);
604    let whole = ((f64::from(extent) / f64::from(size.pixels())).round() as u32).clamp(1, 4);
605    render_stock_icon_at_extent(role, size, mode, whole, extent)
606}
607
608fn render_stock_icon_at_extent(
609    role: IconRole,
610    size: IconSize,
611    mode: ThemeMode,
612    scale: u32,
613    extent: u32,
614) -> StockIcon {
615    // Device pixels per logical glyph unit; whole for the integer path.
616    let pixel_scale = extent as f32 / size.pixels() as f32;
617    let theme = Theme::for_mode(mode);
618    let shapes = glyph(role);
619
620    let mut pixels = vec![0u8; (extent * extent * 4) as usize];
621    let samples = (SUPERSAMPLE * SUPERSAMPLE) as f32;
622    let mut top_counts = vec![0u32; shapes.len()];
623
624    for py in 0..extent {
625        for px in 0..extent {
626            top_counts.iter_mut().for_each(|count| *count = 0);
627            for sy in 0..SUPERSAMPLE {
628                for sx in 0..SUPERSAMPLE {
629                    let logical_x =
630                        (px as f32 + (sx as f32 + 0.5) / SUPERSAMPLE as f32) / pixel_scale;
631                    let logical_y =
632                        (py as f32 + (sy as f32 + 0.5) / SUPERSAMPLE as f32) / pixel_scale;
633                    let mut top = None;
634                    for (index, (shape, _)) in shapes.iter().enumerate() {
635                        if covers(shape, logical_x, logical_y) {
636                            top = Some(index);
637                        }
638                    }
639                    if let Some(index) = top {
640                        top_counts[index] += 1;
641                    }
642                }
643            }
644
645            // Composite the glyph in paint order, straight-alpha.
646            let mut out = [0.0f32; 4];
647            for (index, (_, ink)) in shapes.iter().enumerate() {
648                let coverage = top_counts[index] as f32 / samples;
649                if coverage > 0.0 {
650                    let color = ink_color(*ink, &theme);
651                    out = blend(out, color, coverage);
652                }
653            }
654
655            let offset = ((py * extent + px) * 4) as usize;
656            for (channel, value) in out.iter().enumerate() {
657                pixels[offset + channel] = (value * 255.0 + 0.5) as u8;
658            }
659        }
660    }
661
662    StockIcon {
663        role,
664        size,
665        mode,
666        scale,
667        source: IconSource::Portable,
668        width: extent,
669        height: extent,
670        pixels,
671    }
672}
673
674/// Supersampling factor per axis; 4x4 samples give smooth 16 px glyphs.
675const SUPERSAMPLE: u32 = 4;
676
677/// Ink slot for a glyph shape; resolved against the active theme.
678#[derive(Debug, Clone, Copy, PartialEq, Eq)]
679enum Ink {
680    Text,
681    Accent,
682    Warning,
683    Error,
684    Surface,
685}
686
687fn ink_color(ink: Ink, theme: &Theme) -> Color {
688    match ink {
689        Ink::Text => theme.colors.text,
690        Ink::Accent => theme.colors.accent,
691        Ink::Warning => theme.colors.warning,
692        Ink::Error => theme.colors.error,
693        Ink::Surface => theme.colors.surface,
694    }
695}
696
697/// Analytic glyph shape in the logical 16x16 grid.
698///
699/// Glyphs are built from these primitives and rasterized by point-in-shape
700/// tests with supersampling, so no external rasterizer or font is involved.
701#[derive(Debug, Clone, PartialEq)]
702enum Shape {
703    Rect {
704        x: f32,
705        y: f32,
706        w: f32,
707        h: f32,
708    },
709    RoundRect {
710        x: f32,
711        y: f32,
712        w: f32,
713        h: f32,
714        r: f32,
715    },
716    /// Rectangle outline: inside the outer bounds but outside the inset.
717    Frame {
718        x: f32,
719        y: f32,
720        w: f32,
721        h: f32,
722        t: f32,
723    },
724    Circle {
725        cx: f32,
726        cy: f32,
727        r: f32,
728    },
729    /// Circle outline of thickness `t`.
730    Ring {
731        cx: f32,
732        cy: f32,
733        r: f32,
734        t: f32,
735    },
736    /// Ring segment from `a0` to `a1` degrees, measured clockwise on screen
737    /// (0 = +x, 90 = +y/down) and traversed by increasing angle.
738    RingSeg {
739        cx: f32,
740        cy: f32,
741        r: f32,
742        t: f32,
743        a0: f32,
744        a1: f32,
745    },
746    /// Line segment with round caps, thickness `t`.
747    Segment {
748        x0: f32,
749        y0: f32,
750        x1: f32,
751        y1: f32,
752        t: f32,
753    },
754    /// Simple (non-self-intersecting) filled polygon.
755    Polygon(Vec<(f32, f32)>),
756}
757
758fn covers(shape: &Shape, px: f32, py: f32) -> bool {
759    match shape {
760        Shape::Rect { x, y, w, h } => px >= *x && px <= x + w && py >= *y && py <= y + h,
761        Shape::RoundRect { x, y, w, h, r } => {
762            let inner_x = px.clamp(x + r, x + w - r);
763            let inner_y = py.clamp(y + r, y + h - r);
764            let dx = px - inner_x;
765            let dy = py - inner_y;
766            dx * dx + dy * dy <= r * r
767        }
768        Shape::Frame { x, y, w, h, t } => {
769            px >= *x
770                && px <= x + w
771                && py >= *y
772                && py <= y + h
773                && !(px >= x + t && px <= x + w - t && py >= y + t && py <= y + h - t)
774        }
775        Shape::Circle { cx, cy, r } => {
776            let dx = px - cx;
777            let dy = py - cy;
778            dx * dx + dy * dy <= r * r
779        }
780        Shape::Ring { cx, cy, r, t } => {
781            let dx = px - cx;
782            let dy = py - cy;
783            let distance = (dx * dx + dy * dy).sqrt();
784            (distance - r).abs() <= t / 2.0
785        }
786        Shape::RingSeg {
787            cx,
788            cy,
789            r,
790            t,
791            a0,
792            a1,
793        } => {
794            let dx = px - cx;
795            let dy = py - cy;
796            let distance = (dx * dx + dy * dy).sqrt();
797            if (distance - r).abs() > t / 2.0 {
798                return false;
799            }
800            let mut angle = dy.atan2(dx).to_degrees();
801            if angle < 0.0 {
802                angle += 360.0;
803            }
804            let mut end = *a1;
805            if end <= *a0 {
806                end += 360.0;
807            }
808            if angle < *a0 {
809                angle += 360.0;
810            }
811            angle >= *a0 && angle <= end
812        }
813        Shape::Segment { x0, y0, x1, y1, t } => {
814            let vx = x1 - x0;
815            let vy = y1 - y0;
816            let length_sq = vx * vx + vy * vy;
817            let projection = if length_sq == 0.0 {
818                0.0
819            } else {
820                (((px - x0) * vx + (py - y0) * vy) / length_sq).clamp(0.0, 1.0)
821            };
822            let dx = px - (x0 + projection * vx);
823            let dy = py - (y0 + projection * vy);
824            dx * dx + dy * dy <= (t / 2.0) * (t / 2.0)
825        }
826        Shape::Polygon(points) => {
827            let mut inside = false;
828            let mut j = points.len() - 1;
829            for i in 0..points.len() {
830                let (xi, yi) = points[i];
831                let (xj, yj) = points[j];
832                if (yi > py) != (yj > py) && px < (xj - xi) * (py - yi) / (yj - yi) + xi {
833                    inside = !inside;
834                }
835                j = i;
836            }
837            inside
838        }
839    }
840}
841
842/// Straight-alpha source-over blending.
843fn blend(dst: [f32; 4], src: Color, coverage: f32) -> [f32; 4] {
844    let src_rgb = [
845        src.r as f32 / 255.0,
846        src.g as f32 / 255.0,
847        src.b as f32 / 255.0,
848    ];
849    let out_alpha = coverage + dst[3] * (1.0 - coverage);
850    if out_alpha <= 0.0 {
851        return [0.0, 0.0, 0.0, 0.0];
852    }
853    let mut out = [0.0f32; 4];
854    for channel in 0..3 {
855        out[channel] =
856            (src_rgb[channel] * coverage + dst[channel] * dst[3] * (1.0 - coverage)) / out_alpha;
857    }
858    out[3] = out_alpha;
859    out
860}
861
862/// Builds the glyph for a role in the logical 16x16 grid.
863fn glyph(role: IconRole) -> Vec<(Shape, Ink)> {
864    use Ink::{Accent, Error, Surface, Text, Warning};
865    let seg = |x0: f32, y0: f32, x1: f32, y1: f32, t: f32| Shape::Segment { x0, y0, x1, y1, t };
866    let rect = |x: f32, y: f32, w: f32, h: f32| Shape::Rect { x, y, w, h };
867    let frame = |x: f32, y: f32, w: f32, h: f32, t: f32| Shape::Frame { x, y, w, h, t };
868    let circle = |cx: f32, cy: f32, r: f32| Shape::Circle { cx, cy, r };
869    let round = |x: f32, y: f32, w: f32, h: f32, r: f32| Shape::RoundRect { x, y, w, h, r };
870
871    match role {
872        IconRole::New => vec![
873            (frame(3.5, 1.5, 8.0, 13.0, 1.4), Text),
874            (seg(10.5, 9.5, 10.5, 15.5, 1.6), Accent),
875            (seg(7.5, 12.5, 13.5, 12.5, 1.6), Accent),
876        ],
877        IconRole::Open => vec![
878            (
879                Shape::Polygon(vec![
880                    (1.5, 3.5),
881                    (6.2, 3.5),
882                    (7.4, 5.6),
883                    (14.5, 5.6),
884                    (14.5, 13.5),
885                    (1.5, 13.5),
886                ]),
887                Accent,
888            ),
889            (
890                Shape::Polygon(vec![(1.5, 7.0), (15.2, 7.0), (12.8, 14.0), (1.5, 14.0)]),
891                Text,
892            ),
893        ],
894        IconRole::Save => vec![
895            (round(2.5, 1.5, 11.0, 13.0, 1.4), Accent),
896            (rect(5.5, 1.5, 5.0, 4.0), Surface),
897            (frame(5.0, 9.0, 6.0, 5.5, 1.2), Surface),
898        ],
899        IconRole::Close => vec![
900            (seg(3.5, 3.5, 12.5, 12.5, 1.8), Error),
901            (seg(12.5, 3.5, 3.5, 12.5, 1.8), Error),
902        ],
903        IconRole::Delete => vec![
904            (seg(3.0, 4.2, 13.0, 4.2, 1.5), Error),
905            (seg(6.4, 2.4, 9.6, 2.4, 1.5), Error),
906            (
907                Shape::Polygon(vec![(4.4, 5.2), (11.6, 5.2), (10.6, 14.0), (5.4, 14.0)]),
908                Error,
909            ),
910            (seg(6.9, 7.0, 6.9, 12.2, 1.1), Surface),
911            (seg(9.1, 7.0, 9.1, 12.2, 1.1), Surface),
912        ],
913        IconRole::Copy => vec![
914            (frame(2.2, 2.2, 7.6, 7.6, 1.4), Text),
915            (frame(6.2, 6.2, 7.6, 7.6, 1.4), Accent),
916        ],
917        IconRole::Paste => vec![
918            (frame(4.0, 2.8, 8.0, 11.2, 1.4), Text),
919            (rect(6.2, 1.4, 3.6, 2.6), Accent),
920        ],
921        IconRole::Undo => vec![
922            (seg(12.5, 4.5, 12.5, 8.5, 1.6), Accent),
923            (seg(12.5, 8.5, 5.5, 8.5, 1.6), Accent),
924            (
925                Shape::Polygon(vec![(2.0, 8.5), (6.5, 6.3), (6.5, 10.7)]),
926                Accent,
927            ),
928        ],
929        IconRole::Redo => vec![
930            (seg(3.5, 4.5, 3.5, 8.5, 1.6), Accent),
931            (seg(3.5, 8.5, 10.5, 8.5, 1.6), Accent),
932            (
933                Shape::Polygon(vec![(14.0, 8.5), (9.5, 6.3), (9.5, 10.7)]),
934                Accent,
935            ),
936        ],
937        IconRole::Refresh => vec![
938            (
939                Shape::RingSeg {
940                    cx: 8.0,
941                    cy: 8.0,
942                    r: 5.0,
943                    t: 1.6,
944                    a0: 40.0,
945                    a1: 330.0,
946                },
947                Accent,
948            ),
949            (
950                Shape::Polygon(vec![(10.6, 11.0), (14.2, 9.4), (13.0, 13.4)]),
951                Accent,
952            ),
953        ],
954        IconRole::Search => vec![
955            (
956                Shape::Ring {
957                    cx: 6.6,
958                    cy: 6.6,
959                    r: 4.0,
960                    t: 1.6,
961                },
962                Accent,
963            ),
964            (seg(9.6, 9.6, 14.0, 14.0, 2.0), Text),
965        ],
966        IconRole::Preferences => {
967            let mut shapes = vec![
968                (circle(8.0, 8.0, 4.6), Accent),
969                (circle(8.0, 8.0, 1.9), Surface),
970            ];
971            for step in 0..6 {
972                let angle = (30.0 + 60.0 * step as f32).to_radians();
973                let (sin, cos) = angle.sin_cos();
974                shapes.push((
975                    seg(
976                        8.0 + 4.6 * cos,
977                        8.0 + 4.6 * sin,
978                        8.0 + 6.6 * cos,
979                        8.0 + 6.6 * sin,
980                        2.0,
981                    ),
982                    Accent,
983                ));
984            }
985            shapes
986        }
987        IconRole::Home => vec![
988            (
989                Shape::Polygon(vec![(8.0, 1.8), (14.6, 7.6), (1.4, 7.6)]),
990                Accent,
991            ),
992            (rect(3.6, 7.6, 8.8, 6.8), Text),
993            (rect(6.6, 10.4, 2.8, 4.0), Surface),
994        ],
995        IconRole::Folder => vec![(
996            Shape::Polygon(vec![
997                (1.5, 3.6),
998                (6.2, 3.6),
999                (7.4, 5.7),
1000                (14.5, 5.7),
1001                (14.5, 13.6),
1002                (1.5, 13.6),
1003            ]),
1004            Accent,
1005        )],
1006        IconRole::File => vec![
1007            (frame(3.6, 1.5, 8.8, 13.0, 1.4), Text),
1008            (
1009                Shape::Polygon(vec![(9.0, 1.5), (12.4, 5.0), (9.0, 5.0)]),
1010                Text,
1011            ),
1012        ],
1013        IconRole::Information => vec![
1014            (circle(8.0, 8.0, 6.0), Accent),
1015            (rect(7.1, 7.0, 1.8, 4.6), Surface),
1016            (rect(7.1, 4.4, 1.8, 1.6), Surface),
1017        ],
1018        IconRole::Warning => vec![
1019            (
1020                Shape::Polygon(vec![(8.0, 1.4), (15.0, 14.0), (1.0, 14.0)]),
1021                Warning,
1022            ),
1023            (rect(7.2, 5.8, 1.6, 4.6), Surface),
1024            (rect(7.2, 11.4, 1.6, 1.6), Surface),
1025        ],
1026        IconRole::Error => vec![
1027            (circle(8.0, 8.0, 6.0), Error),
1028            (seg(5.6, 5.6, 10.4, 10.4, 1.6), Surface),
1029            (seg(10.4, 5.6, 5.6, 10.4, 1.6), Surface),
1030        ],
1031        IconRole::Question => vec![
1032            (circle(8.0, 8.0, 6.0), Accent),
1033            (
1034                Shape::RingSeg {
1035                    cx: 8.0,
1036                    cy: 6.8,
1037                    r: 2.4,
1038                    t: 1.6,
1039                    a0: 180.0,
1040                    a1: 350.0,
1041                },
1042                Surface,
1043            ),
1044            (seg(8.0, 8.9, 8.0, 10.8, 1.6), Surface),
1045            (circle(8.0, 12.6, 0.9), Surface),
1046        ],
1047        IconRole::Help => {
1048            let mut shapes = vec![
1049                (
1050                    Shape::Ring {
1051                        cx: 8.0,
1052                        cy: 8.0,
1053                        r: 5.2,
1054                        t: 1.8,
1055                    },
1056                    Accent,
1057                ),
1058                (circle(8.0, 8.0, 2.6), Surface),
1059                (
1060                    Shape::Ring {
1061                        cx: 8.0,
1062                        cy: 8.0,
1063                        r: 2.0,
1064                        t: 1.4,
1065                    },
1066                    Accent,
1067                ),
1068            ];
1069            for step in 0..4 {
1070                let angle = (45.0 + 90.0 * step as f32).to_radians();
1071                let (sin, cos) = angle.sin_cos();
1072                shapes.push((
1073                    seg(
1074                        8.0 + 2.6 * cos,
1075                        8.0 + 2.6 * sin,
1076                        8.0 + 4.8 * cos,
1077                        8.0 + 4.8 * sin,
1078                        1.6,
1079                    ),
1080                    Accent,
1081                ));
1082            }
1083            shapes
1084        }
1085        IconRole::Play => vec![(
1086            Shape::Polygon(vec![(4.6, 2.6), (13.4, 8.0), (4.6, 13.4)]),
1087            Accent,
1088        )],
1089        IconRole::Stop => vec![(round(3.4, 3.4, 9.2, 9.2, 1.2), Error)],
1090        IconRole::NavigateBack => vec![
1091            (seg(13.6, 8.0, 4.0, 8.0, 1.8), Accent),
1092            (
1093                Shape::Polygon(vec![(7.6, 4.4), (7.6, 11.6), (2.4, 8.0)]),
1094                Accent,
1095            ),
1096        ],
1097        IconRole::NavigateForward => vec![
1098            (seg(2.4, 8.0, 12.0, 8.0, 1.8), Accent),
1099            (
1100                Shape::Polygon(vec![(8.4, 4.4), (8.4, 11.6), (13.6, 8.0)]),
1101                Accent,
1102            ),
1103        ],
1104        IconRole::NavigateUp => vec![
1105            (seg(8.0, 13.6, 8.0, 4.0, 1.8), Accent),
1106            (
1107                Shape::Polygon(vec![(4.4, 7.6), (11.6, 7.6), (8.0, 2.4)]),
1108                Accent,
1109            ),
1110        ],
1111        IconRole::Application => vec![
1112            (round(2.0, 2.6, 12.0, 10.8, 1.4), Accent),
1113            (seg(2.0, 5.4, 14.0, 5.4, 0.9), Surface),
1114            (circle(4.0, 4.0, 0.7), Surface),
1115            (circle(6.0, 4.0, 0.7), Surface),
1116        ],
1117        IconRole::FormatBold => vec![
1118            (round(3.0, 2.0, 3.5, 12.0, 1.0), Text),
1119            (round(3.5, 2.0, 8.0, 6.4, 2.2), Text),
1120            (round(5.8, 3.8, 4.0, 2.8, 1.0), Surface),
1121            (round(3.5, 7.6, 9.2, 6.4, 2.2), Text),
1122            (round(5.8, 9.4, 5.0, 2.8, 1.0), Surface),
1123        ],
1124        IconRole::FormatItalic => vec![
1125            (seg(5.5, 2.5, 12.0, 2.5, 2.0), Text),
1126            (seg(4.0, 13.5, 10.5, 13.5, 2.0), Text),
1127            (seg(9.5, 2.5, 6.5, 13.5, 2.2), Text),
1128        ],
1129        IconRole::FormatStrikethrough => vec![
1130            (seg(11.0, 3.5, 6.5, 3.5, 1.8), Text),
1131            (seg(5.5, 4.5, 5.5, 7.0, 1.8), Text),
1132            (seg(5.5, 7.0, 10.5, 9.0, 1.8), Text),
1133            (seg(10.5, 9.0, 10.5, 11.5, 1.8), Text),
1134            (seg(10.5, 12.5, 5.0, 12.5, 1.8), Text),
1135            (seg(2.5, 8.0, 13.5, 8.0, 2.0), Accent),
1136        ],
1137        IconRole::FormatCode => vec![
1138            (seg(5.5, 4.5, 2.5, 8.0, 1.6), Text),
1139            (seg(2.5, 8.0, 5.5, 11.5, 1.6), Text),
1140            (seg(9.0, 3.5, 7.0, 12.5, 1.6), Accent),
1141            (seg(10.5, 4.5, 13.5, 8.0, 1.6), Text),
1142            (seg(13.5, 8.0, 10.5, 11.5, 1.6), Text),
1143        ],
1144        IconRole::FormatHeading => vec![
1145            (seg(2.8, 3.0, 2.8, 13.0, 1.8), Text),
1146            (seg(8.2, 3.0, 8.2, 13.0, 1.8), Text),
1147            (seg(2.8, 8.0, 8.2, 8.0, 1.8), Text),
1148            (seg(11.2, 6.8, 12.8, 5.2, 1.4), Accent),
1149            (seg(12.8, 5.2, 12.8, 13.0, 1.6), Accent),
1150            (seg(11.2, 13.0, 14.4, 13.0, 1.4), Accent),
1151        ],
1152        IconRole::ListBulleted => vec![
1153            (circle(3.5, 4.2, 1.3), Accent),
1154            (seg(6.8, 4.2, 14.0, 4.2, 1.6), Text),
1155            (circle(3.5, 8.0, 1.3), Accent),
1156            (seg(6.8, 8.0, 14.0, 8.0, 1.6), Text),
1157            (circle(3.5, 11.8, 1.3), Accent),
1158            (seg(6.8, 11.8, 14.0, 11.8, 1.6), Text),
1159        ],
1160        IconRole::ListNumbered => vec![
1161            (seg(2.4, 4.2, 3.6, 3.0, 1.2), Accent),
1162            (seg(3.6, 3.0, 3.6, 6.8, 1.4), Accent),
1163            (seg(6.8, 4.8, 14.0, 4.8, 1.6), Text),
1164            (seg(2.0, 9.6, 4.8, 9.6, 1.2), Accent),
1165            (seg(4.8, 9.6, 2.0, 12.8, 1.2), Accent),
1166            (seg(2.0, 12.8, 5.0, 12.8, 1.2), Accent),
1167            (seg(6.8, 11.2, 14.0, 11.2, 1.6), Text),
1168        ],
1169        IconRole::ListTask => vec![
1170            (frame(2.0, 2.5, 5.0, 5.0, 1.1), Accent),
1171            (seg(2.8, 5.0, 4.0, 6.2, 1.1), Accent),
1172            (seg(4.0, 6.2, 6.5, 3.2, 1.1), Accent),
1173            (seg(8.5, 5.0, 14.0, 5.0, 1.6), Text),
1174            (frame(2.0, 9.5, 5.0, 5.0, 1.1), Accent),
1175            (seg(8.5, 12.0, 14.0, 12.0, 1.6), Text),
1176        ],
1177        IconRole::Quote => vec![
1178            (rect(2.2, 2.5, 2.0, 11.0), Accent),
1179            (seg(6.0, 4.5, 13.8, 4.5, 1.5), Text),
1180            (seg(6.0, 8.0, 13.8, 8.0, 1.5), Text),
1181            (seg(6.0, 11.5, 11.0, 11.5, 1.5), Text),
1182        ],
1183        IconRole::InsertLink => vec![
1184            (seg(3.5, 12.5, 6.5, 9.5, 1.8), Accent),
1185            (seg(3.5, 12.5, 6.5, 14.5, 1.6), Accent),
1186            (seg(6.5, 14.5, 8.5, 12.5, 1.6), Accent),
1187            (seg(9.5, 6.5, 12.5, 3.5, 1.8), Accent),
1188            (seg(9.5, 3.5, 12.5, 3.5, 1.6), Accent),
1189            (seg(7.5, 5.5, 9.5, 3.5, 1.6), Accent),
1190            (seg(5.5, 10.5, 10.5, 5.5, 2.0), Text),
1191        ],
1192        IconRole::InsertImage => vec![
1193            (frame(2.0, 2.5, 12.0, 11.0, 1.4), Text),
1194            (circle(5.2, 5.6, 1.3), Accent),
1195            (
1196                Shape::Polygon(vec![
1197                    (3.4, 12.0),
1198                    (7.0, 7.6),
1199                    (9.8, 10.8),
1200                    (11.8, 8.8),
1201                    (12.6, 12.0),
1202                ]),
1203                Accent,
1204            ),
1205        ],
1206        IconRole::InsertTable => vec![
1207            (frame(2.0, 2.5, 12.0, 11.0, 1.4), Text),
1208            (rect(2.0, 2.5, 12.0, 3.5), Accent),
1209            (seg(2.0, 6.0, 14.0, 6.0, 1.4), Text),
1210            (seg(2.0, 9.5, 14.0, 9.5, 1.2), Text),
1211            (seg(8.0, 2.5, 8.0, 13.5, 1.4), Text),
1212            (seg(8.0, 2.5, 8.0, 6.0, 1.2), Surface),
1213        ],
1214        IconRole::InsertRule => vec![
1215            (seg(2.0, 8.0, 14.0, 8.0, 2.0), Accent),
1216            (seg(4.0, 4.0, 12.0, 4.0, 1.0), Text),
1217            (seg(4.0, 12.0, 12.0, 12.0, 1.0), Text),
1218        ],
1219        IconRole::ThemeToggle => vec![
1220            (
1221                Shape::Ring {
1222                    cx: 8.0,
1223                    cy: 8.0,
1224                    r: 5.2,
1225                    t: 1.6,
1226                },
1227                Accent,
1228            ),
1229            (seg(8.0, 2.8, 8.0, 13.2, 1.4), Accent),
1230            (
1231                Shape::Polygon(vec![
1232                    (8.0, 2.8),
1233                    (6.0, 3.2),
1234                    (4.4, 4.6),
1235                    (3.3, 6.2),
1236                    (3.0, 8.0),
1237                    (3.3, 9.8),
1238                    (4.4, 11.4),
1239                    (6.0, 12.8),
1240                    (8.0, 13.2),
1241                ]),
1242                Accent,
1243            ),
1244        ],
1245    }
1246}
1247
1248#[cfg(test)]
1249mod tests {
1250    use super::*;
1251
1252    /// A 150 % display gets a 24 px raster for a 16 px icon, and the
1253    /// fractional path matches the integer one at whole factors.
1254    #[test]
1255    fn fractional_scale_icons_render_at_the_scaled_edge() {
1256        let icon =
1257            render_stock_icon_for_scale(IconRole::Save, IconSize::Small, ThemeMode::Light, 1.5);
1258        assert_eq!((icon.width, icon.height), (24, 24));
1259        assert_eq!(icon.pixels.len(), 24 * 24 * 4);
1260        assert!(icon.has_visible_pixels());
1261        assert_eq!(stock_icon_edge_for_scale(IconSize::Small, 1.25), 20);
1262        assert_eq!(
1263            stock_icon_edge_for_scale(IconSize::Small, 0.5),
1264            16,
1265            "never below 1x"
1266        );
1267        assert_eq!(
1268            stock_icon_edge_for_scale(IconSize::Small, 9.0),
1269            64,
1270            "never above 4x"
1271        );
1272        assert_eq!(stock_icon_edge_for_scale(IconSize::Small, f64::NAN), 16);
1273        for whole in 1..=4u32 {
1274            let integer =
1275                render_stock_icon(IconRole::Save, IconSize::Small, ThemeMode::Dark, whole);
1276            let fractional = render_stock_icon_for_scale(
1277                IconRole::Save,
1278                IconSize::Small,
1279                ThemeMode::Dark,
1280                f64::from(whole),
1281            );
1282            assert_eq!(integer, fractional, "scale {whole}");
1283        }
1284    }
1285
1286    fn has_color_near(icon: &StockIcon, color: Color, tolerance: i32) -> bool {
1287        icon.pixels.as_chunks::<4>().0.iter().any(|px| {
1288            px[3] > 200
1289                && (px[0] as i32 - color.r as i32).abs() <= tolerance
1290                && (px[1] as i32 - color.g as i32).abs() <= tolerance
1291                && (px[2] as i32 - color.b as i32).abs() <= tolerance
1292        })
1293    }
1294
1295    fn alpha_channel(icon: &StockIcon) -> Vec<u8> {
1296        icon.pixels
1297            .as_chunks::<4>()
1298            .0
1299            .iter()
1300            .map(|px| px[3])
1301            .collect()
1302    }
1303
1304    #[test]
1305    fn every_role_resolves_every_size_and_mode() {
1306        assert_eq!(IconRole::ALL.len(), 40);
1307        for role in IconRole::ALL {
1308            for size in IconSize::ALL {
1309                for mode in [ThemeMode::Light, ThemeMode::Dark] {
1310                    let icon = render_stock_icon(role, size, mode, 1);
1311                    assert_eq!(icon.width, size.pixels(), "{role:?}/{size:?}");
1312                    assert_eq!(icon.height, size.pixels(), "{role:?}/{size:?}");
1313                    assert_eq!(icon.pixels.len(), (icon.width * icon.height * 4) as usize);
1314                    assert!(
1315                        icon.has_visible_pixels(),
1316                        "{role:?}/{size:?}/{mode:?} rendered empty"
1317                    );
1318                }
1319            }
1320        }
1321    }
1322
1323    #[test]
1324    fn dpi_scale_multiplies_the_raster_and_is_deterministic() {
1325        let first = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 2);
1326        let second = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 2);
1327        assert_eq!(first.width, 32);
1328        assert_eq!(first.height, 32);
1329        assert_eq!(first, second, "renderer must be deterministic");
1330
1331        let large = render_stock_icon(IconRole::Warning, IconSize::Large, ThemeMode::Light, 1);
1332        assert_eq!(large.width, 32);
1333        assert_ne!(
1334            first, large,
1335            "Small@2x and Large@1x are different DPI variants even at equal raster size"
1336        );
1337
1338        let clamped = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 0);
1339        assert_eq!(clamped.scale, 1);
1340        assert_eq!(clamped.width, 16);
1341        let capped = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 9);
1342        assert_eq!(capped.scale, 4);
1343        assert_eq!(capped.width, 64);
1344    }
1345
1346    #[test]
1347    fn theme_mode_changes_ink_but_not_geometry() {
1348        let light = render_stock_icon(IconRole::Error, IconSize::Large, ThemeMode::Light, 1);
1349        let dark = render_stock_icon(IconRole::Error, IconSize::Large, ThemeMode::Dark, 1);
1350        assert_eq!(light.width, dark.width);
1351        assert_eq!(
1352            alpha_channel(&light),
1353            alpha_channel(&dark),
1354            "theme must not change glyph coverage"
1355        );
1356        assert_ne!(light.pixels, dark.pixels, "theme must change the palette");
1357
1358        let theme_light = Theme::light();
1359        let theme_dark = Theme::dark();
1360        assert!(has_color_near(&light, theme_light.colors.error, 8));
1361        assert!(has_color_near(&dark, theme_dark.colors.error, 8));
1362    }
1363
1364    #[test]
1365    fn severity_and_action_roles_use_their_theme_tokens() {
1366        let theme = Theme::light();
1367        let warning = render_stock_icon(IconRole::Warning, IconSize::Large, ThemeMode::Light, 1);
1368        let information =
1369            render_stock_icon(IconRole::Information, IconSize::Large, ThemeMode::Light, 1);
1370        let play = render_stock_icon(IconRole::Play, IconSize::Large, ThemeMode::Light, 1);
1371        assert!(has_color_near(&warning, theme.colors.warning, 8));
1372        assert!(has_color_near(&information, theme.colors.accent, 8));
1373        assert!(has_color_near(&play, theme.colors.accent, 8));
1374    }
1375
1376    #[test]
1377    fn size_mode_and_role_identifiers_are_stable_and_unique() {
1378        let mut role_ids: Vec<&str> = IconRole::ALL.iter().map(|role| role.as_str()).collect();
1379        role_ids.sort_unstable();
1380        role_ids.dedup();
1381        assert_eq!(
1382            role_ids.len(),
1383            IconRole::ALL.len(),
1384            "role identifiers must be unique"
1385        );
1386        assert!(role_ids.iter().all(|value| !value.is_empty()));
1387
1388        let mut xdg: Vec<&str> = IconRole::ALL.iter().map(|role| role.xdg_name()).collect();
1389        let before = xdg.len();
1390        xdg.sort_unstable();
1391        xdg.dedup();
1392        assert_eq!(xdg.len(), before, "xdg icon names must be unique");
1393        assert!(xdg.iter().all(|value| !value.is_empty()));
1394
1395        assert_eq!(IconSize::Small.pixels(), 16);
1396        assert_eq!(IconSize::Large.pixels(), 32);
1397        assert_eq!(IconSize::Small.as_str(), "small");
1398        assert_eq!(IconSize::Large.as_str(), "large");
1399        assert_eq!(IconSource::Portable.as_str(), "portable");
1400        assert_eq!(IconSource::Native.as_str(), "native");
1401    }
1402
1403    #[test]
1404    fn capability_constructors_report_expected_flags() {
1405        assert_eq!(ArtCapabilities::none(), ArtCapabilities::default());
1406        assert!(!ArtCapabilities::none().native_icons);
1407        let native = ArtCapabilities::native(true, false);
1408        assert!(native.native_icons);
1409        assert!(native.dpi_variants);
1410        assert!(!native.theme_aware);
1411    }
1412
1413    #[test]
1414    fn resamplers_preserve_alpha_and_aspect() {
1415        let pixel = |buffer: &[u8], x: usize, y: usize, width: usize| -> [u8; 4] {
1416            let offset = (y * width + x) * 4;
1417            [
1418                buffer[offset],
1419                buffer[offset + 1],
1420                buffer[offset + 2],
1421                buffer[offset + 3],
1422            ]
1423        };
1424
1425        // 2x2 raster with a single opaque red pixel.
1426        let mut source = vec![0u8; 2 * 2 * 4];
1427        source[0..4].copy_from_slice(&[255, 0, 0, 255]);
1428        let (width, height, scaled) = resample_rgba(&source, 2, 2, 4, 4).expect("resample");
1429        assert_eq!((width, height), (4, 4));
1430        assert_eq!(scaled.len(), 4 * 4 * 4);
1431        assert_eq!(pixel(&scaled, 0, 0, 4), [255, 0, 0, 255]);
1432        assert_eq!(pixel(&scaled, 3, 3, 4)[3], 0);
1433
1434        // A wide raster is letterboxed, not stretched.
1435        let mut wide = vec![0u8; 4 * 2 * 4];
1436        for index in 0..8 {
1437            wide[index * 4] = 10;
1438            wide[index * 4 + 1] = 200;
1439            wide[index * 4 + 2] = 30;
1440            wide[index * 4 + 3] = 255;
1441        }
1442        let (width, height, centered) = resample_rgba_centered(&wide, 4, 2, 8).expect("center");
1443        assert_eq!((width, height), (8, 8));
1444        assert_eq!(centered.len(), 8 * 8 * 4);
1445        assert_eq!(pixel(&centered, 0, 0, 8)[3], 0);
1446        assert_eq!(pixel(&centered, 4, 4, 8)[3], 255);
1447        assert_eq!(pixel(&centered, 7, 7, 8)[3], 0);
1448
1449        assert!(resample_rgba(&source, 2, 2, 4, 4).is_ok());
1450        assert!(matches!(
1451            resample_rgba(&source, 3, 3, 4, 4),
1452            Err(GuiError::Backend(_))
1453        ));
1454    }
1455
1456    #[test]
1457    fn bmp_export_has_a_valid_header_and_composites_alpha() {
1458        let icon = render_stock_icon(IconRole::Folder, IconSize::Small, ThemeMode::Light, 1);
1459        let background = Color::rgb(0x10, 0x20, 0x30);
1460        let bmp = icon.to_bmp(background);
1461        assert_eq!(&bmp[0..2], b"BM");
1462        let declared_size = u32::from_le_bytes([bmp[2], bmp[3], bmp[4], bmp[5]]);
1463        assert_eq!(declared_size as usize, bmp.len());
1464        let offset = u32::from_le_bytes([bmp[10], bmp[11], bmp[12], bmp[13]]);
1465        assert_eq!(offset, 54);
1466        let header_size = u32::from_le_bytes([bmp[14], bmp[15], bmp[16], bmp[17]]);
1467        assert_eq!(header_size, 40);
1468        let width = i32::from_le_bytes([bmp[18], bmp[19], bmp[20], bmp[21]]);
1469        let height = i32::from_le_bytes([bmp[22], bmp[23], bmp[24], bmp[25]]);
1470        assert_eq!((width, height), (16, 16));
1471        let bits = u16::from_le_bytes([bmp[28], bmp[29]]);
1472        assert_eq!(bits, 24);
1473
1474        // Rows are bottom-up, 3 bytes per pixel padded to 4.
1475        let row_stride = (16 * 3 + 3) & !3;
1476        assert_eq!(bmp.len(), 54 + row_stride * 16);
1477
1478        // The top-left corner of the Folder glyph is transparent, so the BMP
1479        // must show the background color there (bottom row in file order).
1480        let corner_row_start = 54 + row_stride * 15;
1481        let (b, g, r) = (
1482            bmp[corner_row_start],
1483            bmp[corner_row_start + 1],
1484            bmp[corner_row_start + 2],
1485        );
1486        assert_eq!((r, g, b), (background.r, background.g, background.b));
1487
1488        // A visible pixel in the glyph must differ from the background.
1489        let opaque = (0..16u32)
1490            .flat_map(|y| (0..16u32).map(move |x| (x, y)))
1491            .find(|(x, y)| icon.pixel(*x, *y).map(|px| px[3] > 200).unwrap_or(false));
1492        assert!(opaque.is_some(), "folder glyph should have opaque pixels");
1493        assert!(bmp.len() > 54);
1494    }
1495
1496    #[test]
1497    fn sf_symbols_cover_all_portable_roles() {
1498        for role in IconRole::ALL {
1499            let symbol = role.sf_symbol_name();
1500            assert!(symbol.is_some(), "{role:?} must have an SF Symbol mapping");
1501            assert!(
1502                !symbol.unwrap().is_empty(),
1503                "{role:?} SF Symbol name cannot be empty"
1504            );
1505        }
1506    }
1507
1508    #[test]
1509    fn formatting_roles_resolve_and_render_crisply() {
1510        let formatting_roles = [
1511            IconRole::FormatBold,
1512            IconRole::FormatItalic,
1513            IconRole::FormatStrikethrough,
1514            IconRole::FormatCode,
1515            IconRole::FormatHeading,
1516            IconRole::ListBulleted,
1517            IconRole::ListNumbered,
1518            IconRole::ListTask,
1519            IconRole::Quote,
1520            IconRole::InsertLink,
1521            IconRole::InsertImage,
1522            IconRole::InsertTable,
1523            IconRole::InsertRule,
1524            IconRole::ThemeToggle,
1525        ];
1526        assert_eq!(formatting_roles.len(), 14);
1527
1528        for role in formatting_roles {
1529            assert!(
1530                role.as_str().starts_with("format-")
1531                    || role.as_str().starts_with("list-")
1532                    || role.as_str().starts_with("insert-")
1533                    || role.as_str() == "quote"
1534                    || role.as_str() == "theme-toggle",
1535                "unexpected as_str: {}",
1536                role.as_str()
1537            );
1538            assert!(
1539                !role.xdg_name().is_empty(),
1540                "xdg_name cannot be empty for {role:?}"
1541            );
1542            assert!(
1543                role.sf_symbol_name().is_some(),
1544                "sf_symbol_name cannot be None for {role:?}"
1545            );
1546
1547            for size in IconSize::ALL {
1548                for mode in [ThemeMode::Light, ThemeMode::Dark] {
1549                    let icon = render_stock_icon(role, size, mode, 1);
1550                    assert_eq!(icon.width, size.pixels());
1551                    assert_eq!(icon.height, size.pixels());
1552                    assert!(
1553                        icon.has_visible_pixels(),
1554                        "formatting role {role:?} ({size:?}, {mode:?}) rendered empty"
1555                    );
1556                }
1557            }
1558        }
1559    }
1560}