waft-winui 0.8.2

WinUI 3 controls and Fluent styling for the Waft UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! The XAML `IconElement` family from `core/elements/icon.cpp`: `FontIcon`, a glyph centred in
//! the icon's bounds, and `PathIcon`, a geometry filled with the icon's foreground. Each takes
//! the enclosing control's text foreground when it carries none of its own. The bundled open
//! Fluent System Icons font stands in for the Windows `Segoe Fluent Icons` family.

use std::sync::Arc;

use waft_embedder::valo::Path;
use waft_embedder::{
    Canvas, Color, FillRule, FontStyle, FontWeight, Paint, Size, TextAlign, TextDirection,
};
use waft_foundation::App;
use waft_painting::{PaintingBinding, TextScaler, TextStyle};
use waft_rendering::CustomPainter;
use waft_widgets::*;

/// `g_ClientCoreFontSize` of `icon.cpp`: the glyph size an icon uses when its `FontSize` is left
/// at its default, rather than the enclosing control's text size.
pub const ICON_FONT_SIZE: f64 = 20.0;

/// The colour an icon falls back to when neither it nor its surroundings name a foreground,
/// matching what a `TextBlock` in the same position would draw.
const DEFAULT_ICON_FOREGROUND: Color = Color::from_argb(255, 0, 0, 0);

/// The family under which the bundled open icon font is registered.
pub const FLUENT_ICON_FONT_FAMILY: &str = "FluentSystemIcons-Regular";

/// Registers the bundled font before the first icon is laid out.
pub fn install_icon_font(app: &mut App) {
    PaintingBinding::instance(app).register_font(
        app,
        FLUENT_ICON_FONT_FAMILY,
        include_bytes!("../../assets/fluent-system-icons/FluentSystemIcons-Regular.ttf").to_vec(),
    );
}

/// Built-in control symbols, mapped to the open Fluent System Icons codepoints.
/// These names intentionally do not promise Segoe's private-use glyph mapping.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FluentSymbol {
    /// A list of menu commands.
    MenuList,
    /// A menu check mark.
    Checkmark,
    /// General information.
    Info,
    /// Successful completion.
    CheckmarkCircle,
    /// An error status.
    DismissCircle,
    /// A warning status.
    Warning,
    /// An exclamation mark inside a circle.
    ErrorCircle,
    /// Progress or elapsed time.
    Timer,
    /// Collapsible sections.
    ChevronDownUp,

    /// Activate an action.
    CursorClick,
    /// Switch a setting.
    ToggleLeft,
    /// A checked choice.
    CheckboxChecked,
    /// A mixed selection.
    CheckboxIndeterminate,
    /// Choose one option.
    RadioButton,
    /// Arrange rows and columns.
    Grid,
    /// Adjust a value or configuration.
    Options,
    /// A side pane with content.
    PanelLeft,
    /// Switch between tabbed pages.
    Tab,
    /// Switch between a few views.
    Tabs,
    /// Contextual help.
    TooltipQuote,
    /// Layered surfaces and materials.
    Layer,
    /// Navigate to a link.
    Link,
    /// Repeat an action.
    ArrowRepeatAll,
    /// Text and typography.
    TextFont,
    /// A collection of symbols or features.
    Apps,
    /// Switch to a dark theme.
    WeatherMoon,
    /// Switch to a light theme.
    WeatherSunny,
    /// Add a tab or item.
    Add,
    /// Close a tab or dismiss a surface.
    Dismiss,
    /// Scroll toward the leading edge in left-to-right layout.
    ChevronLeft,
    /// Scroll toward the trailing edge in left-to-right layout.
    ChevronRight,
    /// Expand a child list or open a menu.
    ChevronDown,
    /// Upward disclosure or scroll affordance.
    ChevronUp,
    /// A value that steps up or down, as NumberBox's popup indicator.
    ChevronUpDown,
    /// Toggle the navigation pane.
    Navigation,
    /// Opens the navigation search presenter.
    Search,
    /// Navigate back.
    Back,
    /// Open settings.
    Settings,
    /// Open the overflow menu.
    More,
    /// Temporarily reveal concealed text.
    Eye,
    /// Editable text input.
    TextField,
    /// Password or protected input.
    LockClosed,
    /// A status dot or badge.
    Circle,
    /// Colour choice: a palette.
    Color,
    /// A hierarchy of items.
    TextBulletListTree,
    /// Work whose completion is shown as a ring.
    SpinnerIos,
    /// A page of an app's content.
    Document,
    /// Rows of a list.
    List,
    /// Rows and columns of a table.
    Table,
    /// A box of tools: a bar of commands.
    Toolbox,
    /// A camera; WinUI's `Symbol.Camera`.
    Camera,
    /// A microphone; WinUI's `Symbol.Microphone`.
    Mic,
    /// A folder; WinUI's `Symbol.Folder`.
    Folder,
    /// A globe; WinUI's `Symbol.Globe`.
    Globe,
    /// A shield, for security and protection.
    Shield,
    /// A clipboard; WinUI's `Symbol.Paste` shows one.
    Clipboard,
    /// A bell, for notifications and alerts.
    Alert,
    /// A console window, for a terminal.
    WindowConsole,
    /// A plug in its socket, for a connection.
    PlugConnected,
    /// A point sending out waves, for something live or listening.
    Live,
    /// A question mark; WinUI's `Symbol.Help`.
    Question,
    /// A desktop computer, for a machine.
    Desktop,
    /// A pulse line, for activity.
    Pulse,
    /// A triangle pointing forward; WinUI's `Symbol.Play`.
    Play,
    /// A square; WinUI's `Symbol.Stop`.
    Stop,
}

impl FluentSymbol {
    /// The glyph from the bundled revision's `codepoints.json`.
    pub fn glyph(self) -> char {
        char::from_u32(match self {
            Self::MenuList => 60642,
            Self::Checkmark => 62099,
            Self::Info => 62626,
            Self::CheckmarkCircle => 62103,
            Self::DismissCircle => 62316,
            Self::Warning => 63592,
            Self::ErrorCircle => 62448,
            Self::Timer => 60808,
            Self::ChevronDownUp => 983404,
            Self::CursorClick => 58437,
            Self::ToggleLeft => 60816,
            Self::CheckboxChecked => 62093,
            Self::CheckboxIndeterminate => 58110,
            Self::RadioButton => 63044,
            Self::Grid => 62562,
            Self::Options => 62855,
            Self::PanelLeft => 59568,
            Self::Tab => 63300,
            Self::Tabs => 60527,
            Self::TooltipQuote => 63419,
            Self::Layer => 62667,
            Self::Link => 62692,
            Self::ArrowRepeatAll => 61809,
            Self::TextFont => 63460,
            Self::Apps => 61747,
            Self::WeatherMoon => 63613,
            Self::WeatherSunny => 63649,
            Self::Add => 61704,
            Self::Dismiss => 62312,
            Self::ChevronLeft => 62121,
            Self::ChevronRight => 62127,
            Self::ChevronDown => 62114,
            Self::ChevronUp => 62134,
            Self::ChevronUpDown => 58158,
            Self::Search => 63119,
            Self::Navigation => 62816,
            Self::Back => 61787,
            Self::Settings => 63145,
            Self::More => 59428,
            Self::Eye => 58866,
            Self::TextField => 63455,
            Self::LockClosed => 59279,
            Self::Circle => 62140,
            Self::Color => 62197,
            Self::TextBulletListTree => 63406,
            Self::SpinnerIos => 63241,
            Self::Document => 62329,
            Self::List => 62702,
            Self::Table => 63326,
            Self::Toolbox => 63534,
            Self::Camera => 62036,
            Self::Mic => 59385,
            Self::Folder => 62488,
            Self::Globe => 62554,
            Self::Shield => 63166,
            Self::Clipboard => 62153,
            Self::Alert => 61716,
            Self::WindowConsole => 61039,
            Self::PlugConnected => 59801,
            Self::Live => 62704,
            Self::Question => 63032,
            Self::Desktop => 62297,
            Self::Pulse => 59868,
            Self::Play => 62981,
            Self::Stop => 63274,
        })
        .unwrap()
    }
}

/// XAML `FontIcon`: a glyph centred in the icon's bounds, drawn in `FontFamily` at `FontSize`
/// and optionally reflected in right-to-left layout. The glyph shapes use the documented open
/// font substitute.
#[derive(Clone, Debug)]
pub struct FontIcon {
    /// `Glyph`: the character or characters shown.
    pub glyph: String,
    /// `FontFamily`: the family the glyph is taken from; the bundled icon font by default.
    pub font_family: String,
    /// `FontSize`: `g_ClientCoreFontSize`, 20, unless the caller sets it.
    pub font_size: f64,
    /// `FontWeight`.
    pub font_weight: FontWeight,
    /// `FontStyle`.
    pub font_style: FontStyle,
    /// `MirroredWhenRightToLeft`: whether the glyph is reflected horizontally in right-to-left
    /// layout.
    pub mirrored_when_right_to_left: bool,
    /// `IconElement.Foreground`, or the enclosing control's text foreground.
    pub foreground: Option<Color>,
    /// Identity retained across parent rebuilds.
    pub key: Option<KeyRef>,
}

impl FontIcon {
    /// Creates an icon for the glyph, in the bundled icon font at the source default size.
    pub fn new(glyph: impl Into<String>) -> Self {
        Self {
            glyph: glyph.into(),
            font_family: FLUENT_ICON_FONT_FAMILY.to_string(),
            font_size: ICON_FONT_SIZE,
            font_weight: FontWeight::NORMAL,
            font_style: FontStyle::Normal,
            mirrored_when_right_to_left: false,
            foreground: None,
            key: None,
        }
    }

    /// Creates an icon for one of the kit's built-in control symbols.
    pub fn symbol(symbol: FluentSymbol) -> Self {
        Self::new(symbol.glyph().to_string())
    }

    /// Sets the XAML `FontFamily` the glyph is taken from.
    pub fn font_family(mut self, value: impl Into<String>) -> Self {
        self.font_family = value.into();
        self
    }

    /// Sets the XAML `FontSize`.
    pub fn font_size(mut self, value: f64) -> Self {
        self.font_size = value;
        self
    }

    /// Sets the XAML `FontWeight`.
    pub fn font_weight(mut self, value: FontWeight) -> Self {
        self.font_weight = value;
        self
    }

    /// Sets the XAML `FontStyle`.
    pub fn font_style(mut self, value: FontStyle) -> Self {
        self.font_style = value;
        self
    }

    /// Sets the XAML `MirroredWhenRightToLeft`.
    pub fn mirrored_when_right_to_left(mut self, value: bool) -> Self {
        self.mirrored_when_right_to_left = value;
        self
    }

    /// Sets the XAML `Foreground` instead of inheriting the label colour.
    pub fn foreground(mut self, value: Color) -> Self {
        self.foreground = Some(value);
        self
    }

    /// Sets the identity retained across rebuilds.
    pub fn key(mut self, value: KeyRef) -> Self {
        self.key = Some(value);
        self
    }
}

impl StatelessWidget for FontIcon {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let mut style = TextStyle::new()
            .font_family(self.font_family.clone())
            .font_size(self.font_size)
            .font_weight(self.font_weight)
            .font_style(self.font_style);
        if let Some(color) = self.foreground {
            style = style.color(color);
        }
        // FontIcon's child TextBlock is centred and disables text scale factors.
        let glyph = Text::new(self.glyph.clone())
            .style(style)
            .text_align(TextAlign::Center)
            .text_scaler(TextScaler::NO_SCALING);
        let glyph = Center::new()
            .width_factor(1.0)
            .height_factor(1.0)
            .child(glyph);
        if self.mirrored_when_right_to_left
            && Directionality::of(app, context) == TextDirection::Rtl
        {
            Transform::scale(None, Some(-1.0), Some(1.0))
                .child(glyph)
                .into_widget()
        } else {
            glyph.into_widget()
        }
    }
}

/// XAML `PathIcon`: a geometry filled with the icon's foreground. As `Shape` lays out with
/// `Stretch.None`, the icon asks for the space between the origin and the geometry's far edges,
/// and the geometry keeps its own coordinates.
#[derive(Clone, Debug)]
pub struct PathIcon {
    /// `Data`: the geometry to fill.
    pub data: Arc<Path>,
    /// `Geometry.FillRule`: which regions of a self-crossing geometry are filled;
    /// `XcpFillModeAlternate`, the even-odd rule, is the source default.
    pub fill_rule: FillRule,
    /// `IconElement.Foreground`, or the enclosing control's text foreground.
    pub foreground: Option<Color>,
    /// Identity retained across parent rebuilds.
    pub key: Option<KeyRef>,
}

impl PathIcon {
    /// Creates an icon filling the geometry.
    pub fn new(data: impl Into<Arc<Path>>) -> Self {
        Self {
            data: data.into(),
            fill_rule: FillRule::EvenOdd,
            foreground: None,
            key: None,
        }
    }

    /// Sets the XAML `Geometry.FillRule`.
    pub fn fill_rule(mut self, value: FillRule) -> Self {
        self.fill_rule = value;
        self
    }

    /// Sets the XAML `Foreground` instead of inheriting the label colour.
    pub fn foreground(mut self, value: Color) -> Self {
        self.foreground = Some(value);
        self
    }

    /// Sets the identity retained across rebuilds.
    pub fn key(mut self, value: KeyRef) -> Self {
        self.key = Some(value);
        self
    }
}

impl StatelessWidget for PathIcon {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let fill = self.foreground.unwrap_or_else(|| {
            DefaultTextStyle::of(app, context)
                .style
                .color
                .map_or(DEFAULT_ICON_FOREGROUND, |color| color.color())
        });
        // CShape::MeasureOverride with Stretch.None asks for the geometry's far edges.
        let bounds = self.data.tight_bounds();
        let size = Size::new(
            f64::from(bounds.x + bounds.width).max(0.0),
            f64::from(bounds.y + bounds.height).max(0.0),
        );
        CustomPaint::new()
            .size(size)
            .painter(PathIconPainter {
                data: self.data.clone(),
                fill_rule: self.fill_rule,
                fill,
            })
            .into_widget()
    }
}

/// The `Path` inside `PathIcon`'s template, filled with the resolved foreground.
#[derive(Clone, Debug)]
struct PathIconPainter {
    data: Arc<Path>,
    fill_rule: FillRule,
    fill: Color,
}

impl CustomPainter for PathIconPainter {
    fn paint(&self, _app: &mut App, canvas: &mut Canvas, _size: Size) {
        canvas.draw_path(
            &self.data,
            self.fill_rule,
            &Paint::from_color(self.fill.into()),
        );
    }

    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
        match old_delegate.as_any().downcast_ref::<Self>() {
            Some(old) => {
                old.fill != self.fill
                    || old.fill_rule != self.fill_rule
                    || !Arc::ptr_eq(&old.data, &self.data)
                        && !old.data.elements().eq(self.data.elements())
            }
            None => true,
        }
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::FluentSymbol;

    // Each name is the bundled font's own: its glyph is the one `codepoints.json` gives that name.
    #[test]
    fn the_inspectors_symbols_are_the_fonts_named_glyphs() {
        let codepoints = include_str!("../../assets/fluent-system-icons/codepoints.json");
        for (symbol, name) in [
            (FluentSymbol::Camera, "ic_fluent_camera_20_regular"),
            (FluentSymbol::Mic, "ic_fluent_mic_20_regular"),
            (FluentSymbol::Folder, "ic_fluent_folder_20_regular"),
            (FluentSymbol::Globe, "ic_fluent_globe_20_regular"),
            (FluentSymbol::Shield, "ic_fluent_shield_20_regular"),
            (FluentSymbol::Clipboard, "ic_fluent_clipboard_20_regular"),
            (FluentSymbol::Alert, "ic_fluent_alert_20_regular"),
            (
                FluentSymbol::WindowConsole,
                "ic_fluent_window_console_20_regular",
            ),
            (
                FluentSymbol::PlugConnected,
                "ic_fluent_plug_connected_20_regular",
            ),
            (FluentSymbol::Live, "ic_fluent_live_20_regular"),
            (FluentSymbol::Question, "ic_fluent_question_20_regular"),
            (FluentSymbol::Desktop, "ic_fluent_desktop_20_regular"),
            (FluentSymbol::Pulse, "ic_fluent_pulse_20_regular"),
            (FluentSymbol::Play, "ic_fluent_play_20_regular"),
            (FluentSymbol::Stop, "ic_fluent_stop_20_regular"),
        ] {
            let entry = format!("\"{name}\": {}", symbol.glyph() as u32);
            assert!(codepoints.contains(&entry), "{symbol:?} is {name}");
        }
    }
}