Skip to main content

waft_winui/controls/
check_box.rs

1//! XAML `CheckBox` with the `DefaultCheckBoxStyle` of `CheckBox_themeresources.xaml`.
2//!
3//! Template, top to bottom: `RootGrid` (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`; columns `Auto` and `*`); in column 0 a 20 × 20 grid centred vertically holding `NormalRectangle` (the box: `CheckBoxCheckBackgroundFill*` / `Stroke*`, `CheckBoxBorderThickness`, radius `CornerRadius`) and `CheckGlyph` (an `AnimatedIcon` playing `AnimatedAcceptVisualSource`, `Margin="0,1,0,-1"`, `Margin="0"` in the indeterminate states; its `FallbackIconSource` is the `DownLevelCheckGlyph` FontIcon); in column 1 the `ContentPresenter` with `Margin="{TemplateBinding Padding}"`, `HorizontalContentAlignment="Left"`, `VerticalContentAlignment="Top"`. The `CombinedStates` group (`UncheckedNormal` … `IndeterminateDisabled`) swaps the six brushes discretely; there is no `BrushTransition`.
4//!
5//! The glyph is not a font glyph on a Windows 11 host: `AnimatedIcon` renders the composition program in `controls/dev/AnimatedIcon/AnimatedVisuals/AnimatedAcceptVisualSource.cpp` (LottieGen output), which this file transcribes: a 48 × 48 canvas, the check as a polyline stroked 4 wide with round caps and joins under the layer transforms, drawn on by `TrimEnd` and erased by `TrimStart`, and the indeterminate bar as a line. `AnimatedIcon::ArrangeOverride` scales the canvas uniformly into the icon's bounds and centres it.
6
7use crate::{
8    BackgroundSizing, Brush, ColumnDefinition, CommonState, CommonStates, ControlBorder,
9    ControlStates, FocusVisual, Grid, GridCell, GridLength, ThemeResources, control_text_style,
10};
11use std::{any::TypeId, collections::HashMap, fmt, rc::Rc, time::Duration};
12use waft_animation::{
13    Animation, AnimationBehavior, AnimationController, AnimationStatusListener, Cubic, Curve,
14};
15use waft_embedder::valo::{Cap, FillRule, Join, Point};
16use waft_embedder::{
17    Canvas, Color, FontWeight, Offset, Paint, PaintStyle, PathBuilder, Size, Stroke,
18};
19use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
20use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry};
21use waft_rendering::{BoxConstraints, CustomPainter};
22use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
23use waft_services::LogicalKeyboardKey;
24use waft_widgets::*;
25
26/// `Control.BorderThickness`: the style sets none, so `RootGrid` draws no border.
27pub const CHECK_BOX_ROOT_BORDER_THICKNESS: f64 = 0.0;
28/// `CheckGlyph`'s `Margin="0,1,0,-1"`: the glyph sits one pixel below the box's centre in the checked and unchecked states.
29pub const CHECK_GLYPH_OFFSET: Offset = Offset::new(0.0, 1.0);
30
31/// `AnimatedAcceptVisualSource::Size()`.
32pub const ACCEPT_VISUAL_SIZE: f64 = 48.0;
33/// `AnimatedAcceptVisualSource::Duration()`: `c_durationTicks` of 100 ns, 160 frames at 60 fps.
34pub const ACCEPT_VISUAL_DURATION: Duration = Duration::from_nanos(26_666_666 * 100);
35/// The `NormalOffToNormalOn` markers; `PointerOverOffToPointerOverOn` and `PressedOffToNormalOn` span the same length, with the same `TrimEnd` keyframes.
36pub const NORMAL_OFF_TO_NORMAL_ON: (f64, f64) = (0.0940625, 0.2128125);
37/// The `NormalOnToNormalOff` markers; `PointerOverOnToPointerOverOff` and `PressedOnToNormalOff` span the same length, with the same `TrimStart` keyframes.
38pub const NORMAL_ON_TO_NORMAL_OFF: (f64, f64) = (0.0, 0.0253125);
39/// `CubicBezierEasingFunction_0`, easing every `TrimEnd` keyframe.
40pub const TRIM_END_EASING: [f64; 4] = [0.55, 0.0, 0.0, 1.0];
41/// `CubicBezierEasingFunction_1`, easing every `TrimStart` keyframe.
42pub const TRIM_START_EASING: [f64; 4] = [0.167, 0.167, 0.833, 0.833];
43/// `CompositionSpriteShape::StrokeThickness` of every shape in the program.
44pub const ACCEPT_STROKE_THICKNESS: f32 = 4.0;
45/// `Geometry_1`: the check, in shape space.
46pub const CHECK_POLYLINE: [(f32, f32); 3] = [(-15.172, 0.016), (-5.0, 10.188), (15.337, -10.337)];
47/// `Geometry_0`: the indeterminate bar, in shape space.
48pub const INDETERMINATE_POLYLINE: [(f32, f32); 2] = [(-11.75, -0.125), (11.875, -0.125)];
49/// The sprite shapes' `TransformMatrix`: scale 0.7 then offset (24, 23) for the check layers and (24, 24) for the indeterminate layer.
50pub const SPRITE_SCALE: f32 = 0.7;
51pub const CHECK_SPRITE_OFFSET: (f32, f32) = (24.0, 23.0);
52pub const INDETERMINATE_SPRITE_OFFSET: (f32, f32) = (24.0, 24.0);
53/// `Null 230`: every layer's container scales 1.05 about the canvas centre (offset (−24, −24), scale 1.05, offset (24, 24)).
54pub const LAYER_SCALE: f32 = 1.05;
55
56/// How long `AnimatedIcon::PlaySegment` plays a segment: the visual's duration times the marker span.
57pub fn segment_duration(markers: (f64, f64)) -> Duration {
58    ACCEPT_VISUAL_DURATION.mul_f64(markers.1 - markers.0)
59}
60
61/// XAML `ToggleButton.IsChecked`, whose `IReference<bool>` is null for indeterminate.
62///
63/// Internal: the control's own `is_checked` is already `Option<bool>`, as Flutter's
64/// `Checkbox(value:)`; this names the three drawing states for the template.
65#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
66pub(crate) enum CheckState {
67    #[default]
68    Unchecked,
69    Checked,
70    Indeterminate,
71}
72
73impl CheckState {
74    pub(crate) fn from_is_checked(is_checked: Option<bool>) -> CheckState {
75        match is_checked {
76            Some(true) => CheckState::Checked,
77            Some(false) => CheckState::Unchecked,
78            None => CheckState::Indeterminate,
79        }
80    }
81}
82
83/// `ToggleButton::OnToggleImpl`: indeterminate → unchecked; checked → indeterminate when three-state, else unchecked; unchecked → checked.
84pub fn toggle_is_checked(is_checked: Option<bool>, is_three_state: bool) -> Option<bool> {
85    match is_checked {
86        None => Some(false),
87        Some(true) if is_three_state => None,
88        Some(true) => Some(false),
89        Some(false) => Some(true),
90    }
91}
92
93/// The brushes one `CombinedStates` storyboard names.
94#[derive(Clone, Copy, Debug, PartialEq)]
95pub struct CheckBoxBrushes {
96    /// `ContentPresenter.Foreground`.
97    pub foreground: Color,
98    /// `RootGrid.Background`.
99    pub background: Color,
100    /// `RootGrid.BorderBrush`.
101    pub border: Color,
102    /// `NormalRectangle.Stroke`.
103    pub box_stroke: Color,
104    /// `NormalRectangle.Fill`.
105    pub box_fill: Color,
106    /// `CheckGlyph.Foreground`.
107    pub glyph: Color,
108}
109
110/// The `{ThemeResource …}` values the `CombinedStates` storyboard for (`check`, `common`) names.
111pub(crate) fn check_box_brushes(
112    r: &ThemeResources,
113    check: CheckState,
114    common: CommonState,
115) -> CheckBoxBrushes {
116    match (check, common) {
117        // `UncheckedNormal`: the template's own values.
118        (CheckState::Unchecked, CommonState::Normal) => CheckBoxBrushes {
119            foreground: r.check_box_foreground_unchecked,
120            background: r.check_box_background_unchecked,
121            border: r.check_box_border_brush_unchecked,
122            box_stroke: r.check_box_check_background_stroke_unchecked,
123            box_fill: r.check_box_check_background_fill_unchecked,
124            glyph: r.check_box_check_glyph_foreground_unchecked,
125        },
126        (CheckState::Unchecked, CommonState::PointerOver) => CheckBoxBrushes {
127            foreground: r.check_box_foreground_unchecked_pointer_over,
128            background: r.check_box_background_unchecked_pointer_over,
129            border: r.check_box_border_brush_unchecked_pointer_over,
130            box_stroke: r.check_box_check_background_stroke_unchecked_pointer_over,
131            box_fill: r.check_box_check_background_fill_unchecked_pointer_over,
132            glyph: r.check_box_check_glyph_foreground_unchecked_pointer_over,
133        },
134        (CheckState::Unchecked, CommonState::Pressed) => CheckBoxBrushes {
135            foreground: r.check_box_foreground_unchecked_pressed,
136            background: r.check_box_background_unchecked_pressed,
137            border: r.check_box_border_brush_unchecked_pressed,
138            box_stroke: r.check_box_check_background_stroke_unchecked_pressed,
139            box_fill: r.check_box_check_background_fill_unchecked_pressed,
140            glyph: r.check_box_check_glyph_foreground_unchecked_pressed,
141        },
142        (CheckState::Unchecked, CommonState::Disabled) => CheckBoxBrushes {
143            foreground: r.check_box_foreground_unchecked_disabled,
144            background: r.check_box_background_unchecked_disabled,
145            border: r.check_box_border_brush_unchecked_disabled,
146            box_stroke: r.check_box_check_background_stroke_unchecked_disabled,
147            box_fill: r.check_box_check_background_fill_unchecked_disabled,
148            glyph: r.check_box_check_glyph_foreground_unchecked_disabled,
149        },
150        (CheckState::Checked, CommonState::Normal) => CheckBoxBrushes {
151            foreground: r.check_box_foreground_checked,
152            background: r.check_box_background_checked,
153            border: r.check_box_border_brush_checked,
154            box_stroke: r.check_box_check_background_stroke_checked,
155            box_fill: r.check_box_check_background_fill_checked,
156            glyph: r.check_box_check_glyph_foreground_checked,
157        },
158        (CheckState::Checked, CommonState::PointerOver) => CheckBoxBrushes {
159            foreground: r.check_box_foreground_checked_pointer_over,
160            background: r.check_box_background_checked_pointer_over,
161            border: r.check_box_border_brush_checked_pointer_over,
162            box_stroke: r.check_box_check_background_stroke_checked_pointer_over,
163            box_fill: r.check_box_check_background_fill_checked_pointer_over,
164            glyph: r.check_box_check_glyph_foreground_checked_pointer_over,
165        },
166        (CheckState::Checked, CommonState::Pressed) => CheckBoxBrushes {
167            foreground: r.check_box_foreground_checked_pressed,
168            background: r.check_box_background_checked_pressed,
169            border: r.check_box_border_brush_checked_pressed,
170            box_stroke: r.check_box_check_background_stroke_checked_pressed,
171            box_fill: r.check_box_check_background_fill_checked_pressed,
172            glyph: r.check_box_check_glyph_foreground_checked_pressed,
173        },
174        (CheckState::Checked, CommonState::Disabled) => CheckBoxBrushes {
175            foreground: r.check_box_foreground_checked_disabled,
176            background: r.check_box_background_checked_disabled,
177            border: r.check_box_border_brush_checked_disabled,
178            box_stroke: r.check_box_check_background_stroke_checked_disabled,
179            box_fill: r.check_box_check_background_fill_checked_disabled,
180            glyph: r.check_box_check_glyph_foreground_checked_disabled,
181        },
182        (CheckState::Indeterminate, CommonState::Normal) => CheckBoxBrushes {
183            foreground: r.check_box_foreground_indeterminate,
184            background: r.check_box_background_indeterminate,
185            border: r.check_box_border_brush_indeterminate,
186            box_stroke: r.check_box_check_background_stroke_indeterminate,
187            box_fill: r.check_box_check_background_fill_indeterminate,
188            glyph: r.check_box_check_glyph_foreground_indeterminate,
189        },
190        (CheckState::Indeterminate, CommonState::PointerOver) => CheckBoxBrushes {
191            foreground: r.check_box_foreground_indeterminate_pointer_over,
192            background: r.check_box_background_indeterminate_pointer_over,
193            border: r.check_box_border_brush_indeterminate_pointer_over,
194            box_stroke: r.check_box_check_background_stroke_indeterminate_pointer_over,
195            box_fill: r.check_box_check_background_fill_indeterminate_pointer_over,
196            glyph: r.check_box_check_glyph_foreground_indeterminate_pointer_over,
197        },
198        (CheckState::Indeterminate, CommonState::Pressed) => CheckBoxBrushes {
199            foreground: r.check_box_foreground_indeterminate_pressed,
200            background: r.check_box_background_indeterminate_pressed,
201            border: r.check_box_border_brush_indeterminate_pressed,
202            box_stroke: r.check_box_check_background_stroke_indeterminate_pressed,
203            box_fill: r.check_box_check_background_fill_indeterminate_pressed,
204            glyph: r.check_box_check_glyph_foreground_indeterminate_pressed,
205        },
206        (CheckState::Indeterminate, CommonState::Disabled) => CheckBoxBrushes {
207            foreground: r.check_box_foreground_indeterminate_disabled,
208            background: r.check_box_background_indeterminate_disabled,
209            border: r.check_box_border_brush_indeterminate_disabled,
210            box_stroke: r.check_box_check_background_stroke_indeterminate_disabled,
211            box_fill: r.check_box_check_background_fill_indeterminate_disabled,
212            glyph: r.check_box_check_glyph_foreground_indeterminate_disabled,
213        },
214    }
215}
216
217/// The handler for XAML `Checked`, `Unchecked` and `Indeterminate`, given the `IsChecked` the control wants.
218pub type CheckBoxCheckedHandler = Rc<dyn Fn(&mut App, Option<bool>)>;
219
220/// XAML `CheckBox`: `IsChecked` (`None` is indeterminate) with `IsThreeState`, `Content`, and the `Checked` / `Unchecked` / `Indeterminate` events as one handler.
221#[derive(Clone)]
222pub struct CheckBox {
223    pub is_checked: Option<bool>,
224    /// XAML `Checked`, `Unchecked` and `Indeterminate`, with the value the control wants.
225    pub checked: CheckBoxCheckedHandler,
226    pub content: Option<WidgetRef>,
227    pub is_three_state: bool,
228    pub is_enabled: bool,
229    pub key: Option<KeyRef>,
230}
231
232impl CheckBox {
233    pub fn new(
234        is_checked: Option<bool>,
235        checked: impl Fn(&mut App, Option<bool>) + 'static,
236    ) -> CheckBox {
237        CheckBox {
238            is_checked,
239            checked: Rc::new(checked),
240            content: None,
241            is_three_state: false,
242            is_enabled: true,
243            key: None,
244        }
245    }
246
247    /// XAML `Content`.
248    #[cfg_attr(debug_assertions, track_caller)]
249    pub fn content<K>(mut self, content: impl IntoWidget<K>) -> CheckBox {
250        self.content = Some(content.into_widget());
251        self
252    }
253
254    /// XAML `IsThreeState`.
255    pub fn is_three_state(mut self, three_state: bool) -> CheckBox {
256        self.is_three_state = three_state;
257        self
258    }
259
260    /// XAML `IsEnabled`.
261    pub fn is_enabled(mut self, enabled: bool) -> CheckBox {
262        self.is_enabled = enabled;
263        self
264    }
265
266    pub fn key(mut self, key: KeyRef) -> CheckBox {
267        self.key = Some(key);
268        self
269    }
270
271    fn set_is_checked(&self, value: Option<bool>) -> Listener {
272        let checked = self.checked.clone();
273        Listener::new(move |app| checked(app, value))
274    }
275}
276
277impl fmt::Debug for CheckBox {
278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279        f.debug_struct("CheckBox")
280            .field("is_checked", &self.is_checked)
281            .field("is_three_state", &self.is_three_state)
282            .field("is_enabled", &self.is_enabled)
283            .finish_non_exhaustive()
284    }
285}
286
287impl StatelessWidget for CheckBox {
288    fn key(&self) -> Option<&KeyRef> {
289        self.key.as_ref()
290    }
291
292    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
293        let widget = self.clone();
294        // `ToggleButton::OnClick` → `OnToggle`.
295        let click = self.set_is_checked(toggle_is_checked(self.is_checked, self.is_three_state));
296        // `CheckBox::Initialize`: `SetAcceptsReturn(false)`.
297        let states = CommonStates::new(click, move |app, context, states| {
298            template(app, context, &widget, states)
299        })
300        .is_enabled(self.is_enabled)
301        .accepts_return(false);
302        CheckBoxKeys {
303            check: self.set_is_checked(Some(true)),
304            uncheck: self.set_is_checked(Some(false)),
305            is_three_state: self.is_three_state,
306            is_enabled: self.is_enabled,
307            child: states.into_widget(),
308        }
309        .into_widget()
310    }
311}
312
313/// The `ControlTemplate` for one set of states.
314fn template(
315    app: &mut App,
316    context: BuildContext,
317    widget: &CheckBox,
318    states: ControlStates,
319) -> WidgetRef {
320    let resources = ThemeResources::of(app, context);
321    let check = CheckState::from_is_checked(widget.is_checked);
322    let brushes = check_box_brushes(&resources, check, states.common);
323    // `RootGrid`.
324    let root = Grid::new()
325        .column_definitions([
326            ColumnDefinition::new(GridLength::AUTO),
327            ColumnDefinition::new(GridLength::STAR),
328        ])
329        .background(Brush::Solid(brushes.background))
330        .border_brush(Brush::Solid(brushes.border))
331        .border_thickness(CHECK_BOX_ROOT_BORDER_THICKNESS)
332        .corner_radius(resources.control_corner_radius[0])
333        .children([
334            GridCell::new(check_area(&resources, &brushes, check)).into_widget(),
335            GridCell::new(content_presenter(&resources, widget, &brushes))
336                .column(1)
337                .into_widget(),
338        ]);
339    // The style's `MinWidth` and `MinHeight`.
340    let body = ConstrainedBox::new(
341        BoxConstraints::new()
342            .min_width(resources.check_box_min_width)
343            .min_height(resources.check_box_height),
344    )
345    .child(root);
346    FocusVisual::new(body, resources.theme)
347        .visible(states.focused)
348        .margin(resources.check_box_focus_visual_margin)
349        .corner_radius(resources.control_corner_radius[0])
350        .into_widget()
351}
352
353/// The 20 × 20 grid in column 0 (`VerticalAlignment="Center"`) with `NormalRectangle` and `CheckGlyph` in its one cell.
354fn check_area(r: &ThemeResources, brushes: &CheckBoxBrushes, check: CheckState) -> WidgetRef {
355    // `NormalRectangle`: a `Rectangle` fills under its stroke.
356    let rectangle = ControlBorder::new(
357        Brush::Solid(brushes.box_fill),
358        Brush::Solid(brushes.box_stroke),
359    )
360    .border_thickness(r.check_box_border_thickness)
361    .corner_radius(r.control_corner_radius[0])
362    .background_sizing(BackgroundSizing::OuterBorderEdge);
363    let glyph = CheckGlyph {
364        check,
365        color: brushes.glyph,
366    };
367    // `CheckGlyph.Margin`: `0,1,0,-1`, and `0` from the indeterminate states' setters.
368    let glyph = match check {
369        CheckState::Indeterminate => glyph.into_widget(),
370        _ => Transform::translate(CHECK_GLYPH_OFFSET)
371            .child(glyph)
372            .into_widget(),
373    };
374    let grid = Grid::new().children([
375        GridCell::new(rectangle).into_widget(),
376        GridCell::new(glyph).into_widget(),
377    ]);
378    Center::new()
379        .width_factor(1.0)
380        .height_factor(1.0)
381        .child(
382            SizedBox::new()
383                .width(r.check_box_size)
384                .height(r.check_box_size)
385                .child(grid),
386        )
387        .into_widget()
388}
389
390/// `ContentPresenter` in column 1: `Margin` is the style's `Padding`, aligned left and top.
391fn content_presenter(
392    r: &ThemeResources,
393    widget: &CheckBox,
394    brushes: &CheckBoxBrushes,
395) -> WidgetRef {
396    let [left, top, right, bottom] = r.check_box_padding;
397    let text = control_text_style(
398        r,
399        r.control_content_theme_font_size,
400        FontWeight::W400,
401        brushes.foreground,
402    );
403    let presenter = Align::new()
404        .alignment(AlignmentGeometry::TOP_LEFT)
405        .width_factor(1.0)
406        .height_factor(1.0);
407    let presenter = match &widget.content {
408        Some(content) => presenter.child(DefaultTextStyle::new(text, content.clone())),
409        None => presenter,
410    };
411    Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
412        .child(presenter)
413        .into_widget()
414}
415
416/// `CheckBox::OnKeyDownInternal`: `VirtualKey_Add` checks and `VirtualKey_Subtract` unchecks a two-state box.
417#[derive(Clone)]
418struct CheckBoxKeys {
419    check: Listener,
420    uncheck: Listener,
421    is_three_state: bool,
422    is_enabled: bool,
423    child: WidgetRef,
424}
425
426impl fmt::Debug for CheckBoxKeys {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        f.debug_struct("CheckBoxKeys")
429            .field("is_three_state", &self.is_three_state)
430            .field("is_enabled", &self.is_enabled)
431            .finish_non_exhaustive()
432    }
433}
434
435#[derive(Debug)]
436struct CheckIntent;
437impl Intent for CheckIntent {
438    fn as_any(&self) -> &dyn std::any::Any {
439        self
440    }
441}
442
443#[derive(Debug)]
444struct UncheckIntent;
445impl Intent for UncheckIntent {
446    fn as_any(&self) -> &dyn std::any::Any {
447        self
448    }
449}
450
451struct CheckBoxKeysState {
452    state: StateData<CheckBoxKeys>,
453    actions: HashMap<TypeId, ActionRef>,
454}
455
456impl StatefulWidget for CheckBoxKeys {
457    type State = CheckBoxKeysState;
458    fn create_state(&self) -> CheckBoxKeysState {
459        CheckBoxKeysState {
460            state: StateData::new(),
461            actions: HashMap::new(),
462        }
463    }
464}
465
466impl CheckBoxKeysState {
467    fn shortcuts(widget: &CheckBoxKeys) -> ShortcutMap {
468        let bind =
469            |key: LogicalKeyboardKey, intent: IntentRef| -> (ShortcutActivatorRef, IntentRef) {
470                (Rc::new(SingleActivator::new(key)), intent)
471            };
472        let mut map = Vec::new();
473        if !widget.is_three_state && widget.is_enabled {
474            map.push(bind(LogicalKeyboardKey::NUMPAD_ADD, Rc::new(CheckIntent)));
475            map.push(bind(
476                LogicalKeyboardKey::NUMPAD_SUBTRACT,
477                Rc::new(UncheckIntent),
478            ));
479        }
480        map
481    }
482}
483
484impl State for CheckBoxKeysState {
485    type Widget = CheckBoxKeys;
486    waft_widgets::state_accessors!();
487
488    fn init_state(self: Handle<Self>, app: &mut App) {
489        let check = CallbackAction::<CheckIntent>::new(
490            app,
491            Rc::new(move |app, _| {
492                self.widget(app).check.clone().call(app);
493                None
494            }),
495        );
496        let uncheck = CallbackAction::<UncheckIntent>::new(
497            app,
498            Rc::new(move |app, _| {
499                self.widget(app).uncheck.clone().call(app);
500                None
501            }),
502        );
503        let actions = &mut app.get_mut(self).actions;
504        actions.insert(TypeId::of::<CheckIntent>(), check.into_erased());
505        actions.insert(TypeId::of::<UncheckIntent>(), uncheck.into_erased());
506    }
507
508    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
509        let widget = self.widget(app).clone();
510        let actions = app.get(self).actions.clone();
511        Shortcuts::new(
512            Self::shortcuts(&widget),
513            Actions::new(actions, widget.child),
514        )
515        .into_widget()
516    }
517}
518
519/// `CheckGlyph`: the `AnimatedIcon` showing `AnimatedAcceptVisualSource` at the state's marker, playing the transition segment when the check state changes. `ItemContainer`'s selection check box shows the same glyph.
520#[derive(Clone, Copy, Debug, PartialEq)]
521pub(crate) struct CheckGlyph {
522    pub(crate) check: CheckState,
523    pub(crate) color: Color,
524}
525
526/// Which trim the playing segment animates.
527#[derive(Clone, Copy, Debug, PartialEq, Eq)]
528enum Segment {
529    /// At the marker: the state's still frame.
530    Still,
531    /// `NormalOffToNormalOn`: `TrimEnd` 0 → 1.
532    DrawOn,
533    /// `NormalOnToNormalOff`: `TrimStart` 0 → 1.
534    Erase,
535}
536
537pub(crate) struct CheckGlyphState {
538    state: StateData<CheckGlyph>,
539    single_ticker_provider: SingleTickerProviderStateMixinData,
540    controller: Option<Ref<AnimationController>>,
541    segment: Segment,
542}
543
544impl StatefulWidget for CheckGlyph {
545    type State = CheckGlyphState;
546    fn create_state(&self) -> CheckGlyphState {
547        CheckGlyphState {
548            state: StateData::new(),
549            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
550            controller: None,
551            segment: Segment::Still,
552        }
553    }
554}
555
556impl SingleTickerProviderStateMixin for CheckGlyphState {
557    fn single_ticker_provider_data(
558        self: Handle<Self>,
559        app: &App,
560    ) -> &SingleTickerProviderStateMixinData {
561        &app.get(self).single_ticker_provider
562    }
563    fn single_ticker_provider_data_mut(
564        self: Handle<Self>,
565        app: &mut App,
566    ) -> &mut SingleTickerProviderStateMixinData {
567        &mut app.get_mut(self).single_ticker_provider
568    }
569}
570
571impl TickerProviderObject for CheckGlyphState {
572    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
573        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
574    }
575}
576
577impl CheckGlyphState {
578    fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
579        app.get(self)
580            .controller
581            .handle()
582            .expect("created in init_state")
583    }
584
585    /// `AnimatedIcon::PlaySegment` for the transition `from` → `to`; a transition into or out of the indeterminate state has a single-position marker and jumps.
586    fn play(self: Handle<Self>, app: &mut App, from: CheckState, to: CheckState) {
587        let (segment, markers, easing) = match (from, to) {
588            (CheckState::Unchecked, CheckState::Checked) => {
589                (Segment::DrawOn, NORMAL_OFF_TO_NORMAL_ON, TRIM_END_EASING)
590            }
591            (CheckState::Checked, CheckState::Unchecked) => {
592                (Segment::Erase, NORMAL_ON_TO_NORMAL_OFF, TRIM_START_EASING)
593            }
594            _ => {
595                app.get_mut(self).segment = Segment::Still;
596                self.controller(app).set_value(app, 1.0);
597                return;
598            }
599        };
600        app.get_mut(self).segment = segment;
601        let controller = self.controller(app);
602        controller.set_value(app, 0.0);
603        let [x1, y1, x2, y2] = easing;
604        let curve: Rc<dyn Curve> = Rc::new(Cubic::new(x1, y1, x2, y2));
605        controller.animate_to(app, 1.0, Some(segment_duration(markers)), curve);
606    }
607
608    /// The glyph and its trim at this frame.
609    fn frame(self: Handle<Self>, app: &App) -> Option<(Glyph, (f32, f32))> {
610        let value = self.controller(app).value(app) as f32;
611        let check = self.widget(app).check;
612        match (app.get(self).segment, check) {
613            (Segment::DrawOn, _) => Some((Glyph::Check, (0.0, value))),
614            (Segment::Erase, _) => Some((Glyph::Check, (value, 1.0))),
615            (Segment::Still, CheckState::Checked) => Some((Glyph::Check, (0.0, 1.0))),
616            (Segment::Still, CheckState::Indeterminate) => Some((Glyph::Indeterminate, (0.0, 1.0))),
617            (Segment::Still, CheckState::Unchecked) => None,
618        }
619    }
620}
621
622impl State for CheckGlyphState {
623    type Widget = CheckGlyph;
624    waft_widgets::state_accessors!();
625
626    fn init_state(self: Handle<Self>, app: &mut App) {
627        let controller = AnimationController::new(
628            app,
629            Some(1.0),
630            Some(ACCEPT_VISUAL_DURATION),
631            None,
632            0.0,
633            1.0,
634            AnimationBehavior::Normal,
635            self,
636        );
637        controller.add_listener(app, Listener::new(move |app| self.set_state(app, |_| {})));
638        controller.add_status_listener(
639            app,
640            AnimationStatusListener::new(move |status, app| {
641                if status.is_completed() {
642                    self.set_state(app, |state| state.segment = Segment::Still);
643                }
644            }),
645        );
646        app.get_mut(self).controller = Some(controller);
647    }
648
649    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &CheckGlyph) {
650        let check = self.widget(app).check;
651        if check != old_widget.check {
652            self.play(app, old_widget.check, check);
653        }
654    }
655
656    fn activate(self: Handle<Self>, app: &mut App) {
657        SingleTickerProviderStateMixin::activate(self, app);
658    }
659
660    fn dispose(self: Handle<Self>, app: &mut App) {
661        self.controller(app).dispose(app);
662        SingleTickerProviderStateMixin::dispose(self, app);
663    }
664
665    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
666        let painter = AcceptVisualPainter {
667            frame: self.frame(app),
668            color: self.widget(app).color,
669        };
670        CustomPaint::new().painter(painter).into_widget()
671    }
672}
673
674/// The two geometries of `AnimatedAcceptVisualSource`.
675#[derive(Clone, Copy, Debug, PartialEq, Eq)]
676enum Glyph {
677    /// `Geometry_1`.
678    Check,
679    /// `Geometry_0`.
680    Indeterminate,
681}
682
683impl Glyph {
684    fn polyline(self) -> &'static [(f32, f32)] {
685        match self {
686            Glyph::Check => &CHECK_POLYLINE,
687            Glyph::Indeterminate => &INDETERMINATE_POLYLINE,
688        }
689    }
690
691    fn sprite_offset(self) -> (f32, f32) {
692        match self {
693            Glyph::Check => CHECK_SPRITE_OFFSET,
694            Glyph::Indeterminate => INDETERMINATE_SPRITE_OFFSET,
695        }
696    }
697}
698
699/// Paints one frame of `AnimatedAcceptVisualSource` scaled into its bounds as `AnimatedIcon::ArrangeOverride` does: uniformly, centred.
700#[derive(Clone, Debug, PartialEq)]
701struct AcceptVisualPainter {
702    frame: Option<(Glyph, (f32, f32))>,
703    color: Color,
704}
705
706impl CustomPainter for AcceptVisualPainter {
707    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
708        let Some((glyph, trim)) = self.frame else {
709            return;
710        };
711        let Some(path) = trimmed_polyline(glyph.polyline(), trim) else {
712            return;
713        };
714        let scale = (size.width().min(size.height()) / ACCEPT_VISUAL_SIZE) as f32;
715        let canvas_size = ACCEPT_VISUAL_SIZE as f32 * scale;
716        let (dx, dy) = glyph.sprite_offset();
717        canvas.save();
718        // `AnimatedIcon`: the root visual's offset and scale.
719        canvas.translate(
720            (size.width() as f32 - canvas_size) / 2.0,
721            (size.height() as f32 - canvas_size) / 2.0,
722        );
723        canvas.scale(scale, scale);
724        // `Null 230`: scale 1.05 about the canvas centre.
725        canvas.translate(
726            ACCEPT_VISUAL_SIZE as f32 / 2.0,
727            ACCEPT_VISUAL_SIZE as f32 / 2.0,
728        );
729        canvas.scale(LAYER_SCALE, LAYER_SCALE);
730        canvas.translate(
731            -ACCEPT_VISUAL_SIZE as f32 / 2.0,
732            -ACCEPT_VISUAL_SIZE as f32 / 2.0,
733        );
734        // The sprite shape's `TransformMatrix`.
735        canvas.translate(dx, dy);
736        canvas.scale(SPRITE_SCALE, SPRITE_SCALE);
737        let mut stroke = Stroke::new(ACCEPT_STROKE_THICKNESS);
738        stroke.cap = Cap::Round;
739        stroke.join = Join::Round;
740        let mut paint = Paint::from_color(self.color.into());
741        paint.style = PaintStyle::Stroke(stroke);
742        canvas.draw_path(&path, FillRule::NonZero, &paint);
743        canvas.restore();
744    }
745
746    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
747        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
748    }
749
750    fn as_any(&self) -> &dyn std::any::Any {
751        self
752    }
753}
754
755/// `CompositionPathGeometry.TrimStart` / `TrimEnd`: the part of `points` between the two fractions of its length; `None` when nothing is left.
756fn trimmed_polyline(
757    points: &[(f32, f32)],
758    (start, end): (f32, f32),
759) -> Option<std::sync::Arc<waft_embedder::valo::Path>> {
760    let lengths: Vec<f32> = points
761        .windows(2)
762        .map(|pair| {
763            let (ax, ay) = pair[0];
764            let (bx, by) = pair[1];
765            ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt()
766        })
767        .collect();
768    let total: f32 = lengths.iter().sum();
769    let (from, to) = (start.clamp(0.0, 1.0) * total, end.clamp(0.0, 1.0) * total);
770    if to <= from {
771        return None;
772    }
773    let point_at = |distance: f32| -> Point {
774        let mut travelled = 0.0;
775        let mut index = 0;
776        while index + 1 < lengths.len() && distance > travelled + lengths[index] {
777            travelled += lengths[index];
778            index += 1;
779        }
780        let t = ((distance - travelled) / lengths[index]).clamp(0.0, 1.0);
781        let (ax, ay) = points[index];
782        let (bx, by) = points[index + 1];
783        Point::new(ax + (bx - ax) * t, ay + (by - ay) * t)
784    };
785    let mut path = PathBuilder::new();
786    path.move_to(point_at(from));
787    let mut travelled = 0.0;
788    for (&(x, y), length) in points[1..].iter().zip(&lengths) {
789        travelled += *length;
790        if travelled > from && travelled < to {
791            path.line_to(Point::new(x, y));
792        }
793    }
794    path.line_to(point_at(to));
795    Some(path.build())
796}