Skip to main content

waft_winui/primitives/
icon.rs

1//! The XAML `IconElement` family from `core/elements/icon.cpp`: `FontIcon`, a glyph centred in
2//! the icon's bounds, and `PathIcon`, a geometry filled with the icon's foreground. Each takes
3//! the enclosing control's text foreground when it carries none of its own. The bundled open
4//! Fluent System Icons font stands in for the Windows `Segoe Fluent Icons` family.
5
6use std::sync::Arc;
7
8use waft_embedder::valo::Path;
9use waft_embedder::{
10    Canvas, Color, FillRule, FontStyle, FontWeight, Paint, Size, TextAlign, TextDirection,
11};
12use waft_foundation::App;
13use waft_painting::{PaintingBinding, TextScaler, TextStyle};
14use waft_rendering::CustomPainter;
15use waft_widgets::*;
16
17/// `g_ClientCoreFontSize` of `icon.cpp`: the glyph size an icon uses when its `FontSize` is left
18/// at its default, rather than the enclosing control's text size.
19pub const ICON_FONT_SIZE: f64 = 20.0;
20
21/// The colour an icon falls back to when neither it nor its surroundings name a foreground,
22/// matching what a `TextBlock` in the same position would draw.
23const DEFAULT_ICON_FOREGROUND: Color = Color::from_argb(255, 0, 0, 0);
24
25/// The family under which the bundled open icon font is registered.
26pub const FLUENT_ICON_FONT_FAMILY: &str = "FluentSystemIcons-Regular";
27
28/// Registers the bundled font before the first icon is laid out.
29pub fn install_icon_font(app: &mut App) {
30    PaintingBinding::instance(app).register_font(
31        app,
32        FLUENT_ICON_FONT_FAMILY,
33        include_bytes!("../../assets/fluent-system-icons/FluentSystemIcons-Regular.ttf").to_vec(),
34    );
35}
36
37/// Built-in control symbols, mapped to the open Fluent System Icons codepoints.
38/// These names intentionally do not promise Segoe's private-use glyph mapping.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum FluentSymbol {
41    /// A list of menu commands.
42    MenuList,
43    /// A menu check mark.
44    Checkmark,
45    /// General information.
46    Info,
47    /// Successful completion.
48    CheckmarkCircle,
49    /// An error status.
50    DismissCircle,
51    /// A warning status.
52    Warning,
53    /// An exclamation mark inside a circle.
54    ErrorCircle,
55    /// Progress or elapsed time.
56    Timer,
57    /// Collapsible sections.
58    ChevronDownUp,
59
60    /// Activate an action.
61    CursorClick,
62    /// Switch a setting.
63    ToggleLeft,
64    /// A checked choice.
65    CheckboxChecked,
66    /// A mixed selection.
67    CheckboxIndeterminate,
68    /// Choose one option.
69    RadioButton,
70    /// Arrange rows and columns.
71    Grid,
72    /// Adjust a value or configuration.
73    Options,
74    /// A side pane with content.
75    PanelLeft,
76    /// Switch between tabbed pages.
77    Tab,
78    /// Switch between a few views.
79    Tabs,
80    /// Contextual help.
81    TooltipQuote,
82    /// Layered surfaces and materials.
83    Layer,
84    /// Navigate to a link.
85    Link,
86    /// Repeat an action.
87    ArrowRepeatAll,
88    /// Text and typography.
89    TextFont,
90    /// A collection of symbols or features.
91    Apps,
92    /// Switch to a dark theme.
93    WeatherMoon,
94    /// Switch to a light theme.
95    WeatherSunny,
96    /// Add a tab or item.
97    Add,
98    /// Close a tab or dismiss a surface.
99    Dismiss,
100    /// Scroll toward the leading edge in left-to-right layout.
101    ChevronLeft,
102    /// Scroll toward the trailing edge in left-to-right layout.
103    ChevronRight,
104    /// Expand a child list or open a menu.
105    ChevronDown,
106    /// Upward disclosure or scroll affordance.
107    ChevronUp,
108    /// A value that steps up or down, as NumberBox's popup indicator.
109    ChevronUpDown,
110    /// Toggle the navigation pane.
111    Navigation,
112    /// Opens the navigation search presenter.
113    Search,
114    /// Navigate back.
115    Back,
116    /// Open settings.
117    Settings,
118    /// Open the overflow menu.
119    More,
120    /// Temporarily reveal concealed text.
121    Eye,
122    /// Editable text input.
123    TextField,
124    /// Password or protected input.
125    LockClosed,
126    /// A status dot or badge.
127    Circle,
128    /// Colour choice: a palette.
129    Color,
130    /// A hierarchy of items.
131    TextBulletListTree,
132    /// Work whose completion is shown as a ring.
133    SpinnerIos,
134    /// A page of an app's content.
135    Document,
136    /// Rows of a list.
137    List,
138    /// Rows and columns of a table.
139    Table,
140    /// A box of tools: a bar of commands.
141    Toolbox,
142    /// A camera; WinUI's `Symbol.Camera`.
143    Camera,
144    /// A microphone; WinUI's `Symbol.Microphone`.
145    Mic,
146    /// A folder; WinUI's `Symbol.Folder`.
147    Folder,
148    /// A globe; WinUI's `Symbol.Globe`.
149    Globe,
150    /// A shield, for security and protection.
151    Shield,
152    /// A clipboard; WinUI's `Symbol.Paste` shows one.
153    Clipboard,
154    /// A bell, for notifications and alerts.
155    Alert,
156    /// A console window, for a terminal.
157    WindowConsole,
158    /// A plug in its socket, for a connection.
159    PlugConnected,
160    /// A point sending out waves, for something live or listening.
161    Live,
162    /// A question mark; WinUI's `Symbol.Help`.
163    Question,
164    /// A desktop computer, for a machine.
165    Desktop,
166    /// A pulse line, for activity.
167    Pulse,
168    /// A triangle pointing forward; WinUI's `Symbol.Play`.
169    Play,
170    /// A square; WinUI's `Symbol.Stop`.
171    Stop,
172}
173
174impl FluentSymbol {
175    /// The glyph from the bundled revision's `codepoints.json`.
176    pub fn glyph(self) -> char {
177        char::from_u32(match self {
178            Self::MenuList => 60642,
179            Self::Checkmark => 62099,
180            Self::Info => 62626,
181            Self::CheckmarkCircle => 62103,
182            Self::DismissCircle => 62316,
183            Self::Warning => 63592,
184            Self::ErrorCircle => 62448,
185            Self::Timer => 60808,
186            Self::ChevronDownUp => 983404,
187            Self::CursorClick => 58437,
188            Self::ToggleLeft => 60816,
189            Self::CheckboxChecked => 62093,
190            Self::CheckboxIndeterminate => 58110,
191            Self::RadioButton => 63044,
192            Self::Grid => 62562,
193            Self::Options => 62855,
194            Self::PanelLeft => 59568,
195            Self::Tab => 63300,
196            Self::Tabs => 60527,
197            Self::TooltipQuote => 63419,
198            Self::Layer => 62667,
199            Self::Link => 62692,
200            Self::ArrowRepeatAll => 61809,
201            Self::TextFont => 63460,
202            Self::Apps => 61747,
203            Self::WeatherMoon => 63613,
204            Self::WeatherSunny => 63649,
205            Self::Add => 61704,
206            Self::Dismiss => 62312,
207            Self::ChevronLeft => 62121,
208            Self::ChevronRight => 62127,
209            Self::ChevronDown => 62114,
210            Self::ChevronUp => 62134,
211            Self::ChevronUpDown => 58158,
212            Self::Search => 63119,
213            Self::Navigation => 62816,
214            Self::Back => 61787,
215            Self::Settings => 63145,
216            Self::More => 59428,
217            Self::Eye => 58866,
218            Self::TextField => 63455,
219            Self::LockClosed => 59279,
220            Self::Circle => 62140,
221            Self::Color => 62197,
222            Self::TextBulletListTree => 63406,
223            Self::SpinnerIos => 63241,
224            Self::Document => 62329,
225            Self::List => 62702,
226            Self::Table => 63326,
227            Self::Toolbox => 63534,
228            Self::Camera => 62036,
229            Self::Mic => 59385,
230            Self::Folder => 62488,
231            Self::Globe => 62554,
232            Self::Shield => 63166,
233            Self::Clipboard => 62153,
234            Self::Alert => 61716,
235            Self::WindowConsole => 61039,
236            Self::PlugConnected => 59801,
237            Self::Live => 62704,
238            Self::Question => 63032,
239            Self::Desktop => 62297,
240            Self::Pulse => 59868,
241            Self::Play => 62981,
242            Self::Stop => 63274,
243        })
244        .unwrap()
245    }
246}
247
248/// XAML `FontIcon`: a glyph centred in the icon's bounds, drawn in `FontFamily` at `FontSize`
249/// and optionally reflected in right-to-left layout. The glyph shapes use the documented open
250/// font substitute.
251#[derive(Clone, Debug)]
252pub struct FontIcon {
253    /// `Glyph`: the character or characters shown.
254    pub glyph: String,
255    /// `FontFamily`: the family the glyph is taken from; the bundled icon font by default.
256    pub font_family: String,
257    /// `FontSize`: `g_ClientCoreFontSize`, 20, unless the caller sets it.
258    pub font_size: f64,
259    /// `FontWeight`.
260    pub font_weight: FontWeight,
261    /// `FontStyle`.
262    pub font_style: FontStyle,
263    /// `MirroredWhenRightToLeft`: whether the glyph is reflected horizontally in right-to-left
264    /// layout.
265    pub mirrored_when_right_to_left: bool,
266    /// `IconElement.Foreground`, or the enclosing control's text foreground.
267    pub foreground: Option<Color>,
268    /// Identity retained across parent rebuilds.
269    pub key: Option<KeyRef>,
270}
271
272impl FontIcon {
273    /// Creates an icon for the glyph, in the bundled icon font at the source default size.
274    pub fn new(glyph: impl Into<String>) -> Self {
275        Self {
276            glyph: glyph.into(),
277            font_family: FLUENT_ICON_FONT_FAMILY.to_string(),
278            font_size: ICON_FONT_SIZE,
279            font_weight: FontWeight::NORMAL,
280            font_style: FontStyle::Normal,
281            mirrored_when_right_to_left: false,
282            foreground: None,
283            key: None,
284        }
285    }
286
287    /// Creates an icon for one of the kit's built-in control symbols.
288    pub fn symbol(symbol: FluentSymbol) -> Self {
289        Self::new(symbol.glyph().to_string())
290    }
291
292    /// Sets the XAML `FontFamily` the glyph is taken from.
293    pub fn font_family(mut self, value: impl Into<String>) -> Self {
294        self.font_family = value.into();
295        self
296    }
297
298    /// Sets the XAML `FontSize`.
299    pub fn font_size(mut self, value: f64) -> Self {
300        self.font_size = value;
301        self
302    }
303
304    /// Sets the XAML `FontWeight`.
305    pub fn font_weight(mut self, value: FontWeight) -> Self {
306        self.font_weight = value;
307        self
308    }
309
310    /// Sets the XAML `FontStyle`.
311    pub fn font_style(mut self, value: FontStyle) -> Self {
312        self.font_style = value;
313        self
314    }
315
316    /// Sets the XAML `MirroredWhenRightToLeft`.
317    pub fn mirrored_when_right_to_left(mut self, value: bool) -> Self {
318        self.mirrored_when_right_to_left = value;
319        self
320    }
321
322    /// Sets the XAML `Foreground` instead of inheriting the label colour.
323    pub fn foreground(mut self, value: Color) -> Self {
324        self.foreground = Some(value);
325        self
326    }
327
328    /// Sets the identity retained across rebuilds.
329    pub fn key(mut self, value: KeyRef) -> Self {
330        self.key = Some(value);
331        self
332    }
333}
334
335impl StatelessWidget for FontIcon {
336    fn key(&self) -> Option<&KeyRef> {
337        self.key.as_ref()
338    }
339
340    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
341        let mut style = TextStyle::new()
342            .font_family(self.font_family.clone())
343            .font_size(self.font_size)
344            .font_weight(self.font_weight)
345            .font_style(self.font_style);
346        if let Some(color) = self.foreground {
347            style = style.color(color);
348        }
349        // FontIcon's child TextBlock is centred and disables text scale factors.
350        let glyph = Text::new(self.glyph.clone())
351            .style(style)
352            .text_align(TextAlign::Center)
353            .text_scaler(TextScaler::NO_SCALING);
354        let glyph = Center::new()
355            .width_factor(1.0)
356            .height_factor(1.0)
357            .child(glyph);
358        if self.mirrored_when_right_to_left
359            && Directionality::of(app, context) == TextDirection::Rtl
360        {
361            Transform::scale(None, Some(-1.0), Some(1.0))
362                .child(glyph)
363                .into_widget()
364        } else {
365            glyph.into_widget()
366        }
367    }
368}
369
370/// XAML `PathIcon`: a geometry filled with the icon's foreground. As `Shape` lays out with
371/// `Stretch.None`, the icon asks for the space between the origin and the geometry's far edges,
372/// and the geometry keeps its own coordinates.
373#[derive(Clone, Debug)]
374pub struct PathIcon {
375    /// `Data`: the geometry to fill.
376    pub data: Arc<Path>,
377    /// `Geometry.FillRule`: which regions of a self-crossing geometry are filled;
378    /// `XcpFillModeAlternate`, the even-odd rule, is the source default.
379    pub fill_rule: FillRule,
380    /// `IconElement.Foreground`, or the enclosing control's text foreground.
381    pub foreground: Option<Color>,
382    /// Identity retained across parent rebuilds.
383    pub key: Option<KeyRef>,
384}
385
386impl PathIcon {
387    /// Creates an icon filling the geometry.
388    pub fn new(data: impl Into<Arc<Path>>) -> Self {
389        Self {
390            data: data.into(),
391            fill_rule: FillRule::EvenOdd,
392            foreground: None,
393            key: None,
394        }
395    }
396
397    /// Sets the XAML `Geometry.FillRule`.
398    pub fn fill_rule(mut self, value: FillRule) -> Self {
399        self.fill_rule = value;
400        self
401    }
402
403    /// Sets the XAML `Foreground` instead of inheriting the label colour.
404    pub fn foreground(mut self, value: Color) -> Self {
405        self.foreground = Some(value);
406        self
407    }
408
409    /// Sets the identity retained across rebuilds.
410    pub fn key(mut self, value: KeyRef) -> Self {
411        self.key = Some(value);
412        self
413    }
414}
415
416impl StatelessWidget for PathIcon {
417    fn key(&self) -> Option<&KeyRef> {
418        self.key.as_ref()
419    }
420
421    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
422        let fill = self.foreground.unwrap_or_else(|| {
423            DefaultTextStyle::of(app, context)
424                .style
425                .color
426                .map_or(DEFAULT_ICON_FOREGROUND, |color| color.color())
427        });
428        // CShape::MeasureOverride with Stretch.None asks for the geometry's far edges.
429        let bounds = self.data.tight_bounds();
430        let size = Size::new(
431            f64::from(bounds.x + bounds.width).max(0.0),
432            f64::from(bounds.y + bounds.height).max(0.0),
433        );
434        CustomPaint::new()
435            .size(size)
436            .painter(PathIconPainter {
437                data: self.data.clone(),
438                fill_rule: self.fill_rule,
439                fill,
440            })
441            .into_widget()
442    }
443}
444
445/// The `Path` inside `PathIcon`'s template, filled with the resolved foreground.
446#[derive(Clone, Debug)]
447struct PathIconPainter {
448    data: Arc<Path>,
449    fill_rule: FillRule,
450    fill: Color,
451}
452
453impl CustomPainter for PathIconPainter {
454    fn paint(&self, _app: &mut App, canvas: &mut Canvas, _size: Size) {
455        canvas.draw_path(
456            &self.data,
457            self.fill_rule,
458            &Paint::from_color(self.fill.into()),
459        );
460    }
461
462    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
463        match old_delegate.as_any().downcast_ref::<Self>() {
464            Some(old) => {
465                old.fill != self.fill
466                    || old.fill_rule != self.fill_rule
467                    || !Arc::ptr_eq(&old.data, &self.data)
468                        && !old.data.elements().eq(self.data.elements())
469            }
470            None => true,
471        }
472    }
473
474    fn as_any(&self) -> &dyn std::any::Any {
475        self
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::FluentSymbol;
482
483    // Each name is the bundled font's own: its glyph is the one `codepoints.json` gives that name.
484    #[test]
485    fn the_inspectors_symbols_are_the_fonts_named_glyphs() {
486        let codepoints = include_str!("../../assets/fluent-system-icons/codepoints.json");
487        for (symbol, name) in [
488            (FluentSymbol::Camera, "ic_fluent_camera_20_regular"),
489            (FluentSymbol::Mic, "ic_fluent_mic_20_regular"),
490            (FluentSymbol::Folder, "ic_fluent_folder_20_regular"),
491            (FluentSymbol::Globe, "ic_fluent_globe_20_regular"),
492            (FluentSymbol::Shield, "ic_fluent_shield_20_regular"),
493            (FluentSymbol::Clipboard, "ic_fluent_clipboard_20_regular"),
494            (FluentSymbol::Alert, "ic_fluent_alert_20_regular"),
495            (
496                FluentSymbol::WindowConsole,
497                "ic_fluent_window_console_20_regular",
498            ),
499            (
500                FluentSymbol::PlugConnected,
501                "ic_fluent_plug_connected_20_regular",
502            ),
503            (FluentSymbol::Live, "ic_fluent_live_20_regular"),
504            (FluentSymbol::Question, "ic_fluent_question_20_regular"),
505            (FluentSymbol::Desktop, "ic_fluent_desktop_20_regular"),
506            (FluentSymbol::Pulse, "ic_fluent_pulse_20_regular"),
507            (FluentSymbol::Play, "ic_fluent_play_20_regular"),
508            (FluentSymbol::Stop, "ic_fluent_stop_20_regular"),
509        ] {
510            let entry = format!("\"{name}\": {}", symbol.glyph() as u32);
511            assert!(codepoints.contains(&entry), "{symbol:?} is {name}");
512        }
513    }
514}