Skip to main content

waft_material/
button_style_button.rs

1//! Flutter counterpart: material_ui's `button_style_button.dart`.
2//!
3//! Dart's abstract `ButtonStyleButton` widget is two pieces a subclass holds and implements:
4//! the [`ButtonStyleButtonData`] bag of its fields, and the [`ButtonStyleButton`] trait with
5//! its override points [`default_style_of`](ButtonStyleButton::default_style_of) and
6//! [`theme_style_of`](ButtonStyleButton::theme_style_of). Every subclass keeps its own widget
7//! type and shares Dart's `_ButtonStyleState` as [`ButtonStyleState<Self>`].
8//!
9//! # Writing a subclass
10//!
11//! A subclass (`ElevatedButton`, `TextButton`, …) is a struct with the bag under the field
12//! `button_style_button` and its own fields after it:
13//!
14//! ```text
15//! pub struct ElevatedButton {
16//!     button_style_button: ButtonStyleButtonData,
17//!     add_padding: bool,
18//! }
19//!
20//! impl ElevatedButton {
21//!     pub fn new<K>(
22//!         on_pressed: Option<Listener>,
23//!         child: Option<impl IntoWidget<K>>,
24//!     ) -> ElevatedButton {
25//!         ElevatedButton {
26//!             button_style_button: ButtonStyleButtonData::new(
27//!                 on_pressed,
28//!                 child.map(|child| child.into_widget()),
29//!             ),
30//!             add_padding: false,
31//!         }
32//!     }
33//!
34//!     // The `super.` arguments of the Dart constructor, by their field names.
35//!     crate::button_style_button_setters!(
36//!         ElevatedButton;
37//!         key, on_long_press, on_hover, on_focus_change, style, focus_node, autofocus,
38//!         clip_behavior, states_controller, is_selected,
39//!     );
40//! }
41//!
42//! impl ButtonStyleButton for ElevatedButton {
43//!     crate::button_style_button_accessors!();
44//!
45//!     fn default_style_of(&self, app: &mut App, context: BuildContext) -> Box<dyn ButtonStyleGetters> { … }
46//!     fn theme_style_of(&self, app: &mut App, context: BuildContext) -> Option<ButtonStyle> { … }
47//! }
48//!
49//! impl StatefulWidget for ElevatedButton {
50//!     type State = ButtonStyleState<ElevatedButton>;
51//!
52//!     fn key(&self) -> Option<&KeyRef> {
53//!         self.button_style_button.key.as_ref()
54//!     }
55//!
56//!     fn create_state(&self) -> ButtonStyleState<ElevatedButton> {
57//!         ButtonStyleState::new()
58//!     }
59//! }
60//!
61//! impl Debug for ElevatedButton {
62//!     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63//!         Debug::fmt(&self.button_style_button, f)
64//!     }
65//! }
66//! ```
67//!
68//! A default the Dart subclass gives a `super.` argument (`super.autofocus = false`,
69//! `super.clipBehavior = Clip.none`) is set on the bag in its `new`. Dart's static helpers
70//! are `<dyn ButtonStyleButton>::all_or_null`, `::default_color` and `::scaled_padding`.
71#![allow(deprecated)]
72
73use std::fmt::{self, Debug};
74use std::rc::Rc;
75use std::time::Duration;
76
77use waft_animation::{
78    AnimationBehavior, AnimationController, AnimationLocalStatusListenersMixin, AnimationStatus,
79    AnimationStatusListener,
80};
81use waft_embedder::{Clip, Color, Offset, Size, TextBaseline};
82use waft_foundation::{
83    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Handle, Listenable,
84    Listener, OptionRetained, Ref, ValueChanged,
85};
86use waft_painting::{Alignment, EdgeInsets, EdgeInsetsGeometry, ShapeBorderRef, force_to_point};
87use waft_rendering::{
88    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, BoxParentData,
89    ChildLayoutHelper, ChildLayouter, PaintingContext, RenderBox, RenderBoxBase, RenderBoxData,
90    RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
91    RenderObjectWithChildMixin, RenderShiftedBox,
92};
93use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
94use waft_services::MouseCursorRef;
95use waft_widgets::{
96    Align, BuildContext, ConstrainedBox, FocusNodeRef, IconTheme, IconThemeData, IntoWidget,
97    KeyRef, Padding, RenderObjectWidget, Semantics, SingleChildRenderObjectWidget, State,
98    StateData, StatefulWidget, TickerProviderStateMixin, TickerProviderStateMixinData, WidgetRef,
99    WidgetState, WidgetStateMouseCursor, WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
100    downcast_widget,
101};
102
103use crate::button_style::ButtonStyle;
104use crate::button_style::ButtonStyleGetters;
105use crate::colors::Colors;
106use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
107use crate::ink_well::InkWell;
108use crate::material::{Material, MaterialType};
109use crate::material_state::{MaterialStatePropertyAll, MaterialStatesController};
110use crate::theme::{AnimatedTheme, Theme};
111use crate::theme_data::MaterialTapTargetSize;
112use crate::tooltip::Tooltip;
113
114/// Determines the alignment of the icon within the widgets such as:
115///   - `ElevatedButton::icon`,
116///   - `FilledButton::icon`,
117///   - `FilledButton::tonal_icon`.
118///   - `OutlinedButton::icon`,
119///   - `TextButton::icon`,
120///
121/// The effect of `icon_alignment` depends on `TextDirection`. If text direction is
122/// `TextDirection::Ltr` then [`IconAlignment::Start`] and [`IconAlignment::End`] align the
123/// icon on the left or right respectively.  If text direction is `TextDirection::Rtl` the
124/// the alignments are reversed.
125///
126/// Defaults to [`IconAlignment::Start`].
127#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
128pub enum IconAlignment {
129    /// The icon is placed at the start of the button.
130    Start,
131
132    /// The icon is placed at the end of the button.
133    End,
134}
135
136/// The fields of Dart's abstract `ButtonStyleButton`, which every subclass carries under the
137/// field `button_style_button`.
138#[derive(Clone)]
139pub struct ButtonStyleButtonData {
140    /// See [`Widget::key`](waft_widgets::Widget::key).
141    pub key: Option<KeyRef>,
142
143    /// Called when the button is tapped or otherwise activated.
144    ///
145    /// If this callback and [`on_long_press`](Self::on_long_press) are null, then the button
146    /// will be disabled.
147    ///
148    /// See also:
149    ///
150    ///  * [`ButtonStyleButton::enabled`], which is true if the button is enabled.
151    pub on_pressed: Option<Listener>,
152
153    /// Called when the button is long-pressed.
154    ///
155    /// If this callback and [`on_pressed`](Self::on_pressed) are null, then the button will
156    /// be disabled.
157    ///
158    /// See also:
159    ///
160    ///  * [`ButtonStyleButton::enabled`], which is true if the button is enabled.
161    pub on_long_press: Option<Listener>,
162
163    /// Called when a pointer enters or exits the button response area.
164    ///
165    /// The value passed to the callback is true if a pointer has entered this
166    /// part of the material and false if a pointer has exited this part of the
167    /// material.
168    pub on_hover: Option<ValueChanged<bool>>,
169
170    /// Handler called when the focus changes.
171    ///
172    /// Called with true if this widget's node gains focus, and false if it loses
173    /// focus.
174    pub on_focus_change: Option<ValueChanged<bool>>,
175
176    /// Customizes this button's appearance.
177    ///
178    /// Non-null properties of this style override the corresponding
179    /// properties in [`ButtonStyleButton::theme_style_of`] and
180    /// [`ButtonStyleButton::default_style_of`]. [`WidgetStateProperty`]s that resolve to
181    /// non-null values will similarly override the corresponding [`WidgetStateProperty`]s in
182    /// [`ButtonStyleButton::theme_style_of`] and [`ButtonStyleButton::default_style_of`].
183    ///
184    /// Null by default.
185    pub style: Option<ButtonStyle>,
186
187    /// The content will be clipped (or not) according to this option.
188    ///
189    /// Defaults to [`Clip::None`] unless [`ButtonStyle::background_builder`] or
190    /// [`ButtonStyle::foreground_builder`] is specified. In those
191    /// cases the default is [`Clip::AntiAlias`].
192    pub clip_behavior: Option<Clip>,
193
194    /// An optional focus node to use as the focus node for this widget.
195    pub focus_node: Option<FocusNodeRef>,
196
197    /// True if this widget will be selected as the initial focus when no other
198    /// node in its scope is currently focused.
199    pub autofocus: bool,
200
201    /// Represents the interactive "state" of this widget in terms of a set of
202    /// [`WidgetState`]s, like [`WidgetState::Pressed`] and [`WidgetState::Focused`].
203    ///
204    /// Classes based on this one can provide their own [`MaterialStatesController`] to which
205    /// they've added listeners. They can also update the controller's value however, this may
206    /// only be done when it's safe to call `State::set_state`, like in an event handler.
207    pub states_controller: Option<Ref<MaterialStatesController>>,
208
209    /// Whether this button is in the selected state.
210    ///
211    /// If null, the button is not selectable. Otherwise, this value is the source
212    /// of truth for the button's selected state. It is written to
213    /// [`WidgetState::Selected`] when the button is first built, when a new
214    /// [`states_controller`](Self::states_controller) is provided, and whenever
215    /// [`is_selected`](Self::is_selected) changes. It also
216    /// controls the button's selected semantics. Tapping the button does not
217    /// change [`is_selected`](Self::is_selected); update it in
218    /// [`on_pressed`](Self::on_pressed) to create a toggle button.
219    ///
220    /// Avoid also updating [`WidgetState::Selected`] through
221    /// [`states_controller`](Self::states_controller). That changes only the button's
222    /// appearance, not its semantics, and is overwritten the next time
223    /// [`is_selected`](Self::is_selected) changes.
224    pub is_selected: Option<bool>,
225
226    /// Determine whether this subtree represents a button.
227    ///
228    /// If this is null, the screen reader will not announce "button" when this
229    /// is focused. This is useful for `MenuItemButton` and `SubmenuButton` when we
230    /// traverse the menu system.
231    ///
232    /// Defaults to true.
233    pub is_semantic_button: Option<bool>,
234
235    /// Determines the alignment of the icon within the button; see [`IconAlignment`].
236    #[deprecated(
237        note = "Remove this parameter as it is now ignored. Use ButtonStyle.iconAlignment instead. This feature was deprecated after v3.28.0-1.0.pre."
238    )]
239    pub icon_alignment: Option<IconAlignment>,
240
241    /// Text that describes the action that will occur when the button is pressed or
242    /// hovered over.
243    ///
244    /// This text is displayed when the user long-presses or hovers over the button
245    /// in a tooltip. This string is also used for accessibility.
246    ///
247    /// If null, the button will not display a tooltip.
248    pub tooltip: Option<String>,
249
250    /// Typically the button's label.
251    ///
252    /// The widget below this widget in the tree.
253    pub child: Option<WidgetRef>,
254}
255
256impl ButtonStyleButtonData {
257    /// The fields a subclass's constructor passes on, with Dart's `required` `onPressed` and
258    /// `child`; the rest start at the base class's defaults and are set by
259    /// [`button_style_button_setters!`](crate::button_style_button_setters).
260    pub fn new(on_pressed: Option<Listener>, child: Option<WidgetRef>) -> ButtonStyleButtonData {
261        ButtonStyleButtonData {
262            key: None,
263            on_pressed,
264            on_long_press: None,
265            on_hover: None,
266            on_focus_change: None,
267            style: None,
268            clip_behavior: None,
269            focus_node: None,
270            autofocus: false,
271            states_controller: None,
272            is_selected: None,
273            is_semantic_button: Some(true),
274            icon_alignment: None,
275            tooltip: None,
276            child,
277        }
278    }
279
280    /// Whether the button is enabled or disabled; see [`ButtonStyleButton::enabled`].
281    pub fn enabled(&self) -> bool {
282        self.on_pressed.is_some() || self.on_long_press.is_some()
283    }
284
285    /// Dart's `ButtonStyleButton.debugFillProperties`, shared by every subclass.
286    pub(crate) fn debug_fill_properties(
287        &self,
288        app: &App,
289        properties: &mut DiagnosticPropertiesBuilder,
290    ) {
291        properties.add(FlagProperty::new("enabled", Some(self.enabled())).if_false("disabled"));
292        properties.add(
293            DiagnosticsProperty::<ButtonStyle>::new("style", self.style.clone())
294                .default_value(None),
295        );
296        properties.add(
297            DiagnosticsProperty::<String>::new(
298                "focusNode",
299                self.focus_node.as_ref().map(|node| node.to_string(app)),
300            )
301            .default_value(None),
302        );
303    }
304}
305
306impl Debug for ButtonStyleButtonData {
307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308        let mut properties = f.debug_struct("ButtonStyleButton");
309        if !self.enabled() {
310            properties.field("enabled", &"disabled");
311        }
312        if self.is_selected == Some(true) {
313            properties.field("selected", &"selected");
314        }
315        if let Some(style) = &self.style {
316            properties.field("style", style);
317        }
318        if self.focus_node.is_some() {
319            properties.field("focus_node", &"FocusNode");
320        }
321        properties.finish()
322    }
323}
324
325/// The [`ButtonStyleButtonData`] accessor a [`ButtonStyleButton`] implementor writes; the bag
326/// lives under the field `button_style_button`.
327#[macro_export]
328macro_rules! button_style_button_accessors {
329    () => {
330        fn button_style_button_data(&self) -> &$crate::ButtonStyleButtonData {
331            &self.button_style_button
332        }
333    };
334}
335
336/// The fluent setters of the `super.` arguments a subclass's Dart constructor takes, named by
337/// their [`ButtonStyleButtonData`] fields: `button_style_button_setters!(TextButton; key,
338/// style, autofocus)`. Each writes the field of the bag under `button_style_button`.
339#[macro_export]
340macro_rules! button_style_button_setters {
341    ($name:ident; $($field:ident),* $(,)?) => {
342        $($crate::button_style_button_setters!(@setter $name $field);)*
343    };
344    (@setter $name:ident key) => {
345        $crate::button_style_button_setters!(@option $name key: ::waft_widgets::KeyRef => "key");
346    };
347    (@setter $name:ident on_long_press) => {
348        $crate::button_style_button_setters!(
349            @option $name on_long_press: ::waft_foundation::Listener => "onLongPress"
350        );
351    };
352    (@setter $name:ident on_hover) => {
353        $crate::button_style_button_setters!(
354            @option $name on_hover: ::waft_foundation::ValueChanged<bool> => "onHover"
355        );
356    };
357    (@setter $name:ident on_focus_change) => {
358        $crate::button_style_button_setters!(
359            @option $name on_focus_change: ::waft_foundation::ValueChanged<bool> => "onFocusChange"
360        );
361    };
362    (@setter $name:ident style) => {
363        $crate::button_style_button_setters!(@option $name style: $crate::ButtonStyle => "style");
364    };
365    (@setter $name:ident focus_node) => {
366        $crate::button_style_button_setters!(
367            @option $name focus_node: ::waft_widgets::FocusNodeRef => "focusNode"
368        );
369    };
370    (@setter $name:ident clip_behavior) => {
371        $crate::button_style_button_setters!(
372            @option $name clip_behavior: ::waft_embedder::Clip => "clipBehavior"
373        );
374    };
375    (@setter $name:ident states_controller) => {
376        $crate::button_style_button_setters!(
377            @option $name states_controller:
378                ::waft_foundation::Ref<::waft_widgets::WidgetStatesController> => "statesController"
379        );
380    };
381    (@setter $name:ident is_selected) => {
382        #[doc = concat!("Dart `", stringify!($name), "(isSelected:)`.")]
383        #[allow(clippy::wrong_self_convention)]
384        pub fn is_selected(mut self, is_selected: bool) -> $name {
385            self.button_style_button.is_selected = Some(is_selected);
386            self
387        }
388    };
389    (@setter $name:ident is_semantic_button) => {
390        #[doc = concat!("Dart `", stringify!($name), "(isSemanticButton:)`.")]
391        #[allow(clippy::wrong_self_convention)]
392        pub fn is_semantic_button(mut self, is_semantic_button: bool) -> $name {
393            self.button_style_button.is_semantic_button = Some(is_semantic_button);
394            self
395        }
396    };
397    (@setter $name:ident tooltip) => {
398        #[doc = concat!("Dart `", stringify!($name), "(tooltip:)`.")]
399        pub fn tooltip(mut self, tooltip: impl Into<String>) -> $name {
400            self.button_style_button.tooltip = Some(tooltip.into());
401            self
402        }
403    };
404    (@setter $name:ident autofocus) => {
405        #[doc = concat!("Dart `", stringify!($name), "(autofocus:)`.")]
406        pub fn autofocus(mut self, autofocus: bool) -> $name {
407            self.button_style_button.autofocus = autofocus;
408            self
409        }
410    };
411    (@option $name:ident $field:ident: $ty:ty => $dart:literal) => {
412        #[doc = concat!("Dart `", stringify!($name), "(", $dart, ":)`.")]
413        pub fn $field(mut self, $field: $ty) -> $name {
414            self.button_style_button.$field = Some($field);
415            self
416        }
417    };
418}
419
420/// The base widget for buttons whose style is defined by a [`ButtonStyle`] object; Dart's
421/// abstract `ButtonStyleButton`, whose state is [`ButtonStyleState`].
422///
423/// Concrete subclasses must override [`default_style_of`](Self::default_style_of) and
424/// [`theme_style_of`](Self::theme_style_of). A subclass is its own widget type: see the
425/// module documentation for its shape.
426///
427/// See also:
428///  * `ElevatedButton`, a filled button whose material elevates when pressed.
429///  * `FilledButton`, a filled button that doesn't elevate when pressed.
430///  * `FilledButton::tonal`, a filled button variant that uses a secondary fill color.
431///  * `OutlinedButton`, a button with an outlined border and no fill color.
432///  * `TextButton`, a button with no outline or fill color.
433///  * <https://m3.material.io/components/buttons/overview>, an overview of each of
434///    the Material Design button types and how they should be used in designs.
435pub trait ButtonStyleButton: 'static {
436    /// The [`ButtonStyleButtonData`] bag
437    /// ([`button_style_button_accessors!`](crate::button_style_button_accessors)).
438    fn button_style_button_data(&self) -> &ButtonStyleButtonData;
439
440    /// Returns a [`ButtonStyle`] that's based primarily on the `Theme`'s
441    /// `ThemeData::text_theme` and `ThemeData::color_scheme`, but has most values
442    /// filled out (non-null).
443    ///
444    /// The returned style can be overridden by the [`ButtonStyleButtonData::style`]
445    /// parameter and by the style returned by [`theme_style_of`](Self::theme_style_of) that
446    /// some button-specific themes like `TextButtonTheme` or `ElevatedButtonTheme` override.
447    /// For example the default style of the `TextButton` subclass can be overridden with its
448    /// `TextButton::style` constructor parameter, or with a `TextButtonTheme`.
449    ///
450    /// Concrete button subclasses should return a [`ButtonStyle`] with as many
451    /// non-null properties as possible, where all of the non-null
452    /// [`WidgetStateProperty`] properties resolve to non-null values.
453    ///
454    /// ## Properties that can be null
455    ///
456    /// Some properties, like [`ButtonStyle::fixed_size`] would override other values
457    /// in the same [`ButtonStyle`] if set, so they are allowed to be null.  Here is
458    /// a summary of properties that are allowed to be null when returned in the
459    /// [`ButtonStyle`] returned by this function, an why:
460    ///
461    /// - [`ButtonStyle::fixed_size`] because it would override other values in the
462    ///   same [`ButtonStyle`], like [`ButtonStyle::maximum_size`].
463    /// - [`ButtonStyle::side`] because null is a valid value for a button that has
464    ///   no side. `OutlinedButton` returns a non-null default for this, however.
465    /// - [`ButtonStyle::background_builder`] and [`ButtonStyle::foreground_builder`]
466    ///   because they would override the [`ButtonStyle::foreground_color`] and
467    ///   [`ButtonStyle::background_color`] of the same [`ButtonStyle`].
468    ///
469    /// See also:
470    ///
471    /// * [`theme_style_of`](Self::theme_style_of), returns the ButtonStyle of this button's
472    ///   component theme.
473    fn default_style_of(&self, app: &mut App, context: BuildContext)
474    -> Box<dyn ButtonStyleGetters>;
475
476    /// Returns the ButtonStyle that belongs to the button's component theme.
477    ///
478    /// The returned style can be overridden by the [`ButtonStyleButtonData::style`]
479    /// parameter.
480    ///
481    /// Concrete button subclasses should return the ButtonStyle for the
482    /// nearest subclass-specific inherited theme, and if no such theme
483    /// exists, then the same value from the overall `Theme`.
484    ///
485    /// See also:
486    ///
487    ///  * [`default_style_of`](Self::default_style_of), Returns the default [`ButtonStyle`]
488    ///    for this button.
489    fn theme_style_of(&self, app: &mut App, context: BuildContext) -> Option<ButtonStyle>;
490
491    /// Whether the button is enabled or disabled.
492    ///
493    /// Buttons are disabled by default. To enable a button, set its
494    /// [`on_pressed`](ButtonStyleButtonData::on_pressed) or
495    /// [`on_long_press`](ButtonStyleButtonData::on_long_press) properties to a non-null value.
496    fn enabled(&self) -> bool {
497        self.button_style_button_data().enabled()
498    }
499}
500
501impl dyn ButtonStyleButton {
502    /// Returns null if `value` is null, otherwise `WidgetStatePropertyAll<T>(value)`.
503    ///
504    /// A convenience method for subclasses.
505    pub fn all_or_null<T: Clone + Debug + PartialEq + 'static>(
506        value: Option<T>,
507    ) -> Option<WidgetStatePropertyRef<Option<T>>> {
508        value.map(|value| {
509            Rc::new(MaterialStatePropertyAll::new(Some(value))) as WidgetStatePropertyRef<_>
510        })
511    }
512
513    /// Returns null if `enabled` and `disabled` are null.
514    /// Otherwise, returns a [`WidgetStateProperty`] that resolves to `disabled`
515    /// when [`WidgetState::Disabled`] is active, and `enabled` otherwise.
516    ///
517    /// A convenience method for subclasses.
518    pub fn default_color(
519        enabled: Option<Color>,
520        disabled: Option<Color>,
521    ) -> Option<WidgetStatePropertyRef<Option<Color>>> {
522        enabled.or(disabled)?;
523        Some(<dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
524            (WidgetState::Disabled.into(), disabled),
525            (WidgetState::any(), enabled),
526        ]))
527    }
528
529    /// A convenience method used by subclasses in the framework, that returns an
530    /// interpolated value based on the `font_size_multiplier` parameter:
531    ///
532    ///  * 0 - 1 `geometry1x`
533    ///  * 1 - 2 lerp(`geometry1x`, `geometry2x`, `font_size_multiplier` - 1)
534    ///  * 2 - 3 lerp(`geometry2x`, `geometry3x`, `font_size_multiplier` - 2)
535    ///  * otherwise `geometry3x`
536    ///
537    /// This method is used by the framework for estimating the default paddings to
538    /// use on a button with a text label, when the system text scaling setting
539    /// changes. It's usually supplied with empirical `geometry1x`, `geometry2x`,
540    /// `geometry3x` values adjusted for different system text scaling values, when
541    /// the unscaled font size is set to 14.0 (the default `TextTheme::label_large`
542    /// value).
543    ///
544    /// The `font_size_multiplier` argument, for historical reasons, is the default
545    /// font size specified in the [`ButtonStyle`], scaled by the ambient font
546    /// scaler, then divided by 14.0 (the default font size used in buttons).
547    pub fn scaled_padding(
548        geometry1x: EdgeInsetsGeometry,
549        geometry2x: EdgeInsetsGeometry,
550        geometry3x: EdgeInsetsGeometry,
551        font_size_multiplier: f64,
552    ) -> EdgeInsetsGeometry {
553        match font_size_multiplier {
554            multiplier if multiplier <= 1.0 => geometry1x,
555            multiplier if multiplier < 2.0 => {
556                EdgeInsetsGeometry::lerp(Some(geometry1x), Some(geometry2x), multiplier - 1.0)
557                    .expect("both sides")
558            }
559            multiplier if multiplier < 3.0 => {
560                EdgeInsetsGeometry::lerp(Some(geometry2x), Some(geometry3x), multiplier - 2.0)
561                    .expect("both sides")
562            }
563            _ => geometry3x,
564        }
565    }
566}
567
568/// The base [`State`] class for buttons whose style is defined by a [`ButtonStyle`] object;
569/// Dart's private `_ButtonStyleState`, which a subclass names as its `StatefulWidget::State`.
570///
571/// See also:
572///
573///  * [`ButtonStyleButton`], the widget for which this class is the [`State`].
574///  * `ElevatedButton`, a filled button whose material elevates when pressed.
575///  * `FilledButton`, a filled ButtonStyleButton that doesn't elevate when pressed.
576///  * `OutlinedButton`, similar to `TextButton`, but with an outline.
577///  * `TextButton`, a simple button without a shadow.
578pub struct ButtonStyleState<W>
579where
580    W: ButtonStyleButton + StatefulWidget<State = ButtonStyleState<W>>,
581{
582    state: StateData<W>,
583    ticker_provider: TickerProviderStateMixinData,
584    controller: Option<Ref<AnimationController>>,
585    elevation: Option<f64>,
586    background_color: Option<Color>,
587    internal_states_controller: Option<Ref<MaterialStatesController>>,
588}
589
590impl<W> ButtonStyleState<W>
591where
592    W: ButtonStyleButton + StatefulWidget<State = ButtonStyleState<W>>,
593{
594    /// The state a subclass's `create_state` returns.
595    pub fn new() -> ButtonStyleState<W> {
596        ButtonStyleState {
597            state: StateData::new(),
598            ticker_provider: TickerProviderStateMixinData::new(),
599            controller: None,
600            elevation: None,
601            background_color: None,
602            internal_states_controller: None,
603        }
604    }
605
606    fn handle_states_controller_change(self: Handle<Self>, app: &mut App) {
607        // Force a rebuild to resolve WidgetStateProperty properties
608        self.set_state(app, |_state| {});
609    }
610
611    fn states_controller(self: Handle<Self>, app: &App) -> Ref<MaterialStatesController> {
612        self.widget(app)
613            .button_style_button_data()
614            .states_controller
615            .clone()
616            .or_else(|| app.get(self).internal_states_controller.clone())
617            .expect("created in init_states_controller")
618    }
619
620    fn init_states_controller(self: Handle<Self>, app: &mut App) {
621        if self
622            .widget(app)
623            .button_style_button_data()
624            .states_controller
625            .is_none()
626        {
627            let controller = MaterialStatesController::new(app, None);
628            app.get_mut(self).internal_states_controller = Some(controller);
629        }
630        let enabled = self.widget(app).enabled();
631        let is_selected = self.widget(app).button_style_button_data().is_selected;
632        let states_controller = self.states_controller(app);
633        states_controller.update(app, WidgetState::Disabled, !enabled);
634        if let Some(is_selected) = is_selected {
635            states_controller.update(app, WidgetState::Selected, is_selected);
636        }
637        states_controller.add_listener(
638            app,
639            Listener::handle_method(self, Self::handle_states_controller_change),
640        );
641    }
642
643    fn handle_controller_status(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
644        if status == AnimationStatus::Completed {
645            self.set_state(app, |_state| {}); // Rebuild with the final background color.
646        }
647    }
648}
649
650impl<W> Default for ButtonStyleState<W>
651where
652    W: ButtonStyleButton + StatefulWidget<State = ButtonStyleState<W>>,
653{
654    fn default() -> ButtonStyleState<W> {
655        ButtonStyleState::new()
656    }
657}
658
659impl<W> TickerProviderStateMixin for ButtonStyleState<W>
660where
661    W: ButtonStyleButton + StatefulWidget<State = ButtonStyleState<W>>,
662{
663    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
664        &app.get(self).ticker_provider
665    }
666
667    fn ticker_provider_data_mut(
668        self: Handle<Self>,
669        app: &mut App,
670    ) -> &mut TickerProviderStateMixinData {
671        &mut app.get_mut(self).ticker_provider
672    }
673}
674
675/// Dart's `vsync: this`.
676impl<W> TickerProviderObject for ButtonStyleState<W>
677where
678    W: ButtonStyleButton + StatefulWidget<State = ButtonStyleState<W>>,
679{
680    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
681        TickerProviderStateMixin::create_ticker(self, app, on_tick)
682    }
683}
684
685impl<W> State for ButtonStyleState<W>
686where
687    W: ButtonStyleButton + StatefulWidget<State = ButtonStyleState<W>>,
688{
689    type Widget = W;
690    waft_widgets::state_accessors!();
691
692    fn init_state(self: Handle<Self>, app: &mut App) {
693        self.init_states_controller(app);
694    }
695
696    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &W) {
697        let old = old_widget.button_style_button_data();
698        let widget_states_controller = self
699            .widget(app)
700            .button_style_button_data()
701            .states_controller
702            .clone();
703        if widget_states_controller != old.states_controller {
704            if let Some(old_states_controller) = old.states_controller.clone() {
705                old_states_controller.remove_listener(
706                    app,
707                    &Listener::handle_method(self, Self::handle_states_controller_change),
708                );
709            }
710            if widget_states_controller.is_some()
711                && let Some(internal) = app.get_mut(self).internal_states_controller.take()
712            {
713                internal.dispose(app);
714            }
715            self.init_states_controller(app);
716        }
717        let enabled = self.widget(app).enabled();
718        if enabled != old_widget.enabled() {
719            let states_controller = self.states_controller(app);
720            states_controller.update(app, WidgetState::Disabled, !enabled);
721            if !enabled {
722                // The button may have been disabled while a press gesture is currently underway.
723                states_controller.update(app, WidgetState::Pressed, false);
724            }
725        }
726        let is_selected = self.widget(app).button_style_button_data().is_selected;
727        if is_selected != old.is_selected {
728            let states_controller = self.states_controller(app);
729            states_controller.update(app, WidgetState::Selected, is_selected.unwrap_or(false));
730        }
731    }
732
733    fn activate(self: Handle<Self>, app: &mut App) {
734        TickerProviderStateMixin::activate(self, app);
735    }
736
737    fn dispose(self: Handle<Self>, app: &mut App) {
738        self.states_controller(app).remove_listener(
739            app,
740            &Listener::handle_method(self, Self::handle_states_controller_change),
741        );
742        if let Some(internal) = app.get_mut(self).internal_states_controller.take() {
743            internal.dispose(app);
744        }
745        if let Some(controller) = app.get(self).controller.handle() {
746            controller.dispose(app);
747        }
748        TickerProviderStateMixin::dispose(self, app);
749    }
750
751    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
752        let theme = Theme::of(app, context);
753        let icon_theme = IconTheme::of(app, context);
754        let widget_ref = context.widget(app).clone();
755        let widget =
756            downcast_widget::<W>(&*widget_ref).expect("a ButtonStyleState builds its button");
757        let button = widget.button_style_button_data();
758        let styles = ButtonStyleLayers {
759            widget_style: button.style.clone(),
760            theme_style: widget.theme_style_of(app, context),
761            default_style: widget.default_style_of(app, context),
762        };
763        let states = app.get(&self.states_controller(app)).value().clone();
764
765        let resolved_elevation = styles.resolve(app, &states, |style, app| style.elevation(app));
766        let resolved_text_style = styles.resolve(app, &states, |style, app| style.text_style(app));
767        let mut resolved_background_color =
768            styles.resolve(app, &states, |style, app| style.background_color(app));
769        let resolved_foreground_color =
770            styles.resolve(app, &states, |style, app| style.foreground_color(app));
771        let resolved_shadow_color =
772            styles.resolve(app, &states, |style, app| style.shadow_color(app));
773        let resolved_surface_tint_color =
774            styles.resolve(app, &states, |style, app| style.surface_tint_color(app));
775        let resolved_padding = styles.resolve(app, &states, |style, app| style.padding(app));
776        let resolved_minimum_size =
777            styles.resolve(app, &states, |style, app| style.minimum_size(app));
778        let resolved_fixed_size = styles.resolve(app, &states, |style, app| style.fixed_size(app));
779        let resolved_maximum_size =
780            styles.resolve(app, &states, |style, app| style.maximum_size(app));
781        let resolved_icon_color = styles.effective_icon_color(app, &states);
782        let resolved_icon_size = styles.resolve(app, &states, |style, app| style.icon_size(app));
783        let resolved_side = styles.resolve(app, &states, |style, app| style.side(app));
784        let resolved_shape = styles.resolve(app, &states, |style, app| style.shape(app));
785
786        let mouse_cursors = styles.properties(app, |style, app| style.mouse_cursor(app));
787        let mouse_cursor = mouse_cursor(move |states| {
788            ButtonStyleLayers::effective_resolved_value(&mouse_cursors, states)
789        });
790
791        let overlay_colors = styles.properties(app, |style, app| style.overlay_color(app));
792        let overlay_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
793            ButtonStyleLayers::effective_resolved_value(&overlay_colors, states)
794        });
795
796        let resolved_visual_density =
797            styles.effective_value(app, |style, app| style.visual_density(app));
798        let resolved_tap_target_size =
799            styles.effective_value(app, |style, app| style.tap_target_size(app));
800        let resolved_animation_duration =
801            styles.effective_value(app, |style, app| style.animation_duration(app));
802        let resolved_enable_feedback = styles
803            .effective_value(app, |style, app| style.enable_feedback(app))
804            .unwrap_or(true);
805        let resolved_alignment = styles.effective_value(app, |style, app| style.alignment(app));
806        let resolved_visual_density =
807            resolved_visual_density.expect("the default style has a visual density");
808        let density_adjustment = resolved_visual_density.base_size_adjustment();
809        let resolved_splash_factory =
810            styles.effective_value(app, |style, app| style.splash_factory(app));
811        let resolved_background_builder =
812            styles.effective_value(app, |style, app| style.background_builder(app));
813        let resolved_foreground_builder =
814            styles.effective_value(app, |style, app| style.foreground_builder(app));
815
816        let effective_clip_behavior = button.clip_behavior.unwrap_or(
817            if resolved_background_builder.is_some() || resolved_foreground_builder.is_some() {
818                Clip::AntiAlias
819            } else {
820                Clip::None
821            },
822        );
823
824        let resolved_minimum_size =
825            resolved_minimum_size.expect("the default style has a minimum size");
826        let resolved_maximum_size =
827            resolved_maximum_size.expect("the default style has a maximum size");
828        let mut effective_constraints = resolved_visual_density.effective_constraints(
829            BoxConstraints::new()
830                .min_width(resolved_minimum_size.width())
831                .min_height(resolved_minimum_size.height())
832                .max_width(resolved_maximum_size.width())
833                .max_height(resolved_maximum_size.height()),
834        );
835        if let Some(resolved_fixed_size) = resolved_fixed_size {
836            let size = effective_constraints.constrain(resolved_fixed_size);
837            if size.width().is_finite() {
838                effective_constraints = effective_constraints
839                    .min_width(size.width())
840                    .max_width(size.width());
841            }
842            if size.height().is_finite() {
843                effective_constraints = effective_constraints
844                    .min_height(size.height())
845                    .max_height(size.height());
846            }
847        }
848
849        // Per the Material Design team: don't allow the VisualDensity
850        // adjustment to reduce the width of the left/right padding. If we
851        // did, VisualDensity.compact, the default for desktop/web, would
852        // reduce the horizontal padding to zero.
853        let dy = density_adjustment.dy();
854        let dx = density_adjustment.dx().max(0.0);
855        let padding = resolved_padding
856            .expect("the default style has a padding")
857            .add(EdgeInsets::from_ltrb(dx, dy, dx, dy).into())
858            .clamp(&EdgeInsets::ZERO.into(), &EdgeInsetsGeometry::INFINITY);
859
860        // If an opaque button's background is becoming translucent while its
861        // elevation is changing, change the elevation first. Material implicitly
862        // animates its elevation but not its color. SKIA renders non-zero
863        // elevations as a shadow colored fill behind the Material's background.
864        let resolved_animation_duration =
865            resolved_animation_duration.expect("the default style has an animation duration");
866        let elevation = app.get(self).elevation;
867        let background_color = app.get(self).background_color;
868        if resolved_animation_duration > Duration::ZERO
869            && let Some(background_color) = background_color
870            && elevation.is_some()
871            && elevation != resolved_elevation
872            && background_color.value()
873                != resolved_background_color
874                    .expect("a background color to compare with")
875                    .value()
876            && background_color.opacity() == 1.0
877            && resolved_background_color
878                .expect("a background color to compare with")
879                .opacity()
880                < 1.0
881            && resolved_elevation == Some(0.0)
882        {
883            let controller = app.get(self).controller.handle();
884            if controller.map(|controller| app.get(controller).duration)
885                != Some(Some(resolved_animation_duration))
886            {
887                if let Some(controller) = controller {
888                    controller.dispose(app);
889                }
890                let controller = AnimationController::new(
891                    app,
892                    None,
893                    Some(resolved_animation_duration),
894                    None,
895                    0.0,
896                    1.0,
897                    AnimationBehavior::Normal,
898                    self,
899                );
900                controller.add_status_listener(
901                    app,
902                    AnimationStatusListener::handle_method(self, Self::handle_controller_status),
903                );
904                app.get_mut(self).controller = Some(controller);
905            }
906            resolved_background_color = Some(background_color); // Defer changing the background color.
907            let controller = app.get(self).controller.handle().expect("created above");
908            controller.set_value(app, 0.0);
909            controller.forward(app, None);
910        }
911        let this = app.get_mut(self);
912        this.elevation = resolved_elevation;
913        this.background_color = resolved_background_color;
914
915        let mut align = Align::new()
916            .alignment(resolved_alignment.expect("the default style has an alignment"))
917            .width_factor(1.0)
918            .height_factor(1.0);
919        align.child = match &resolved_foreground_builder {
920            Some(foreground_builder) => {
921                Some(foreground_builder.call(app, context, &states, button.child.clone()))
922            }
923            None => button.child.clone(),
924        };
925        let mut result = Padding::new(padding).child(align).into_widget();
926        if let Some(background_builder) = &resolved_background_builder {
927            result = background_builder.call(app, context, &states, Some(result));
928        }
929
930        let resolved_shape = resolved_shape.expect("the default style has a shape");
931        let mut icon_theme_data = IconThemeData::new();
932        if let Some(resolved_icon_color) = resolved_icon_color {
933            icon_theme_data = icon_theme_data.color(resolved_icon_color);
934        }
935        if let Some(resolved_icon_size) = resolved_icon_size {
936            icon_theme_data = icon_theme_data.size(resolved_icon_size);
937        }
938        let custom_border: ShapeBorderRef = resolved_shape.copy_with(resolved_side).into();
939        let mut ink_well = InkWell::new()
940            .mouse_cursor(MouseCursorRef::from(mouse_cursor))
941            .enable_feedback(resolved_enable_feedback)
942            .can_request_focus(widget.enabled())
943            .autofocus(button.autofocus)
944            .overlay_color(overlay_color)
945            .highlight_color(Colors::TRANSPARENT)
946            .custom_border(custom_border)
947            .states_controller(self.states_controller(app))
948            .child(result);
949        ink_well.ink_response.on_tap = button.on_pressed.clone();
950        ink_well.ink_response.on_long_press = button.on_long_press.clone();
951        ink_well.ink_response.on_hover = button.on_hover.clone();
952        ink_well.ink_response.focus_node = button.focus_node.clone();
953        ink_well.ink_response.on_focus_change = button.on_focus_change.clone();
954        ink_well.ink_response.splash_factory = resolved_splash_factory;
955        let mut result = AnimatedTheme::new(
956            theme
957                .copy_with()
958                .icon_theme(icon_theme.merge(Some(&icon_theme_data)))
959                .build(),
960            ink_well,
961        )
962        .duration(resolved_animation_duration)
963        .into_widget();
964
965        if let Some(tooltip) = &button.tooltip {
966            result = Tooltip::new()
967                .message(tooltip.clone())
968                .child(result)
969                .into_widget();
970        }
971
972        let min_size =
973            match resolved_tap_target_size.expect("the default style has a tap target size") {
974                MaterialTapTargetSize::Padded => {
975                    let min_size = Size::new(
976                        K_MIN_INTERACTIVE_DIMENSION + density_adjustment.dx(),
977                        K_MIN_INTERACTIVE_DIMENSION + density_adjustment.dy(),
978                    );
979                    debug_assert!(min_size.width() >= 0.0);
980                    debug_assert!(min_size.height() >= 0.0);
981                    min_size
982                }
983                MaterialTapTargetSize::ShrinkWrap => Size::ZERO,
984            };
985
986        let shape: ShapeBorderRef = resolved_shape.copy_with(resolved_side).into();
987        let mut material = Material::new()
988            .elevation(resolved_elevation.expect("the default style has an elevation"))
989            .shape(shape)
990            .r#type(if resolved_background_color.is_none() {
991                MaterialType::Transparency
992            } else {
993                MaterialType::Button
994            })
995            .animation_duration(resolved_animation_duration)
996            .clip_behavior(effective_clip_behavior)
997            .border_on_foreground(false)
998            .child(result);
999        material.text_style =
1000            resolved_text_style.map(|text_style| match resolved_foreground_color {
1001                Some(resolved_foreground_color) => {
1002                    text_style.copy_with().color(resolved_foreground_color)
1003                }
1004                None => text_style.copy_with(),
1005            });
1006        material.color = resolved_background_color;
1007        material.shadow_color = resolved_shadow_color;
1008        material.surface_tint_color = resolved_surface_tint_color;
1009
1010        let mut semantics = Semantics::new().container(true).enabled(widget.enabled());
1011        if let Some(is_semantic_button) = button.is_semantic_button {
1012            semantics = semantics.button(is_semantic_button);
1013        }
1014        if let Some(is_selected) = button.is_selected {
1015            semantics = semantics.selected(is_selected);
1016        }
1017        semantics
1018            .child(InputPadding {
1019                min_size,
1020                child: Some(
1021                    ConstrainedBox::new(effective_constraints)
1022                        .child(material)
1023                        .into_widget(),
1024                ),
1025            })
1026            .into_widget()
1027    }
1028}
1029
1030/// The three styles `_ButtonStyleState.build` reads, highest precedence first: the button's
1031/// own, its component theme's and its default. Its methods are Dart's local functions
1032/// `effectiveValue`, `resolve` and `effectiveIconColor`.
1033struct ButtonStyleLayers {
1034    widget_style: Option<ButtonStyle>,
1035    theme_style: Option<ButtonStyle>,
1036    default_style: Box<dyn ButtonStyleGetters>,
1037}
1038
1039impl ButtonStyleLayers {
1040    /// The widget's, the theme's and the default style's value of one property, which Dart's
1041    /// `effectiveValue` reads from all three.
1042    fn properties<T>(
1043        &self,
1044        app: &mut App,
1045        get_property: impl Fn(&dyn ButtonStyleGetters, &mut App) -> Option<T>,
1046    ) -> [Option<T>; 3] {
1047        let widget_value = self
1048            .widget_style
1049            .as_ref()
1050            .and_then(|style| get_property(style, app));
1051        let theme_value = self
1052            .theme_style
1053            .as_ref()
1054            .and_then(|style| get_property(style, app));
1055        let default_value = get_property(&*self.default_style, app);
1056        [widget_value, theme_value, default_value]
1057    }
1058
1059    fn effective_value<T>(
1060        &self,
1061        app: &mut App,
1062        get_property: impl Fn(&dyn ButtonStyleGetters, &mut App) -> Option<T>,
1063    ) -> Option<T> {
1064        let [widget_value, theme_value, default_value] = self.properties(app, get_property);
1065        widget_value.or(theme_value).or(default_value)
1066    }
1067
1068    fn resolve<T: 'static>(
1069        &self,
1070        app: &mut App,
1071        states: &WidgetStates,
1072        get_property: impl Fn(
1073            &dyn ButtonStyleGetters,
1074            &mut App,
1075        ) -> Option<WidgetStatePropertyRef<Option<T>>>,
1076    ) -> Option<T> {
1077        let properties = self.properties(app, get_property);
1078        ButtonStyleLayers::effective_resolved_value(&properties, states)
1079    }
1080
1081    /// Dart's `effectiveValue((style) => style?.property?.resolve(states))` over the three
1082    /// styles' properties, read when the button was built: the property a button resolves later,
1083    /// without the `App`, is a `WidgetStateProperty` it built with them.
1084    fn effective_resolved_value<T: 'static>(
1085        properties: &[Option<WidgetStatePropertyRef<Option<T>>>; 3],
1086        states: &WidgetStates,
1087    ) -> Option<T> {
1088        properties
1089            .iter()
1090            .flatten()
1091            .find_map(|property| property.resolve(states))
1092    }
1093
1094    fn effective_icon_color(&self, app: &mut App, states: &WidgetStates) -> Option<Color> {
1095        let resolve = |property: Option<WidgetStatePropertyRef<Option<Color>>>| {
1096            property.and_then(|property| property.resolve(states))
1097        };
1098        self.widget_style
1099            .as_ref()
1100            .and_then(|style| resolve(style.icon_color.clone()))
1101            .or_else(|| {
1102                self.theme_style
1103                    .as_ref()
1104                    .and_then(|style| resolve(style.icon_color.clone()))
1105            })
1106            .or_else(|| {
1107                self.widget_style
1108                    .as_ref()
1109                    .and_then(|style| resolve(style.foreground_color.clone()))
1110            })
1111            .or_else(|| {
1112                self.theme_style
1113                    .as_ref()
1114                    .and_then(|style| resolve(style.foreground_color.clone()))
1115            })
1116            .or_else(|| resolve(self.default_style.icon_color(app)))
1117            // Fallback to foregroundColor if iconColor is null.
1118            .or_else(|| resolve(self.default_style.foreground_color(app)))
1119    }
1120}
1121
1122/// Dart's `_MouseCursor`: a [`WidgetStateMouseCursor`] that resolves through
1123/// `resolve_callback`, which must answer.
1124fn mouse_cursor(
1125    resolve_callback: impl Fn(&WidgetStates) -> Option<MouseCursorRef> + 'static,
1126) -> WidgetStateMouseCursor {
1127    WidgetStateMouseCursor::resolve_with(
1128        move |states| resolve_callback(states).expect("a button style resolves a mouse cursor"),
1129        Some("ButtonStyleButton_MouseCursor"),
1130    )
1131}
1132
1133/// A widget to pad the area around a [`ButtonStyleButton`]'s inner `Material`.
1134///
1135/// Redirect taps that occur in the padded area around the child to the center
1136/// of the child. This increases the size of the button and the button's
1137/// "tap target", but not its material or its ink splashes.
1138#[derive(Debug)]
1139struct InputPadding {
1140    min_size: Size,
1141    child: Option<WidgetRef>,
1142}
1143
1144impl RenderObjectWidget for InputPadding {
1145    type RenderObject = RenderInputPadding;
1146
1147    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1148        RenderInputPadding::new(app, self.min_size, None).as_object()
1149    }
1150
1151    fn update_render_object(
1152        &self,
1153        app: &mut App,
1154        _context: BuildContext,
1155        render_object: RenderHandle<RenderInputPadding>,
1156    ) {
1157        render_object.set_min_size(app, self.min_size);
1158    }
1159}
1160
1161impl SingleChildRenderObjectWidget for InputPadding {
1162    fn child(&self) -> Option<&WidgetRef> {
1163        self.child.as_ref()
1164    }
1165}
1166
1167/// Dart's `_RenderInputPadding`.
1168struct RenderInputPadding {
1169    render_object: RenderObjectData,
1170    render_box: RenderBoxData,
1171    child: RenderObjectWithChildData<AnyRenderBox>,
1172    min_size: Size,
1173}
1174
1175impl RenderInputPadding {
1176    fn new(
1177        app: &mut App,
1178        min_size: Size,
1179        child: Option<AnyRenderBox>,
1180    ) -> RenderHandle<RenderInputPadding> {
1181        let this = RenderHandle::new_box(
1182            app,
1183            RenderInputPadding {
1184                render_object: RenderObjectData::new(),
1185                render_box: RenderBoxData::new(),
1186                child: RenderObjectWithChildData::new(),
1187                min_size,
1188            },
1189        );
1190        this.set_child(app, child);
1191        this
1192    }
1193
1194    fn min_size(self: RenderHandle<Self>, app: &App) -> Size {
1195        self.get(app).min_size
1196    }
1197
1198    fn set_min_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
1199        if self.get(app).min_size == value {
1200            return;
1201        }
1202        self.get_mut(app).min_size = value;
1203        RenderBox::mark_needs_layout(self, app);
1204    }
1205
1206    fn compute_size(
1207        self: RenderHandle<Self>,
1208        app: &mut App,
1209        constraints: BoxConstraints,
1210        layout_child: ChildLayouter,
1211    ) -> Size {
1212        if let Some(child) = self.child(app) {
1213            let child_size = layout_child(app, child, constraints);
1214            let min_size = self.min_size(app);
1215            let width = child_size.width().max(min_size.width());
1216            let height = child_size.height().max(min_size.height());
1217            return constraints.constrain(Size::new(width, height));
1218        }
1219        Size::ZERO
1220    }
1221}
1222
1223impl RenderObjectWithChildMixin for RenderInputPadding {
1224    type ChildType = AnyRenderBox;
1225
1226    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1227        &self.get(app).child
1228    }
1229
1230    fn child_data_mut(
1231        self: RenderHandle<Self>,
1232        app: &mut App,
1233    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1234        &mut self.get_mut(app).child
1235    }
1236}
1237
1238impl RenderShiftedBox for RenderInputPadding {}
1239
1240impl RenderObject for RenderInputPadding {
1241    waft_rendering::render_object_accessors!();
1242
1243    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1244        let constraints = self.constraints(app);
1245        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
1246        self.set_size(app, size);
1247        if let Some(child) = self.child(app) {
1248            let child_size = child.size(app);
1249            child.parent_data_of_mut::<BoxParentData>(app).offset =
1250                Alignment::CENTER.along_offset(size - child_size);
1251        }
1252    }
1253
1254    fn paint(
1255        self: RenderHandle<Self>,
1256        app: &mut App,
1257        context: &mut PaintingContext,
1258        offset: Offset,
1259    ) {
1260        RenderShiftedBox::paint(self, app, context, offset);
1261    }
1262
1263    fn visit_children(
1264        self: RenderHandle<Self>,
1265        app: &App,
1266        visitor: &mut dyn FnMut(AnyRenderObject),
1267    ) {
1268        if let Some(child) = self.child(app) {
1269            visitor(child.as_object());
1270        }
1271    }
1272}
1273
1274impl RenderBox for RenderInputPadding {
1275    waft_rendering::render_box_accessors!();
1276
1277    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1278        if let Some(child) = self.child(app) {
1279            return child
1280                .get_min_intrinsic_width(app, height)
1281                .max(self.min_size(app).width());
1282        }
1283        0.0
1284    }
1285
1286    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1287        if let Some(child) = self.child(app) {
1288            return child
1289                .get_min_intrinsic_height(app, width)
1290                .max(self.min_size(app).height());
1291        }
1292        0.0
1293    }
1294
1295    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1296        if let Some(child) = self.child(app) {
1297            return child
1298                .get_max_intrinsic_width(app, height)
1299                .max(self.min_size(app).width());
1300        }
1301        0.0
1302    }
1303
1304    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1305        if let Some(child) = self.child(app) {
1306            return child
1307                .get_max_intrinsic_height(app, width)
1308                .max(self.min_size(app).height());
1309        }
1310        0.0
1311    }
1312
1313    fn compute_dry_layout(
1314        self: RenderHandle<Self>,
1315        app: &mut App,
1316        constraints: BoxConstraints,
1317    ) -> Size {
1318        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
1319    }
1320
1321    fn compute_dry_baseline(
1322        self: RenderHandle<Self>,
1323        app: &mut App,
1324        constraints: BoxConstraints,
1325        baseline: TextBaseline,
1326    ) -> Option<f64> {
1327        let child = self.child(app)?;
1328        let result = child.get_dry_baseline(app, constraints, baseline)?;
1329        let child_size = child.get_dry_layout(app, constraints);
1330        let size = self.as_box().get_dry_layout(app, constraints);
1331        Some(result + Alignment::CENTER.along_offset(size - child_size).dy())
1332    }
1333
1334    fn compute_distance_to_actual_baseline(
1335        self: RenderHandle<Self>,
1336        app: &mut App,
1337        baseline: TextBaseline,
1338    ) -> Option<f64> {
1339        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1340    }
1341
1342    fn hit_test_children(
1343        self: RenderHandle<Self>,
1344        app: &mut App,
1345        result: &mut BoxHitTestResult<'_>,
1346        position: Offset,
1347    ) -> bool {
1348        RenderShiftedBox::hit_test_children(self, app, result, position)
1349    }
1350
1351    fn hit_test(
1352        self: RenderHandle<Self>,
1353        app: &mut App,
1354        result: &mut BoxHitTestResult<'_>,
1355        position: Offset,
1356    ) -> bool {
1357        if RenderBoxBase::hit_test(self, app, result, position) {
1358            return true;
1359        }
1360        let child = self.child(app).expect("an input padding has a child");
1361        let center = child.size(app).center(Offset::ZERO);
1362        result.add_with_raw_transform(Some(force_to_point(center)), center, |result, position| {
1363            debug_assert!(
1364                (position.dx() - center.dx()).abs() <= center.dx().abs() * f32::EPSILON as f64
1365                    && (position.dy() - center.dy()).abs()
1366                        <= center.dy().abs() * f32::EPSILON as f64,
1367                "the forced transform maps every hit to the child's center"
1368            );
1369            child.hit_test(app, result, center)
1370        })
1371    }
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376    use std::cell::{Cell, RefCell};
1377    use waft_painting::OutlinedBorderRef;
1378
1379    use waft_embedder::{Radius, Rect, TextDirection};
1380    use waft_painting::{AlignmentGeometry, BorderRadius, BoxDecoration, RoundedRectangleBorder};
1381    use waft_rendering::{
1382        RenderClipPath, RenderCustomClip, RenderDecoratedBox, RenderPhysicalModelBase,
1383        RenderPhysicalShape,
1384    };
1385    use waft_services::SystemMouseCursors;
1386    use waft_widgets::{
1387        Builder, Center, Column, DecoratedBox, DefaultTextStyle, Directionality, FocusNode,
1388        GlobalKey, MainAxisSize, SizedBox, WidgetStatePropertyAll,
1389    };
1390
1391    use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
1392
1393    use super::*;
1394    use crate::button_style::ButtonLayerBuilder;
1395    use crate::color_scheme::ColorScheme;
1396    use crate::constants::K_THEME_CHANGE_DURATION;
1397    use crate::ink_ripple::InkRipple;
1398    use crate::theme_data::{ThemeData, VisualDensity};
1399
1400    /// A leaf of [`ButtonStyleButton`] whose default style is Dart's `ElevatedButton`'s in
1401    /// Material 2 at a text scale of 1, with no component theme: the base class's behaviour
1402    /// is what the cases below test, as Flutter's do through a concrete button.
1403    struct TestButton {
1404        button_style_button: ButtonStyleButtonData,
1405    }
1406
1407    impl TestButton {
1408        fn new<K>(on_pressed: Option<Listener>, child: impl IntoWidget<K>) -> TestButton {
1409            TestButton {
1410                button_style_button: ButtonStyleButtonData::new(
1411                    on_pressed,
1412                    Some(child.into_widget()),
1413                ),
1414            }
1415        }
1416
1417        crate::button_style_button_setters!(
1418            TestButton;
1419            key, on_long_press, style, focus_node, states_controller, is_selected,
1420        );
1421    }
1422
1423    fn all<T: Clone + Debug + PartialEq + 'static>(value: T) -> WidgetStatePropertyRef<Option<T>> {
1424        Rc::new(WidgetStatePropertyAll::new(Some(value)))
1425    }
1426
1427    impl ButtonStyleButton for TestButton {
1428        crate::button_style_button_accessors!();
1429
1430        // `ElevatedButton.defaultStyleOf`'s Material 2 branch, through `styleFrom`.
1431        fn default_style_of(
1432            &self,
1433            app: &mut App,
1434            context: BuildContext,
1435        ) -> Box<dyn ButtonStyleGetters> {
1436            let theme = Theme::of(app, context);
1437            let color_scheme = &theme.color_scheme;
1438            let on_primary = color_scheme.on_primary();
1439            Box::new(
1440                ButtonStyle::new()
1441                    .text_style(Rc::new(WidgetStatePropertyAll::new(
1442                        theme.text_theme.label_large.clone(),
1443                    )))
1444                    .background_color(
1445                        <dyn ButtonStyleButton>::default_color(
1446                            Some(color_scheme.primary()),
1447                            Some(color_scheme.on_surface().with_opacity(0.12)),
1448                        )
1449                        .expect("both colors"),
1450                    )
1451                    .foreground_color(
1452                        <dyn ButtonStyleButton>::default_color(
1453                            Some(on_primary),
1454                            Some(color_scheme.on_surface().with_opacity(0.38)),
1455                        )
1456                        .expect("both colors"),
1457                    )
1458                    .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
1459                        (
1460                            WidgetState::Pressed.into(),
1461                            Some(on_primary.with_opacity(0.1)),
1462                        ),
1463                        (
1464                            WidgetState::Hovered.into(),
1465                            Some(on_primary.with_opacity(0.08)),
1466                        ),
1467                        (
1468                            WidgetState::Focused.into(),
1469                            Some(on_primary.with_opacity(0.1)),
1470                        ),
1471                        (WidgetState::any(), None),
1472                    ]))
1473                    .shadow_color(all(theme.shadow_color))
1474                    .elevation(<dyn WidgetStateProperty<Option<f64>>>::from_map(vec![
1475                        (WidgetState::Disabled.into(), Some(0.0)),
1476                        (WidgetState::Pressed.into(), Some(2.0 + 6.0)),
1477                        (WidgetState::Hovered.into(), Some(2.0 + 2.0)),
1478                        (WidgetState::Focused.into(), Some(2.0 + 2.0)),
1479                        (WidgetState::any(), Some(2.0)),
1480                    ]))
1481                    .padding(all(EdgeInsetsGeometry::symmetric(0.0, 16.0)))
1482                    .minimum_size(all(Size::new(64.0, 36.0)))
1483                    .maximum_size(all(Size::INFINITE))
1484                    .shape(all(OutlinedBorderRef::new(RoundedRectangleBorder::new(
1485                        waft_painting::BorderSide::NONE,
1486                        BorderRadius::all(Radius::circular(4.0)).into(),
1487                    ))))
1488                    .mouse_cursor(<dyn WidgetStateProperty<Option<MouseCursorRef>>>::from_map(
1489                        vec![
1490                            (
1491                                WidgetState::Disabled.into(),
1492                                Some(SystemMouseCursors::BASIC.into()),
1493                            ),
1494                            (WidgetState::any(), Some(SystemMouseCursors::BASIC.into())),
1495                        ],
1496                    ))
1497                    .visual_density(theme.visual_density)
1498                    .tap_target_size(theme.material_tap_target_size)
1499                    .animation_duration(K_THEME_CHANGE_DURATION)
1500                    .enable_feedback(true)
1501                    .alignment(AlignmentGeometry::CENTER)
1502                    .splash_factory(InkRipple::splash_factory()),
1503            )
1504        }
1505
1506        fn theme_style_of(&self, _app: &mut App, _context: BuildContext) -> Option<ButtonStyle> {
1507            None
1508        }
1509    }
1510
1511    impl StatefulWidget for TestButton {
1512        type State = ButtonStyleState<TestButton>;
1513
1514        fn key(&self) -> Option<&KeyRef> {
1515            self.button_style_button.key.as_ref()
1516        }
1517
1518        fn create_state(&self) -> ButtonStyleState<TestButton> {
1519            ButtonStyleState::new()
1520        }
1521    }
1522
1523    impl Debug for TestButton {
1524        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1525            Debug::fmt(&self.button_style_button, f)
1526        }
1527    }
1528
1529    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
1530        Directionality::new(TextDirection::Ltr, child).into_widget()
1531    }
1532
1533    /// `MaterialApp(theme: theme, home: child)`, as far as a button reads it.
1534    fn themed<K>(tester: &WidgetTester, theme: ThemeData, child: impl IntoWidget<K>) -> WidgetRef {
1535        let _ = tester;
1536        Theme::new(theme, ltr(child)).into_widget()
1537    }
1538
1539    fn material2(tester: &WidgetTester) -> ThemeData {
1540        ThemeData::builder()
1541            .use_material3(false)
1542            .build(&tester.cell.borrow())
1543    }
1544
1545    fn pressed() -> Listener {
1546        Listener::new(|_app| {})
1547    }
1548
1549    fn rect_of(tester: &WidgetTester, key: &GlobalKey) -> Rect {
1550        let render = tester.render_object(key).as_box().expect("a render box");
1551        let app = tester.cell.borrow();
1552        render.local_to_global(&app, Offset::ZERO, None) & render.size(&app)
1553    }
1554
1555    fn sized(width: f64, height: f64) -> SizedBox {
1556        SizedBox::new().width(width).height(height)
1557    }
1558
1559    fn counter(count: &Rc<Cell<usize>>) -> Listener {
1560        let count = Rc::clone(count);
1561        Listener::new(move |_app| count.set(count.get() + 1))
1562    }
1563
1564    fn states(states: &[WidgetState]) -> WidgetStates {
1565        states.iter().copied().collect()
1566    }
1567
1568    fn value(tester: &WidgetTester, controller: Handle<MaterialStatesController>) -> WidgetStates {
1569        tester.cell.borrow().get(controller).value().clone()
1570    }
1571
1572    fn physical_shape(tester: &WidgetTester) -> (f64, Color) {
1573        let shape = tester.first::<RenderPhysicalShape>();
1574        let app = tester.cell.borrow();
1575        (shape.elevation(&app), shape.color(&app))
1576    }
1577
1578    #[test]
1579    fn default_color_is_null_without_colors_and_resolves_disabled_apart() {
1580        assert!(<dyn ButtonStyleButton>::default_color(None, None).is_none());
1581        let red = Color::new(0xffff0000);
1582        let blue = Color::new(0xff0000ff);
1583        let color =
1584            <dyn ButtonStyleButton>::default_color(Some(red), Some(blue)).expect("two colors");
1585        assert_eq!(color.resolve(&WidgetStates::new()), Some(red));
1586        assert_eq!(color.resolve(&states(&[WidgetState::Disabled])), Some(blue));
1587        let only_disabled =
1588            <dyn ButtonStyleButton>::default_color(None, Some(blue)).expect("one color");
1589        assert_eq!(only_disabled.resolve(&WidgetStates::new()), None);
1590        assert!(<dyn ButtonStyleButton>::all_or_null::<f64>(None).is_none());
1591        assert_eq!(
1592            <dyn ButtonStyleButton>::all_or_null(Some(2.0))
1593                .expect("a value")
1594                .resolve(&WidgetStates::new()),
1595            Some(2.0)
1596        );
1597    }
1598
1599    #[test]
1600    fn scaled_padding_interpolates_between_the_three_geometries() {
1601        let one = EdgeInsetsGeometry::all(12.0);
1602        let two = EdgeInsetsGeometry::all(8.0);
1603        let three = EdgeInsetsGeometry::all(4.0);
1604        let scaled =
1605            |multiplier| <dyn ButtonStyleButton>::scaled_padding(one, two, three, multiplier);
1606        assert!(scaled(0.5) == one);
1607        assert!(scaled(1.0) == one);
1608        assert!(scaled(1.5) == EdgeInsetsGeometry::all(10.0));
1609        assert!(scaled(2.5) == EdgeInsetsGeometry::all(6.0));
1610        assert!(scaled(3.0) == three);
1611    }
1612
1613    // elevated_button_test.dart 'ElevatedButton onPressed and onLongPress callbacks are
1614    // distinctly recognized'.
1615    #[test]
1616    fn a_tap_and_a_long_press_reach_their_own_callbacks() {
1617        test_widgets(|tester| {
1618            let did_press_button = Rc::new(Cell::new(0));
1619            let did_long_press_button = Rc::new(Cell::new(0));
1620            let key = GlobalKey::new();
1621            tester.pump_widget(ltr(Center::new().child(
1622                TestButton::new(Some(counter(&did_press_button)), sized(100.0, 20.0))
1623                    .on_long_press(counter(&did_long_press_button))
1624                    .key(key.clone().into()),
1625            )));
1626            let center = tester.get_center(&key);
1627
1628            assert_eq!(did_press_button.get(), 0);
1629            tester.tap_at(center, 1);
1630            tester.pump_and_settle();
1631            assert_eq!(did_press_button.get(), 1);
1632
1633            assert_eq!(did_long_press_button.get(), 0);
1634            tester.long_press_at(center, 2);
1635            tester.pump_and_settle();
1636            assert_eq!(did_long_press_button.get(), 1);
1637        });
1638    }
1639
1640    // elevated_button_test.dart 'ElevatedButton size is configurable by
1641    // ThemeData.materialTapTargetSize'.
1642    #[test]
1643    fn the_theme_tap_target_size_pads_the_button_to_48() {
1644        test_widgets(|tester| {
1645            // Specifying minimumSize to mimic the original minimumSize for
1646            // RaisedButton so that the corresponding button size matches
1647            // the original version of this test.
1648            let style = ButtonStyle::new().minimum_size(all(Size::new(88.0, 36.0)));
1649            let build_frame =
1650                |tester: &WidgetTester, tap_target_size: MaterialTapTargetSize, key: &GlobalKey| {
1651                    let theme = ThemeData::builder()
1652                        .use_material3(false)
1653                        .material_tap_target_size(tap_target_size)
1654                        .build(&tester.cell.borrow());
1655                    themed(
1656                        tester,
1657                        theme,
1658                        Center::new().child(
1659                            TestButton::new(Some(pressed()), sized(50.0, 8.0))
1660                                .key(key.clone().into())
1661                                .style(style.clone()),
1662                        ),
1663                    )
1664                };
1665
1666            let key1 = GlobalKey::new();
1667            let frame = build_frame(tester, MaterialTapTargetSize::Padded, &key1);
1668            tester.pump_widget(frame);
1669            assert_eq!(tester.get_size(&key1), Size::new(88.0, 48.0));
1670
1671            let key2 = GlobalKey::new();
1672            let frame = build_frame(tester, MaterialTapTargetSize::ShrinkWrap, &key2);
1673            tester.pump_widget(frame);
1674            assert_eq!(tester.get_size(&key2), Size::new(88.0, 36.0));
1675        });
1676    }
1677
1678    // elevated_button_test.dart 'ElevatedButton has no clip by default': nothing in the
1679    // button clips, so it paints no `clipPath`.
1680    #[test]
1681    fn a_button_does_not_clip_by_default() {
1682        test_widgets(|tester| {
1683            tester.pump_widget(ltr(TestButton::new(Some(pressed()), sized(10.0, 10.0))));
1684            let shape = tester.first::<RenderPhysicalShape>();
1685            assert_eq!(
1686                RenderCustomClip::clip_behavior(shape, &tester.cell.borrow()),
1687                Clip::None
1688            );
1689            assert!(tester.all::<RenderClipPath>().is_empty());
1690        });
1691    }
1692
1693    // elevated_button_test.dart 'ElevatedButton responds to density changes.'; the `Text`
1694    // child is the 56x14 box FlutterTest lays 'Text' out in.
1695    #[test]
1696    fn visual_density_grows_and_shrinks_the_button_around_its_child() {
1697        test_widgets(|tester| {
1698            let key = GlobalKey::new();
1699            let child_key = GlobalKey::new();
1700            let build_test =
1701                |tester: &mut WidgetTester, visual_density: VisualDensity, use_text: bool| {
1702                    let child = if use_text {
1703                        sized(56.0, 14.0).key(child_key.clone().into())
1704                    } else {
1705                        sized(100.0, 100.0).key(child_key.clone().into())
1706                    };
1707                    let theme = material2(tester);
1708                    let frame = Theme::new(
1709                        theme,
1710                        Directionality::new(
1711                            TextDirection::Rtl,
1712                            Center::new().child(
1713                                TestButton::new(Some(pressed()), child)
1714                                    .style(
1715                                        ButtonStyle::new()
1716                                            .visual_density(visual_density)
1717                                            // Specifying minimumSize to mimic the original
1718                                            // minimumSize for RaisedButton so that the
1719                                            // corresponding button size matches the original
1720                                            // version of this test.
1721                                            .minimum_size(all(Size::new(88.0, 36.0))),
1722                                    )
1723                                    .key(key.clone().into()),
1724                            ),
1725                        ),
1726                    )
1727                    .into_widget();
1728                    tester.pump_widget(frame);
1729                };
1730
1731            build_test(tester, VisualDensity::STANDARD, false);
1732            let child_rect = rect_of(tester, &child_key);
1733            tester.pump_and_settle();
1734            assert_eq!(tester.get_size(&key), Size::new(132.0, 100.0));
1735            assert_eq!(child_rect, Rect::from_ltrb(350.0, 250.0, 450.0, 350.0));
1736
1737            build_test(tester, VisualDensity::new(3.0, 3.0), false);
1738            tester.pump_and_settle();
1739            assert_eq!(tester.get_size(&key), Size::new(156.0, 124.0));
1740            assert_eq!(
1741                rect_of(tester, &child_key),
1742                Rect::from_ltrb(350.0, 250.0, 450.0, 350.0)
1743            );
1744
1745            build_test(tester, VisualDensity::new(-3.0, -3.0), false);
1746            tester.pump_and_settle();
1747            assert_eq!(tester.get_size(&key), Size::new(132.0, 100.0));
1748            assert_eq!(
1749                rect_of(tester, &child_key),
1750                Rect::from_ltrb(350.0, 250.0, 450.0, 350.0)
1751            );
1752
1753            build_test(tester, VisualDensity::STANDARD, true);
1754            tester.pump_and_settle();
1755            assert_eq!(tester.get_size(&key), Size::new(88.0, 48.0));
1756            assert_eq!(
1757                rect_of(tester, &child_key),
1758                Rect::from_ltrb(372.0, 293.0, 428.0, 307.0)
1759            );
1760
1761            build_test(tester, VisualDensity::new(3.0, 3.0), true);
1762            tester.pump_and_settle();
1763            assert_eq!(tester.get_size(&key), Size::new(112.0, 60.0));
1764            assert_eq!(
1765                rect_of(tester, &child_key),
1766                Rect::from_ltrb(372.0, 293.0, 428.0, 307.0)
1767            );
1768
1769            build_test(tester, VisualDensity::new(-3.0, -3.0), true);
1770            tester.pump_and_settle();
1771            assert_eq!(tester.get_size(&key), Size::new(88.0, 36.0));
1772            assert_eq!(
1773                rect_of(tester, &child_key),
1774                Rect::from_ltrb(372.0, 293.0, 428.0, 307.0)
1775            );
1776        });
1777    }
1778
1779    // elevated_button_test.dart 'Elevated buttons animate elevation before color on disable'.
1780    #[test]
1781    fn a_disabled_button_lowers_its_elevation_before_it_changes_color() {
1782        // This is a regression test for https://github.com/flutter/flutter/issues/387
1783        test_widgets(|tester| {
1784            let color_scheme = ColorScheme::light();
1785            let background_color = color_scheme.primary();
1786            let disabled_background_color = color_scheme.on_surface().with_opacity(0.12);
1787            let build_frame = |tester: &WidgetTester, enabled: bool| {
1788                let theme = ThemeData::from(color_scheme.clone())
1789                    .use_material3(false)
1790                    .build(&tester.cell.borrow());
1791                themed(
1792                    tester,
1793                    theme,
1794                    Center::new().child(TestButton::new(enabled.then(pressed), sized(40.0, 10.0))),
1795                )
1796            };
1797
1798            // Default elevation is 2, background color is primary.
1799            let frame = build_frame(tester, true);
1800            tester.pump_widget(frame);
1801            assert_eq!(physical_shape(tester), (2.0, background_color));
1802
1803            // Disabled elevation animates to 0 over 200ms, THEN the background
1804            // color changes to onSurface.withOpacity(0.12)
1805            let frame = build_frame(tester, false);
1806            tester.pump_widget(frame);
1807            tester.pump_by(Duration::from_millis(50));
1808            let (elevation, color) = physical_shape(tester);
1809            assert!(elevation < 2.0);
1810            assert_eq!(color, background_color);
1811            tester.pump_by(Duration::from_millis(150));
1812            assert_eq!(physical_shape(tester), (0.0, background_color));
1813            tester.pump_and_settle();
1814            assert_eq!(physical_shape(tester), (0.0, disabled_background_color));
1815        });
1816    }
1817
1818    // elevated_button_test.dart 'Fixed size ElevatedButtons'.
1819    #[test]
1820    fn a_fixed_size_sets_each_finite_dimension() {
1821        test_widgets(|tester| {
1822            let keys = [GlobalKey::new(), GlobalKey::new(), GlobalKey::new()];
1823            let fixed_sizes = [
1824                Size::new(100.0, 100.0),
1825                Size::from_width(200.0),
1826                Size::from_height(200.0),
1827            ];
1828            let buttons = keys.iter().zip(fixed_sizes).map(|(key, fixed_size)| {
1829                TestButton::new(Some(pressed()), sized(20.0, 10.0))
1830                    .key(key.clone().into())
1831                    .style(ButtonStyle::new().fixed_size(all(fixed_size)))
1832                    .into_widget()
1833            });
1834            let theme = ThemeData::new(&tester.cell.borrow());
1835            let frame = themed(
1836                tester,
1837                theme,
1838                Column::new()
1839                    .main_axis_size(MainAxisSize::Min)
1840                    .children(buttons.collect::<Vec<_>>()),
1841            );
1842            tester.pump_widget(frame);
1843
1844            assert_eq!(tester.get_size(&keys[0]), Size::new(100.0, 100.0));
1845            assert_eq!(tester.get_size(&keys[1]).width(), 200.0);
1846            assert_eq!(tester.get_size(&keys[2]).height(), 200.0);
1847        });
1848    }
1849
1850    // elevated_button_test.dart 'Fixed size ElevatedButton, same as minimumSize == maximumSize'.
1851    #[test]
1852    fn a_fixed_size_sizes_like_equal_minimum_and_maximum_sizes() {
1853        test_widgets(|tester| {
1854            let fixed = GlobalKey::new();
1855            let bounded = GlobalKey::new();
1856            let theme = ThemeData::new(&tester.cell.borrow());
1857            let frame = themed(
1858                tester,
1859                theme,
1860                Column::new().main_axis_size(MainAxisSize::Min).children([
1861                    TestButton::new(Some(pressed()), sized(20.0, 10.0))
1862                        .key(fixed.clone().into())
1863                        .style(ButtonStyle::new().fixed_size(all(Size::new(200.0, 200.0))))
1864                        .into_widget(),
1865                    TestButton::new(Some(pressed()), sized(20.0, 10.0))
1866                        .key(bounded.clone().into())
1867                        .style(
1868                            ButtonStyle::new()
1869                                .minimum_size(all(Size::new(200.0, 200.0)))
1870                                .maximum_size(all(Size::new(200.0, 200.0))),
1871                        )
1872                        .into_widget(),
1873                ]),
1874            );
1875            tester.pump_widget(frame);
1876
1877            assert_eq!(tester.get_size(&fixed), Size::new(200.0, 200.0));
1878            assert_eq!(tester.get_size(&bounded), Size::new(200.0, 200.0));
1879        });
1880    }
1881
1882    // elevated_button_test.dart 'ElevatedButton statesController'.
1883    #[test]
1884    fn a_states_controller_follows_hover_press_and_disable() {
1885        test_widgets(|tester| {
1886            let count = Rc::new(Cell::new(0));
1887            let controller = MaterialStatesController::new(&mut tester.cell.borrow_mut(), None);
1888            controller.add_listener(&mut tester.cell.borrow_mut(), counter(&count));
1889            let key = GlobalKey::new();
1890            let build_frame = |tester: &WidgetTester, enabled: bool| {
1891                let theme = ThemeData::new(&tester.cell.borrow());
1892                themed(
1893                    tester,
1894                    theme,
1895                    Center::new().child(
1896                        TestButton::new(enabled.then(pressed), sized(40.0, 10.0))
1897                            .key(key.clone().into())
1898                            .states_controller(controller.clone()),
1899                    ),
1900                )
1901            };
1902
1903            let frame = build_frame(tester, true);
1904            tester.pump_widget(frame);
1905
1906            assert_eq!(value(tester, controller.handle()), states(&[]));
1907            assert_eq!(count.get(), 0);
1908
1909            let center = tester.get_center(&key);
1910            let mut gesture: TestPointer = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1911            tester.add_pointer(&mut gesture, Offset::ZERO);
1912            tester.move_to(&mut gesture, center, false);
1913            tester.pump_and_settle();
1914
1915            assert_eq!(
1916                value(tester, controller.handle()),
1917                states(&[WidgetState::Hovered])
1918            );
1919            assert_eq!(count.get(), 1);
1920
1921            tester.move_to(&mut gesture, Offset::ZERO, false);
1922            tester.pump_and_settle();
1923
1924            assert_eq!(value(tester, controller.handle()), states(&[]));
1925            assert_eq!(count.get(), 2);
1926
1927            tester.move_to(&mut gesture, center, false);
1928            tester.pump_and_settle();
1929
1930            assert_eq!(
1931                value(tester, controller.handle()),
1932                states(&[WidgetState::Hovered])
1933            );
1934            assert_eq!(count.get(), 3);
1935
1936            tester.send(&gesture, waft_embedder::PointerChange::Down);
1937            tester.pump_and_settle();
1938
1939            assert_eq!(
1940                value(tester, controller.handle()),
1941                states(&[WidgetState::Hovered, WidgetState::Pressed])
1942            );
1943            assert_eq!(count.get(), 4);
1944
1945            tester.up(&gesture);
1946            tester.pump_and_settle();
1947
1948            assert_eq!(
1949                value(tester, controller.handle()),
1950                states(&[WidgetState::Hovered])
1951            );
1952            assert_eq!(count.get(), 5);
1953
1954            tester.move_to(&mut gesture, Offset::ZERO, false);
1955            tester.pump_and_settle();
1956
1957            assert_eq!(value(tester, controller.handle()), states(&[]));
1958            assert_eq!(count.get(), 6);
1959
1960            tester.down(&mut gesture, center);
1961            tester.pump_and_settle();
1962            assert_eq!(
1963                value(tester, controller.handle()),
1964                states(&[WidgetState::Hovered, WidgetState::Pressed])
1965            );
1966            assert_eq!(count.get(), 8); // adds hovered and pressed - two changes
1967
1968            // If the button is rebuilt disabled, then the pressed state is
1969            // removed.
1970            let frame = build_frame(tester, false);
1971            tester.pump_widget(frame);
1972            tester.pump_and_settle();
1973            assert_eq!(
1974                value(tester, controller.handle()),
1975                states(&[WidgetState::Hovered, WidgetState::Disabled])
1976            );
1977            assert_eq!(count.get(), 10); // removes pressed and adds disabled - two changes
1978            tester.move_to(&mut gesture, Offset::ZERO, true);
1979            tester.pump_and_settle();
1980            assert_eq!(
1981                value(tester, controller.handle()),
1982                states(&[WidgetState::Disabled])
1983            );
1984            assert_eq!(count.get(), 11);
1985        });
1986    }
1987
1988    // elevated_button_test.dart 'Disabled ElevatedButton statesController'.
1989    #[test]
1990    fn a_disabled_button_marks_its_states_controller_disabled() {
1991        test_widgets(|tester| {
1992            let count = Rc::new(Cell::new(0));
1993            let controller = MaterialStatesController::new(&mut tester.cell.borrow_mut(), None);
1994            controller.add_listener(&mut tester.cell.borrow_mut(), counter(&count));
1995            let theme = ThemeData::new(&tester.cell.borrow());
1996            let frame = themed(
1997                tester,
1998                theme,
1999                Center::new().child(
2000                    TestButton::new(None, sized(40.0, 10.0)).states_controller(controller.clone()),
2001                ),
2002            );
2003            tester.pump_widget(frame);
2004            assert_eq!(
2005                value(tester, controller.handle()),
2006                states(&[WidgetState::Disabled])
2007            );
2008            assert_eq!(count.get(), 1);
2009        });
2010    }
2011
2012    // elevated_button_test.dart 'ElevatedButton isSelected updates a provided statesController'.
2013    #[test]
2014    fn is_selected_writes_the_selected_state_of_a_provided_controller() {
2015        test_widgets(|tester| {
2016            let controller = MaterialStatesController::new(&mut tester.cell.borrow_mut(), None);
2017            let build_button = |tester: &WidgetTester, is_selected: Option<bool>| {
2018                let mut button = TestButton::new(Some(pressed()), sized(40.0, 10.0))
2019                    .states_controller(controller.clone());
2020                button.button_style_button.is_selected = is_selected;
2021                let theme = ThemeData::new(&tester.cell.borrow());
2022                themed(tester, theme, Center::new().child(button))
2023            };
2024
2025            let frame = build_button(tester, Some(true));
2026            tester.pump_widget(frame);
2027            assert!(value(tester, controller.handle()).contains(&WidgetState::Selected));
2028
2029            let frame = build_button(tester, Some(false));
2030            tester.pump_widget(frame);
2031            assert!(!value(tester, controller.handle()).contains(&WidgetState::Selected));
2032
2033            let frame = build_button(tester, Some(true));
2034            tester.pump_widget(frame);
2035            assert!(value(tester, controller.handle()).contains(&WidgetState::Selected));
2036
2037            let frame = build_button(tester, None);
2038            tester.pump_widget(frame);
2039            assert!(!value(tester, controller.handle()).contains(&WidgetState::Selected));
2040        });
2041    }
2042
2043    fn decorated(color: Color, child: Option<WidgetRef>) -> WidgetRef {
2044        let mut decorated = DecoratedBox::new(BoxDecoration::new().color(color));
2045        decorated.child = child;
2046        decorated.into_widget()
2047    }
2048
2049    fn decoration_colors(tester: &WidgetTester) -> Vec<Option<Color>> {
2050        let decorations = tester.all::<RenderDecoratedBox>();
2051        let app = tester.cell.borrow();
2052        decorations
2053            .into_iter()
2054            .map(|render| {
2055                render
2056                    .decoration(&app)
2057                    .as_any()
2058                    .downcast_ref::<BoxDecoration>()
2059                    .expect("a box decoration")
2060                    .color
2061                    .as_ref()
2062                    .map(|color| color.color())
2063            })
2064            .collect()
2065    }
2066
2067    fn is_inside(tester: &WidgetTester, ancestor: AnyRenderObject, key: &GlobalKey) -> bool {
2068        let app = tester.cell.borrow();
2069        let mut node = key
2070            .current_context(&app)
2071            .and_then(|context| context.find_render_object(&app));
2072        while let Some(current) = node {
2073            if current == ancestor {
2074                return true;
2075            }
2076            node = current.parent(&app);
2077        }
2078        false
2079    }
2080
2081    // elevated_button_test.dart 'ElevatedButton backgroundBuilder and foregroundBuilder'.
2082    #[test]
2083    fn the_layer_builders_wrap_the_button_child_behind_and_in_front() {
2084        test_widgets(|tester| {
2085            let background_color = Color::new(0xFF000011);
2086            let foreground_color = Color::new(0xFF000022);
2087            let child_key = GlobalKey::new();
2088
2089            tester.pump_widget(ltr(TestButton::new(
2090                Some(pressed()),
2091                sized(40.0, 10.0).key(child_key.clone().into()),
2092            )
2093            .style(
2094                ButtonStyle::new()
2095                    .background_builder(ButtonLayerBuilder::new(
2096                        move |_app, _context, _states, child| decorated(background_color, child),
2097                    ))
2098                    .foreground_builder(ButtonLayerBuilder::new(
2099                        move |_app, _context, _states, child| decorated(foreground_color, child),
2100                    )),
2101            )));
2102
2103            assert_eq!(
2104                decoration_colors(tester),
2105                vec![Some(background_color), Some(foreground_color)]
2106            );
2107            let decorations = tester.all::<RenderDecoratedBox>();
2108            assert!(is_inside(tester, decorations[0].as_object(), &child_key));
2109            assert!(is_inside(tester, decorations[1].as_object(), &child_key));
2110        });
2111    }
2112
2113    // elevated_button_test.dart 'ElevatedButton backgroundBuilder drops button child and
2114    // foregroundBuilder return value'.
2115    #[test]
2116    fn a_background_builder_that_drops_its_child_drops_the_whole_foreground() {
2117        test_widgets(|tester| {
2118            let background_color = Color::new(0xFF000011);
2119            let foreground_color = Color::new(0xFF000022);
2120            let child_key = GlobalKey::new();
2121
2122            tester.pump_widget(ltr(TestButton::new(
2123                Some(pressed()),
2124                sized(40.0, 10.0).key(child_key.clone().into()),
2125            )
2126            .style(
2127                ButtonStyle::new()
2128                    .background_builder(ButtonLayerBuilder::new(
2129                        move |_app, _context, _states, _child| decorated(background_color, None),
2130                    ))
2131                    .foreground_builder(ButtonLayerBuilder::new(
2132                        move |_app, _context, _states, _child| decorated(foreground_color, None),
2133                    )),
2134            )));
2135
2136            assert_eq!(decoration_colors(tester), vec![Some(background_color)]);
2137            assert!(
2138                child_key
2139                    .current_context(&tester.cell.borrow_mut())
2140                    .is_none()
2141            );
2142        });
2143    }
2144
2145    // elevated_button_test.dart 'ElevatedButton foregroundBuilder drops button child'.
2146    #[test]
2147    fn a_foreground_builder_that_drops_its_child_drops_the_button_child() {
2148        test_widgets(|tester| {
2149            let foreground_color = Color::new(0xFF000022);
2150            let child_key = GlobalKey::new();
2151
2152            tester.pump_widget(ltr(TestButton::new(
2153                Some(pressed()),
2154                sized(40.0, 10.0).key(child_key.clone().into()),
2155            )
2156            .style(
2157                ButtonStyle::new().foreground_builder(ButtonLayerBuilder::new(
2158                    move |_app, _context, _states, _child| decorated(foreground_color, None),
2159                )),
2160            )));
2161
2162            assert_eq!(decoration_colors(tester), vec![Some(foreground_color)]);
2163            assert!(
2164                child_key
2165                    .current_context(&tester.cell.borrow_mut())
2166                    .is_none()
2167            );
2168        });
2169    }
2170
2171    // elevated_button_test.dart 'ElevatedButton foreground and background builders are
2172    // applied to the correct states'.
2173    #[test]
2174    fn the_layer_builders_see_the_button_states() {
2175        test_widgets(|tester| {
2176            let foreground_states = Rc::new(RefCell::new(WidgetStates::new()));
2177            let background_states = Rc::new(RefCell::new(WidgetStates::new()));
2178            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
2179                .into_erased::<waft_widgets::AnyFocusNode>();
2180            let key = GlobalKey::new();
2181            let record = |seen: &Rc<RefCell<WidgetStates>>| {
2182                let seen = Rc::clone(seen);
2183                ButtonLayerBuilder::new(move |_app, _context, states, child| {
2184                    *seen.borrow_mut() = states.clone();
2185                    child.expect("the button's child")
2186                })
2187            };
2188            let theme = ThemeData::new(&tester.cell.borrow());
2189            let frame = themed(
2190                tester,
2191                theme,
2192                Center::new().child(
2193                    TestButton::new(Some(pressed()), sized(40.0, 10.0))
2194                        .key(key.clone().into())
2195                        .focus_node(focus_node.clone())
2196                        .style(
2197                            ButtonStyle::new()
2198                                .background_builder(record(&background_states))
2199                                .foreground_builder(record(&foreground_states)),
2200                        ),
2201                ),
2202            );
2203            tester.pump_widget(frame);
2204
2205            // Default.
2206            assert!(background_states.borrow().is_empty());
2207            assert!(foreground_states.borrow().is_empty());
2208
2209            let focused_states = states(&[WidgetState::Focused]);
2210            let focused_hovered_states = states(&[WidgetState::Focused, WidgetState::Hovered]);
2211            let focused_hovered_pressed_states = states(&[
2212                WidgetState::Focused,
2213                WidgetState::Hovered,
2214                WidgetState::Pressed,
2215            ]);
2216
2217            // Focused.
2218            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2219            tester.pump_and_settle();
2220            assert_eq!(*background_states.borrow(), focused_states);
2221            assert_eq!(*foreground_states.borrow(), focused_states);
2222
2223            // Hovered.
2224            let center = tester.get_center(&key);
2225            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
2226            tester.add_pointer(&mut gesture, Offset::ZERO);
2227            tester.move_to(&mut gesture, center, false);
2228            tester.pump_and_settle();
2229            assert_eq!(*background_states.borrow(), focused_hovered_states);
2230            assert_eq!(*foreground_states.borrow(), focused_hovered_states);
2231
2232            // Highlighted (pressed).
2233            tester.send(&gesture, waft_embedder::PointerChange::Down);
2234            tester.pump(); // Start the splash and highlight animations.
2235            // Wait for splash and highlight to be well under way.
2236            tester.pump_by(Duration::from_millis(800));
2237            assert_eq!(*background_states.borrow(), focused_hovered_pressed_states);
2238            assert_eq!(*foreground_states.borrow(), focused_hovered_pressed_states);
2239        });
2240    }
2241
2242    /// The colours a probe in the button's child reads: the ambient icon theme's and the
2243    /// default text style's.
2244    type Seen = Rc<RefCell<(Option<Color>, Option<Color>)>>;
2245
2246    fn color_probe(seen: &Seen) -> Builder {
2247        let seen = Rc::clone(seen);
2248        Builder::new(move |app, context| {
2249            let icon_color = IconTheme::of(app, context).color.map(|color| color.color());
2250            let text_color = DefaultTextStyle::of(app, context)
2251                .style
2252                .color
2253                .map(|color| color.color());
2254            *seen.borrow_mut() = (icon_color, text_color);
2255            sized(40.0, 10.0).into_widget()
2256        })
2257    }
2258
2259    // elevated_button_test.dart 'ElevatedButton icon uses provided foregroundColor over
2260    // default icon color'.
2261    #[test]
2262    fn the_icon_color_falls_back_to_the_given_foreground_color() {
2263        test_widgets(|tester| {
2264            let foreground_color = Color::new(0xFFFF1234);
2265            let seen: Seen = Rc::default();
2266            let theme = ThemeData::new(&tester.cell.borrow());
2267            let frame = themed(
2268                tester,
2269                theme,
2270                Center::new().child(
2271                    TestButton::new(Some(pressed()), color_probe(&seen))
2272                        .style(ButtonStyle::new().foreground_color(all(foreground_color))),
2273                ),
2274            );
2275            tester.pump_widget(frame);
2276            assert_eq!(seen.borrow().0, Some(foreground_color));
2277        });
2278    }
2279
2280    // elevated_button_test.dart 'ElevatedButton text and icon respect animation duration'.
2281    #[test]
2282    fn the_text_and_icon_colors_animate_over_the_animation_duration() {
2283        test_widgets(|tester| {
2284            let hovered_color = Color::new(0xFFFF0000);
2285            let idle_color = Color::new(0xFF000000);
2286            let halfway = hovered_color.with_values(None, Some(0.5), None, None, None);
2287            let seen: Seen = Rc::default();
2288            let key = GlobalKey::new();
2289            let color = || {
2290                <dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
2291                    (WidgetState::Hovered.into(), Some(hovered_color)),
2292                    (WidgetState::any(), Some(idle_color)),
2293                ])
2294            };
2295            let build_button = |tester: &WidgetTester, animation_duration: Option<Duration>| {
2296                let mut style = ButtonStyle::new()
2297                    .icon_color(color())
2298                    .foreground_color(color());
2299                style.animation_duration = animation_duration;
2300                let theme = ThemeData::new(&tester.cell.borrow());
2301                themed(
2302                    tester,
2303                    theme,
2304                    Material::new().child(
2305                        Center::new().child(
2306                            TestButton::new(Some(pressed()), color_probe(&seen))
2307                                .key(key.clone().into())
2308                                .style(style),
2309                        ),
2310                    ),
2311                )
2312            };
2313
2314            // Test default animation duration.
2315            let frame = build_button(tester, None);
2316            tester.pump_widget(frame);
2317
2318            assert_eq!(*seen.borrow(), (Some(idle_color), Some(idle_color)));
2319
2320            let button_center = tester.get_center(&key);
2321            let mut gesture = TestPointer::mouse(1, 0);
2322            tester.add_pointer(&mut gesture, Offset::ZERO);
2323            tester.move_to(&mut gesture, button_center, false);
2324
2325            tester.pump();
2326            tester.pump_by(Duration::from_millis(100));
2327            assert_eq!(*seen.borrow(), (Some(halfway), Some(halfway)));
2328
2329            tester.pump();
2330            tester.pump_by(Duration::from_millis(200));
2331            assert_eq!(*seen.borrow(), (Some(hovered_color), Some(hovered_color)));
2332
2333            tester.send(&gesture, waft_embedder::PointerChange::Remove);
2334
2335            // Test custom animation duration.
2336            let frame = build_button(tester, Some(Duration::from_secs(2)));
2337            tester.pump_widget(frame);
2338            tester.pump_and_settle();
2339
2340            tester.add_pointer(&mut gesture, Offset::ZERO);
2341            tester.move_to(&mut gesture, button_center, false);
2342
2343            tester.pump();
2344            tester.pump_by(Duration::from_secs(1));
2345            assert_eq!(*seen.borrow(), (Some(halfway), Some(halfway)));
2346
2347            tester.pump();
2348            tester.pump_by(Duration::from_secs(1));
2349            assert_eq!(*seen.borrow(), (Some(hovered_color), Some(hovered_color)));
2350        });
2351    }
2352
2353    // elevated_button_test.dart 'ElevatedButton does not crash at zero area'.
2354    #[test]
2355    fn a_button_in_a_zero_area_has_zero_size() {
2356        test_widgets(|tester| {
2357            let key = GlobalKey::new();
2358            let theme = ThemeData::new(&tester.cell.borrow());
2359            let frame = themed(
2360                tester,
2361                theme,
2362                Center::new().child(SizedBox::shrink().child(
2363                    TestButton::new(Some(pressed()), sized(10.0, 10.0)).key(key.clone().into()),
2364                )),
2365            );
2366            tester.pump_widget(frame);
2367            assert_eq!(tester.get_size(&key), Size::ZERO);
2368        });
2369    }
2370
2371    #[test]
2372    fn a_tap_in_the_padded_tap_target_reaches_the_button() {
2373        test_widgets(|tester| {
2374            let taps = Rc::new(Cell::new(0));
2375            let key = GlobalKey::new();
2376            let frame = themed(
2377                tester,
2378                material2(tester),
2379                Center::new().child(
2380                    TestButton::new(Some(counter(&taps)), sized(100.0, 20.0))
2381                        .key(key.clone().into()),
2382                ),
2383            );
2384            tester.pump_widget(frame);
2385            // The button's material is 36 high and centred in the 48 high tap target.
2386            let rect = rect_of(tester, &key);
2387            assert_eq!(rect.height(), 48.0);
2388            tester.tap_at(Offset::new(rect.center().dx(), rect.top + 2.0), 1);
2389            tester.pump_and_settle();
2390            assert_eq!(taps.get(), 1);
2391        });
2392    }
2393
2394    /// The `Semantics` around each button's `_InputPadding` bounds its hit test, so the padding
2395    /// of the later button in a column does not take a tap on the earlier one.
2396    #[test]
2397    fn a_tap_on_the_first_of_two_buttons_in_a_column_reaches_it() {
2398        test_widgets(|tester| {
2399            let first_taps = Rc::new(Cell::new(0));
2400            let second_taps = Rc::new(Cell::new(0));
2401            let first = GlobalKey::new();
2402            let frame = themed(
2403                tester,
2404                material2(tester),
2405                Center::new().child(
2406                    Column::new().main_axis_size(MainAxisSize::Min).children([
2407                        TestButton::new(Some(counter(&first_taps)), sized(100.0, 20.0))
2408                            .key(first.clone().into())
2409                            .into_widget(),
2410                        TestButton::new(Some(counter(&second_taps)), sized(100.0, 20.0))
2411                            .into_widget(),
2412                    ]),
2413                ),
2414            );
2415            tester.pump_widget(frame);
2416            let rect = rect_of(tester, &first);
2417            tester.tap_at(rect.center(), 1);
2418            tester.pump_and_settle();
2419            assert_eq!(first_taps.get(), 1);
2420            assert_eq!(second_taps.get(), 0);
2421        });
2422    }
2423
2424    #[test]
2425    fn a_button_wraps_its_input_padding_in_a_container_semantics() {
2426        test_widgets(|tester| {
2427            let frame = themed(
2428                tester,
2429                material2(tester),
2430                Center::new()
2431                    .child(TestButton::new(Some(pressed()), sized(100.0, 20.0)).is_selected(true)),
2432            );
2433            tester.pump_widget(frame);
2434            let semantics = tester.first::<waft_rendering::RenderSemanticsAnnotations>();
2435            let app = tester.cell.borrow();
2436            use waft_rendering::SemanticsAnnotationsMixin;
2437            assert!(semantics.container(&app));
2438            let properties = semantics.properties(&app);
2439            assert_eq!(properties.button, Some(true));
2440            assert_eq!(properties.enabled, Some(true));
2441            assert_eq!(properties.selected, Some(true));
2442        });
2443    }
2444}