Skip to main content

waft_material/
checkbox.rs

1//! Flutter counterpart: material_ui's `checkbox.dart`, with its part
2//! `generated/checkbox_defaults_m3.g.dart` in `crate::generated::checkbox_defaults_m3`.
3//!
4//! [`CheckboxState`] is a [`ToggleableStateMixin`], and its painter an arena
5//! [`ToggleablePainter`] the state keeps for its lifetime, as Dart's `_painter` field is.
6
7use std::fmt::{self, Debug};
8use std::time::Duration;
9
10use waft_animation::AnimationStatus;
11use waft_cupertino::CupertinoCheckbox;
12use waft_embedder::{
13    Canvas, Color, FillRule, Offset, Paint, PaintStyle, PathBuilder, Radius, Rect, Size, Stroke,
14    TargetPlatform, clamp_double,
15};
16use waft_foundation::{
17    App, ChangeNotifier, ChangeNotifierData, Handle, OptionRetained, Ref, ValueChanged,
18};
19use waft_painting::{
20    AnyBorderSide, BorderRadiusGeometry, BorderSide, EdgeInsets, OutlinedBorder, OutlinedBorderRef,
21    RoundedRectangleBorder, ShapeBorder,
22};
23use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
24use waft_services::MouseCursorRef;
25use waft_widgets::{
26    BuildContext, FocusNodeRef, IntoWidget, KeyRef, Semantics, State, StateData, StatefulWidget,
27    TickerProviderStateMixin, TickerProviderStateMixinData, ToggleablePainter,
28    ToggleablePainterData, ToggleablePainterRef, ToggleableStateMixin, ToggleableStateMixinData,
29    WidgetRef, WidgetState, WidgetStateBorderSide, WidgetStateMouseCursor, WidgetStateProperty,
30    WidgetStatePropertyRef, WidgetStates,
31};
32
33use crate::checkbox_theme::{CheckboxTheme, CheckboxThemeData, CheckboxThemeDataGetters};
34use crate::colors::Colors;
35use crate::constants::{
36    K_MIN_INTERACTIVE_DIMENSION, K_RADIAL_REACTION_ALPHA, K_RADIAL_REACTION_DURATION,
37    K_RADIAL_REACTION_RADIUS,
38};
39use crate::debug::debug_check_has_material;
40use crate::generated::checkbox_defaults_m3::CheckboxDefaultsM3;
41use crate::theme::Theme;
42use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
43use crate::theme_data_getters::DefaultsContext;
44
45/// Dart's `_CheckboxType`.
46#[derive(Clone, Copy, Debug)]
47enum CheckboxType {
48    Material,
49    Adaptive,
50}
51
52/// A Material Design checkbox.
53///
54/// The checkbox itself does not maintain any state. Instead, when the state of
55/// the checkbox changes, the widget calls the [`on_changed`](Self::on_changed) callback. Most
56/// widgets that use a checkbox will listen for the [`on_changed`](Self::on_changed) callback
57/// and rebuild the checkbox with a new [`value`](Self::value) to update the visual appearance
58/// of the checkbox.
59///
60/// The checkbox can optionally display three values - true, false, and null -
61/// if [`tristate`](Self::tristate) is true. When [`value`](Self::value) is null a dash is
62/// displayed. By default [`tristate`](Self::tristate) is false and the checkbox's
63/// [`value`](Self::value) must be true or false.
64///
65/// Requires one of its ancestors to be a `Material` widget.
66///
67/// See also:
68///
69///  * `CheckboxListTile`, which combines this widget with a `ListTile` so that
70///    you can give the checkbox a label.
71///  * `Switch`, a widget with semantics similar to [`Checkbox`].
72///  * `Radio`, for selecting among a set of explicit values.
73///  * `Slider`, for selecting a value in a range.
74///  * <https://material.io/design/components/selection-controls.html#checkboxes>
75///  * <https://material.io/design/components/lists.html#types>
76#[derive(Clone)]
77pub struct Checkbox {
78    pub key: Option<KeyRef>,
79    /// Whether this checkbox is checked.
80    ///
81    /// When [`tristate`](Self::tristate) is true, a value of null corresponds to the mixed
82    /// state. When [`tristate`](Self::tristate) is false, this value must not be null.
83    pub value: Option<bool>,
84    /// Called when the value of the checkbox should change.
85    ///
86    /// The checkbox passes the new value to the callback but does not actually
87    /// change state until the parent widget rebuilds the checkbox with the new
88    /// value.
89    ///
90    /// If this callback is null, the checkbox will be displayed as disabled
91    /// and will not respond to input gestures.
92    ///
93    /// When the checkbox is tapped, if [`tristate`](Self::tristate) is false (the default)
94    /// then the [`on_changed`](Self::on_changed) callback will be applied to `!value`. If
95    /// [`tristate`](Self::tristate) is true this callback cycle from false to true to null.
96    ///
97    /// The callback provided to [`on_changed`](Self::on_changed) should update the state of
98    /// the parent `StatefulWidget` using the `State::set_state` method, so that the parent
99    /// gets rebuilt.
100    pub on_changed: Option<ValueChanged<Option<bool>>>,
101    /// The cursor for a mouse pointer when it enters or is hovering over the
102    /// widget.
103    ///
104    /// If [`mouse_cursor`](Self::mouse_cursor) is a [`WidgetStateMouseCursor`],
105    /// [`WidgetStateProperty::resolve`] is used for the following [`WidgetState`]s:
106    ///
107    ///  * [`WidgetState::Selected`].
108    ///  * [`WidgetState::Focused`].
109    ///  * [`WidgetState::Disabled`].
110    ///
111    /// When [`value`](Self::value) is null and [`tristate`](Self::tristate) is true,
112    /// [`WidgetState::Selected`] is included as a state.
113    ///
114    /// If this property is null, the value of [`CheckboxThemeData::mouse_cursor`] is used.
115    /// If that is also null, [`WidgetStateMouseCursor::adaptive_clickable`] is used.
116    pub mouse_cursor: Option<MouseCursorRef>,
117    /// The color to use when this checkbox is checked.
118    ///
119    /// Defaults to `ColorScheme::secondary`.
120    ///
121    /// If [`fill_color`](Self::fill_color) returns a non-null color in the
122    /// [`WidgetState::Selected`] state, it will be used instead of this color.
123    pub active_color: Option<Color>,
124    /// The color that fills the checkbox, in all [`WidgetState`]s.
125    ///
126    /// Resolves in the following states:
127    ///  * [`WidgetState::Selected`].
128    ///  * [`WidgetState::Hovered`].
129    ///  * [`WidgetState::Focused`].
130    ///  * [`WidgetState::Disabled`].
131    ///
132    /// If null, then the value of [`active_color`](Self::active_color) is used in the selected
133    /// state. If that is also null, the value of [`CheckboxThemeData::fill_color`]
134    /// is used. If that is also null, then `ThemeData::disabled_color` is used in
135    /// the disabled state, `ColorScheme::secondary` is used in the
136    /// selected state, and `ThemeData::unselected_widget_color` is used in the
137    /// default state.
138    pub fill_color: Option<WidgetStatePropertyRef<Option<Color>>>,
139    /// The color to use for the check icon when this checkbox is checked.
140    ///
141    /// If null, then the value of [`CheckboxThemeData::check_color`] is used. If
142    /// that is also null, then Color(0xFFFFFFFF) is used.
143    pub check_color: Option<Color>,
144    /// If true the checkbox's [`value`](Self::value) can be true, false, or null.
145    ///
146    /// [`Checkbox`] displays a dash when its value is null.
147    ///
148    /// When a tri-state checkbox ([`tristate`](Self::tristate) is true) is tapped, its
149    /// [`on_changed`](Self::on_changed) callback will be applied to true if the current value
150    /// is false, to null if value is true, and to false if value is null (i.e. it cycles
151    /// through false => true => null => false when tapped).
152    ///
153    /// If tristate is false (the default), [`value`](Self::value) must not be null.
154    pub tristate: bool,
155    /// Configures the minimum size of the tap target.
156    ///
157    /// If null, then the value of [`CheckboxThemeData::material_tap_target_size`] is
158    /// used. If that is also null, then the value of
159    /// `ThemeData::material_tap_target_size` is used.
160    ///
161    /// See also:
162    ///
163    ///  * [`MaterialTapTargetSize`], for a description of how this affects tap targets.
164    pub material_tap_target_size: Option<MaterialTapTargetSize>,
165    /// Defines how compact the checkbox's layout will be.
166    ///
167    /// If null, then the value of [`CheckboxThemeData::visual_density`] is used. If
168    /// that is also null and if `ThemeData::use_material3` is false, then the
169    /// value of `ThemeData::visual_density` is used. Otherwise, the default value
170    /// is [`VisualDensity::STANDARD`].
171    ///
172    /// See also:
173    ///
174    ///  * `ThemeData::visual_density`, which specifies the [`visual_density`](Self::visual_density)
175    ///    for all widgets within a `Theme`.
176    pub visual_density: Option<VisualDensity>,
177    /// The color for the checkbox's `Material` when it has the input focus.
178    ///
179    /// If [`overlay_color`](Self::overlay_color) returns a non-null color in the
180    /// [`WidgetState::Focused`] state, it will be used instead.
181    ///
182    /// If null, then the value of [`CheckboxThemeData::overlay_color`] is used in the
183    /// focused state. If that is also null, then the value of
184    /// `ThemeData::focus_color` is used.
185    pub focus_color: Option<Color>,
186    /// The color for the checkbox's `Material` when a pointer is hovering over it.
187    ///
188    /// If [`overlay_color`](Self::overlay_color) returns a non-null color in the
189    /// [`WidgetState::Hovered`] state, it will be used instead.
190    ///
191    /// If null, then the value of [`CheckboxThemeData::overlay_color`] is used in the
192    /// hovered state. If that is also null, then the value of
193    /// `ThemeData::hover_color` is used.
194    pub hover_color: Option<Color>,
195    /// The color for the checkbox's `Material`.
196    ///
197    /// Resolves in the following states:
198    ///  * [`WidgetState::Pressed`].
199    ///  * [`WidgetState::Selected`].
200    ///  * [`WidgetState::Hovered`].
201    ///  * [`WidgetState::Focused`].
202    ///
203    /// If null, then the value of [`active_color`](Self::active_color) with alpha
204    /// [`K_RADIAL_REACTION_ALPHA`], [`focus_color`](Self::focus_color) and
205    /// [`hover_color`](Self::hover_color) is used in the pressed, focused and hovered state.
206    /// If that is also null, the value of [`CheckboxThemeData::overlay_color`] is used. If
207    /// that is also null, then the value of `ColorScheme::secondary` with alpha
208    /// [`K_RADIAL_REACTION_ALPHA`], `ThemeData::focus_color` and `ThemeData::hover_color`
209    /// is used in the pressed, focused and hovered state.
210    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
211    /// The splash radius of the circular `Material` ink response.
212    ///
213    /// If null, then the value of [`CheckboxThemeData::splash_radius`] is used. If
214    /// that is also null, then [`K_RADIAL_REACTION_RADIUS`] is used.
215    pub splash_radius: Option<f64>,
216    /// An optional focus node to use as the focus node for this widget.
217    pub focus_node: Option<FocusNodeRef>,
218    /// True if this widget will be selected as the initial focus when no other node in its
219    /// scope is currently focused.
220    pub autofocus: bool,
221    /// The shape of the checkbox's `Material`.
222    ///
223    /// If this property is null then the ambient [`CheckboxThemeData::shape`]
224    /// is used. If that's null then the shape will be a [`RoundedRectangleBorder`]
225    /// with a circular corner radius of 1.0 in Material 2, and 2.0 in Material 3.
226    pub shape: Option<OutlinedBorderRef>,
227    /// The color and width of the checkbox's border.
228    ///
229    /// This property can be a [`WidgetStateBorderSide`] that can
230    /// specify different border color and widths depending on the
231    /// checkbox's state.
232    ///
233    /// Resolves in the following states:
234    ///  * [`WidgetState::Pressed`].
235    ///  * [`WidgetState::Selected`].
236    ///  * [`WidgetState::Hovered`].
237    ///  * [`WidgetState::Focused`].
238    ///  * [`WidgetState::Disabled`].
239    ///  * [`WidgetState::Error`].
240    ///
241    /// If this property is not a [`WidgetStateBorderSide`] and it is
242    /// non-null, then it is only rendered when the checkbox's value is
243    /// false. The difference in interpretation is for backwards
244    /// compatibility.
245    ///
246    /// If this property is null, then the ambient [`CheckboxThemeData::side`] is
247    /// used. If that is also null, then the side will be width 2.
248    pub side: Option<AnyBorderSide>,
249    /// True if this checkbox wants to show an error state.
250    ///
251    /// The checkbox will have different default container color and check color when
252    /// this is true. This is only used when `ThemeData::use_material3` is set to true.
253    ///
254    /// Defaults to false.
255    pub is_error: bool,
256    /// The semantic label for the checkbox that will be announced by screen readers.
257    ///
258    /// This is announced by assistive technologies (e.g TalkBack/VoiceOver).
259    ///
260    /// This label does not show in the UI.
261    pub semantic_label: Option<String>,
262    /// The insets applied around the check mark when the checkbox is checked or
263    /// in its indeterminate (tristate) state.
264    ///
265    /// This insets the check mark inward; the size of the checkbox box itself
266    /// is not affected. The check mark and its stroke shrink to fit the
267    /// remaining space, so the mark stays proportional. Its size is the smaller
268    /// of the remaining width and height, and it is centered in the remaining
269    /// space, so an inset on one axis also shrinks it on the other. For example,
270    /// `EdgeInsets::only(9.0, 0.0, 0.0, 0.0)` draws a half-size mark centered in the right
271    /// half of the box.
272    ///
273    /// On iOS and macOS, when using [`Checkbox::adaptive`], this property has no
274    /// effect, because the checkbox delegates to [`CupertinoCheckbox`], which does
275    /// not support insets.
276    ///
277    /// Must be non-negative. If the horizontal or vertical insets are
278    /// greater than or equal to the checkbox size, the check mark or indeterminate
279    /// dash is not painted.
280    ///
281    /// If null, [`CheckboxThemeData::mark_insets`] is used. If that is also null,
282    /// it defaults to [`EdgeInsets::ZERO`] and the check mark renders at full size.
283    pub mark_insets: Option<EdgeInsets>,
284    checkbox_type: CheckboxType,
285}
286
287impl Checkbox {
288    /// The width of a checkbox widget.
289    pub const WIDTH: f64 = 18.0;
290
291    /// Creates a Material Design checkbox.
292    ///
293    /// The checkbox itself does not maintain any state. Instead, when the state of
294    /// the checkbox changes, the widget calls the [`on_changed`](Self::on_changed) callback.
295    /// Most widgets that use a checkbox will listen for the [`on_changed`](Self::on_changed)
296    /// callback and rebuild the checkbox with a new [`value`](Self::value) to update the
297    /// visual appearance of the checkbox.
298    ///
299    /// The following arguments are required:
300    ///
301    /// * `value`, which determines whether the checkbox is checked. The `value`
302    ///   can only be null if [`tristate`](Self::tristate) is true.
303    /// * `on_changed`, which is called when the value of the checkbox should
304    ///   change. It can be set to null to disable the checkbox.
305    pub fn new(value: Option<bool>, on_changed: Option<ValueChanged<Option<bool>>>) -> Checkbox {
306        Checkbox::with_type(value, on_changed, CheckboxType::Material)
307    }
308
309    /// Creates an adaptive [`Checkbox`] based on whether the target platform is iOS
310    /// or macOS, following Material design's
311    /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
312    ///
313    /// On iOS and macOS, this constructor creates a [`CupertinoCheckbox`], which has
314    /// matching functionality and presentation as Material checkboxes, and are the
315    /// graphics expected on iOS. On other platforms, this creates a Material
316    /// design [`Checkbox`].
317    ///
318    /// If a [`CupertinoCheckbox`] is created, the following parameters are ignored:
319    /// [`fill_color`](Self::fill_color), [`hover_color`](Self::hover_color),
320    /// [`overlay_color`](Self::overlay_color), [`splash_radius`](Self::splash_radius),
321    /// [`material_tap_target_size`](Self::material_tap_target_size),
322    /// [`visual_density`](Self::visual_density), [`is_error`](Self::is_error),
323    /// [`mark_insets`](Self::mark_insets). However, [`shape`](Self::shape) and
324    /// [`side`](Self::side) will still affect the [`CupertinoCheckbox`] and should be
325    /// handled if native fidelity is important.
326    ///
327    /// The target platform is based on the current `Theme`: `ThemeData::platform`.
328    pub fn adaptive(
329        value: Option<bool>,
330        on_changed: Option<ValueChanged<Option<bool>>>,
331    ) -> Checkbox {
332        Checkbox::with_type(value, on_changed, CheckboxType::Adaptive)
333    }
334
335    fn with_type(
336        value: Option<bool>,
337        on_changed: Option<ValueChanged<Option<bool>>>,
338        checkbox_type: CheckboxType,
339    ) -> Checkbox {
340        Checkbox {
341            key: None,
342            value,
343            on_changed,
344            mouse_cursor: None,
345            active_color: None,
346            fill_color: None,
347            check_color: None,
348            tristate: false,
349            material_tap_target_size: None,
350            visual_density: None,
351            focus_color: None,
352            hover_color: None,
353            overlay_color: None,
354            splash_radius: None,
355            focus_node: None,
356            autofocus: false,
357            shape: None,
358            side: None,
359            is_error: false,
360            semantic_label: None,
361            mark_insets: None,
362            checkbox_type,
363        }
364    }
365
366    /// Dart `Checkbox(key:)`.
367    pub fn key(mut self, key: KeyRef) -> Checkbox {
368        self.key = Some(key);
369        self
370    }
371
372    /// Dart `Checkbox(tristate:)`.
373    pub fn tristate(mut self, tristate: bool) -> Checkbox {
374        self.tristate = tristate;
375        self
376    }
377
378    /// Dart `Checkbox(mouseCursor:)`.
379    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> Checkbox {
380        self.mouse_cursor = Some(mouse_cursor);
381        self
382    }
383
384    /// Dart `Checkbox(activeColor:)`.
385    pub fn active_color(mut self, active_color: Color) -> Checkbox {
386        self.active_color = Some(active_color);
387        self
388    }
389
390    /// Dart `Checkbox(fillColor:)`.
391    pub fn fill_color(mut self, fill_color: WidgetStatePropertyRef<Option<Color>>) -> Checkbox {
392        self.fill_color = Some(fill_color);
393        self
394    }
395
396    /// Dart `Checkbox(checkColor:)`.
397    pub fn check_color(mut self, check_color: Color) -> Checkbox {
398        self.check_color = Some(check_color);
399        self
400    }
401
402    /// Dart `Checkbox(focusColor:)`.
403    pub fn focus_color(mut self, focus_color: Color) -> Checkbox {
404        self.focus_color = Some(focus_color);
405        self
406    }
407
408    /// Dart `Checkbox(hoverColor:)`.
409    pub fn hover_color(mut self, hover_color: Color) -> Checkbox {
410        self.hover_color = Some(hover_color);
411        self
412    }
413
414    /// Dart `Checkbox(overlayColor:)`.
415    pub fn overlay_color(
416        mut self,
417        overlay_color: WidgetStatePropertyRef<Option<Color>>,
418    ) -> Checkbox {
419        self.overlay_color = Some(overlay_color);
420        self
421    }
422
423    /// Dart `Checkbox(splashRadius:)`.
424    pub fn splash_radius(mut self, splash_radius: f64) -> Checkbox {
425        self.splash_radius = Some(splash_radius);
426        self
427    }
428
429    /// Dart `Checkbox(materialTapTargetSize:)`.
430    pub fn material_tap_target_size(
431        mut self,
432        material_tap_target_size: MaterialTapTargetSize,
433    ) -> Checkbox {
434        self.material_tap_target_size = Some(material_tap_target_size);
435        self
436    }
437
438    /// Dart `Checkbox(visualDensity:)`.
439    pub fn visual_density(mut self, visual_density: VisualDensity) -> Checkbox {
440        self.visual_density = Some(visual_density);
441        self
442    }
443
444    /// Dart `Checkbox(focusNode:)`.
445    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Checkbox {
446        self.focus_node = Some(focus_node);
447        self
448    }
449
450    /// Dart `Checkbox(autofocus:)`.
451    pub fn autofocus(mut self, autofocus: bool) -> Checkbox {
452        self.autofocus = autofocus;
453        self
454    }
455
456    /// Dart `Checkbox(shape:)`.
457    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> Checkbox {
458        self.shape = Some(shape.into());
459        self
460    }
461
462    /// Dart `Checkbox(side:)`.
463    pub fn side(mut self, side: impl Into<AnyBorderSide>) -> Checkbox {
464        self.side = Some(side.into());
465        self
466    }
467
468    /// Dart `Checkbox(isError:)`.
469    pub fn is_error(mut self, is_error: bool) -> Checkbox {
470        self.is_error = is_error;
471        self
472    }
473
474    /// Dart `Checkbox(semanticLabel:)`.
475    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> Checkbox {
476        self.semantic_label = Some(semantic_label.into());
477        self
478    }
479
480    /// Dart `Checkbox(markInsets:)`.
481    pub fn mark_insets(mut self, mark_insets: EdgeInsets) -> Checkbox {
482        self.mark_insets = Some(mark_insets);
483        self
484    }
485}
486
487impl Debug for Checkbox {
488    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489        f.debug_struct("Checkbox")
490            .field("value", &self.value)
491            .field("tristate", &self.tristate)
492            .field(
493                "on_changed",
494                &if self.on_changed.is_some() {
495                    "enabled"
496                } else {
497                    "disabled"
498                },
499            )
500            .finish_non_exhaustive()
501    }
502}
503
504impl StatefulWidget for Checkbox {
505    type State = CheckboxState;
506
507    fn key(&self) -> Option<&KeyRef> {
508        self.key.as_ref()
509    }
510
511    fn debug_check_constructor(&self) {
512        debug_assert!(self.tristate || self.value.is_some());
513    }
514
515    fn create_state(&self) -> CheckboxState {
516        CheckboxState {
517            state: StateData::new(),
518            ticker_provider: TickerProviderStateMixinData::new(),
519            toggleable: ToggleableStateMixinData::new(),
520            painter: None,
521            previous_value: None,
522        }
523    }
524}
525
526/// Dart's `_CheckboxState`.
527pub struct CheckboxState {
528    state: StateData<Checkbox>,
529    ticker_provider: TickerProviderStateMixinData,
530    toggleable: ToggleableStateMixinData,
531    /// Dart's `final _CheckboxPainter _painter = _CheckboxPainter()`, created in `init_state`
532    /// because a painter is an arena object and a state is created without the `App`.
533    painter: Option<Ref<CheckboxPainter>>,
534    previous_value: Option<bool>,
535}
536
537impl CheckboxState {
538    fn painter(self: Handle<Self>, app: &App) -> Handle<CheckboxPainter> {
539        app.get(self)
540            .painter
541            .handle()
542            .expect("created in init_state")
543    }
544
545    /// Dart's `_widgetFillColor`.
546    fn widget_fill_color(self: Handle<Self>, app: &App) -> WidgetStatePropertyRef<Option<Color>> {
547        let active_color = self.widget(app).active_color;
548        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
549            if states.contains(&WidgetState::Disabled) {
550                return None;
551            }
552            if states.contains(&WidgetState::Selected) {
553                return active_color;
554            }
555            None
556        })
557    }
558
559    /// Dart's `_resolveSide`: `resolve_as` answers Dart's `is WidgetStateBorderSide` itself.
560    fn resolve_side(side: &Option<AnyBorderSide>, states: &WidgetStates) -> Option<BorderSide> {
561        if side
562            .as_ref()
563            .is_some_and(|side| side.extension::<WidgetStateBorderSide>().is_some())
564        {
565            return <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(side, states)
566                .map(|side| *side);
567        }
568        if !states.contains(&WidgetState::Selected) {
569            return side.as_ref().map(|side| **side);
570        }
571        None
572    }
573
574    /// Dart's `effectiveMouseCursor`, built from the widget's and the theme's cursors.
575    fn effective_mouse_cursor(
576        mouse_cursor: Option<MouseCursorRef>,
577        theme_mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
578    ) -> WidgetStatePropertyRef<MouseCursorRef> {
579        <dyn WidgetStateProperty<MouseCursorRef>>::resolve_with(move |states: &WidgetStates| {
580            <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&mouse_cursor, states)
581                .or_else(|| {
582                    theme_mouse_cursor
583                        .as_ref()
584                        .and_then(|mouse_cursor| mouse_cursor.resolve(states))
585                })
586                .unwrap_or_else(|| WidgetStateMouseCursor::adaptive_clickable().resolve(states))
587        })
588    }
589
590    /// The [`CupertinoCheckbox`] Dart's `Checkbox.adaptive` builds on iOS and macOS.
591    fn build_cupertino_checkbox(self: Handle<Self>, app: &App) -> WidgetRef {
592        let widget = self.widget(app);
593        let mut checkbox = CupertinoCheckbox::new(
594            ToggleableStateMixin::value(self, app),
595            ToggleableStateMixin::on_changed(self, app),
596        )
597        .tristate(ToggleableStateMixin::tristate(self, app))
598        .autofocus(widget.autofocus);
599        checkbox.mouse_cursor = widget.mouse_cursor.clone();
600        checkbox.active_color = widget.active_color;
601        checkbox.check_color = widget.check_color;
602        checkbox.focus_color = widget.focus_color;
603        checkbox.focus_node = widget.focus_node.clone();
604        checkbox.side = widget.side.clone();
605        checkbox.shape = widget.shape.clone();
606        checkbox.semantic_label = widget.semantic_label.clone();
607        checkbox.into_widget()
608    }
609}
610
611impl TickerProviderStateMixin for CheckboxState {
612    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
613        &app.get(self).ticker_provider
614    }
615
616    fn ticker_provider_data_mut(
617        self: Handle<Self>,
618        app: &mut App,
619    ) -> &mut TickerProviderStateMixinData {
620        &mut app.get_mut(self).ticker_provider
621    }
622}
623
624/// Dart's `with TickerProviderStateMixin`.
625impl TickerProviderObject for CheckboxState {
626    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
627        TickerProviderStateMixin::create_ticker(self, app, on_tick)
628    }
629}
630
631impl ToggleableStateMixin for CheckboxState {
632    fn toggleable_data(self: Handle<Self>, app: &App) -> &ToggleableStateMixinData {
633        &app.get(self).toggleable
634    }
635
636    fn toggleable_data_mut(self: Handle<Self>, app: &mut App) -> &mut ToggleableStateMixinData {
637        &mut app.get_mut(self).toggleable
638    }
639
640    fn on_changed(self: Handle<Self>, app: &App) -> Option<ValueChanged<Option<bool>>> {
641        self.widget(app).on_changed.clone()
642    }
643
644    fn tristate(self: Handle<Self>, app: &App) -> bool {
645        self.widget(app).tristate
646    }
647
648    fn value(self: Handle<Self>, app: &App) -> Option<bool> {
649        self.widget(app).value
650    }
651
652    fn reaction_animation_duration(self: Handle<Self>, _app: &App) -> Option<Duration> {
653        Some(K_RADIAL_REACTION_DURATION)
654    }
655}
656
657impl State for CheckboxState {
658    type Widget = Checkbox;
659    waft_widgets::state_accessors!();
660
661    fn init_state(self: Handle<Self>, app: &mut App) {
662        let painter = CheckboxPainter::new(app);
663        app.get_mut(self).painter = Some(painter);
664        ToggleableStateMixin::init_state(self, app);
665        app.get_mut(self).previous_value = self.widget(app).value;
666    }
667
668    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Checkbox) {
669        if old_widget.value != self.widget(app).value {
670            app.get_mut(self).previous_value = old_widget.value;
671            self.animate_to_value(app);
672        }
673    }
674
675    fn activate(self: Handle<Self>, app: &mut App) {
676        TickerProviderStateMixin::activate(self, app);
677    }
678
679    fn dispose(self: Handle<Self>, app: &mut App) {
680        let painter = self.painter(app);
681        ToggleablePainter::dispose(painter, app);
682        ToggleableStateMixin::dispose(self, app);
683        TickerProviderStateMixin::dispose(self, app);
684    }
685
686    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
687        let widget = self.widget(app).clone();
688
689        match widget.checkbox_type {
690            CheckboxType::Material => {}
691            CheckboxType::Adaptive => {
692                let theme = Theme::of(app, context);
693                match theme.platform {
694                    TargetPlatform::Android
695                    | TargetPlatform::Fuchsia
696                    | TargetPlatform::Linux
697                    | TargetPlatform::Windows => {}
698                    TargetPlatform::IOS | TargetPlatform::MacOS => {
699                        return self.build_cupertino_checkbox(app);
700                    }
701                }
702            }
703        }
704
705        debug_assert!(debug_check_has_material(app, context));
706        let checkbox_theme = CheckboxTheme::of(app, context);
707        let defaults: Box<dyn CheckboxThemeDataGetters> = if Theme::of(app, context).use_material3 {
708            Box::new(CheckboxDefaultsM3::new(app, context))
709        } else {
710            Box::new(CheckboxDefaultsM2::new(app, context))
711        };
712        let effective_material_tap_target_size = widget
713            .material_tap_target_size
714            .or(checkbox_theme.material_tap_target_size)
715            .or_else(|| defaults.material_tap_target_size(app))
716            .expect("the defaults give a tap target size");
717        let effective_visual_density = widget
718            .visual_density
719            .or(checkbox_theme.visual_density)
720            .or_else(|| defaults.visual_density(app))
721            .expect("the defaults give a visual density");
722        let mut size = match effective_material_tap_target_size {
723            MaterialTapTargetSize::Padded => {
724                Size::new(K_MIN_INTERACTIVE_DIMENSION, K_MIN_INTERACTIVE_DIMENSION)
725            }
726            MaterialTapTargetSize::ShrinkWrap => Size::new(
727                K_MIN_INTERACTIVE_DIMENSION - 8.0,
728                K_MIN_INTERACTIVE_DIMENSION - 8.0,
729            ),
730        };
731        size = size + effective_visual_density.base_size_adjustment();
732
733        let effective_mouse_cursor = Self::effective_mouse_cursor(
734            widget.mouse_cursor.clone(),
735            checkbox_theme.mouse_cursor.clone(),
736        );
737
738        // Colors need to be resolved in selected and non selected states separately
739        let mut active_states = self.states(app);
740        active_states.insert(WidgetState::Selected);
741        let mut inactive_states = self.states(app);
742        inactive_states.remove(&WidgetState::Selected);
743        if widget.is_error {
744            active_states.insert(WidgetState::Error);
745            inactive_states.insert(WidgetState::Error);
746        }
747        let widget_fill_color = self.widget_fill_color(app);
748        let resolve_fill_color = |states: &WidgetStates| {
749            resolve(&widget.fill_color, states)
750                .or_else(|| widget_fill_color.resolve(states))
751                .or_else(|| resolve(&checkbox_theme.fill_color, states))
752        };
753        let active_color = resolve_fill_color(&active_states);
754        let effective_active_color = active_color.unwrap_or_else(|| {
755            resolve(&defaults.fill_color(app), &active_states).expect("default")
756        });
757        let inactive_color = resolve_fill_color(&inactive_states);
758        let effective_inactive_color = inactive_color.unwrap_or_else(|| {
759            resolve(&defaults.fill_color(app), &inactive_states).expect("default")
760        });
761
762        let effective_side = |app: &mut App, states: &WidgetStates| {
763            Self::resolve_side(&widget.side, states)
764                .or_else(|| Self::resolve_side(&checkbox_theme.side, states))
765                .or_else(|| Self::resolve_side(&defaults.side(app), states))
766                .expect("the defaults give a side")
767        };
768        let active_side = effective_side(app, &active_states);
769        let inactive_side = effective_side(app, &inactive_states);
770
771        let mut focused_states = self.states(app);
772        focused_states.insert(WidgetState::Focused);
773        if widget.is_error {
774            focused_states.insert(WidgetState::Error);
775        }
776        let mut effective_focus_overlay_color = resolve(&widget.overlay_color, &focused_states)
777            .or(widget.focus_color)
778            .or_else(|| resolve(&checkbox_theme.overlay_color, &focused_states))
779            .unwrap_or_else(|| {
780                resolve(&defaults.overlay_color(app), &focused_states).expect("default")
781            });
782
783        let mut hovered_states = self.states(app);
784        hovered_states.insert(WidgetState::Hovered);
785        if widget.is_error {
786            hovered_states.insert(WidgetState::Error);
787        }
788        let mut effective_hover_overlay_color = resolve(&widget.overlay_color, &hovered_states)
789            .or(widget.hover_color)
790            .or_else(|| resolve(&checkbox_theme.overlay_color, &hovered_states))
791            .unwrap_or_else(|| {
792                resolve(&defaults.overlay_color(app), &hovered_states).expect("default")
793            });
794
795        let resolve_pressed_overlay_color =
796            |app: &mut App, states: &WidgetStates, fill_color: Option<Color>| {
797                resolve(&widget.overlay_color, states)
798                    .or_else(|| resolve(&checkbox_theme.overlay_color, states))
799                    .or_else(|| fill_color.map(|color| color.with_alpha(K_RADIAL_REACTION_ALPHA)))
800                    .unwrap_or_else(|| {
801                        resolve(&defaults.overlay_color(app), states).expect("default")
802                    })
803            };
804        let mut active_pressed_states = active_states;
805        active_pressed_states.insert(WidgetState::Pressed);
806        let effective_active_pressed_overlay_color =
807            resolve_pressed_overlay_color(app, &active_pressed_states, active_color);
808
809        let mut inactive_pressed_states = inactive_states;
810        inactive_pressed_states.insert(WidgetState::Pressed);
811        let effective_inactive_pressed_overlay_color =
812            resolve_pressed_overlay_color(app, &inactive_pressed_states, inactive_color);
813
814        if self.down_position(app).is_some() {
815            let pressed_overlay_color = if self.states(app).contains(&WidgetState::Selected) {
816                effective_active_pressed_overlay_color
817            } else {
818                effective_inactive_pressed_overlay_color
819            };
820            effective_hover_overlay_color = pressed_overlay_color;
821            effective_focus_overlay_color = pressed_overlay_color;
822        }
823
824        let mut check_states = self.states(app);
825        if widget.is_error {
826            check_states.insert(WidgetState::Error);
827        }
828        let effective_check_color = widget
829            .check_color
830            .or_else(|| resolve(&checkbox_theme.check_color, &check_states))
831            .unwrap_or_else(|| {
832                resolve(&defaults.check_color(app), &check_states).expect("default")
833            });
834
835        let effective_splash_radius = widget
836            .splash_radius
837            .or(checkbox_theme.splash_radius)
838            .or_else(|| defaults.splash_radius(app))
839            .expect("the defaults give a splash radius");
840
841        let mark_insets = widget
842            .mark_insets
843            .or(checkbox_theme.mark_insets)
844            .unwrap_or(EdgeInsets::ZERO);
845
846        let shape = widget
847            .shape
848            .clone()
849            .or_else(|| checkbox_theme.shape.clone())
850            .or_else(|| defaults.shape(app))
851            .expect("the defaults give a shape");
852
853        let states = self.states(app);
854        let painter = app
855            .get(self)
856            .painter
857            .clone()
858            .expect("created in init_state");
859        painter.set_position(app, self.position(app).erase());
860        painter.set_reaction(app, self.reaction(app).erase());
861        painter.set_reaction_focus_fade(app, self.reaction_focus_fade(app).erase());
862        painter.set_reaction_hover_fade(app, self.reaction_hover_fade(app).erase());
863        painter.set_inactive_reaction_color(app, effective_inactive_pressed_overlay_color);
864        painter.set_reaction_color(app, effective_active_pressed_overlay_color);
865        painter.set_hover_color(app, effective_hover_overlay_color);
866        painter.set_focus_color(app, effective_focus_overlay_color);
867        painter.set_splash_radius(app, effective_splash_radius);
868        painter.set_down_position(app, self.down_position(app));
869        painter.set_is_focused(app, Some(states.contains(&WidgetState::Focused)));
870        painter.set_is_hovered(app, Some(states.contains(&WidgetState::Hovered)));
871        painter.set_active_color(app, effective_active_color);
872        painter.set_inactive_color(app, effective_inactive_color);
873        painter.set_check_color(app, effective_check_color);
874        painter.set_value(app, ToggleableStateMixin::value(self, app));
875        painter.set_previous_value(app, app.get(self).previous_value);
876        painter.set_shape(app, shape);
877        painter.set_active_side(app, active_side);
878        painter.set_mark_insets(app, mark_insets);
879        painter.set_inactive_side(app, inactive_side);
880
881        let mut semantics = Semantics::new().checked(widget.value.unwrap_or(false));
882        if let Some(semantic_label) = &widget.semantic_label {
883            semantics = semantics.label(semantic_label.clone());
884        }
885        if widget.tristate {
886            semantics = semantics.mixed(widget.value.is_none());
887        }
888        semantics
889            .child(self.build_toggleable(
890                app,
891                widget.focus_node,
892                None,
893                widget.autofocus,
894                Some(effective_mouse_cursor),
895                size,
896                ToggleablePainterRef::new(painter),
897            ))
898            .into_widget()
899    }
900}
901
902/// Dart's `property?.resolve(states)` on a nullable `WidgetStateProperty<Color?>`.
903fn resolve(
904    property: &Option<WidgetStatePropertyRef<Option<Color>>>,
905    states: &WidgetStates,
906) -> Option<Color> {
907    property
908        .as_ref()
909        .and_then(|property| property.resolve(states))
910}
911
912const K_EDGE_SIZE: f64 = Checkbox::WIDTH;
913const K_STROKE_WIDTH: f64 = 2.0;
914
915/// Dart's `_CheckboxPainter`.
916struct CheckboxPainter {
917    change_notifier: ChangeNotifierData,
918    toggleable_painter: ToggleablePainterData,
919    check_color: Option<Color>,
920    value: Option<bool>,
921    previous_value: Option<bool>,
922    shape: Option<OutlinedBorderRef>,
923    mark_insets: EdgeInsets,
924    active_side: Option<BorderSide>,
925    inactive_side: Option<BorderSide>,
926}
927
928impl CheckboxPainter {
929    fn new(app: &mut App) -> Ref<CheckboxPainter> {
930        app.create(CheckboxPainter {
931            change_notifier: ChangeNotifierData::new(),
932            toggleable_painter: ToggleablePainterData::new(),
933            check_color: None,
934            value: None,
935            previous_value: None,
936            shape: None,
937            mark_insets: EdgeInsets::ZERO,
938            active_side: None,
939            inactive_side: None,
940        })
941    }
942
943    fn check_color(self: Handle<Self>, app: &App) -> Color {
944        app.get(self).check_color.expect("set before painting")
945    }
946
947    fn set_check_color(self: Handle<Self>, app: &mut App, value: Color) {
948        if app.get(self).check_color == Some(value) {
949            return;
950        }
951        app.get_mut(self).check_color = Some(value);
952        self.notify_listeners(app);
953    }
954
955    fn value(self: Handle<Self>, app: &App) -> Option<bool> {
956        app.get(self).value
957    }
958
959    fn set_value(self: Handle<Self>, app: &mut App, value: Option<bool>) {
960        if app.get(self).value == value {
961            return;
962        }
963        app.get_mut(self).value = value;
964        self.notify_listeners(app);
965    }
966
967    fn previous_value(self: Handle<Self>, app: &App) -> Option<bool> {
968        app.get(self).previous_value
969    }
970
971    fn set_previous_value(self: Handle<Self>, app: &mut App, value: Option<bool>) {
972        if app.get(self).previous_value == value {
973            return;
974        }
975        app.get_mut(self).previous_value = value;
976        self.notify_listeners(app);
977    }
978
979    fn shape(self: Handle<Self>, app: &App) -> &dyn OutlinedBorder {
980        app.get(self).shape.as_deref().expect("set before painting")
981    }
982
983    fn set_shape(self: Handle<Self>, app: &mut App, value: OutlinedBorderRef) {
984        if let Some(shape) = &app.get(self).shape {
985            let (old, new): (&dyn ShapeBorder, &dyn ShapeBorder) = (&**shape, &*value);
986            if old == new {
987                return;
988            }
989        }
990        app.get_mut(self).shape = Some(value);
991        self.notify_listeners(app);
992    }
993
994    fn mark_insets(self: Handle<Self>, app: &App) -> EdgeInsets {
995        app.get(self).mark_insets
996    }
997
998    fn set_mark_insets(self: Handle<Self>, app: &mut App, value: EdgeInsets) {
999        debug_assert!(value.is_non_negative(), "markInsets must be non-negative.");
1000        if app.get(self).mark_insets == value {
1001            return;
1002        }
1003        app.get_mut(self).mark_insets = value;
1004        // triggers repaint when it changes
1005        self.notify_listeners(app);
1006    }
1007
1008    fn active_side(self: Handle<Self>, app: &App) -> BorderSide {
1009        app.get(self).active_side.expect("set before painting")
1010    }
1011
1012    fn set_active_side(self: Handle<Self>, app: &mut App, value: BorderSide) {
1013        if app.get(self).active_side == Some(value) {
1014            return;
1015        }
1016        app.get_mut(self).active_side = Some(value);
1017        self.notify_listeners(app);
1018    }
1019
1020    fn inactive_side(self: Handle<Self>, app: &App) -> BorderSide {
1021        app.get(self).inactive_side.expect("set before painting")
1022    }
1023
1024    fn set_inactive_side(self: Handle<Self>, app: &mut App, value: BorderSide) {
1025        if app.get(self).inactive_side == Some(value) {
1026            return;
1027        }
1028        app.get_mut(self).inactive_side = Some(value);
1029        self.notify_listeners(app);
1030    }
1031
1032    // The square outer bounds of the checkbox at t, with the specified origin.
1033    // At t == 0.0, the outer rect's size is _kEdgeSize (Checkbox.width)
1034    // At t == 0.5, .. is _kEdgeSize - _kStrokeWidth
1035    // At t == 1.0, .. is _kEdgeSize
1036    fn outer_rect_at(origin: Offset, t: f64) -> Rect {
1037        let inset = 1.0 - (t - 0.5).abs() * 2.0;
1038        let size = K_EDGE_SIZE - inset * K_STROKE_WIDTH;
1039        Rect::from_ltwh(origin.dx() + inset, origin.dy() + inset, size, size)
1040    }
1041
1042    // The checkbox's fill color
1043    fn color_at(self: Handle<Self>, app: &App, t: f64) -> Color {
1044        // As t goes from 0.0 to 0.25, animate from the inactiveColor to activeColor.
1045        if t >= 0.25 {
1046            self.active_color(app)
1047        } else {
1048            Color::lerp(
1049                Some(self.inactive_color(app)),
1050                Some(self.active_color(app)),
1051                t * 4.0,
1052            )
1053            .expect("lerping non-null colors")
1054        }
1055    }
1056
1057    // White stroke used to paint the check and dash.
1058    fn create_stroke_paint(self: Handle<Self>, app: &App) -> Paint {
1059        Paint {
1060            color: self.check_color(app).into(),
1061            style: PaintStyle::Stroke(Stroke::new(K_STROKE_WIDTH as f32)),
1062            ..Paint::default()
1063        }
1064    }
1065
1066    // The square that the check mark or the indeterminate dash is drawn in.
1067    //
1068    // The square is inset by [markInsets] and then scaled down uniformly to fit
1069    // whatever space is left, so that the mark keeps its aspect ratio no matter
1070    // how asymmetric the insets are. It is centered in the space the insets leave
1071    // behind. Returns null when the insets leave no room to draw in.
1072    fn mark_square(self: Handle<Self>, app: &App) -> Option<Rect> {
1073        let mark_insets = self.mark_insets(app);
1074        let inner_width = clamp_double(K_EDGE_SIZE - mark_insets.horizontal(), 0.0, K_EDGE_SIZE);
1075        let inner_height = clamp_double(K_EDGE_SIZE - mark_insets.vertical(), 0.0, K_EDGE_SIZE);
1076        if inner_width <= 0.0 || inner_height <= 0.0 {
1077            return None;
1078        }
1079        let side = if inner_width < inner_height {
1080            inner_width
1081        } else {
1082            inner_height
1083        };
1084        Some(Rect::from_ltwh(
1085            mark_insets.left + (inner_width - side) / 2.0,
1086            mark_insets.top + (inner_height - side) / 2.0,
1087            side,
1088            side,
1089        ))
1090    }
1091
1092    fn draw_box(
1093        self: Handle<Self>,
1094        app: &App,
1095        canvas: &mut Canvas,
1096        outer: Rect,
1097        paint: &Paint,
1098        side: Option<BorderSide>,
1099    ) {
1100        let shape = self.shape(app);
1101        if shape.prefer_paint_interior() {
1102            shape.paint_interior(canvas, outer, paint, None);
1103        } else {
1104            let path = shape.get_outer_path(outer, None);
1105            canvas.draw_path(path.as_valo(), path.fill_type, paint);
1106        }
1107        if let Some(side) = side {
1108            shape.copy_with(Some(side)).paint(canvas, outer, None);
1109        }
1110    }
1111
1112    fn draw_check(
1113        self: Handle<Self>,
1114        app: &App,
1115        canvas: &mut Canvas,
1116        origin: Offset,
1117        t: f64,
1118        paint: &mut Paint,
1119    ) {
1120        debug_assert!((0.0..=1.0).contains(&t));
1121        // As t goes from 0.0 to 1.0, animate the two check mark strokes from the
1122        // short side to the long side.
1123        let Some(square) = self.mark_square(app) else {
1124            return;
1125        };
1126        // Shrink the stroke by the same factor so a smaller mark doesn't look chunky.
1127        set_stroke_width(paint, K_STROKE_WIDTH * (square.width() / K_EDGE_SIZE));
1128
1129        let mut path = PathBuilder::new();
1130        let start = Offset::new(
1131            square.left + square.width() * 0.15,
1132            square.top + square.height() * 0.45,
1133        );
1134        let mid = Offset::new(
1135            square.left + square.width() * 0.4,
1136            square.top + square.height() * 0.7,
1137        );
1138        let end = Offset::new(
1139            square.left + square.width() * 0.85,
1140            square.top + square.height() * 0.25,
1141        );
1142
1143        if t < 0.5 {
1144            let stroke_t = t * 2.0;
1145            let draw_mid = Offset::lerp(Some(start), Some(mid), stroke_t).expect("non-null");
1146            path.move_to(Offset::new(
1147                origin.dx() + start.dx(),
1148                origin.dy() + start.dy(),
1149            ));
1150            path.line_to(Offset::new(
1151                origin.dx() + draw_mid.dx(),
1152                origin.dy() + draw_mid.dy(),
1153            ));
1154        } else {
1155            let stroke_t = (t - 0.5) * 2.0;
1156            let draw_end = Offset::lerp(Some(mid), Some(end), stroke_t).expect("non-null");
1157            path.move_to(Offset::new(
1158                origin.dx() + start.dx(),
1159                origin.dy() + start.dy(),
1160            ));
1161            path.line_to(Offset::new(origin.dx() + mid.dx(), origin.dy() + mid.dy()));
1162            path.line_to(Offset::new(
1163                origin.dx() + draw_end.dx(),
1164                origin.dy() + draw_end.dy(),
1165            ));
1166        }
1167        canvas.draw_path(&path.build(), FillRule::NonZero, paint);
1168    }
1169
1170    fn draw_dash(
1171        self: Handle<Self>,
1172        app: &App,
1173        canvas: &mut Canvas,
1174        origin: Offset,
1175        t: f64,
1176        paint: &mut Paint,
1177    ) {
1178        debug_assert!((0.0..=1.0).contains(&t));
1179        // As t goes from 0.0 to 1.0, animate the horizontal line from the
1180        // mid point outwards.
1181        let Some(square) = self.mark_square(app) else {
1182            return;
1183        };
1184        set_stroke_width(paint, K_STROKE_WIDTH * (square.width() / K_EDGE_SIZE));
1185
1186        let start = Offset::new(
1187            square.left + square.width() * 0.2,
1188            square.top + square.height() * 0.5,
1189        );
1190        let mid = Offset::new(
1191            square.left + square.width() * 0.5,
1192            square.top + square.height() * 0.5,
1193        );
1194        let end = Offset::new(
1195            square.left + square.width() * 0.8,
1196            square.top + square.height() * 0.5,
1197        );
1198
1199        let draw_start = Offset::lerp(Some(start), Some(mid), 1.0 - t).expect("non-null");
1200        let draw_end = Offset::lerp(Some(mid), Some(end), t).expect("non-null");
1201        draw_line(canvas, origin + draw_start, origin + draw_end, paint);
1202    }
1203}
1204
1205/// Dart's `paint.strokeWidth = width` on a stroke paint.
1206fn set_stroke_width(paint: &mut Paint, width: f64) {
1207    if let PaintStyle::Stroke(stroke) = &mut paint.style {
1208        stroke.width = width as f32;
1209    }
1210}
1211
1212/// Dart's `Canvas.drawLine`: a stroked two-point path.
1213fn draw_line(canvas: &mut Canvas, p1: Offset, p2: Offset, paint: &Paint) {
1214    let mut path = PathBuilder::new();
1215    path.move_to(p1);
1216    path.line_to(p2);
1217    canvas.draw_path(&path.build(), FillRule::NonZero, paint);
1218}
1219
1220impl ChangeNotifier for CheckboxPainter {
1221    fn change_notifier_data(&self) -> &ChangeNotifierData {
1222        &self.change_notifier
1223    }
1224
1225    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1226        &mut self.change_notifier
1227    }
1228}
1229
1230impl ToggleablePainter for CheckboxPainter {
1231    fn toggleable_painter_data(self: Handle<Self>, app: &App) -> &ToggleablePainterData {
1232        &app.get(self).toggleable_painter
1233    }
1234
1235    fn toggleable_painter_data_mut(
1236        self: Handle<Self>,
1237        app: &mut App,
1238    ) -> &mut ToggleablePainterData {
1239        &mut app.get_mut(self).toggleable_painter
1240    }
1241
1242    fn paint(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size) {
1243        self.paint_radial_reaction(app, canvas, Offset::ZERO, size.center(Offset::ZERO));
1244
1245        let mut stroke_paint = self.create_stroke_paint(app);
1246        let origin = size / 2.0 - Size::square(K_EDGE_SIZE) / 2.0;
1247        let position = self.position(app);
1248        let t_normalized = match position.status(app) {
1249            AnimationStatus::Forward | AnimationStatus::Completed => position.value(app),
1250            AnimationStatus::Reverse | AnimationStatus::Dismissed => 1.0 - position.value(app),
1251        };
1252        let value = self.value(app);
1253        let previous_value = self.previous_value(app);
1254
1255        // Four cases: false to null, false to true, null to false, true to false
1256        if previous_value == Some(false) || value == Some(false) {
1257            let t = if value == Some(false) {
1258                1.0 - t_normalized
1259            } else {
1260                t_normalized
1261            };
1262            let outer = Self::outer_rect_at(origin, t);
1263            let paint = Paint::from_color(self.color_at(app, t).into());
1264
1265            if t <= 0.5 {
1266                let border = BorderSide::lerp(self.inactive_side(app), self.active_side(app), t);
1267                self.draw_box(app, canvas, outer, &paint, Some(border));
1268            } else {
1269                self.draw_box(app, canvas, outer, &paint, Some(self.active_side(app)));
1270                let t_shrink = (t - 0.5) * 2.0;
1271                if previous_value.is_none() || value.is_none() {
1272                    self.draw_dash(app, canvas, origin, t_shrink, &mut stroke_paint);
1273                } else {
1274                    self.draw_check(app, canvas, origin, t_shrink, &mut stroke_paint);
1275                }
1276            }
1277        } else {
1278            // Two cases: null to true, true to null
1279            let outer = Self::outer_rect_at(origin, 1.0);
1280            let paint = Paint::from_color(self.color_at(app, 1.0).into());
1281
1282            self.draw_box(app, canvas, outer, &paint, Some(self.active_side(app)));
1283            if t_normalized <= 0.5 {
1284                let t_shrink = 1.0 - t_normalized * 2.0;
1285                if previous_value.unwrap_or(false) {
1286                    self.draw_check(app, canvas, origin, t_shrink, &mut stroke_paint);
1287                } else {
1288                    self.draw_dash(app, canvas, origin, t_shrink, &mut stroke_paint);
1289                }
1290            } else {
1291                let t_expand = (t_normalized - 0.5) * 2.0;
1292                if value.unwrap_or(false) {
1293                    self.draw_check(app, canvas, origin, t_expand, &mut stroke_paint);
1294                } else {
1295                    self.draw_dash(app, canvas, origin, t_expand, &mut stroke_paint);
1296                }
1297            }
1298        }
1299    }
1300}
1301
1302/// Hand coded defaults based on Material Design 2: Dart's `_CheckboxDefaultsM2`.
1303struct CheckboxDefaultsM2 {
1304    /// Dart's `super(..)` arguments.
1305    checkbox_theme_data: CheckboxThemeData,
1306    context: DefaultsContext,
1307}
1308
1309impl CheckboxDefaultsM2 {
1310    fn new(app: &mut App, context: BuildContext) -> CheckboxDefaultsM2 {
1311        CheckboxDefaultsM2 {
1312            checkbox_theme_data: CheckboxThemeData::new(),
1313            context: DefaultsContext::with_theme(app, context),
1314        }
1315    }
1316}
1317
1318impl CheckboxThemeDataGetters for CheckboxDefaultsM2 {
1319    fn checkbox_theme_data(&self) -> &CheckboxThemeData {
1320        &self.checkbox_theme_data
1321    }
1322
1323    fn side(&self, app: &mut App) -> Option<AnyBorderSide> {
1324        let theme = self.context.theme(app);
1325        let disabled_color = theme.disabled_color;
1326        let unselected_widget_color = theme.unselected_widget_color;
1327        let side = WidgetStateBorderSide::resolve_with(move |states: &WidgetStates| {
1328            if states.contains(&WidgetState::Disabled) {
1329                if states.contains(&WidgetState::Selected) {
1330                    return Some(BorderSide {
1331                        width: 2.0,
1332                        color: Colors::TRANSPARENT,
1333                        ..BorderSide::default()
1334                    });
1335                }
1336                return Some(BorderSide {
1337                    width: 2.0,
1338                    color: disabled_color,
1339                    ..BorderSide::default()
1340                });
1341            }
1342            if states.contains(&WidgetState::Selected) {
1343                return Some(BorderSide {
1344                    width: 2.0,
1345                    color: Colors::TRANSPARENT,
1346                    ..BorderSide::default()
1347                });
1348            }
1349            Some(BorderSide {
1350                width: 2.0,
1351                color: unselected_widget_color,
1352                ..BorderSide::default()
1353            })
1354        });
1355        Some(side.into_any())
1356    }
1357
1358    fn fill_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
1359        let theme = self.context.theme(app);
1360        let disabled_color = theme.disabled_color;
1361        let secondary = theme.color_scheme.secondary();
1362        Some(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
1363            move |states| {
1364                if states.contains(&WidgetState::Disabled) {
1365                    if states.contains(&WidgetState::Selected) {
1366                        return Some(disabled_color);
1367                    }
1368                    return Some(Colors::TRANSPARENT);
1369                }
1370                if states.contains(&WidgetState::Selected) {
1371                    return Some(secondary);
1372                }
1373                Some(Colors::TRANSPARENT)
1374            },
1375        ))
1376    }
1377
1378    fn check_color(&self, _app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
1379        Some(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
1380            Color::new(0xFFFFFFFF),
1381        )))
1382    }
1383
1384    fn overlay_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
1385        let fill_color = self.fill_color(app).expect("the fill color is given");
1386        let theme = self.context.theme(app);
1387        let hover_color = theme.hover_color;
1388        let focus_color = theme.focus_color;
1389        Some(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
1390            move |states| {
1391                if states.contains(&WidgetState::Pressed) {
1392                    return fill_color
1393                        .resolve(states)
1394                        .map(|color| color.with_alpha(K_RADIAL_REACTION_ALPHA));
1395                }
1396                if states.contains(&WidgetState::Hovered) {
1397                    return Some(hover_color);
1398                }
1399                if states.contains(&WidgetState::Focused) {
1400                    return Some(focus_color);
1401                }
1402                Some(Colors::TRANSPARENT)
1403            },
1404        ))
1405    }
1406
1407    fn splash_radius(&self, _app: &mut App) -> Option<f64> {
1408        Some(K_RADIAL_REACTION_RADIUS)
1409    }
1410
1411    fn material_tap_target_size(&self, app: &mut App) -> Option<MaterialTapTargetSize> {
1412        let theme = self.context.theme(app);
1413        Some(theme.material_tap_target_size)
1414    }
1415
1416    fn visual_density(&self, app: &mut App) -> Option<VisualDensity> {
1417        let theme = self.context.theme(app);
1418        Some(theme.visual_density)
1419    }
1420
1421    fn shape(&self, _app: &mut App) -> Option<OutlinedBorderRef> {
1422        Some(OutlinedBorderRef::new(RoundedRectangleBorder::new(
1423            BorderSide::NONE,
1424            BorderRadiusGeometry::all(Radius::circular(1.0)),
1425        )))
1426    }
1427}
1428
1429#[cfg(test)]
1430// Dart's cases build their expected colours with the deprecated `withOpacity`.
1431#[allow(deprecated)]
1432pub(crate) mod tests {
1433    use std::rc::Rc;
1434    use waft_widgets::AnyFocusNode;
1435
1436    use waft_embedder::valo::Op;
1437    use waft_embedder::{PointerChange, RRect};
1438    use waft_foundation::K_IS_WEB;
1439    use waft_rendering::{
1440        AnyRenderObject, RenderBox, RenderCustomPaint, RenderHandle, RenderObject,
1441    };
1442    use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey, SystemMouseCursors};
1443    use waft_widgets::{
1444        AnyElement, Center, Container, FocusHighlightStrategy, FocusNode, MouseRegion,
1445        StatefulBuilder,
1446    };
1447
1448    use waft_rendering::testing::{CanvasMethod, PaintCall, PaintedStyle, RecordedCall, draws};
1449    use waft_widgets::testing::{
1450        TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_nothing,
1451        finds_one_widget, test_widgets, test_widgets_variant,
1452    };
1453
1454    use super::*;
1455    use crate::material::Material;
1456    use crate::test_support::material_app;
1457    use crate::theme_data::ThemeData;
1458    pub(crate) use crate::tooltip::tests::{m2, m3};
1459
1460    /// A callback that ignores the value it is handed: Dart's `(bool? value) {}`.
1461    pub(crate) fn ignore() -> Option<ValueChanged<Option<bool>>> {
1462        Some(Rc::new(|_app: &mut App, _value: Option<bool>| {}))
1463    }
1464
1465    /// `tester.pumpWidget(MaterialApp(theme:, home: Material(child: Center(child: checkbox))))`.
1466    pub(crate) fn pump_checkbox(
1467        tester: &mut WidgetTester,
1468        theme: impl FnOnce(&App) -> ThemeData,
1469        checkbox: impl FnOnce(&mut App) -> WidgetRef,
1470    ) {
1471        let root = {
1472            let mut app = tester.cell.borrow_mut();
1473            let theme = theme(&app);
1474            let checkbox = checkbox(&mut app);
1475            material_app(
1476                theme,
1477                Material::new()
1478                    .child(Center::new().child(checkbox))
1479                    .into_widget(),
1480            )
1481        };
1482        tester.pump_widget(root);
1483    }
1484
1485    /// A checkbox whose value is kept by a `StatefulBuilder` and set by its own `on_changed`.
1486    pub(crate) fn stateful(
1487        value: Rc<std::cell::Cell<Option<bool>>>,
1488        configure: impl Fn(Checkbox) -> Checkbox + 'static,
1489    ) -> WidgetRef {
1490        StatefulBuilder::new(move |_app, _context, set_state| {
1491            let value_now = Rc::clone(&value);
1492            configure(Checkbox::new(
1493                value.get(),
1494                Some(Rc::new(move |app: &mut App, new_value: Option<bool>| {
1495                    let value = Rc::clone(&value_now);
1496                    set_state(app, &mut |_app| value.set(new_value));
1497                })),
1498            ))
1499            .into_widget()
1500        })
1501        .into_widget()
1502    }
1503
1504    /// Dart's `find.byType(Checkbox)`, which expects one.
1505    pub(crate) fn checkbox_element(tester: &WidgetTester) -> AnyElement {
1506        let checkboxes = find::by_type::<Checkbox>().evaluate(tester);
1507        assert_eq!(checkboxes.len(), 1, "one Checkbox");
1508        checkboxes[0]
1509    }
1510
1511    /// Dart's `tester.getCenter(find.byType(Checkbox))`.
1512    pub(crate) fn checkbox_center(tester: &WidgetTester) -> Offset {
1513        tester.get_rect(checkbox_element(tester)).center()
1514    }
1515
1516    /// Dart's `tester.getSize(find.byType(Checkbox))`.
1517    pub(crate) fn checkbox_size(tester: &WidgetTester) -> Size {
1518        let render = tester.render_box_of(checkbox_element(tester));
1519        render.size(&tester.cell.borrow())
1520    }
1521
1522    fn find<T: RenderObject>(app: &App, node: AnyRenderObject) -> Option<RenderHandle<T>> {
1523        if let Some(found) = node.downcast::<T>(app) {
1524            return Some(found);
1525        }
1526        let mut found = None;
1527        node.visit_children(app, &mut |child| {
1528            if found.is_none() {
1529                found = find::<T>(app, child);
1530            }
1531        });
1532        found
1533    }
1534
1535    /// The ops the checkbox's painter records, in paint order, in the checkbox's coordinates.
1536    fn ops(tester: &WidgetTester) -> Vec<Op> {
1537        let element = checkbox_element(tester);
1538        let mut app = tester.cell.borrow_mut();
1539        let root = element
1540            .find_render_object(&app)
1541            .expect("the checkbox has been laid out");
1542        let custom = find::<RenderCustomPaint>(&app, root).expect("the checkbox's paint");
1543        let painter = custom.painter(&app).expect("the checkbox's painter");
1544        let size = custom.size(&app);
1545        let mut canvas = Canvas::new();
1546        painter.paint(&mut app, &mut canvas, size);
1547        canvas.build().ops().to_vec()
1548    }
1549
1550    /// Dart's `expect(renderer, paints..a..b)` on what the checkbox's painter draws.
1551    pub(crate) fn assert_paints(tester: &WidgetTester, expected: &[PaintCall]) {
1552        waft_rendering::testing::assert_paints(&ops(tester), expected);
1553    }
1554
1555    /// Dart's `expect(renderer, isNot(paints..a..b))`.
1556    pub(crate) fn assert_does_not_paint(tester: &WidgetTester, expected: &[PaintCall]) {
1557        let ops = ops(tester);
1558        assert!(
1559            waft_rendering::testing::paints(&ops, expected).is_err(),
1560            "did not expect the pattern in {ops:?}"
1561        );
1562    }
1563
1564    /// Dart's `startGesture(center)`: a touch held down on the checkbox.
1565    pub(crate) fn press(tester: &mut WidgetTester, pointer: i64) -> TestPointer {
1566        let center = checkbox_center(tester);
1567        let mut touch = TestPointer::touch(pointer);
1568        tester.down(&mut touch, center);
1569        touch
1570    }
1571
1572    /// Dart's `createGesture(kind: mouse)`, `addPointer()` and `moveTo(center)`.
1573    pub(crate) fn hover(tester: &mut WidgetTester) -> TestPointer {
1574        let center = checkbox_center(tester);
1575        let mut mouse = TestPointer::mouse(1, 0);
1576        tester.add_pointer(&mut mouse, Offset::ZERO);
1577        tester.move_to(&mut mouse, center, false);
1578        mouse
1579    }
1580
1581    fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
1582        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased::<waft_widgets::AnyFocusNode>()
1583    }
1584
1585    fn has_primary_focus(tester: &WidgetTester, node: AnyFocusNode) -> bool {
1586        node.has_primary_focus(&tester.cell.borrow())
1587    }
1588
1589    fn rrect(left: f64, top: f64, right: f64, bottom: f64, radius: f64) -> RRect {
1590        RRect::from_ltrbr(left, top, right, bottom, Radius::circular(radius))
1591    }
1592
1593    fn orange() -> Color {
1594        Colors::ORANGE.shade500()
1595    }
1596
1597    #[test]
1598    fn checkbox_size_is_configurable_by_theme_data_material_tap_target_size() {
1599        test_widgets(|tester| {
1600            for (size, expected) in [
1601                (MaterialTapTargetSize::Padded, 48.0),
1602                (MaterialTapTargetSize::ShrinkWrap, 40.0),
1603            ] {
1604                pump_checkbox(
1605                    tester,
1606                    |app| {
1607                        ThemeData::new(app)
1608                            .copy_with()
1609                            .material_tap_target_size(size)
1610                            .build()
1611                    },
1612                    |_| Checkbox::new(Some(true), ignore()).into_widget(),
1613                );
1614                // `MaterialApp` animates to the new theme, which Dart's bare `Theme` does not.
1615                tester.pump_and_settle();
1616                assert_eq!(checkbox_size(tester), Size::new(expected, expected));
1617            }
1618        });
1619    }
1620
1621    #[test]
1622    fn checkbox_tristate_true() {
1623        test_widgets(|tester| {
1624            let value = Rc::new(std::cell::Cell::new(None));
1625            let host = stateful(Rc::clone(&value), |checkbox| checkbox.tristate(true));
1626            pump_checkbox(tester, m3, |_| host);
1627            let shown = |tester: &WidgetTester| {
1628                tester.widget(checkbox_element(tester), |checkbox: &Checkbox| {
1629                    checkbox.value
1630                })
1631            };
1632            assert_eq!(shown(tester), None);
1633            for expected in [Some(false), Some(true), None] {
1634                let center = checkbox_center(tester);
1635                tester.tap_at(center, 1);
1636                tester.pump_and_settle();
1637                assert_eq!(value.get(), expected);
1638            }
1639        });
1640    }
1641
1642    fn tristate_rendering(theme: fn(&App) -> ThemeData) {
1643        test_widgets(|tester| {
1644            let colors = theme(&tester.cell.borrow()).color_scheme.clone();
1645            let use_material3 = theme(&tester.cell.borrow()).use_material3;
1646            let (fill, check) = if use_material3 {
1647                (colors.primary(), colors.on_primary())
1648            } else {
1649                (colors.secondary(), Color::new(0xFFFFFFFF))
1650            };
1651            let frame = |tester: &mut WidgetTester, value: Option<bool>| {
1652                pump_checkbox(tester, theme, move |_| {
1653                    Checkbox::new(value, ignore()).tristate(true).into_widget()
1654                });
1655                tester.pump_and_settle();
1656            };
1657            let assert_empty = |tester: &WidgetTester| {
1658                // The transparent fill is not recorded: the ring is the first draw.
1659                assert_eq!(
1660                    draws(&ops(tester)).first().map(CanvasMethod::of),
1661                    Some(CanvasMethod::DrawDRRect)
1662                );
1663                // null is rendered as a line (a "dash")
1664                assert_does_not_paint(
1665                    tester,
1666                    &[PaintCall::Line {
1667                        p1: None,
1668                        p2: None,
1669                        color: None,
1670                        stroke_width: None,
1671                    }],
1672                );
1673            };
1674
1675            frame(tester, Some(false));
1676            assert_empty(tester);
1677
1678            frame(tester, Some(true));
1679            // checkmark is rendered as a path
1680            assert_paints(
1681                tester,
1682                &[PaintCall::rrect(Some(fill)), PaintCall::path(Some(check))],
1683            );
1684
1685            frame(tester, Some(false));
1686            assert_empty(tester);
1687
1688            frame(tester, None);
1689            assert_paints(
1690                tester,
1691                &[PaintCall::Line {
1692                    p1: None,
1693                    p2: None,
1694                    color: None,
1695                    stroke_width: None,
1696                }],
1697            );
1698
1699            frame(tester, Some(true));
1700            assert_paints(
1701                tester,
1702                &[PaintCall::rrect(Some(fill)), PaintCall::path(Some(check))],
1703            );
1704
1705            frame(tester, None);
1706            assert_paints(
1707                tester,
1708                &[PaintCall::Line {
1709                    p1: None,
1710                    p2: None,
1711                    color: None,
1712                    stroke_width: None,
1713                }],
1714            );
1715        });
1716    }
1717
1718    #[test]
1719    fn material2_checkbox_tristate_rendering_programmatic_transitions() {
1720        tristate_rendering(m2);
1721    }
1722
1723    #[test]
1724    fn material3_checkbox_tristate_rendering_programmatic_transitions() {
1725        tristate_rendering(m3);
1726    }
1727
1728    fn color_rendering(use_material3: bool, border_color: Color) {
1729        test_widgets(|tester| {
1730            let theme =
1731                move |app: &App| ThemeData::builder().use_material3(use_material3).build(app);
1732            let frame = |tester: &mut WidgetTester,
1733                         theme: &dyn Fn(&App) -> ThemeData,
1734                         active_color: Option<Color>,
1735                         check_color: Option<Color>| {
1736                pump_checkbox(tester, theme, move |_| {
1737                    let mut checkbox = Checkbox::new(Some(true), ignore());
1738                    checkbox.active_color = active_color;
1739                    checkbox.check_color = check_color;
1740                    checkbox.into_widget()
1741                });
1742                tester.pump_and_settle();
1743            };
1744
1745            // paints's color is 0xFFFFFFFF (default color)
1746            let check_color = Color::new(0xFFFFFFFF);
1747            frame(tester, &theme, None, Some(check_color));
1748            assert_paints(
1749                tester,
1750                &[
1751                    PaintCall::rrect(Some(border_color)),
1752                    PaintCall::path(Some(check_color)),
1753                ],
1754            );
1755
1756            // paints's color is 0xFF000000 (params)
1757            let check_color = Color::new(0xFF000000);
1758            frame(tester, &theme, None, Some(check_color));
1759            assert_paints(
1760                tester,
1761                &[
1762                    PaintCall::rrect(Some(border_color)),
1763                    PaintCall::path(Some(check_color)),
1764                ],
1765            );
1766
1767            // paints's color is 0xFF00FF00 (theme)
1768            let active_color = Color::new(0xFF00FF00);
1769            let themed = move |app: &App| {
1770                let color_scheme = if use_material3 {
1771                    ColorSchemeLight::light().with_primary(active_color)
1772                } else {
1773                    ColorSchemeLight::light().with_secondary(active_color)
1774                };
1775                theme(app).copy_with().color_scheme(color_scheme).build()
1776            };
1777            frame(tester, &themed, None, None);
1778            assert_paints(tester, &[PaintCall::rrect(Some(active_color))]);
1779
1780            let active_color = Color::new(0xFF000000);
1781            frame(tester, &theme, Some(active_color), None);
1782            assert_paints(tester, &[PaintCall::rrect(Some(active_color))]);
1783        });
1784    }
1785
1786    use crate::color_scheme::ColorScheme as ColorSchemeLight;
1787
1788    #[test]
1789    fn material2_checkbox_color_rendering() {
1790        color_rendering(false, Color::new(0xff2196f3));
1791    }
1792
1793    #[test]
1794    fn material3_checkbox_color_rendering() {
1795        color_rendering(true, Color::new(0xFF6750A4));
1796    }
1797
1798    /// The focus cases' `buildApp`: a focused, autofocusing checkbox whose host keeps its value.
1799    fn focus_frame(
1800        tester: &mut WidgetTester,
1801        theme: fn(&App) -> ThemeData,
1802        value: Option<bool>,
1803        enabled: bool,
1804        node: FocusNodeRef,
1805    ) {
1806        pump_checkbox(tester, theme, move |_| {
1807            Checkbox::new(value, if enabled { ignore() } else { None })
1808                .focus_color(orange())
1809                .autofocus(true)
1810                .focus_node(node.clone())
1811                .into_widget()
1812        });
1813        tester.pump_and_settle();
1814    }
1815
1816    #[test]
1817    fn material2_checkbox_is_focusable_and_has_correct_focus_color() {
1818        test_widgets(|tester| {
1819            let node = focus_node(tester);
1820            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1821
1822            focus_frame(tester, m2, Some(true), true, node.clone());
1823            assert!(has_primary_focus(tester, node.handle()));
1824            assert_paints(
1825                tester,
1826                &[
1827                    PaintCall::circle(Some(orange())),
1828                    PaintCall::rrect(Some(Color::new(0xff2196f3))),
1829                    PaintCall::path(Some(Colors::WHITE)),
1830                ],
1831            );
1832
1833            // Check the false value.
1834            focus_frame(tester, m2, Some(false), true, node.clone());
1835            assert!(has_primary_focus(tester, node.handle()));
1836            assert_paints(
1837                tester,
1838                &[
1839                    PaintCall::circle(Some(orange())),
1840                    PaintCall::drrect_between(
1841                        rrect(15.0, 15.0, 33.0, 33.0, 1.0),
1842                        rrect(17.0, 17.0, 31.0, 31.0, 0.0),
1843                        Some(Color::new(0x8a000000)),
1844                    ),
1845                ],
1846            );
1847
1848            // Check what happens when disabled.
1849            focus_frame(tester, m2, Some(false), false, node.clone());
1850            assert!(!has_primary_focus(tester, node.handle()));
1851            assert_paints(
1852                tester,
1853                &[PaintCall::drrect_between(
1854                    rrect(15.0, 15.0, 33.0, 33.0, 1.0),
1855                    rrect(17.0, 17.0, 31.0, 31.0, 0.0),
1856                    Some(Color::new(0x61000000)),
1857                )],
1858            );
1859        });
1860    }
1861
1862    #[test]
1863    fn material3_checkbox_is_focusable_and_has_correct_focus_color() {
1864        test_widgets(|tester| {
1865            let colors = m3(&tester.cell.borrow()).color_scheme.clone();
1866            let node = focus_node(tester);
1867            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1868
1869            focus_frame(tester, m3, Some(true), true, node.clone());
1870            assert!(has_primary_focus(tester, node.handle()));
1871            assert_paints(
1872                tester,
1873                &[
1874                    PaintCall::circle(Some(orange())),
1875                    PaintCall::rrect(Some(colors.primary())),
1876                    PaintCall::path(Some(colors.on_primary())),
1877                ],
1878            );
1879
1880            // Check the false value.
1881            focus_frame(tester, m3, Some(false), true, node.clone());
1882            assert!(has_primary_focus(tester, node.handle()));
1883            assert_paints(
1884                tester,
1885                &[
1886                    PaintCall::circle(Some(orange())),
1887                    PaintCall::drrect_between(
1888                        rrect(15.0, 15.0, 33.0, 33.0, 2.0),
1889                        rrect(17.0, 17.0, 31.0, 31.0, 0.0),
1890                        Some(colors.on_surface()),
1891                    ),
1892                ],
1893            );
1894
1895            // Check what happens when disabled.
1896            focus_frame(tester, m3, Some(false), false, node.clone());
1897            assert!(!has_primary_focus(tester, node.handle()));
1898            assert_paints(
1899                tester,
1900                &[PaintCall::drrect_between(
1901                    rrect(15.0, 15.0, 33.0, 33.0, 2.0),
1902                    rrect(17.0, 17.0, 31.0, 31.0, 0.0),
1903                    Some(colors.on_surface().with_opacity(0.38)),
1904                )],
1905            );
1906        });
1907    }
1908
1909    #[test]
1910    fn checkbox_with_splash_radius_set() {
1911        test_widgets(|tester| {
1912            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1913            const SPLASH_RADIUS: f64 = 30.0;
1914            pump_checkbox(tester, m3, |_| {
1915                Checkbox::new(Some(false), ignore())
1916                    .focus_color(orange())
1917                    .autofocus(true)
1918                    .splash_radius(SPLASH_RADIUS)
1919                    .into_widget()
1920            });
1921            tester.pump_and_settle();
1922            assert_paints(
1923                tester,
1924                &[PaintCall::Circle {
1925                    x: None,
1926                    y: None,
1927                    radius: Some(SPLASH_RADIUS),
1928                    color: Some(orange()),
1929                    style: None,
1930                }],
1931            );
1932        });
1933    }
1934
1935    #[test]
1936    fn checkbox_starts_the_splash_in_center_even_when_tap_is_on_the_corner() {
1937        test_widgets(|tester| {
1938            pump_checkbox(tester, m3, |_| {
1939                Checkbox::new(Some(false), ignore()).into_widget()
1940            });
1941            let rect = tester.get_rect(checkbox_element(tester));
1942            let checkbox_center_local = rect.center() - rect.top_left();
1943            let mut gesture = TestPointer::touch(1);
1944            tester.down(&mut gesture, rect.top_left());
1945            tester.pump();
1946            // Wait for the splash to be drawn, but not long enough for it to animate towards
1947            // the center, since we want to catch it in its starting position.
1948            tester.pump_by(Duration::from_millis(1));
1949            assert_paints(
1950                tester,
1951                &[PaintCall::Circle {
1952                    x: Some((checkbox_center_local).dx()),
1953                    y: Some((checkbox_center_local).dy()),
1954                    radius: None,
1955                    color: None,
1956                    style: None,
1957                }],
1958            );
1959
1960            // Finish gesture to release resources.
1961            tester.up(&gesture);
1962            tester.pump_and_settle();
1963        });
1964    }
1965
1966    fn hover_color_case(theme: fn(&App) -> ThemeData) {
1967        test_widgets(|tester| {
1968            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1969            let data = theme(&tester.cell.borrow());
1970            let colors = data.color_scheme.clone();
1971            let (fill, check) = if data.use_material3 {
1972                (Color::new(0xff6750a4), colors.on_primary())
1973            } else {
1974                (Color::new(0xff2196f3), Color::new(0xffffffff))
1975            };
1976            let frame = |tester: &mut WidgetTester, enabled: bool| {
1977                pump_checkbox(tester, theme, move |_| {
1978                    Checkbox::new(Some(true), if enabled { ignore() } else { None })
1979                        .hover_color(orange())
1980                        .into_widget()
1981                });
1982                tester.pump_and_settle();
1983            };
1984
1985            frame(tester, true);
1986            assert_paints(
1987                tester,
1988                &[
1989                    PaintCall::rrect(Some(fill)),
1990                    PaintCall::Path {
1991                        color: Some(check),
1992                        style: Some(PaintedStyle::Stroke(Some(2.0))),
1993                        includes: vec![],
1994                        excludes: vec![],
1995                    },
1996                ],
1997            );
1998
1999            // Start hovering
2000            let center = checkbox_center(tester);
2001            let mut gesture = TestPointer::mouse(1, 0);
2002            tester.add_pointer(&mut gesture, Offset::ZERO);
2003            tester.move_to(&mut gesture, center, false);
2004
2005            frame(tester, true);
2006            assert_paints(
2007                tester,
2008                &[
2009                    PaintCall::circle(Some(orange())),
2010                    PaintCall::rrect(Some(fill)),
2011                    PaintCall::Path {
2012                        color: Some(check),
2013                        style: Some(PaintedStyle::Stroke(Some(2.0))),
2014                        includes: vec![],
2015                        excludes: vec![],
2016                    },
2017                ],
2018            );
2019
2020            // Check what happens when disabled.
2021            frame(tester, false);
2022            let (disabled_fill, disabled_check) = if data.use_material3 {
2023                (colors.on_surface().with_opacity(0.38), colors.surface())
2024            } else {
2025                (Color::new(0x61000000), Color::new(0xffffffff))
2026            };
2027            assert_paints(
2028                tester,
2029                &[
2030                    PaintCall::rrect(Some(disabled_fill)),
2031                    PaintCall::Path {
2032                        color: Some(disabled_check),
2033                        style: Some(PaintedStyle::Stroke(Some(2.0))),
2034                        includes: vec![],
2035                        excludes: vec![],
2036                    },
2037                ],
2038            );
2039            tester.send(&gesture, PointerChange::Remove);
2040        });
2041    }
2042
2043    #[test]
2044    fn material2_checkbox_can_be_hovered_and_has_correct_hover_color() {
2045        hover_color_case(m2);
2046    }
2047
2048    #[test]
2049    fn material3_checkbox_can_be_hovered_and_has_correct_hover_color() {
2050        hover_color_case(m3);
2051    }
2052
2053    #[test]
2054    fn checkbox_can_be_toggled_by_keyboard_shortcuts() {
2055        test_widgets(|tester| {
2056            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2057            let value = Rc::new(std::cell::Cell::new(Some(true)));
2058            let host = stateful(Rc::clone(&value), |checkbox| {
2059                checkbox.focus_color(orange()).autofocus(true)
2060            });
2061            pump_checkbox(tester, m3, |_| host);
2062            tester.pump_and_settle();
2063            tester.send_key_event(PhysicalKeyboardKey::ENTER, LogicalKeyboardKey::ENTER);
2064            tester.pump_and_settle();
2065            // On web, checkboxes don't respond to the enter key.
2066            assert_eq!(value.get(), Some(K_IS_WEB));
2067            tester.send_key_event(PhysicalKeyboardKey::ENTER, LogicalKeyboardKey::ENTER);
2068            tester.pump_and_settle();
2069            assert_eq!(value.get(), Some(true));
2070            tester.send_key_event(PhysicalKeyboardKey::SPACE, LogicalKeyboardKey::SPACE);
2071            tester.pump_and_settle();
2072            assert_eq!(value.get(), Some(false));
2073            tester.send_key_event(PhysicalKeyboardKey::SPACE, LogicalKeyboardKey::SPACE);
2074            tester.pump_and_settle();
2075            assert_eq!(value.get(), Some(true));
2076        });
2077    }
2078
2079    #[test]
2080    fn material3_checkbox_visual_density_cannot_be_overridden_by_theme_data_visual_density() {
2081        test_widgets(|tester| {
2082            pump_checkbox(
2083                tester,
2084                |app| {
2085                    ThemeData::new(app)
2086                        .copy_with()
2087                        .visual_density(VisualDensity::COMPACT)
2088                        .build()
2089                },
2090                |_| Checkbox::new(Some(true), ignore()).into_widget(),
2091            );
2092            tester.pump_and_settle();
2093            assert_eq!(checkbox_size(tester), Size::new(48.0, 48.0));
2094        });
2095    }
2096
2097    #[test]
2098    fn material3_checkbox_with_material_tap_target_size_padded_meets_material_guidelines_on_desktop()
2099     {
2100        for platform in [
2101            TargetPlatform::Linux,
2102            TargetPlatform::MacOS,
2103            TargetPlatform::Windows,
2104        ] {
2105            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2106                pump_checkbox(tester, m3, |_| {
2107                    Checkbox::new(Some(true), ignore())
2108                        .material_tap_target_size(MaterialTapTargetSize::Padded)
2109                        .into_widget()
2110                });
2111                tester.pump_and_settle();
2112                assert_eq!(checkbox_size(tester), Size::new(48.0, 48.0), "{platform:?}");
2113            });
2114        }
2115    }
2116
2117    #[test]
2118    fn checkbox_responds_to_density_changes() {
2119        test_widgets(|tester| {
2120            for (visual_density, expected) in [
2121                (None, Size::new(48.0, 48.0)),
2122                (Some(VisualDensity::STANDARD), Size::new(48.0, 48.0)),
2123                (Some(VisualDensity::COMPACT), Size::new(40.0, 40.0)),
2124                (Some(VisualDensity::new(3.0, 3.0)), Size::new(60.0, 60.0)),
2125                (Some(VisualDensity::new(-3.0, -3.0)), Size::new(36.0, 36.0)),
2126                (Some(VisualDensity::new(3.0, -3.0)), Size::new(60.0, 36.0)),
2127            ] {
2128                pump_checkbox(tester, m3, move |_| {
2129                    let mut checkbox = Checkbox::new(Some(true), ignore());
2130                    checkbox.visual_density = visual_density;
2131                    checkbox.into_widget()
2132                });
2133                tester.pump_and_settle();
2134                assert_eq!(checkbox_size(tester), expected, "{visual_density:?}");
2135            }
2136        });
2137    }
2138
2139    #[test]
2140    fn checkbox_stops_hover_animation_when_removed_from_the_tree() {
2141        test_widgets(|tester| {
2142            let theme = |app: &App| {
2143                ThemeData::builder()
2144                    .material_tap_target_size(MaterialTapTargetSize::Padded)
2145                    .build(app)
2146            };
2147            let value = Rc::new(std::cell::Cell::new(Some(true)));
2148            let host = stateful(Rc::clone(&value), |checkbox| checkbox);
2149            pump_checkbox(tester, theme, |_| host);
2150
2151            let checkbox_center = checkbox_center(tester);
2152            let mut test_gesture = TestPointer::mouse(1, 0);
2153            tester.add_pointer(&mut test_gesture, Offset::ZERO);
2154            tester.move_to(&mut test_gesture, checkbox_center, false);
2155
2156            tester.pump(); // start animation
2157            // hover animation duration is 50 ms. It is half-way.
2158            tester.pump_by(Duration::from_millis(25));
2159
2160            // Hover animation should not trigger an exception when the checkbox is removed
2161            // before the hover animation should complete.
2162            pump_checkbox(tester, theme, |_| Container::new().into_widget());
2163
2164            tester.send(&test_gesture, PointerChange::Remove);
2165        });
2166    }
2167
2168    fn selected_grab_mouse_cursor() -> MouseCursorRef {
2169        WidgetStateMouseCursor::resolve_with(
2170            |states| {
2171                if states.contains(&WidgetState::Selected) {
2172                    SystemMouseCursors::GRAB.into()
2173                } else {
2174                    SystemMouseCursors::BASIC.into()
2175                }
2176            },
2177            Some("_SelectedGrabMouseCursor()"),
2178        )
2179        .into()
2180    }
2181
2182    #[test]
2183    fn checkbox_changes_mouse_cursor_when_hovered() {
2184        test_widgets(|tester| {
2185            let frame = |tester: &mut WidgetTester, checkbox: Checkbox| {
2186                let root = {
2187                    let app = tester.cell.borrow();
2188                    material_app(
2189                        m3(&app),
2190                        crate::scaffold::Scaffold::new()
2191                            .body(
2192                                waft_widgets::Align::new()
2193                                    .alignment(waft_painting::AlignmentGeometry::TOP_LEFT)
2194                                    .child(
2195                                        Material::new().child(
2196                                            MouseRegion::new()
2197                                                .cursor(SystemMouseCursors::FORBIDDEN.into())
2198                                                .child(checkbox),
2199                                        ),
2200                                    ),
2201                            )
2202                            .into_widget(),
2203                    )
2204                };
2205                tester.pump_widget(root);
2206            };
2207
2208            // Test Checkbox() constructor
2209            frame(
2210                tester,
2211                Checkbox::new(Some(true), ignore()).mouse_cursor(SystemMouseCursors::TEXT.into()),
2212            );
2213            let center = checkbox_center(tester);
2214            let mut gesture = TestPointer::mouse(1, 0);
2215            tester.add_pointer(&mut gesture, center);
2216            tester.pump();
2217            assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
2218
2219            // Test default cursor
2220            frame(tester, Checkbox::new(Some(true), ignore()));
2221            let expected: MouseCursorRef = if K_IS_WEB {
2222                SystemMouseCursors::CLICK.into()
2223            } else {
2224                SystemMouseCursors::BASIC.into()
2225            };
2226            assert_eq!(Some(tester.active_cursor(1)), Some(expected));
2227
2228            // Test default cursor when disabled
2229            frame(tester, Checkbox::new(Some(true), None));
2230            assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
2231
2232            // Test cursor when tristate
2233            frame(
2234                tester,
2235                Checkbox::new(None, None)
2236                    .tristate(true)
2237                    .mouse_cursor(selected_grab_mouse_cursor()),
2238            );
2239            assert_eq!(tester.active_cursor(1), SystemMouseCursors::GRAB.into());
2240
2241            tester.pump_and_settle();
2242            tester.send(&gesture, PointerChange::Remove);
2243        });
2244    }
2245
2246    #[test]
2247    fn checkbox_fill_color_resolves_in_enabled_disabled_states() {
2248        test_widgets(|tester| {
2249            const ACTIVE_ENABLED_FILL_COLOR: Color = Color::new(0xFF000001);
2250            const ACTIVE_DISABLED_FILL_COLOR: Color = Color::new(0xFF000002);
2251            let fill_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
2252                if states.contains(&WidgetState::Disabled) {
2253                    return Some(ACTIVE_DISABLED_FILL_COLOR);
2254                }
2255                Some(ACTIVE_ENABLED_FILL_COLOR)
2256            });
2257            for (enabled, expected) in [
2258                (true, ACTIVE_ENABLED_FILL_COLOR),
2259                (false, ACTIVE_DISABLED_FILL_COLOR),
2260            ] {
2261                let fill_color = Rc::clone(&fill_color);
2262                pump_checkbox(tester, m3, move |_| {
2263                    Checkbox::new(Some(true), if enabled { ignore() } else { None })
2264                        .fill_color(fill_color)
2265                        .into_widget()
2266                });
2267                tester.pump_and_settle();
2268                assert_paints(tester, &[PaintCall::rrect(Some(expected))]);
2269            }
2270        });
2271    }
2272
2273    #[test]
2274    fn checkbox_fill_color_resolves_in_hovered_focused_states() {
2275        test_widgets(|tester| {
2276            let node = focus_node(tester);
2277            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2278            const HOVERED_FILL_COLOR: Color = Color::new(0xFF000001);
2279            const FOCUSED_FILL_COLOR: Color = Color::new(0xFF000002);
2280            let fill_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
2281                if states.contains(&WidgetState::Hovered) {
2282                    return Some(HOVERED_FILL_COLOR);
2283                }
2284                if states.contains(&WidgetState::Focused) {
2285                    return Some(FOCUSED_FILL_COLOR);
2286                }
2287                Some(Colors::TRANSPARENT)
2288            });
2289            pump_checkbox(tester, m3, {
2290                let node = node.clone();
2291                move |_| {
2292                    Checkbox::new(Some(true), ignore())
2293                        .focus_node(node.clone())
2294                        .autofocus(true)
2295                        .fill_color(fill_color)
2296                        .into_widget()
2297                }
2298            });
2299            tester.pump_and_settle();
2300            assert!(has_primary_focus(tester, node.handle()));
2301            assert_paints(tester, &[PaintCall::rrect(Some(FOCUSED_FILL_COLOR))]);
2302
2303            // Start hovering
2304            let gesture = hover(tester);
2305            tester.pump_and_settle();
2306            assert_paints(tester, &[PaintCall::rrect(Some(HOVERED_FILL_COLOR))]);
2307            tester.send(&gesture, PointerChange::Remove);
2308        });
2309    }
2310
2311    #[test]
2312    fn checkbox_respects_shape_and_side() {
2313        test_widgets(|tester| {
2314            let rounded_rectangle_border = RoundedRectangleBorder::new(
2315                BorderSide::NONE,
2316                BorderRadiusGeometry::all(Radius::circular(5.0)),
2317            );
2318            let side = BorderSide {
2319                width: 4.0,
2320                color: Color::new(0xfff44336),
2321                ..BorderSide::default()
2322            };
2323            let border = rounded_rectangle_border;
2324            pump_checkbox(tester, m3, move |_| {
2325                Checkbox::new(Some(false), ignore())
2326                    .shape(border)
2327                    .side(side)
2328                    .into_widget()
2329            });
2330            tester.pump_and_settle();
2331
2332            tester.widget(checkbox_element(tester), |checkbox: &Checkbox| {
2333                let shape: &dyn ShapeBorder = checkbox.shape.as_deref().expect("a shape");
2334                assert!(shape == &rounded_rectangle_border as &dyn ShapeBorder);
2335                assert_eq!(checkbox.side, Some(AnyBorderSide::new(side)));
2336            });
2337            assert_paints(
2338                tester,
2339                &[PaintCall::drrect_between(
2340                    rrect(15.0, 15.0, 33.0, 33.0, 5.0),
2341                    rrect(19.0, 19.0, 29.0, 29.0, 1.0),
2342                    Some(Color::new(0xfff44336)),
2343                )],
2344            );
2345        });
2346    }
2347
2348    /// The default overlay cases' `buildCheckbox`: a checkbox in a `Scaffold`'s body.
2349    fn overlay_frame(
2350        tester: &mut WidgetTester,
2351        theme: fn(&App) -> ThemeData,
2352        configure: impl FnOnce(Checkbox) -> Checkbox,
2353        active: bool,
2354        focused: bool,
2355        node: FocusNodeRef,
2356    ) {
2357        let checkbox = configure(
2358            Checkbox::new(Some(active), ignore())
2359                .focus_node(node.clone())
2360                .autofocus(focused),
2361        );
2362        let root = {
2363            let app = tester.cell.borrow();
2364            material_app(
2365                theme(&app),
2366                crate::scaffold::Scaffold::new()
2367                    .body(checkbox)
2368                    .into_widget(),
2369            )
2370        };
2371        tester.pump_widget(root);
2372    }
2373
2374    /// Dart's "Finish gestures to release resources": `gesture.up()` for each touch still down,
2375    /// then `pumpAndSettle`.
2376    fn finish_gestures(tester: &mut WidgetTester, gestures: &[&TestPointer]) {
2377        for gesture in gestures {
2378            tester.up(gesture);
2379        }
2380        tester.pump_and_settle();
2381    }
2382
2383    fn reset(tester: &mut WidgetTester) {
2384        tester.pump_widget(Container::new().into_widget());
2385    }
2386
2387    fn default_overlay_case(
2388        theme: fn(&App) -> ThemeData,
2389        inactive_pressed: fn(&ThemeData) -> Color,
2390        active_pressed: fn(&ThemeData) -> Color,
2391        focused: fn(&ThemeData) -> Color,
2392        hovered: fn(&ThemeData) -> Color,
2393    ) {
2394        test_widgets(|tester| {
2395            let node = focus_node(tester);
2396            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2397            let data = theme(&tester.cell.borrow());
2398
2399            overlay_frame(
2400                tester,
2401                theme,
2402                |checkbox| checkbox,
2403                false,
2404                false,
2405                node.clone(),
2406            );
2407            let gesture1 = press(tester, 1);
2408            tester.pump_and_settle();
2409            // Default inactive pressed Checkbox should have overlay color from default
2410            // fillColor
2411            assert_paints(tester, &[PaintCall::circle(Some(inactive_pressed(&data)))]);
2412
2413            overlay_frame(
2414                tester,
2415                theme,
2416                |checkbox| checkbox,
2417                true,
2418                false,
2419                node.clone(),
2420            );
2421            let gesture2 = press(tester, 2);
2422            tester.pump_and_settle();
2423            // Default active pressed Checkbox should have overlay color from default fillColor
2424            assert_paints(tester, &[PaintCall::circle(Some(active_pressed(&data)))]);
2425
2426            reset(tester);
2427            overlay_frame(
2428                tester,
2429                theme,
2430                |checkbox| checkbox,
2431                false,
2432                true,
2433                node.clone(),
2434            );
2435            tester.pump_and_settle();
2436            assert!(has_primary_focus(tester, node.handle()));
2437            // Focused Checkbox should use default focused overlay color
2438            assert_paints(tester, &[PaintCall::circle(Some(focused(&data)))]);
2439
2440            reset(tester);
2441            overlay_frame(
2442                tester,
2443                theme,
2444                |checkbox| checkbox,
2445                false,
2446                false,
2447                node.clone(),
2448            );
2449            let gesture3 = hover(tester);
2450            tester.pump_and_settle();
2451            // Hovered Checkbox should use default hovered overlay color
2452            assert_paints(tester, &[PaintCall::circle(Some(hovered(&data)))]);
2453
2454            // Finish gestures to release resources.
2455            finish_gestures(tester, &[&gesture1, &gesture2]);
2456            tester.send(&gesture3, PointerChange::Remove);
2457        });
2458    }
2459
2460    #[test]
2461    fn material2_checkbox_default_overlay_color_in_active_pressed_focused_hovered_states() {
2462        default_overlay_case(
2463            m2,
2464            |theme| {
2465                theme
2466                    .unselected_widget_color
2467                    .with_alpha(K_RADIAL_REACTION_ALPHA)
2468            },
2469            |theme| {
2470                theme
2471                    .color_scheme
2472                    .secondary()
2473                    .with_alpha(K_RADIAL_REACTION_ALPHA)
2474            },
2475            |theme| theme.focus_color,
2476            |theme| theme.hover_color,
2477        );
2478    }
2479
2480    #[test]
2481    fn material3_checkbox_default_overlay_color_in_active_pressed_focused_hovered_states() {
2482        default_overlay_case(
2483            m3,
2484            |theme| theme.color_scheme.primary().with_opacity(0.1),
2485            |theme| theme.color_scheme.on_surface().with_opacity(0.1),
2486            |theme| theme.color_scheme.on_surface().with_opacity(0.1),
2487            |theme| theme.color_scheme.on_surface().with_opacity(0.08),
2488        );
2489    }
2490
2491    #[test]
2492    fn checkbox_overlay_color_resolves_in_active_pressed_focused_hovered_states() {
2493        test_widgets(|tester| {
2494            let node = focus_node(tester);
2495            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2496
2497            const FILL_COLOR: Color = Color::new(0xFF000000);
2498            const ACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000001);
2499            const INACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000002);
2500            const HOVER_OVERLAY_COLOR: Color = Color::new(0xFF000003);
2501            const FOCUS_OVERLAY_COLOR: Color = Color::new(0xFF000004);
2502            const HOVER_COLOR: Color = Color::new(0xFF000005);
2503            const FOCUS_COLOR: Color = Color::new(0xFF000006);
2504            const SPLASH_RADIUS: f64 = 24.0;
2505
2506            let overlay_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
2507                if states.contains(&WidgetState::Pressed) {
2508                    if states.contains(&WidgetState::Selected) {
2509                        return Some(ACTIVE_PRESSED_OVERLAY_COLOR);
2510                    }
2511                    return Some(INACTIVE_PRESSED_OVERLAY_COLOR);
2512                }
2513                if states.contains(&WidgetState::Hovered) {
2514                    return Some(HOVER_OVERLAY_COLOR);
2515                }
2516                if states.contains(&WidgetState::Focused) {
2517                    return Some(FOCUS_OVERLAY_COLOR);
2518                }
2519                None
2520            });
2521            let frame =
2522                |tester: &mut WidgetTester, active: bool, focused: bool, use_overlay: bool| {
2523                    let overlay_color = Rc::clone(&overlay_color);
2524                    overlay_frame(
2525                        tester,
2526                        m3,
2527                        move |checkbox| {
2528                            let checkbox = checkbox
2529                                .fill_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
2530                                    FILL_COLOR,
2531                                )))
2532                                .hover_color(HOVER_COLOR)
2533                                .focus_color(FOCUS_COLOR)
2534                                .splash_radius(SPLASH_RADIUS);
2535                            if use_overlay {
2536                                checkbox.overlay_color(overlay_color)
2537                            } else {
2538                                checkbox
2539                            }
2540                        },
2541                        active,
2542                        focused,
2543                        node.clone(),
2544                    );
2545                };
2546
2547            frame(tester, false, false, false);
2548            let gesture1 = press(tester, 1);
2549            tester.pump_and_settle();
2550            // Default inactive pressed Checkbox should have overlay color from fillColor
2551            assert_paints(
2552                tester,
2553                &[PaintCall::Circle {
2554                    x: None,
2555                    y: None,
2556                    radius: Some(SPLASH_RADIUS),
2557                    color: Some(FILL_COLOR.with_alpha(K_RADIAL_REACTION_ALPHA)),
2558                    style: None,
2559                }],
2560            );
2561
2562            frame(tester, true, false, false);
2563            let gesture2 = press(tester, 2);
2564            tester.pump_and_settle();
2565            // Default active pressed Checkbox should have overlay color from fillColor
2566            assert_paints(
2567                tester,
2568                &[PaintCall::Circle {
2569                    x: None,
2570                    y: None,
2571                    radius: Some(SPLASH_RADIUS),
2572                    color: Some(FILL_COLOR.with_alpha(K_RADIAL_REACTION_ALPHA)),
2573                    style: None,
2574                }],
2575            );
2576
2577            frame(tester, false, false, true);
2578            let gesture3 = press(tester, 3);
2579            tester.pump_and_settle();
2580            assert_paints(
2581                tester,
2582                &[PaintCall::Circle {
2583                    x: None,
2584                    y: None,
2585                    radius: Some(SPLASH_RADIUS),
2586                    color: Some(INACTIVE_PRESSED_OVERLAY_COLOR),
2587                    style: None,
2588                }],
2589            );
2590
2591            frame(tester, true, false, true);
2592            let gesture4 = press(tester, 4);
2593            tester.pump_and_settle();
2594            assert_paints(
2595                tester,
2596                &[PaintCall::Circle {
2597                    x: None,
2598                    y: None,
2599                    radius: Some(SPLASH_RADIUS),
2600                    color: Some(ACTIVE_PRESSED_OVERLAY_COLOR),
2601                    style: None,
2602                }],
2603            );
2604
2605            reset(tester);
2606            frame(tester, false, true, true);
2607            tester.pump_and_settle();
2608            assert!(has_primary_focus(tester, node.handle()));
2609            // Focused Checkbox should use overlay color over focusColor
2610            assert_paints(
2611                tester,
2612                &[PaintCall::Circle {
2613                    x: None,
2614                    y: None,
2615                    radius: Some(SPLASH_RADIUS),
2616                    color: Some(FOCUS_OVERLAY_COLOR),
2617                    style: None,
2618                }],
2619            );
2620
2621            // Start hovering
2622            let gesture5 = hover(tester);
2623            tester.pump_and_settle();
2624            // Hovered Checkbox should use overlay color over hoverColor
2625            assert_paints(
2626                tester,
2627                &[PaintCall::Circle {
2628                    x: None,
2629                    y: None,
2630                    radius: Some(SPLASH_RADIUS),
2631                    color: Some(HOVER_OVERLAY_COLOR),
2632                    style: None,
2633                }],
2634            );
2635
2636            // Finish gestures to release resources.
2637            finish_gestures(tester, &[&gesture1, &gesture2, &gesture3, &gesture4]);
2638            tester.send(&gesture5, PointerChange::Remove);
2639        });
2640    }
2641
2642    #[test]
2643    fn tristate_checkbox_overlay_color_resolves_in_pressed_active_inactive_states() {
2644        test_widgets(|tester| {
2645            const ACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000001);
2646            const INACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000002);
2647            const SPLASH_RADIUS: f64 = 24.0;
2648            let overlay_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
2649                if states.contains(&WidgetState::Pressed) {
2650                    if states.contains(&WidgetState::Selected) {
2651                        return Some(ACTIVE_PRESSED_OVERLAY_COLOR);
2652                    }
2653                    return Some(INACTIVE_PRESSED_OVERLAY_COLOR);
2654                }
2655                None
2656            });
2657            let value = Rc::new(std::cell::Cell::new(Some(false)));
2658            let host = stateful(Rc::clone(&value), move |checkbox| {
2659                checkbox
2660                    .tristate(true)
2661                    .overlay_color(Rc::clone(&overlay_color))
2662                    .splash_radius(SPLASH_RADIUS)
2663            });
2664            let root = {
2665                let app = tester.cell.borrow();
2666                material_app(
2667                    m3(&app),
2668                    crate::scaffold::Scaffold::new().body(host).into_widget(),
2669                )
2670            };
2671            tester.pump_widget(root);
2672
2673            // The checkbox is inactive.
2674            let mut gesture = press(tester, 1);
2675            tester.pump_and_settle();
2676            assert_eq!(value.get(), Some(false));
2677            assert_paints(
2678                tester,
2679                &[PaintCall::Circle {
2680                    x: None,
2681                    y: None,
2682                    radius: Some(SPLASH_RADIUS),
2683                    color: Some(INACTIVE_PRESSED_OVERLAY_COLOR),
2684                    style: None,
2685                }],
2686            );
2687
2688            for (pointer, expected_value, expected_color) in [
2689                // The checkbox is active.
2690                (2, Some(true), ACTIVE_PRESSED_OVERLAY_COLOR),
2691                // The checkbox is active in tri-state.
2692                (3, None, ACTIVE_PRESSED_OVERLAY_COLOR),
2693                // The checkbox is inactive again.
2694                (4, Some(false), INACTIVE_PRESSED_OVERLAY_COLOR),
2695            ] {
2696                tester.up(&gesture);
2697                gesture = press(tester, pointer);
2698                tester.pump_and_settle();
2699                assert_eq!(value.get(), expected_value);
2700                assert_paints(
2701                    tester,
2702                    &[PaintCall::Circle {
2703                        x: None,
2704                        y: None,
2705                        radius: Some(SPLASH_RADIUS),
2706                        color: Some(expected_color),
2707                        style: None,
2708                    }],
2709                );
2710            }
2711
2712            tester.up(&gesture);
2713        });
2714    }
2715
2716    #[test]
2717    fn do_not_crash_when_widget_disappears_while_pointer_is_down() {
2718        test_widgets(|tester| {
2719            pump_checkbox(tester, m3, |_| {
2720                Checkbox::new(Some(true), ignore()).into_widget()
2721            });
2722            // Put a pointer down on the screen.
2723            let gesture = press(tester, 1);
2724            tester.pump();
2725            // While the pointer is down, the widget disappears.
2726            pump_checkbox(tester, m3, |_| Container::new().into_widget());
2727            expect(tester, &find::by_type::<Checkbox>(), finds_nothing());
2728            // Release pointer after widget disappeared.
2729            tester.up(&gesture);
2730        });
2731    }
2732
2733    #[test]
2734    fn checkbox_border_side_side_only_applies_when_unselected_in_m2() {
2735        test_widgets(|tester| {
2736            const BORDER_COLOR: Color = Color::new(0xfff44336);
2737            const ACTIVE_COLOR: Color = Color::new(0xff123456);
2738            let side = BorderSide {
2739                width: 4.0,
2740                color: BORDER_COLOR,
2741                ..BorderSide::default()
2742            };
2743            let frame = |tester: &mut WidgetTester, value: Option<bool>, enabled: bool| {
2744                pump_checkbox(tester, m2, move |_| {
2745                    Checkbox::new(value, if enabled { ignore() } else { None })
2746                        .tristate(value.is_none())
2747                        .active_color(ACTIVE_COLOR)
2748                        .side(side)
2749                        .into_widget()
2750                });
2751                tester.pump_and_settle();
2752            };
2753            let expect_border = |tester: &WidgetTester| {
2754                assert_paints(
2755                    tester,
2756                    &[PaintCall::drrect_between(
2757                        rrect(15.0, 15.0, 33.0, 33.0, 1.0),
2758                        rrect(19.0, 19.0, 29.0, 29.0, 0.0),
2759                        Some(BORDER_COLOR),
2760                    )],
2761                );
2762            };
2763
2764            // Checkbox is unselected, so the specified BorderSide appears.
2765            frame(tester, Some(false), true);
2766            expect_border(tester);
2767            frame(tester, Some(false), false);
2768            expect_border(tester);
2769
2770            // Checkbox is selected/indeterminate, so the specified BorderSide is transparent,
2771            // which is not recorded.
2772            for value in [Some(true), None] {
2773                frame(tester, value, true);
2774                assert_does_not_paint(tester, &[PaintCall::drrect(Some(BORDER_COLOR))]);
2775                assert_paints(tester, &[PaintCall::rrect(Some(ACTIVE_COLOR))]); // checkbox fill
2776            }
2777        });
2778    }
2779
2780    fn widget_state_border_side_case(theme: fn(&App) -> ThemeData, radius: f64) {
2781        test_widgets(|tester| {
2782            const BORDER_COLOR: Color = Color::new(0xfff44336);
2783            let side = BorderSide {
2784                width: 4.0,
2785                color: BORDER_COLOR,
2786                ..BorderSide::default()
2787            };
2788            for (value, enabled) in [
2789                (Some(false), true),
2790                (Some(false), false),
2791                (Some(true), true),
2792                (None, true),
2793            ] {
2794                pump_checkbox(tester, theme, move |_| {
2795                    Checkbox::new(value, if enabled { ignore() } else { None })
2796                        .tristate(value.is_none())
2797                        .side(WidgetStateBorderSide::resolve_with(move |_| Some(side)))
2798                        .into_widget()
2799                });
2800                tester.pump_and_settle();
2801                assert_paints(
2802                    tester,
2803                    &[PaintCall::drrect_between(
2804                        rrect(15.0, 15.0, 33.0, 33.0, radius),
2805                        rrect(19.0, 19.0, 29.0, 29.0, 0.0),
2806                        Some(BORDER_COLOR),
2807                    )],
2808                );
2809            }
2810        });
2811    }
2812
2813    #[test]
2814    fn material2_checkbox_widget_state_border_side_applies_unconditionally() {
2815        widget_state_border_side_case(m2, 1.0);
2816    }
2817
2818    #[test]
2819    fn material3_checkbox_widget_state_border_side_applies_unconditionally() {
2820        widget_state_border_side_case(m3, 2.0);
2821    }
2822
2823    #[test]
2824    fn disabled_checkbox_shows_tooltip() {
2825        test_widgets(|tester| {
2826            const LONG_PRESS_TOOLTIP: &str = "long press tooltip";
2827            const TAP_TOOLTIP: &str = "tap tooltip";
2828            let frame = |tester: &mut WidgetTester, tooltip: crate::tooltip::Tooltip| {
2829                tester.pump_widget(
2830                    crate::app::MaterialApp::new()
2831                        .home(Material::new().child(tooltip.child(Checkbox::new(Some(true), None))))
2832                        .into_widget(),
2833                );
2834            };
2835            let tooltip_center = |tester: &WidgetTester| {
2836                let tooltip = find::by_type::<crate::tooltip::Tooltip>().evaluate(tester)[0];
2837                tester.get_rect(tooltip).center()
2838            };
2839            frame(
2840                tester,
2841                crate::tooltip::Tooltip::new().message(LONG_PRESS_TOOLTIP),
2842            );
2843
2844            // Default tooltip shows up after long pressed.
2845            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
2846
2847            let center = tooltip_center(tester);
2848            tester.tap_at(center, 1);
2849            tester.pump_by(Duration::from_millis(10));
2850            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
2851
2852            let mut gesture_long_press = TestPointer::touch(2);
2853            tester.down(&mut gesture_long_press, center);
2854            tester.pump();
2855            tester.pump_by(waft_gestures::K_LONG_PRESS_TIMEOUT);
2856            tester.up(&gesture_long_press);
2857            tester.pump();
2858
2859            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_one_widget());
2860
2861            // Tooltip shows up after tapping when set triggerMode to TooltipTriggerMode.tap.
2862            frame(
2863                tester,
2864                crate::tooltip::Tooltip::new()
2865                    .trigger_mode(waft_widgets::TooltipTriggerMode::Tap)
2866                    .message(TAP_TOOLTIP),
2867            );
2868
2869            tester.pump_by(Duration::from_secs(24 * 60 * 60));
2870            tester.pump_and_settle();
2871            expect(tester, &find::text(TAP_TOOLTIP), finds_nothing());
2872            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
2873
2874            let center = tooltip_center(tester);
2875            tester.tap_at(center, 3);
2876            tester.pump_by(Duration::from_millis(10));
2877            expect(tester, &find::text(TAP_TOOLTIP), finds_one_widget());
2878        });
2879    }
2880
2881    #[test]
2882    fn material3_checkbox_has_default_error_color_when_is_error_is_set_to_true() {
2883        test_widgets(|tester| {
2884            let node = focus_node(tester);
2885            let colors = m3(&tester.cell.borrow()).color_scheme.clone();
2886            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2887            let value = Rc::new(std::cell::Cell::new(Some(true)));
2888            let frame = |tester: &mut WidgetTester, auto_focus: bool| {
2889                let host = stateful(Rc::clone(&value), {
2890                    let node = node.clone();
2891                    move |checkbox| {
2892                        checkbox
2893                            .is_error(true)
2894                            .autofocus(auto_focus)
2895                            .focus_node(node.clone())
2896                    }
2897                });
2898                pump_checkbox(tester, m3, |_| host);
2899                tester.pump_and_settle();
2900            };
2901
2902            // Focused
2903            frame(tester, true);
2904            assert!(has_primary_focus(tester, node.handle()));
2905            assert_paints(
2906                tester,
2907                &[
2908                    PaintCall::circle(Some(colors.error().with_opacity(0.1))),
2909                    PaintCall::rrect(Some(colors.error())),
2910                    PaintCall::path(Some(colors.on_error())),
2911                ],
2912            );
2913
2914            // Default color
2915            reset(tester);
2916            frame(tester, false);
2917            assert!(!has_primary_focus(tester, node.handle()));
2918            assert_paints(
2919                tester,
2920                &[
2921                    PaintCall::rrect(Some(colors.error())),
2922                    PaintCall::path(Some(colors.on_error())),
2923                ],
2924            );
2925
2926            // Start hovering
2927            let gesture = hover(tester);
2928            tester.pump_and_settle();
2929            assert_paints(
2930                tester,
2931                &[
2932                    PaintCall::circle(Some(colors.error().with_opacity(0.08))),
2933                    PaintCall::rrect(Some(colors.error())),
2934                ],
2935            );
2936
2937            // Start pressing
2938            let gesture_long_press = press(tester, 2);
2939            tester.pump();
2940            assert_paints(
2941                tester,
2942                &[
2943                    PaintCall::circle(Some(colors.error().with_opacity(0.1))),
2944                    PaintCall::rrect(Some(colors.error())),
2945                ],
2946            );
2947            tester.up(&gesture_long_press);
2948            tester.pump();
2949            tester.send(&gesture, PointerChange::Remove);
2950        });
2951    }
2952
2953    #[test]
2954    fn material3_checkbox_widget_state_border_side_applies_in_error_states() {
2955        test_widgets(|tester| {
2956            let node = focus_node(tester);
2957            const BORDER_COLOR: Color = Color::new(0xffffeb3b);
2958            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2959            let value = Rc::new(std::cell::Cell::new(Some(false)));
2960            let frame = |tester: &mut WidgetTester, auto_focus: bool| {
2961                let host = stateful(Rc::clone(&value), {
2962                    let node = node.clone();
2963                    move |checkbox| {
2964                        checkbox
2965                            .is_error(true)
2966                            .side(WidgetStateBorderSide::resolve_with(|states| {
2967                                if states.contains(&WidgetState::Error) {
2968                                    return Some(BorderSide {
2969                                        color: BORDER_COLOR,
2970                                        width: 4.0,
2971                                        ..BorderSide::default()
2972                                    });
2973                                }
2974                                Some(BorderSide {
2975                                    color: Colors::RED.primary(),
2976                                    width: 2.0,
2977                                    ..BorderSide::default()
2978                                })
2979                            }))
2980                            .autofocus(auto_focus)
2981                            .focus_node(node.clone())
2982                    }
2983                });
2984                pump_checkbox(tester, m3, |_| host);
2985                tester.pump_and_settle();
2986            };
2987            let expect_border = |tester: &WidgetTester| {
2988                assert_paints(
2989                    tester,
2990                    &[PaintCall::drrect_between(
2991                        rrect(15.0, 15.0, 33.0, 33.0, 2.0),
2992                        rrect(19.0, 19.0, 29.0, 29.0, 0.0),
2993                        Some(BORDER_COLOR),
2994                    )],
2995                );
2996            };
2997
2998            frame(tester, true);
2999            expect_border(tester);
3000
3001            // Focused
3002            frame(tester, true);
3003            assert!(has_primary_focus(tester, node.handle()));
3004            expect_border(tester);
3005
3006            // Default color
3007            reset(tester);
3008            frame(tester, false);
3009            assert!(!has_primary_focus(tester, node.handle()));
3010            expect_border(tester);
3011
3012            // Start hovering
3013            let gesture = hover(tester);
3014            tester.pump_and_settle();
3015            expect_border(tester);
3016
3017            // Start pressing
3018            let gesture_long_press = press(tester, 2);
3019            tester.pump();
3020            expect_border(tester);
3021            tester.up(&gesture_long_press);
3022            tester.pump();
3023            tester.send(&gesture, PointerChange::Remove);
3024        });
3025    }
3026
3027    #[test]
3028    fn material3_checkbox_has_correct_default_shape() {
3029        test_widgets(|tester| {
3030            pump_checkbox(tester, m3, |_| {
3031                Checkbox::new(Some(false), ignore()).into_widget()
3032            });
3033            tester.pump_and_settle();
3034
3035            let expected_shape = m3(&tester.cell.borrow()).checkbox_theme.shape;
3036            assert!(expected_shape.is_none());
3037            tester.widget(checkbox_element(tester), |checkbox: &Checkbox| {
3038                assert!(checkbox.shape.is_none());
3039            });
3040            assert_paints(
3041                tester,
3042                &[PaintCall::drrect_between(
3043                    rrect(15.0, 15.0, 33.0, 33.0, 2.0),
3044                    rrect(17.0, 17.0, 31.0, 31.0, 0.0),
3045                    None,
3046                )],
3047            );
3048        });
3049    }
3050
3051    #[test]
3052    fn checkbox_adaptive_shows_the_correct_platform_widget() {
3053        test_widgets(|tester| {
3054            let frame = |tester: &mut WidgetTester, platform: TargetPlatform| {
3055                pump_checkbox(
3056                    tester,
3057                    move |app| ThemeData::builder().platform(platform).build(app),
3058                    |_| Checkbox::adaptive(Some(false), ignore()).into_widget(),
3059                );
3060                tester.pump_and_settle();
3061            };
3062
3063            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
3064                frame(tester, platform);
3065                expect(
3066                    tester,
3067                    &find::by_type::<CupertinoCheckbox>(),
3068                    finds_one_widget(),
3069                );
3070            }
3071
3072            for platform in [
3073                TargetPlatform::Android,
3074                TargetPlatform::Fuchsia,
3075                TargetPlatform::Linux,
3076                TargetPlatform::Windows,
3077            ] {
3078                frame(tester, platform);
3079                assert!(
3080                    find::by_type::<CupertinoCheckbox>()
3081                        .evaluate(tester)
3082                        .is_empty(),
3083                    "{platform:?}"
3084                );
3085            }
3086        });
3087    }
3088
3089    #[test]
3090    fn checkbox_adaptive_respects_checkbox_mouse_cursor_on_ios_macos() {
3091        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
3092            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3093                let frame = |tester: &mut WidgetTester, mouse_cursor: Option<MouseCursorRef>| {
3094                    let root = {
3095                        let app = tester.cell.borrow();
3096                        let mut checkbox = Checkbox::adaptive(Some(true), ignore());
3097                        checkbox.mouse_cursor = mouse_cursor;
3098                        crate::app::MaterialApp::new()
3099                            .theme(m3(&app))
3100                            .home(Material::new().child(checkbox))
3101                            .into_widget()
3102                    };
3103                    tester.pump_widget(root);
3104                };
3105
3106                frame(tester, None);
3107                let cupertino = find::by_type::<CupertinoCheckbox>().evaluate(tester)[0];
3108                let center = tester.get_rect(cupertino).center();
3109                let mut gesture = TestPointer::mouse(1, 0);
3110                tester.add_pointer(&mut gesture, center);
3111                tester.pump();
3112                tester.move_to(&mut gesture, center, false);
3113                let expected: MouseCursorRef = if K_IS_WEB {
3114                    SystemMouseCursors::CLICK.into()
3115                } else {
3116                    SystemMouseCursors::BASIC.into()
3117                };
3118                assert_eq!(
3119                    Some(tester.active_cursor(1)),
3120                    Some(expected),
3121                    "{platform:?}"
3122                );
3123
3124                // Test mouse cursor can be configured.
3125                frame(tester, Some(SystemMouseCursors::CLICK.into()));
3126                assert_eq!(
3127                    tester.active_cursor(1),
3128                    SystemMouseCursors::CLICK.into(),
3129                    "{platform:?}"
3130                );
3131
3132                // Test Checkbox.adaptive can resolve a WidgetStateMouseCursor.
3133                frame(tester, Some(selected_grab_mouse_cursor()));
3134                assert_eq!(
3135                    tester.active_cursor(1),
3136                    SystemMouseCursors::GRAB.into(),
3137                    "{platform:?}"
3138                );
3139
3140                tester.send(&gesture, PointerChange::Remove);
3141            });
3142        }
3143    }
3144
3145    fn fill_color_when_unchecked_case(
3146        theme: fn(&App) -> ThemeData,
3147        enabled_border: fn(&ThemeData) -> Color,
3148        disabled_border: fn(&ThemeData) -> Color,
3149    ) {
3150        test_widgets(|tester| {
3151            let data = theme(&tester.cell.borrow());
3152            const ACTIVE_BACKGROUND_COLOR: Color = Color::new(0xff123456);
3153            const INACTIVE_BACKGROUND_COLOR: Color = Color::new(0xff654321);
3154            let frame = |tester: &mut WidgetTester, enabled: bool| {
3155                pump_checkbox(tester, theme, move |_| {
3156                    Checkbox::new(Some(false), if enabled { ignore() } else { None })
3157                        .fill_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
3158                            |states| {
3159                                if states.contains(&WidgetState::Selected) {
3160                                    return Some(ACTIVE_BACKGROUND_COLOR);
3161                                }
3162                                Some(INACTIVE_BACKGROUND_COLOR)
3163                            },
3164                        ))
3165                        .into_widget()
3166                });
3167                tester.pump_and_settle();
3168            };
3169
3170            // Checkbox is unselected, so the default BorderSide appears and fillColor is
3171            // checkbox's background color.
3172            frame(tester, true);
3173            assert_paints(tester, &[PaintCall::drrect(Some(enabled_border(&data)))]);
3174            assert_paints(tester, &[PaintCall::rrect(Some(INACTIVE_BACKGROUND_COLOR))]);
3175
3176            frame(tester, false);
3177            assert_paints(tester, &[PaintCall::drrect(Some(disabled_border(&data)))]);
3178            assert_paints(tester, &[PaintCall::rrect(Some(INACTIVE_BACKGROUND_COLOR))]);
3179        });
3180    }
3181
3182    #[test]
3183    fn material2_checkbox_respects_fill_color_when_it_is_unchecked() {
3184        fill_color_when_unchecked_case(
3185            m2,
3186            |theme| theme.unselected_widget_color,
3187            |theme| theme.disabled_color,
3188        );
3189    }
3190
3191    #[test]
3192    fn material3_checkbox_respects_fill_color_when_it_is_unchecked() {
3193        fill_color_when_unchecked_case(
3194            m3,
3195            |theme| theme.color_scheme.on_surface_variant(),
3196            |theme| theme.color_scheme.on_surface().with_opacity(0.38),
3197        );
3198    }
3199
3200    #[test]
3201    fn checkbox_renders_at_zero_area() {
3202        test_widgets(|tester| {
3203            tester.pump_widget(
3204                crate::app::MaterialApp::new()
3205                    .home(Center::new().child(waft_widgets::SizedBox::shrink().child(
3206                        crate::scaffold::Scaffold::new().body(Checkbox::new(Some(true), None)),
3207                    )))
3208                    .into_widget(),
3209            );
3210        });
3211    }
3212
3213    /// Dart's `_padFrame`.
3214    pub(crate) fn pad_frame(
3215        tester: &mut WidgetTester,
3216        value: Option<bool>,
3217        mark_insets: Option<EdgeInsets>,
3218        tristate: bool,
3219    ) {
3220        tester.pump_widget(
3221            crate::app::MaterialApp::new()
3222                .home(Material::new().child(Center::new().child({
3223                    let mut checkbox = Checkbox::new(value, ignore()).tristate(tristate);
3224                    checkbox.mark_insets = mark_insets;
3225                    checkbox
3226                })))
3227                .into_widget(),
3228        );
3229    }
3230
3231    /// Dart's `_paintedCheckBounds`: the bounds of the check mark path.
3232    fn painted_check_bounds(tester: &WidgetTester) -> Rect {
3233        ops(tester)
3234            .iter()
3235            .find_map(|op| match RecordedCall::of(op) {
3236                RecordedCall::Path {
3237                    bounds,
3238                    stroke_width: Some(_),
3239                    ..
3240                } => Some(bounds),
3241                _ => None,
3242            })
3243            .expect("No check mark was painted.")
3244    }
3245
3246    /// Dart's `_paintedDashLength`: the length of the indeterminate dash.
3247    fn painted_dash_length(tester: &WidgetTester) -> f64 {
3248        ops(tester)
3249            .iter()
3250            .find_map(|op| match RecordedCall::of(op) {
3251                RecordedCall::Line { p1, p2, .. } => Some((p2.dx() - p1.dx()).abs()),
3252                _ => None,
3253            })
3254            .expect("No indeterminate dash was painted.")
3255    }
3256
3257    #[test]
3258    fn checkbox_mark_insets_defaults_to_null() {
3259        test_widgets(|tester| {
3260            pad_frame(tester, Some(true), None, false);
3261            tester.widget(checkbox_element(tester), |checkbox: &Checkbox| {
3262                assert_eq!(checkbox.mark_insets, None);
3263            });
3264        });
3265    }
3266
3267    #[test]
3268    fn checkbox_with_no_mark_insets_paints_the_check_at_full_stroke_width() {
3269        test_widgets(|tester| {
3270            pad_frame(tester, Some(true), None, false);
3271            tester.pump_and_settle();
3272            // default: scale == 1.0, so strokeWidth stays at _kStrokeWidth (2.0)
3273            assert_paints(
3274                tester,
3275                &[PaintCall::Path {
3276                    color: None,
3277                    style: Some(PaintedStyle::Stroke(Some(2.0))),
3278                    includes: vec![],
3279                    excludes: vec![],
3280                }],
3281            );
3282        });
3283    }
3284
3285    #[test]
3286    fn checkbox_mark_insets_shrinks_the_check_mark_and_its_stroke() {
3287        test_widgets(|tester| {
3288            pad_frame(tester, Some(true), Some(EdgeInsets::all(4.5)), false);
3289            tester.pump_and_settle();
3290            // inner = 18 - 9 = 9, scale = 9/18 = 0.5, strokeWidth = 2.0 * 0.5 = 1.0
3291            assert_paints(
3292                tester,
3293                &[PaintCall::Path {
3294                    color: None,
3295                    style: Some(PaintedStyle::Stroke(Some(1.0))),
3296                    includes: vec![],
3297                    excludes: vec![],
3298                }],
3299            );
3300        });
3301    }
3302
3303    #[test]
3304    fn checkbox_mark_insets_shrinks_the_indeterminate_dash() {
3305        test_widgets(|tester| {
3306            pad_frame(tester, None, Some(EdgeInsets::all(4.5)), true);
3307            tester.pump_and_settle();
3308            assert_paints(
3309                tester,
3310                &[PaintCall::Line {
3311                    p1: None,
3312                    p2: None,
3313                    color: None,
3314                    stroke_width: Some(1.0),
3315                }],
3316            );
3317        });
3318    }
3319
3320    #[test]
3321    fn checkbox_mark_insets_larger_than_the_box_collapses_the_mark_without_crashing() {
3322        test_widgets(|tester| {
3323            pad_frame(tester, Some(true), Some(EdgeInsets::all(9.0)), false);
3324            tester.pump_and_settle();
3325            // mark collapsed away
3326            assert!(
3327                !ops(tester).iter().any(|op| matches!(
3328                    RecordedCall::of(op),
3329                    RecordedCall::Line { .. }
3330                        | RecordedCall::Path {
3331                            stroke_width: Some(_),
3332                            ..
3333                        }
3334                )),
3335                "{:?}",
3336                ops(tester)
3337            );
3338        });
3339    }
3340
3341    #[test]
3342    fn checkbox_mark_insets_keeps_the_check_mark_proportional_with_asymmetric_insets() {
3343        test_widgets(|tester| {
3344            pad_frame(tester, Some(true), None, false);
3345            tester.pump_and_settle();
3346            let uninset = painted_check_bounds(tester);
3347            let aspect = uninset.width() / uninset.height();
3348
3349            // Each of these leaves a different amount of room on each axis. The mark
3350            // shrinks to the smaller of the two, so its shape never changes.
3351            for mark_insets in [
3352                EdgeInsets::only(9.0, 0.0, 0.0, 0.0),
3353                EdgeInsets::only(0.0, 9.0, 0.0, 0.0),
3354                EdgeInsets::only(0.0, 0.0, 4.5, 0.0),
3355                EdgeInsets::symmetric(0.0, 6.0),
3356            ] {
3357                pad_frame(tester, Some(true), Some(mark_insets), false);
3358                tester.pump_and_settle();
3359                let inset = painted_check_bounds(tester);
3360                assert!(
3361                    (inset.width() / inset.height() - aspect).abs() <= 0.001,
3362                    "check mark was distorted by {mark_insets:?}"
3363                );
3364                assert!(inset.width() <= uninset.width());
3365                assert!(inset.height() <= uninset.height());
3366            }
3367        });
3368    }
3369
3370    #[test]
3371    fn checkbox_mark_insets_centers_a_half_size_mark_in_the_right_half_of_the_box() {
3372        test_widgets(|tester| {
3373            pad_frame(tester, Some(true), None, false);
3374            tester.pump_and_settle();
3375            let uninset = painted_check_bounds(tester);
3376            // The 18x18 box is centered in the checkbox's render box.
3377            let box_origin = checkbox_size(tester).center(Offset::ZERO) - Offset::new(9.0, 9.0);
3378
3379            pad_frame(
3380                tester,
3381                Some(true),
3382                Some(EdgeInsets::only(9.0, 0.0, 0.0, 0.0)),
3383                false,
3384            );
3385            tester.pump_and_settle();
3386            let inset = painted_check_bounds(tester);
3387
3388            // The remaining space is 9x18, so the mark is drawn in a 9x9 square at
3389            // (9, 4.5) within the box: half size, vertically centered.
3390            let to_half_square =
3391                |p: Offset| box_origin + Offset::new(9.0, 4.5) + (p - box_origin) / 2.0;
3392            let expected = Rect::from_points(
3393                to_half_square(uninset.top_left()),
3394                to_half_square(uninset.bottom_right()),
3395            );
3396            assert!((inset.left - expected.left).abs() <= 0.001);
3397            assert!((inset.top - expected.top).abs() <= 0.001);
3398            assert!((inset.width() - uninset.width() / 2.0).abs() <= 0.001);
3399            assert!((inset.height() - uninset.height() / 2.0).abs() <= 0.001);
3400        });
3401    }
3402
3403    #[test]
3404    fn checkbox_mark_insets_shrinks_the_indeterminate_dash_by_the_smaller_inset() {
3405        test_widgets(|tester| {
3406            pad_frame(tester, None, None, true);
3407            tester.pump_and_settle();
3408            let uninset = painted_dash_length(tester);
3409
3410            // Only the horizontal axis is inset, but the dash still scales by half,
3411            // matching the check mark rather than stretching to the inner width.
3412            pad_frame(
3413                tester,
3414                None,
3415                Some(EdgeInsets::only(9.0, 0.0, 0.0, 0.0)),
3416                true,
3417            );
3418            tester.pump_and_settle();
3419            assert!((painted_dash_length(tester) - uninset / 2.0).abs() <= 0.001);
3420        });
3421    }
3422
3423    /// `MaterialApp(theme: ThemeData(checkboxTheme: CheckboxThemeData(markInsets:)), home:
3424    /// Material(child: Center(child: checkbox)))`.
3425    fn pump_with_theme_mark_insets(
3426        tester: &mut WidgetTester,
3427        theme_mark_insets: EdgeInsets,
3428        checkbox: Checkbox,
3429    ) {
3430        let root = {
3431            let app = tester.cell.borrow();
3432            crate::app::MaterialApp::new()
3433                .theme(
3434                    ThemeData::builder()
3435                        .checkbox_theme(CheckboxThemeData::new().mark_insets(theme_mark_insets))
3436                        .build(&app),
3437                )
3438                .home(Material::new().child(Center::new().child(checkbox)))
3439                .into_widget()
3440        };
3441        tester.pump_widget(root);
3442    }
3443
3444    #[test]
3445    fn checkbox_mark_insets_falls_back_to_checkbox_theme_data_mark_insets() {
3446        test_widgets(|tester| {
3447            pump_with_theme_mark_insets(
3448                tester,
3449                EdgeInsets::all(4.5),
3450                Checkbox::new(Some(true), ignore()),
3451            );
3452            tester.pump_and_settle();
3453            // theme markInsets applied
3454            assert_paints(
3455                tester,
3456                &[PaintCall::Path {
3457                    color: None,
3458                    style: Some(PaintedStyle::Stroke(Some(1.0))),
3459                    includes: vec![],
3460                    excludes: vec![],
3461                }],
3462            );
3463        });
3464    }
3465
3466    #[test]
3467    fn checkbox_mark_insets_overrides_checkbox_theme_data_mark_insets() {
3468        test_widgets(|tester| {
3469            pump_with_theme_mark_insets(
3470                tester,
3471                EdgeInsets::ZERO,
3472                Checkbox::new(Some(true), ignore()).mark_insets(EdgeInsets::all(4.5)),
3473            );
3474            tester.pump_and_settle();
3475            // widget value wins
3476            assert_paints(
3477                tester,
3478                &[PaintCall::Path {
3479                    color: None,
3480                    style: Some(PaintedStyle::Stroke(Some(1.0))),
3481                    includes: vec![],
3482                    excludes: vec![],
3483                }],
3484            );
3485        });
3486    }
3487}