Skip to main content

waft_material/
segmented_button.rs

1//! Flutter counterpart: material_ui's `segmented_button.dart`.
2
3use std::any::{Any, TypeId};
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_embedder::{
9    Color, Offset, PathBuilder, RRect, Radius, Rect, Size, TextBaseline, clamp_double,
10};
11use waft_foundation::{App, DiagnosticsNode, Handle, Listener, Ref, ValueChanged};
12use waft_painting::{
13    AlignmentGeometry, Axis, BorderSide, ClipContext, EdgeInsets, EdgeInsetsDirectional,
14    EdgeInsetsGeometry, OutlinedBorderRef, RoundedRectangleBorder, TextDirection, TextStyle,
15    draw_line,
16};
17use waft_rendering::{
18    AnyRenderBox, AnyRenderObject, BaselineOffset, BoxConstraints, BoxHitTestResult, BoxParentData,
19    ContainerBoxParentData, ContainerParentData, ContainerParentDataMixin,
20    ContainerRenderObjectData, ContainerRenderObjectMixin, MainAxisSize, PaintingContext,
21    ParentData, PipelineOwner, RenderBox, RenderBoxContainerDefaultsMixin, RenderBoxData,
22    RenderHandle, RenderObject, RenderObjectData,
23};
24use waft_services::MouseCursorRef;
25use waft_widgets::{
26    BuildContext, Directionality, Flexible, IntoWidget, KeyRef, MediaQuery, MergeSemantics,
27    MultiChildRenderObjectWidget, Padding, RenderObjectWidget, Row, Semantics, SizedBox, State,
28    StateData, StatefulWidget, WidgetRef, WidgetState, WidgetStateProperty, WidgetStatePropertyAll,
29    WidgetStatePropertyRef, WidgetStates, WidgetStatesController,
30};
31
32use crate::button_style::ButtonStyle;
33use crate::button_style_button::{ButtonStyleButton, IconAlignment};
34use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
35use crate::generated::segmented_button_defaults_m3::SegmentedButtonDefaultsM3;
36use crate::ink_well::InteractiveInkFeatureFactoryRef;
37use crate::material::{Material, MaterialType};
38use crate::segmented_button_theme::{SegmentedButtonTheme, SegmentedButtonThemeDataGetters};
39use crate::text_button::TextButton;
40use crate::text_button_theme::{TextButtonTheme, TextButtonThemeData};
41use crate::theme::Theme;
42use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
43use crate::tooltip::Tooltip;
44
45/// Data describing a segment of a [`SegmentedButton`].
46///
47/// Two segments are equal when their fields are: their widgets by identity. Where Dart compares
48/// two segments by identity, a [`SegmentedButton`] matches the segments of a rebuild by
49/// [`value`](Self::value), which must be unique.
50#[derive(Clone, Debug)]
51pub struct ButtonSegment<T> {
52    /// Value used to identify the segment.
53    ///
54    /// This value must be unique across all segments in a [`SegmentedButton`].
55    pub value: T,
56
57    /// Optional icon displayed in the segment.
58    pub icon: Option<WidgetRef>,
59
60    /// Optional label displayed in the segment.
61    pub label: Option<WidgetRef>,
62
63    /// Optional tooltip for the segment
64    pub tooltip: Option<String>,
65
66    /// Determines if the segment is available for selection.
67    pub enabled: bool,
68}
69
70impl<T> ButtonSegment<T> {
71    /// Construct a [`ButtonSegment`].
72    ///
73    /// One of [`icon`](Self::icon) or [`label`](Self::label) must be non-null, which
74    /// [`SegmentedButton`] asserts when it is built into a widget.
75    pub fn new(value: T) -> ButtonSegment<T> {
76        ButtonSegment {
77            value,
78            icon: None,
79            label: None,
80            tooltip: None,
81            enabled: true,
82        }
83    }
84
85    /// Dart `ButtonSegment(icon:)`.
86    #[cfg_attr(debug_assertions, track_caller)]
87    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> ButtonSegment<T> {
88        self.icon = Some(icon.into_widget());
89        self
90    }
91
92    /// Dart `ButtonSegment(label:)`.
93    #[cfg_attr(debug_assertions, track_caller)]
94    pub fn label<K>(mut self, label: impl IntoWidget<K>) -> ButtonSegment<T> {
95        self.label = Some(label.into_widget());
96        self
97    }
98
99    /// Dart `ButtonSegment(tooltip:)`.
100    pub fn tooltip(mut self, tooltip: impl Into<String>) -> ButtonSegment<T> {
101        self.tooltip = Some(tooltip.into());
102        self
103    }
104
105    /// Dart `ButtonSegment(enabled:)`.
106    pub fn enabled(mut self, enabled: bool) -> ButtonSegment<T> {
107        self.enabled = enabled;
108        self
109    }
110}
111
112impl<T: PartialEq> PartialEq for ButtonSegment<T> {
113    fn eq(&self, other: &ButtonSegment<T>) -> bool {
114        self.value == other.value
115            && self.enabled == other.enabled
116            && self.tooltip == other.tooltip
117            && same_widget(&self.icon, &other.icon)
118            && same_widget(&self.label, &other.label)
119    }
120}
121
122fn same_widget(a: &Option<WidgetRef>, b: &Option<WidgetRef>) -> bool {
123    match (a, b) {
124        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
125        (None, None) => true,
126        _ => false,
127    }
128}
129
130/// A Material button that allows the user to select from limited set of options.
131///
132/// Segmented buttons are used to help people select options, switch views, or
133/// sort elements. They are typically used in cases where there are only 2-5
134/// options.
135///
136/// The options are represented by segments described with [`ButtonSegment`]
137/// entries in the [`segments`](Self::segments) field. Each segment has a
138/// [`ButtonSegment::value`] that is used to indicate which segments are selected.
139///
140/// The [`selected`](Self::selected) field is a set of selected [`ButtonSegment::value`]s,
141/// each once. This should be updated by the app in response to
142/// [`on_selection_changed`](Self::on_selection_changed) updates.
143///
144/// By default, only a single segment can be selected (for mutually exclusive
145/// choices). This can be relaxed with the
146/// [`multi_selection_enabled`](Self::multi_selection_enabled) field.
147///
148/// Like [`ButtonStyleButton`]s, the [`SegmentedButton`]'s visuals can be
149/// configured with a [`ButtonStyle`] [`style`](Self::style) field. However, unlike other
150/// buttons, some of the style parameters are applied to the entire segmented
151/// button, and others are used for each of the segments.
152///
153/// By default, a checkmark icon is used to show selected items. To configure
154/// this behavior, you can use the [`show_selected_icon`](Self::show_selected_icon) and
155/// [`selected_icon`](Self::selected_icon) fields.
156///
157/// Individual segments can be enabled or disabled with their
158/// [`ButtonSegment::enabled`] flag. If the [`on_selection_changed`](Self::on_selection_changed)
159/// field is null, then the entire segmented button will be disabled, regardless of the
160/// individual segment settings.
161///
162/// See also:
163///
164///   * Material Design spec: <https://m3.material.io/components/segmented-buttons/overview>
165///   * [`ButtonStyle`], which can be used in the [`style`](Self::style) field to configure
166///     the appearance of the button and its segments.
167///   * `ToggleButtons`, a similar widget that was built for Material 2.
168///     [`SegmentedButton`] should be considered as a replacement for
169///     `ToggleButtons`.
170///   * `Radio`, an alternative way to present the user with a mutually exclusive set of options.
171///   * `FilterChip`, `ChoiceChip`, which can be used when you need to show more than five options.
172pub struct SegmentedButton<T> {
173    /// See [`Widget::key`](waft_widgets::Widget::key).
174    pub key: Option<KeyRef>,
175
176    /// Descriptions of the segments in the button.
177    ///
178    /// This a required parameter and must contain at least one segment,
179    /// but it is recommended to contain two to five segments. If you need only
180    /// a single segment, consider using a `Checkbox` or `Radio` widget instead.
181    /// If you need more than five options, consider using `FilterChip` or
182    /// `ChoiceChip` widgets.
183    pub segments: Vec<ButtonSegment<T>>,
184
185    /// The orientation of the button's [`segments`](Self::segments).
186    ///
187    /// If this is [`Axis::Vertical`], the segments will be aligned vertically
188    /// and the first item in [`segments`](Self::segments) will be on the top.
189    ///
190    /// Defaults to [`Axis::Horizontal`].
191    pub direction: Axis,
192
193    /// The set of [`ButtonSegment::value`]s that indicate which [`segments`](Self::segments) are
194    /// selected, in insertion order, each once.
195    ///
196    /// As the [`SegmentedButton`] does not maintain the state of the selection,
197    /// you will need to update this in response to
198    /// [`on_selection_changed`](Self::on_selection_changed) calls.
199    ///
200    /// This is a required parameter.
201    pub selected: Vec<T>,
202
203    /// The function that is called when the selection changes.
204    ///
205    /// The callback's parameter indicates which of the segments are selected.
206    ///
207    /// When the callback is null, the entire [`SegmentedButton`] is disabled,
208    /// and will not respond to input.
209    ///
210    /// The default is null.
211    pub on_selection_changed: Option<ValueChanged<Vec<T>>>,
212
213    /// Determines if multiple segments can be selected at one time.
214    ///
215    /// If true, more than one segment can be selected. When selecting a
216    /// segment, the other selected segments will stay selected. Selecting an
217    /// already selected segment will unselect it.
218    ///
219    /// If false, only one segment may be selected at a time. When a segment
220    /// is selected, any previously selected segment will be unselected.
221    ///
222    /// The default is false, so only a single segment may be selected at one
223    /// time.
224    pub multi_selection_enabled: bool,
225
226    /// Determines if having no selected segments is allowed.
227    ///
228    /// If true, then it is acceptable for none of the segments to be selected.
229    /// This means that [`selected`](Self::selected) can be empty. If the user taps on a
230    /// selected segment, it will be removed from the selection set passed into
231    /// [`on_selection_changed`](Self::on_selection_changed).
232    ///
233    /// If false (the default), there must be at least one segment selected. If
234    /// the user taps on the only selected segment it will not be deselected, and
235    /// [`on_selection_changed`](Self::on_selection_changed) will not be called.
236    pub empty_selection_allowed: bool,
237
238    /// Determines the segmented button's size and padding based on
239    /// [`expanded_insets`](Self::expanded_insets).
240    ///
241    /// If null (default), the button adopts its intrinsic content size. When specified,
242    /// the button expands to fill its parent's space, with the [`EdgeInsets`]
243    /// defining the padding.
244    pub expanded_insets: Option<EdgeInsets>,
245
246    /// Customizes this button's appearance.
247    ///
248    /// The following style properties apply to the entire segmented button:
249    ///
250    ///   * [`ButtonStyle::shadow_color`]
251    ///   * [`ButtonStyle::elevation`]
252    ///   * [`ButtonStyle::side`] - which is used for both the outer shape and
253    ///     dividers between segments.
254    ///   * [`ButtonStyle::shape`]
255    ///
256    /// The following style properties are applied to each of the individual
257    /// button segments. For properties that are a `WidgetStateProperty`,
258    /// they will be resolved with the current state of the segment:
259    ///
260    ///   * [`ButtonStyle::text_style`]
261    ///   * [`ButtonStyle::background_color`]
262    ///   * [`ButtonStyle::foreground_color`]
263    ///   * [`ButtonStyle::overlay_color`]
264    ///   * [`ButtonStyle::surface_tint_color`]
265    ///   * [`ButtonStyle::elevation`]
266    ///   * [`ButtonStyle::padding`]
267    ///   * [`ButtonStyle::icon_color`]
268    ///   * [`ButtonStyle::icon_size`]
269    ///   * [`ButtonStyle::mouse_cursor`]
270    ///   * [`ButtonStyle::visual_density`]
271    ///   * [`ButtonStyle::tap_target_size`]
272    ///   * [`ButtonStyle::animation_duration`]
273    ///   * [`ButtonStyle::enable_feedback`]
274    ///   * [`ButtonStyle::alignment`]
275    ///   * [`ButtonStyle::splash_factory`]
276    ///
277    /// If [`ButtonStyle::side`] is provided, `WidgetStateProperty::resolve` is used
278    /// for the following `WidgetState`s:
279    ///
280    ///  * `WidgetState::Focused`.
281    ///  * `WidgetState::Hovered`.
282    ///  * `WidgetState::Disabled`.
283    ///  * `WidgetState::Selected`.
284    pub style: Option<ButtonStyle>,
285
286    /// Determines if the [`selected_icon`](Self::selected_icon) (usually an icon using
287    /// `Icons::check`) is displayed on the selected segments.
288    ///
289    /// If true, the [`selected_icon`](Self::selected_icon) will be displayed at the start of
290    /// the segment. If both the [`ButtonSegment::label`] and [`ButtonSegment::icon`] are
291    /// provided, then the icon will be replaced with the [`selected_icon`](Self::selected_icon).
292    /// If only the icon or the label is present then the
293    /// [`selected_icon`](Self::selected_icon) will be shown at the start of the segment.
294    ///
295    /// If false, then the [`selected_icon`](Self::selected_icon) is not used and will not be
296    /// displayed on selected segments.
297    ///
298    /// The default is true, meaning the [`selected_icon`](Self::selected_icon) will be shown on
299    /// selected segments.
300    pub show_selected_icon: bool,
301
302    /// An icon that is used to indicate a segment is selected.
303    ///
304    /// If [`show_selected_icon`](Self::show_selected_icon) is true then for selected segments
305    /// this icon will be shown before the [`ButtonSegment::label`], replacing the
306    /// [`ButtonSegment::icon`] if it is specified.
307    ///
308    /// Defaults to an `Icon` with `Icons::check`.
309    pub selected_icon: Option<WidgetRef>,
310}
311
312impl<T: Clone + PartialEq + 'static> SegmentedButton<T> {
313    /// Creates a [`SegmentedButton`].
314    ///
315    /// [`segments`](Self::segments) must contain at least one segment, but it is recommended
316    /// to have two to five segments. If you need only single segment, consider using a
317    /// `Checkbox` or `Radio` widget instead. If you need more than five options, consider
318    /// using `FilterChip` or `ChoiceChip` widgets.
319    ///
320    /// If [`on_selection_changed`](Self::on_selection_changed) is null, then the entire
321    /// segmented button will be disabled.
322    ///
323    /// By default [`selected`](Self::selected) must only contain one entry. However, if
324    /// [`multi_selection_enabled`](Self::multi_selection_enabled) is true, then
325    /// [`selected`](Self::selected) can contain multiple entries. If
326    /// [`empty_selection_allowed`](Self::empty_selection_allowed) is true, then
327    /// [`selected`](Self::selected) can be empty.
328    pub fn new(segments: Vec<ButtonSegment<T>>, selected: Vec<T>) -> SegmentedButton<T> {
329        SegmentedButton {
330            key: None,
331            segments,
332            direction: Axis::Horizontal,
333            selected,
334            on_selection_changed: None,
335            multi_selection_enabled: false,
336            empty_selection_allowed: false,
337            expanded_insets: None,
338            style: None,
339            show_selected_icon: true,
340            selected_icon: None,
341        }
342    }
343
344    /// Dart `SegmentedButton(key:)`.
345    pub fn key(mut self, key: KeyRef) -> SegmentedButton<T> {
346        self.key = Some(key);
347        self
348    }
349
350    /// Dart `SegmentedButton(direction:)`.
351    pub fn direction(mut self, direction: Axis) -> SegmentedButton<T> {
352        self.direction = direction;
353        self
354    }
355
356    /// Dart `SegmentedButton(onSelectionChanged:)`.
357    pub fn on_selection_changed(
358        mut self,
359        on_selection_changed: impl Fn(&mut App, Vec<T>) + 'static,
360    ) -> SegmentedButton<T> {
361        self.on_selection_changed = Some(Rc::new(on_selection_changed));
362        self
363    }
364
365    /// Dart `SegmentedButton(multiSelectionEnabled:)`.
366    pub fn multi_selection_enabled(mut self, multi_selection_enabled: bool) -> SegmentedButton<T> {
367        self.multi_selection_enabled = multi_selection_enabled;
368        self
369    }
370
371    /// Dart `SegmentedButton(emptySelectionAllowed:)`.
372    pub fn empty_selection_allowed(mut self, empty_selection_allowed: bool) -> SegmentedButton<T> {
373        self.empty_selection_allowed = empty_selection_allowed;
374        self
375    }
376
377    /// Dart `SegmentedButton(expandedInsets:)`.
378    pub fn expanded_insets(mut self, expanded_insets: EdgeInsets) -> SegmentedButton<T> {
379        self.expanded_insets = Some(expanded_insets);
380        self
381    }
382
383    /// Dart `SegmentedButton(style:)`.
384    pub fn style(mut self, style: ButtonStyle) -> SegmentedButton<T> {
385        self.style = Some(style);
386        self
387    }
388
389    /// Dart `SegmentedButton(showSelectedIcon:)`.
390    pub fn show_selected_icon(mut self, show_selected_icon: bool) -> SegmentedButton<T> {
391        self.show_selected_icon = show_selected_icon;
392        self
393    }
394
395    /// Dart `SegmentedButton(selectedIcon:)`.
396    #[cfg_attr(debug_assertions, track_caller)]
397    pub fn selected_icon<K>(mut self, selected_icon: impl IntoWidget<K>) -> SegmentedButton<T> {
398        self.selected_icon = Some(selected_icon.into_widget());
399        self
400    }
401}
402
403impl<T> SegmentedButton<T> {
404    /// A static convenience method that constructs a segmented button
405    /// [`ButtonStyle`] given simple values.
406    ///
407    /// The `foreground_color`, `selected_foreground_color`, and `disabled_foreground_color`
408    /// colors are used to create a `WidgetStateProperty` [`ButtonStyle::foreground_color`],
409    /// and a derived [`ButtonStyle::overlay_color`] if `overlay_color` isn't specified.
410    ///
411    /// If `overlay_color` is specified and its value is `Colors::TRANSPARENT`
412    /// then the pressed/focused/hovered highlights are effectively defeated.
413    /// Otherwise a `WidgetStateProperty` with the same opacities as the
414    /// default is created.
415    ///
416    /// The `background_color`, `selected_background_color` and `disabled_background_color`
417    /// colors are used to create a `WidgetStateProperty` [`ButtonStyle::background_color`].
418    ///
419    /// Similarly, the `enabled_mouse_cursor` and `disabled_mouse_cursor`
420    /// parameters are used to construct [`ButtonStyle::mouse_cursor`].
421    ///
422    /// The `icon_color`, `disabled_icon_color` are used to construct
423    /// [`ButtonStyle::icon_color`] and `icon_size` is used to construct
424    /// [`ButtonStyle::icon_size`].
425    ///
426    /// All of the other parameters are either used directly or used to
427    /// create a `WidgetStateProperty` with a single value for all
428    /// states.
429    ///
430    /// All parameters default to null. By default this method returns
431    /// a [`ButtonStyle`] that doesn't override anything.
432    ///
433    /// For example, to override the default text and icon colors for a
434    /// [`SegmentedButton`], as well as its overlay color, with all of the
435    /// standard opacity adjustments for the pressed, focused, and
436    /// hovered states, one could write:
437    ///
438    /// ```text
439    /// SegmentedButton::new(segments, selected).style(
440    ///     SegmentedButton::<i32>::style_from()
441    ///         .foreground_color(Colors::BLACK)
442    ///         .selected_foreground_color(Colors::WHITE)
443    ///         .background_color(Colors::AMBER.primary())
444    ///         .selected_background_color(Colors::RED.primary())
445    ///         .build(),
446    /// )
447    /// ```
448    pub fn style_from() -> SegmentedButtonStyleFromBuilder {
449        SegmentedButtonStyleFromBuilder::default()
450    }
451}
452
453/// Dart's `SegmentedButton.styleFrom(..)` arguments; [`build`](Self::build) makes the
454/// [`ButtonStyle`].
455#[derive(Clone, Default)]
456pub struct SegmentedButtonStyleFromBuilder {
457    foreground_color: Option<Color>,
458    background_color: Option<Color>,
459    selected_foreground_color: Option<Color>,
460    selected_background_color: Option<Color>,
461    disabled_foreground_color: Option<Color>,
462    disabled_background_color: Option<Color>,
463    shadow_color: Option<Color>,
464    surface_tint_color: Option<Color>,
465    icon_color: Option<Color>,
466    icon_size: Option<f64>,
467    disabled_icon_color: Option<Color>,
468    overlay_color: Option<Color>,
469    elevation: Option<f64>,
470    text_style: Option<TextStyle>,
471    padding: Option<EdgeInsetsGeometry>,
472    minimum_size: Option<Size>,
473    fixed_size: Option<Size>,
474    maximum_size: Option<Size>,
475    side: Option<BorderSide>,
476    shape: Option<OutlinedBorderRef>,
477    enabled_mouse_cursor: Option<MouseCursorRef>,
478    disabled_mouse_cursor: Option<MouseCursorRef>,
479    visual_density: Option<VisualDensity>,
480    tap_target_size: Option<MaterialTapTargetSize>,
481    animation_duration: Option<Duration>,
482    enable_feedback: Option<bool>,
483    alignment: Option<AlignmentGeometry>,
484    splash_factory: Option<InteractiveInkFeatureFactoryRef>,
485}
486
487/// The fluent setters of Dart's named `styleFrom` arguments.
488macro_rules! style_from_setters {
489    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
490        $(
491            #[doc = concat!("Dart `SegmentedButton.styleFrom(", $dart, ":)`.")]
492            pub fn $field(mut self, $field: $ty) -> SegmentedButtonStyleFromBuilder {
493                self.$field = Some($field);
494                self
495            }
496        )*
497    };
498}
499
500impl SegmentedButtonStyleFromBuilder {
501    style_from_setters!(
502        foreground_color: Color => "foregroundColor",
503        background_color: Color => "backgroundColor",
504        selected_foreground_color: Color => "selectedForegroundColor",
505        selected_background_color: Color => "selectedBackgroundColor",
506        disabled_foreground_color: Color => "disabledForegroundColor",
507        disabled_background_color: Color => "disabledBackgroundColor",
508        shadow_color: Color => "shadowColor",
509        surface_tint_color: Color => "surfaceTintColor",
510        icon_color: Color => "iconColor",
511        icon_size: f64 => "iconSize",
512        disabled_icon_color: Color => "disabledIconColor",
513        overlay_color: Color => "overlayColor",
514        elevation: f64 => "elevation",
515        text_style: TextStyle => "textStyle",
516        padding: EdgeInsetsGeometry => "padding",
517        minimum_size: Size => "minimumSize",
518        fixed_size: Size => "fixedSize",
519        maximum_size: Size => "maximumSize",
520        side: BorderSide => "side",
521        enabled_mouse_cursor: MouseCursorRef => "enabledMouseCursor",
522        disabled_mouse_cursor: MouseCursorRef => "disabledMouseCursor",
523        visual_density: VisualDensity => "visualDensity",
524        tap_target_size: MaterialTapTargetSize => "tapTargetSize",
525        animation_duration: Duration => "animationDuration",
526        enable_feedback: bool => "enableFeedback",
527        alignment: AlignmentGeometry => "alignment",
528        splash_factory: InteractiveInkFeatureFactoryRef => "splashFactory",
529    );
530
531    /// Dart `SegmentedButton.styleFrom(shape:)`.
532    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> SegmentedButtonStyleFromBuilder {
533        self.shape = Some(shape.into());
534        self
535    }
536
537    /// The [`ButtonStyle`] made from these values.
538    pub fn build(self) -> ButtonStyle {
539        let overlay_color_prop: Option<WidgetStatePropertyRef<Option<Color>>> =
540            if self.foreground_color.is_none()
541                && self.selected_foreground_color.is_none()
542                && self.overlay_color.is_none()
543            {
544                None
545            } else {
546                match self.overlay_color {
547                    Some(overlay_color) if overlay_color.to_argb32() == 0 => Some(Rc::new(
548                        WidgetStatePropertyAll::new(Some(crate::colors::Colors::TRANSPARENT)),
549                    )),
550                    _ => Some(SegmentedButtonDefaultsM3::resolve_state_color(
551                        self.foreground_color,
552                        self.selected_foreground_color,
553                        self.overlay_color,
554                    )),
555                }
556            };
557        let mut text_button_style = TextButton::style_from();
558        macro_rules! forward {
559            ($($field:ident),* $(,)?) => {
560                $(
561                    if let Some($field) = self.$field.clone() {
562                        text_button_style = text_button_style.$field($field);
563                    }
564                )*
565            };
566        }
567        forward!(
568            text_style,
569            shadow_color,
570            surface_tint_color,
571            icon_color,
572            icon_size,
573            disabled_icon_color,
574            elevation,
575            padding,
576            minimum_size,
577            fixed_size,
578            maximum_size,
579            side,
580            shape,
581            enabled_mouse_cursor,
582            disabled_mouse_cursor,
583            visual_density,
584            tap_target_size,
585            animation_duration,
586            enable_feedback,
587            alignment,
588            splash_factory,
589        );
590        let mut style = text_button_style.build();
591        if let Some(foreground_color) = default_color(
592            self.foreground_color,
593            self.disabled_foreground_color,
594            self.selected_foreground_color,
595        ) {
596            style = style.foreground_color(foreground_color);
597        }
598        if let Some(background_color) = default_color(
599            self.background_color,
600            self.disabled_background_color,
601            self.selected_background_color,
602        ) {
603            style = style.background_color(background_color);
604        }
605        if let Some(overlay_color) = overlay_color_prop {
606            style = style.overlay_color(overlay_color);
607        }
608        style
609    }
610}
611
612/// Dart's `SegmentedButton._defaultColor`.
613fn default_color(
614    enabled: Option<Color>,
615    disabled: Option<Color>,
616    selected: Option<Color>,
617) -> Option<WidgetStatePropertyRef<Option<Color>>> {
618    selected.or(enabled).or(disabled)?;
619    Some(<dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
620        (WidgetState::Disabled.into(), disabled),
621        (WidgetState::Selected.into(), selected),
622        (WidgetState::any(), enabled),
623    ]))
624}
625
626impl<T> Clone for SegmentedButton<T>
627where
628    T: Clone,
629{
630    fn clone(&self) -> SegmentedButton<T> {
631        SegmentedButton {
632            key: self.key.clone(),
633            segments: self.segments.clone(),
634            direction: self.direction,
635            selected: self.selected.clone(),
636            on_selection_changed: self.on_selection_changed.clone(),
637            multi_selection_enabled: self.multi_selection_enabled,
638            empty_selection_allowed: self.empty_selection_allowed,
639            expanded_insets: self.expanded_insets,
640            style: self.style.clone(),
641            show_selected_icon: self.show_selected_icon,
642            selected_icon: self.selected_icon.clone(),
643        }
644    }
645}
646
647impl<T: Debug> Debug for SegmentedButton<T> {
648    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649        f.debug_struct("SegmentedButton")
650            .field("segments", &self.segments)
651            .field("selected", &self.selected)
652            .field("direction", &self.direction)
653            .finish_non_exhaustive()
654    }
655}
656
657impl<T: Clone + PartialEq + Debug + 'static> StatefulWidget for SegmentedButton<T> {
658    type State = SegmentedButtonState<T>;
659
660    fn key(&self) -> Option<&KeyRef> {
661        self.key.as_ref()
662    }
663
664    fn debug_check_constructor(&self) {
665        debug_assert!(
666            self.segments
667                .iter()
668                .all(|segment| segment.icon.is_some() || segment.label.is_some())
669        );
670        debug_assert!(!self.segments.is_empty());
671        debug_assert!(!self.selected.is_empty() || self.empty_selection_allowed);
672        debug_assert!(self.selected.len() < 2 || self.multi_selection_enabled);
673    }
674
675    fn create_state(&self) -> SegmentedButtonState<T> {
676        SegmentedButtonState {
677            state: StateData::new(),
678            hovering: false,
679            focused: false,
680            states_controllers: Vec::new(),
681        }
682    }
683}
684
685/// State for [`SegmentedButton`].
686///
687/// Dart marks the class `@visibleForTesting`.
688pub struct SegmentedButtonState<T: Clone + PartialEq + Debug + 'static> {
689    state: StateData<SegmentedButton<T>>,
690    hovering: bool,
691    focused: bool,
692
693    /// Controllers for the [`ButtonSegment`]s, in the order they were first built, each
694    /// keyed by its segment.
695    ///
696    /// Dart's `@visibleForTesting` map.
697    pub states_controllers: Vec<(ButtonSegment<T>, Ref<WidgetStatesController>)>,
698}
699
700impl<T: Clone + PartialEq + Debug + 'static> Debug for SegmentedButtonState<T> {
701    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702        f.debug_struct("SegmentedButtonState")
703            .field("hovering", &self.hovering)
704            .field("focused", &self.focused)
705            .finish_non_exhaustive()
706    }
707}
708
709/// What the three layers of Dart's `build` read a style property from.
710struct SegmentedButtonStyles {
711    widget: Option<ButtonStyle>,
712    theme: Option<ButtonStyle>,
713    defaults: SegmentedButtonDefaultsM3,
714    states: WidgetStates,
715}
716
717impl SegmentedButtonStyles {
718    /// Dart's `effectiveValue`: the widget's, else the theme's, else the defaults' property,
719    /// each read only when the one before is null.
720    fn effective_value<P>(
721        &self,
722        app: &mut App,
723        get_property: impl Fn(Option<&ButtonStyle>) -> Option<P>,
724    ) -> Option<P> {
725        get_property(self.widget.as_ref())
726            .or_else(|| get_property(self.theme.as_ref()))
727            .or_else(|| {
728                let defaults_style = self.defaults.style(app);
729                get_property(defaults_style.as_ref())
730            })
731    }
732
733    /// Dart's `resolve`: the property of the layer that has one, resolved in `states`, or in
734    /// the state's own states.
735    fn resolve<P: 'static>(
736        &self,
737        app: &mut App,
738        get_property: impl Fn(&ButtonStyle) -> Option<&WidgetStatePropertyRef<Option<P>>>,
739        states: Option<&WidgetStates>,
740    ) -> Option<P> {
741        let states = states.unwrap_or(&self.states);
742        self.effective_value(app, |style| {
743            get_property(style?).and_then(|property| property.resolve(states))
744        })
745    }
746}
747
748/// Dart's `setEquals`.
749fn set_equals<T: PartialEq>(a: &[T], b: &[T]) -> bool {
750    a.len() == b.len() && a.iter().all(|item| b.contains(item))
751}
752
753impl<T: Clone + PartialEq + Debug + 'static> SegmentedButtonState<T> {
754    fn enabled(self: Handle<Self>, app: &App) -> bool {
755        self.widget(app).on_selection_changed.is_some()
756    }
757
758    fn selected(self: Handle<Self>, app: &App) -> bool {
759        !self.widget(app).selected.is_empty()
760    }
761
762    fn states(self: Handle<Self>, app: &App) -> WidgetStates {
763        let mut states = WidgetStates::new();
764        if !self.enabled(app) {
765            states.insert(WidgetState::Disabled);
766        }
767        if app.get(self).hovering {
768            states.insert(WidgetState::Hovered);
769        }
770        if app.get(self).focused {
771            states.insert(WidgetState::Focused);
772        }
773        if self.selected(app) {
774            states.insert(WidgetState::Selected);
775        }
776        states
777    }
778
779    fn handle_on_pressed(self: Handle<Self>, app: &mut App, segment_value: T) {
780        if !self.enabled(app) {
781            return;
782        }
783        let widget = self.widget(app).clone();
784        let only_selected_segment =
785            widget.selected.len() == 1 && widget.selected.contains(&segment_value);
786        let valid_change = widget.empty_selection_allowed || !only_selected_segment;
787        if valid_change {
788            let toggle = widget.multi_selection_enabled
789                || (widget.empty_selection_allowed && only_selected_segment);
790            let updated_selection: Vec<T> = if toggle {
791                if widget.selected.contains(&segment_value) {
792                    widget
793                        .selected
794                        .iter()
795                        .filter(|value| **value != segment_value)
796                        .cloned()
797                        .collect()
798                } else {
799                    let mut union = widget.selected.clone();
800                    union.push(segment_value);
801                    union
802                }
803            } else {
804                vec![segment_value]
805            };
806            if !set_equals(&updated_selection, &widget.selected)
807                && let Some(on_selection_changed) = &widget.on_selection_changed
808            {
809                on_selection_changed(app, updated_selection);
810            }
811        }
812    }
813
814    /// Dart's `statesControllers.putIfAbsent(segment, () => MaterialStatesController())`.
815    fn states_controller_for(
816        self: Handle<Self>,
817        app: &mut App,
818        segment: &ButtonSegment<T>,
819    ) -> Ref<WidgetStatesController> {
820        let existing = app
821            .get(self)
822            .states_controllers
823            .iter()
824            .find(|(key, _)| key.value == segment.value)
825            .map(|(_, controller)| controller.clone());
826        if let Some(controller) = existing {
827            return controller;
828        }
829        let controller = WidgetStatesController::new(app, None);
830        app.get_mut(self)
831            .states_controllers
832            .push((segment.clone(), controller.clone()));
833        controller
834    }
835
836    fn button_for(
837        self: Handle<Self>,
838        app: &mut App,
839        context: BuildContext,
840        segment: &ButtonSegment<T>,
841        segment_style: &ButtonStyle,
842        selected_icon: &Option<WidgetRef>,
843    ) -> WidgetRef {
844        let widget = self.widget(app).clone();
845        let label = segment
846            .label
847            .clone()
848            .or_else(|| segment.icon.clone())
849            .unwrap_or_else(|| SizedBox::shrink().into_widget());
850        let segment_selected = widget.selected.contains(&segment.value);
851        let icon = if segment_selected && widget.show_selected_icon {
852            selected_icon.clone()
853        } else if segment.label.is_some() {
854            segment.icon.clone()
855        } else {
856            None
857        };
858        let controller = self.states_controller_for(app, segment);
859        controller.update(app, WidgetState::Selected, segment_selected);
860
861        let mut content = label.clone();
862        let mut effective_segment_style = segment_style.clone();
863        if let Some(icon) = icon {
864            // This logic is needed to get the exact same rendering as using TextButton.icon.
865            // It is duplicated from _TextButtonWithIcon and _TextButtonWithIconChild.
866            // TODO(bleroux): remove once https://github.com/flutter/flutter/issues/173944 is fixed.
867            let use_material3 = Theme::of(app, context).use_material3;
868            let default_font_size = segment_style
869                .text_style
870                .as_ref()
871                .and_then(|text_style| text_style.resolve(&WidgetStates::new()))
872                .and_then(|text_style| text_style.font_size)
873                .unwrap_or(14.0);
874            let effective_text_scale =
875                MediaQuery::text_scaler_of(app, context).scale(default_font_size) / 14.0;
876            let scaled_padding = <dyn ButtonStyleButton>::scaled_padding(
877                if use_material3 {
878                    EdgeInsetsDirectional::from_steb(12.0, 8.0, 16.0, 8.0).into()
879                } else {
880                    EdgeInsets::all(8.0).into()
881                },
882                EdgeInsets::symmetric(4.0, 0.0).into(),
883                EdgeInsets::symmetric(4.0, 0.0).into(),
884                effective_text_scale,
885            );
886            effective_segment_style = segment_style
887                .copy_with()
888                .padding(Rc::new(WidgetStatePropertyAll::new(Some(scaled_padding))));
889            let scale = clamp_double(effective_text_scale, 1.0, 2.0) - 1.0;
890            let text_button_theme = TextButtonTheme::of(app, context);
891            let effective_icon_alignment = text_button_theme
892                .style
893                .as_ref()
894                .and_then(|style| style.icon_alignment)
895                .or(segment_style.icon_alignment)
896                .unwrap_or(IconAlignment::Start);
897            content = Row::new()
898                .main_axis_size(MainAxisSize::Min)
899                .spacing(waft_embedder::lerp_double(Some(8.0), Some(4.0), scale).expect("a value"))
900                .children(if effective_icon_alignment == IconAlignment::Start {
901                    vec![icon, Flexible::new(label).into_widget()]
902                } else {
903                    vec![Flexible::new(label).into_widget(), icon]
904                })
905                .into_widget();
906        }
907
908        let enabled = self.enabled(app);
909        let on_pressed = (enabled && segment.enabled).then(|| {
910            let value = segment.value.clone();
911            Listener::new(move |app| self.handle_on_pressed(app, value.clone()))
912        });
913        let button = TextButton::new(on_pressed, Some(content))
914            .style(effective_segment_style)
915            .states_controller(controller)
916            .on_hover(Rc::new(move |app, hovering| {
917                self.set_state(app, |state| state.hovering = hovering);
918            }))
919            .on_focus_change(Rc::new(move |app, focused| {
920                self.set_state(app, |state| state.focused = focused);
921            }))
922            .into_widget();
923
924        let button_with_tooltip = match &segment.tooltip {
925            Some(tooltip) => Tooltip::new()
926                .message(tooltip.clone())
927                .child(button)
928                .into_widget(),
929            None => button,
930        };
931
932        let mut semantics = Semantics::new().selected(segment_selected);
933        if !widget.multi_selection_enabled {
934            semantics = semantics.in_mutually_exclusive_group(true);
935        }
936        MergeSemantics::new()
937            .child(semantics.child(button_with_tooltip))
938            .into_widget()
939    }
940}
941
942impl<T: Clone + PartialEq + Debug + 'static> State for SegmentedButtonState<T> {
943    type Widget = SegmentedButton<T>;
944    waft_widgets::state_accessors!();
945
946    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SegmentedButton<T>) {
947        if !std::ptr::eq(old_widget, self.widget(app)) {
948            let segments = self.widget(app).segments.clone();
949            let controllers = std::mem::take(&mut app.get_mut(self).states_controllers);
950            let mut kept = Vec::new();
951            for (segment, controller) in controllers {
952                if segments.iter().any(|other| other.value == segment.value) {
953                    kept.push((segment, controller));
954                } else {
955                    controller.dispose(app);
956                }
957            }
958            app.get_mut(self).states_controllers = kept;
959        }
960    }
961
962    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
963        let theme = SegmentedButtonTheme::of(app, context);
964        let defaults = SegmentedButtonDefaultsM3::new(context);
965        let text_direction = Directionality::of(app, context);
966        let disabled_state: WidgetStates = [WidgetState::Disabled].into_iter().collect();
967        let widget = self.widget(app).clone();
968        let styles = SegmentedButtonStyles {
969            widget: widget.style.clone(),
970            theme: theme.style.clone(),
971            defaults,
972            states: self.states(app),
973        };
974
975        let segment_style = segment_style_for(widget.style.as_ref());
976        let defaults_style = styles.defaults.style(app);
977        let segment_theme_style = segment_style_for(theme.style.as_ref())
978            .merge(Some(&segment_style_for(defaults_style.as_ref())));
979        let selected_icon = if widget.show_selected_icon {
980            widget
981                .selected_icon
982                .clone()
983                .or_else(|| theme.selected_icon.clone())
984                .or_else(|| styles.defaults.selected_icon(app))
985        } else {
986            None
987        };
988
989        let effective_border = styles
990            .resolve(app, |style| style.shape.as_ref(), None)
991            .unwrap_or_else(|| OutlinedBorderRef::new(RoundedRectangleBorder::default()));
992        let resolved_disabled_border = styles
993            .resolve(app, |style| style.shape.as_ref(), Some(&disabled_state))
994            .unwrap_or_else(|| OutlinedBorderRef::new(RoundedRectangleBorder::default()));
995        let effective_side = styles
996            .resolve(app, |style| style.side.as_ref(), None)
997            .unwrap_or(BorderSide::NONE);
998        let disabled_side = styles
999            .resolve(app, |style| style.side.as_ref(), Some(&disabled_state))
1000            .unwrap_or(BorderSide::NONE);
1001
1002        let enabled_border = effective_border.copy_with(Some(effective_side));
1003        let disabled_border = resolved_disabled_border.copy_with(Some(disabled_side));
1004        let resolved_visual_density = match segment_style
1005            .visual_density
1006            .or(segment_theme_style.visual_density)
1007        {
1008            Some(visual_density) => visual_density,
1009            None => Theme::of(app, context).visual_density,
1010        };
1011        let resolved_padding = styles
1012            .resolve(app, |style| style.padding.as_ref(), None)
1013            .unwrap_or(EdgeInsetsGeometry::ZERO);
1014        let resolved_tap_target_size = match segment_style
1015            .tap_target_size
1016            .or(segment_theme_style.tap_target_size)
1017        {
1018            Some(tap_target_size) => tap_target_size,
1019            None => Theme::of(app, context).material_tap_target_size,
1020        };
1021        let font_size = styles
1022            .resolve(app, |style| style.text_style.as_ref(), None)
1023            .and_then(|text_style| text_style.font_size)
1024            .unwrap_or(20.0);
1025
1026        let buttons: Vec<WidgetRef> = widget
1027            .segments
1028            .iter()
1029            .map(|segment| self.button_for(app, context, segment, &segment_style, &selected_icon))
1030            .collect();
1031
1032        let density_adjustment = resolved_visual_density.base_size_adjustment();
1033        const TEXT_BUTTON_MIN_HEIGHT: f64 = 40.0;
1034
1035        let adjust_button_min_height = TEXT_BUTTON_MIN_HEIGHT + density_adjustment.dy();
1036        let effective_vertical_padding =
1037            resolved_padding.vertical() + density_adjustment.dy() * 2.0;
1038        let effected_button_height =
1039            (font_size + effective_vertical_padding).max(adjust_button_min_height);
1040        let tap_target_vertical_padding = match resolved_tap_target_size {
1041            MaterialTapTargetSize::ShrinkWrap => 0.0,
1042            MaterialTapTargetSize::Padded => {
1043                (K_MIN_INTERACTIVE_DIMENSION + density_adjustment.dy() - effected_button_height)
1044                    .max(0.0)
1045            }
1046        };
1047
1048        let enabled = self.enabled(app);
1049        let mut material = Material::new()
1050            .r#type(MaterialType::Transparency)
1051            .elevation(
1052                styles
1053                    .resolve(app, |style| style.elevation.as_ref(), None)
1054                    .expect("the default style has an elevation"),
1055            );
1056        if let Some(shadow_color) = styles.resolve(app, |style| style.shadow_color.as_ref(), None) {
1057            material = material.shadow_color(shadow_color);
1058        }
1059        if let Some(surface_tint_color) =
1060            styles.resolve(app, |style| style.surface_tint_color.as_ref(), None)
1061        {
1062            material = material.surface_tint_color(surface_tint_color);
1063        }
1064        material
1065            .child(TextButtonTheme::new(
1066                TextButtonThemeData::new().style(segment_theme_style),
1067                Padding::new(
1068                    widget
1069                        .expanded_insets
1070                        .map_or(EdgeInsetsGeometry::ZERO, Into::into),
1071                )
1072                .child(SegmentedButtonRenderWidget {
1073                    segments: widget.segments.clone(),
1074                    enabled_border: if enabled {
1075                        enabled_border
1076                    } else {
1077                        disabled_border.clone()
1078                    },
1079                    disabled_border,
1080                    direction: widget.direction,
1081                    text_direction,
1082                    tap_target_vertical_padding,
1083                    is_expanded: widget.expanded_insets.is_some(),
1084                    children: buttons,
1085                }),
1086            ))
1087            .into_widget()
1088    }
1089
1090    fn dispose(self: Handle<Self>, app: &mut App) {
1091        let controllers = std::mem::take(&mut app.get_mut(self).states_controllers);
1092        for (_, controller) in controllers {
1093            controller.dispose(app);
1094        }
1095    }
1096}
1097
1098/// Dart's `segmentStyleFor`.
1099fn segment_style_for(style: Option<&ButtonStyle>) -> ButtonStyle {
1100    ButtonStyle {
1101        text_style: style.and_then(|style| style.text_style.clone()),
1102        background_color: style.and_then(|style| style.background_color.clone()),
1103        foreground_color: style.and_then(|style| style.foreground_color.clone()),
1104        overlay_color: style.and_then(|style| style.overlay_color.clone()),
1105        surface_tint_color: style.and_then(|style| style.surface_tint_color.clone()),
1106        elevation: style.and_then(|style| style.elevation.clone()),
1107        padding: style.and_then(|style| style.padding.clone()),
1108        icon_color: style.and_then(|style| style.icon_color.clone()),
1109        icon_size: style.and_then(|style| style.icon_size.clone()),
1110        shape: Some(Rc::new(WidgetStatePropertyAll::new(Some(
1111            OutlinedBorderRef::new(RoundedRectangleBorder::default()),
1112        )))),
1113        mouse_cursor: style.and_then(|style| style.mouse_cursor.clone()),
1114        visual_density: style.and_then(|style| style.visual_density),
1115        tap_target_size: style.and_then(|style| style.tap_target_size),
1116        animation_duration: style.and_then(|style| style.animation_duration),
1117        enable_feedback: style.and_then(|style| style.enable_feedback),
1118        alignment: style.and_then(|style| style.alignment),
1119        splash_factory: style.and_then(|style| style.splash_factory.clone()),
1120        ..ButtonStyle::new()
1121    }
1122}
1123
1124/// Dart's `_SegmentedButtonRenderWidget`.
1125struct SegmentedButtonRenderWidget<T> {
1126    segments: Vec<ButtonSegment<T>>,
1127    enabled_border: OutlinedBorderRef,
1128    disabled_border: OutlinedBorderRef,
1129    direction: Axis,
1130    text_direction: TextDirection,
1131    tap_target_vertical_padding: f64,
1132    is_expanded: bool,
1133    children: Vec<WidgetRef>,
1134}
1135
1136impl<T: Debug> Debug for SegmentedButtonRenderWidget<T> {
1137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138        f.debug_struct("SegmentedButtonRenderWidget")
1139            .field("segments", &self.segments)
1140            .field("direction", &self.direction)
1141            .finish_non_exhaustive()
1142    }
1143}
1144
1145impl<T: Clone + PartialEq + Debug + 'static> RenderObjectWidget for SegmentedButtonRenderWidget<T> {
1146    type RenderObject = RenderSegmentedButton<T>;
1147
1148    fn debug_check_constructor(&self) {
1149        debug_assert_eq!(self.children.len(), self.segments.len());
1150    }
1151
1152    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1153        RenderSegmentedButton::new(
1154            app,
1155            self.segments.clone(),
1156            self.enabled_border.clone(),
1157            self.disabled_border.clone(),
1158            self.text_direction,
1159            self.tap_target_vertical_padding,
1160            self.is_expanded,
1161            self.direction,
1162        )
1163        .as_object()
1164    }
1165
1166    fn update_render_object(
1167        &self,
1168        app: &mut App,
1169        _context: BuildContext,
1170        render_object: RenderHandle<RenderSegmentedButton<T>>,
1171    ) {
1172        render_object.set_segments(app, self.segments.clone());
1173        render_object.set_enabled_border(app, self.enabled_border.clone());
1174        render_object.set_disabled_border(app, self.disabled_border.clone());
1175        render_object.set_direction(app, self.direction);
1176        render_object.set_text_direction(app, self.text_direction);
1177    }
1178}
1179
1180impl<T: Clone + PartialEq + Debug + 'static> MultiChildRenderObjectWidget
1181    for SegmentedButtonRenderWidget<T>
1182{
1183    fn children(&self) -> &[WidgetRef] {
1184        &self.children
1185    }
1186}
1187
1188/// Dart's `_SegmentedButtonContainerBoxParentData`.
1189#[derive(Debug, Default)]
1190struct SegmentedButtonContainerBoxParentData {
1191    box_parent_data: BoxParentData,
1192    container_parent_data: ContainerParentData<AnyRenderBox>,
1193    surrounding_rect: Option<RRect>,
1194}
1195
1196impl SegmentedButtonContainerBoxParentData {
1197    const fn new() -> SegmentedButtonContainerBoxParentData {
1198        SegmentedButtonContainerBoxParentData {
1199            box_parent_data: BoxParentData::new(),
1200            container_parent_data: ContainerParentData::new(),
1201            surrounding_rect: None,
1202        }
1203    }
1204}
1205
1206impl ParentData for SegmentedButtonContainerBoxParentData {
1207    fn detach(&mut self) {
1208        ContainerParentDataMixin::detach(self);
1209    }
1210
1211    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
1212        if id == TypeId::of::<SegmentedButtonContainerBoxParentData>() {
1213            return Some(self);
1214        }
1215        self.box_parent_data.provide(id)
1216    }
1217
1218    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
1219        if id == TypeId::of::<SegmentedButtonContainerBoxParentData>() {
1220            return Some(self);
1221        }
1222        self.box_parent_data.provide_mut(id)
1223    }
1224}
1225
1226impl ContainerParentDataMixin for SegmentedButtonContainerBoxParentData {
1227    type ChildType = AnyRenderBox;
1228
1229    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
1230        &self.container_parent_data
1231    }
1232
1233    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
1234        &mut self.container_parent_data
1235    }
1236}
1237
1238impl ContainerBoxParentData for SegmentedButtonContainerBoxParentData {
1239    fn box_parent_data(&self) -> &BoxParentData {
1240        &self.box_parent_data
1241    }
1242
1243    fn box_parent_data_mut(&mut self) -> &mut BoxParentData {
1244        &mut self.box_parent_data
1245    }
1246}
1247
1248impl fmt::Display for SegmentedButtonContainerBoxParentData {
1249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250        fmt::Display::fmt(&self.box_parent_data, f)
1251    }
1252}
1253
1254/// Dart's `_NextChild`.
1255type NextChild<T> =
1256    fn(RenderHandle<RenderSegmentedButton<T>>, &App, AnyRenderBox) -> Option<AnyRenderBox>;
1257
1258/// Dart's `_RenderSegmentedButton`.
1259struct RenderSegmentedButton<T> {
1260    render_object: RenderObjectData,
1261    render_box: RenderBoxData,
1262    container: ContainerRenderObjectData<AnyRenderBox>,
1263    segments: Vec<ButtonSegment<T>>,
1264    enabled_border: OutlinedBorderRef,
1265    disabled_border: OutlinedBorderRef,
1266    text_direction: TextDirection,
1267    direction: Axis,
1268    tap_target_vertical_padding: f64,
1269    is_expanded: bool,
1270}
1271
1272impl<T: Clone + PartialEq + Debug + 'static> RenderSegmentedButton<T> {
1273    #[expect(
1274        clippy::too_many_arguments,
1275        reason = "Dart's constructor takes them as named arguments"
1276    )]
1277    fn new(
1278        app: &mut App,
1279        segments: Vec<ButtonSegment<T>>,
1280        enabled_border: OutlinedBorderRef,
1281        disabled_border: OutlinedBorderRef,
1282        text_direction: TextDirection,
1283        tap_target_vertical_padding: f64,
1284        is_expanded: bool,
1285        direction: Axis,
1286    ) -> RenderHandle<RenderSegmentedButton<T>> {
1287        RenderHandle::new_box(
1288            app,
1289            RenderSegmentedButton {
1290                render_object: RenderObjectData::new(),
1291                render_box: RenderBoxData::new(),
1292                container: ContainerRenderObjectData::new(),
1293                segments,
1294                enabled_border,
1295                disabled_border,
1296                text_direction,
1297                direction,
1298                tap_target_vertical_padding,
1299                is_expanded,
1300            },
1301        )
1302    }
1303
1304    fn set_segments(self: RenderHandle<Self>, app: &mut App, value: Vec<ButtonSegment<T>>) {
1305        if self.get(app).segments == value {
1306            return;
1307        }
1308        self.get_mut(app).segments = value;
1309        self.mark_needs_layout(app);
1310    }
1311
1312    fn set_enabled_border(self: RenderHandle<Self>, app: &mut App, value: OutlinedBorderRef) {
1313        if self.get(app).enabled_border == value {
1314            return;
1315        }
1316        self.get_mut(app).enabled_border = value;
1317        self.mark_needs_layout(app);
1318    }
1319
1320    fn set_disabled_border(self: RenderHandle<Self>, app: &mut App, value: OutlinedBorderRef) {
1321        if self.get(app).disabled_border == value {
1322            return;
1323        }
1324        self.get_mut(app).disabled_border = value;
1325        self.mark_needs_layout(app);
1326    }
1327
1328    fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
1329        self.get(app).text_direction
1330    }
1331
1332    fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
1333        if value == self.get(app).text_direction {
1334            return;
1335        }
1336        self.get_mut(app).text_direction = value;
1337        self.mark_needs_layout(app);
1338    }
1339
1340    fn direction(self: RenderHandle<Self>, app: &App) -> Axis {
1341        self.get(app).direction
1342    }
1343
1344    fn set_direction(self: RenderHandle<Self>, app: &mut App, value: Axis) {
1345        if value == self.get(app).direction {
1346            return;
1347        }
1348        self.get_mut(app).direction = value;
1349        self.mark_needs_layout(app);
1350    }
1351
1352    fn is_expanded(self: RenderHandle<Self>, app: &App) -> bool {
1353        self.get(app).is_expanded
1354    }
1355
1356    /// Dart's `computeMinIntrinsicWidth`, `computeMaxIntrinsicWidth`,
1357    /// `computeMinIntrinsicHeight` and `computeMaxIntrinsicHeight` bodies, which differ only in
1358    /// the child intrinsic they read.
1359    fn max_child_intrinsic(
1360        self: RenderHandle<Self>,
1361        app: &mut App,
1362        extent: f64,
1363        child_intrinsic: fn(AnyRenderBox, &mut App, f64) -> f64,
1364    ) -> f64 {
1365        let mut child = self.first_child(app);
1366        let mut max_extent: f64 = 0.0;
1367        while let Some(current) = child {
1368            let next_sibling = current
1369                .as_object()
1370                .parent_data_of::<SegmentedButtonContainerBoxParentData>(app)
1371                .next_sibling();
1372            let child_extent = child_intrinsic(current, app, extent);
1373            max_extent = max_extent.max(child_extent);
1374            child = next_sibling;
1375        }
1376        max_extent
1377    }
1378
1379    fn layout_rects(
1380        self: RenderHandle<Self>,
1381        app: &mut App,
1382        next_child: NextChild<T>,
1383        left_child: Option<AnyRenderBox>,
1384        _right_child: Option<AnyRenderBox>,
1385    ) {
1386        let mut child = left_child;
1387        let mut start = 0.0;
1388        let direction = self.direction(app);
1389        while let Some(current) = child {
1390            let child_size = current.size(app);
1391            let (offset, r_child_rect);
1392            if direction == Axis::Vertical {
1393                offset = Offset::new(0.0, start);
1394                let child_rect =
1395                    Rect::from_ltwh(0.0, offset.dy(), child_size.width(), child_size.height());
1396                r_child_rect = RRect::from_rect_and_corners(
1397                    child_rect,
1398                    Radius::ZERO,
1399                    Radius::ZERO,
1400                    Radius::ZERO,
1401                    Radius::ZERO,
1402                );
1403                start += child_size.height();
1404            } else {
1405                offset = Offset::new(start, 0.0);
1406                let child_rect =
1407                    Rect::from_ltwh(start, 0.0, child_size.width(), child_size.height());
1408                r_child_rect = RRect::from_rect_and_corners(
1409                    child_rect,
1410                    Radius::ZERO,
1411                    Radius::ZERO,
1412                    Radius::ZERO,
1413                    Radius::ZERO,
1414                );
1415                start += child_size.width();
1416            }
1417            let child_parent_data = current
1418                .as_object()
1419                .parent_data_of_mut::<SegmentedButtonContainerBoxParentData>(app);
1420            child_parent_data.set_offset(offset);
1421            child_parent_data.surrounding_rect = Some(r_child_rect);
1422            child = next_child(self, app, current);
1423        }
1424    }
1425
1426    fn calculate_child_size(
1427        self: RenderHandle<Self>,
1428        app: &mut App,
1429        constraints: BoxConstraints,
1430    ) -> Size {
1431        if self.direction(app) == Axis::Horizontal {
1432            self.calculate_horizontal_child_size(app, constraints)
1433        } else {
1434            self.calculate_vertical_child_size(app, constraints)
1435        }
1436    }
1437
1438    fn calculate_horizontal_child_size(
1439        self: RenderHandle<Self>,
1440        app: &mut App,
1441        constraints: BoxConstraints,
1442    ) -> Size {
1443        let mut max_height: f64 = 0.0;
1444        let mut child = self.first_child(app);
1445        let child_count = self.child_count(app) as f64;
1446        let mut child_width;
1447        if self.is_expanded(app) {
1448            child_width = constraints.max_width / child_count;
1449        } else {
1450            child_width = constraints.min_width / child_count;
1451            while let Some(current) = child {
1452                child_width = child_width.max(current.get_max_intrinsic_width(app, f64::INFINITY));
1453                child = self.child_after(app, current);
1454            }
1455            child_width = child_width.min(constraints.max_width / child_count);
1456        }
1457        child = self.first_child(app);
1458        while let Some(current) = child {
1459            let box_height = current.get_max_intrinsic_height(app, child_width);
1460            max_height = max_height.max(box_height);
1461            child = self.child_after(app, current);
1462        }
1463        Size::new(child_width, max_height)
1464    }
1465
1466    fn calculate_vertical_child_size(
1467        self: RenderHandle<Self>,
1468        app: &mut App,
1469        constraints: BoxConstraints,
1470    ) -> Size {
1471        let mut max_width: f64 = 0.0;
1472        let mut child = self.first_child(app);
1473        let child_count = self.child_count(app) as f64;
1474        let mut child_height;
1475        if self.is_expanded(app) {
1476            child_height = constraints.max_height / child_count;
1477        } else {
1478            child_height = constraints.min_height / child_count;
1479            while let Some(current) = child {
1480                child_height =
1481                    child_height.max(current.get_max_intrinsic_height(app, f64::INFINITY));
1482                child = self.child_after(app, current);
1483            }
1484            child_height = child_height.min(constraints.max_height / child_count);
1485        }
1486        child = self.first_child(app);
1487        while let Some(current) = child {
1488            let box_width = current.get_max_intrinsic_width(app, max_width);
1489            max_width = max_width.max(box_width);
1490            child = self.child_after(app, current);
1491        }
1492
1493        let mut child_size = Size::new(max_width, child_height);
1494
1495        // When the parent provides a tight width constraint in the vertical
1496        // direction, use that width for layout so the visual size and the
1497        // interactive area match. This preserves the intrinsic (shrink-wrap)
1498        // sizing behavior when the width is unconstrained.
1499        if constraints.has_tight_width() && child_size.width() < constraints.max_width {
1500            child_size = Size::new(constraints.max_width, child_size.height());
1501        }
1502
1503        child_size
1504    }
1505
1506    fn compute_overall_size_from_child_size(
1507        self: RenderHandle<Self>,
1508        app: &App,
1509        child_size: Size,
1510    ) -> Size {
1511        let constraints = self.constraints(app);
1512        let child_count = self.child_count(app) as f64;
1513        if self.direction(app) == Axis::Vertical {
1514            return constraints.constrain(Size::new(
1515                child_size.width(),
1516                child_size.height() * child_count,
1517            ));
1518        }
1519        constraints.constrain(Size::new(
1520            child_size.width() * child_count,
1521            child_size.height(),
1522        ))
1523    }
1524}
1525
1526impl<T: Clone + PartialEq + Debug + 'static> ContainerRenderObjectMixin
1527    for RenderSegmentedButton<T>
1528{
1529    type ChildType = AnyRenderBox;
1530    type ParentDataType = SegmentedButtonContainerBoxParentData;
1531
1532    fn container_data(
1533        self: RenderHandle<Self>,
1534        app: &App,
1535    ) -> &ContainerRenderObjectData<AnyRenderBox> {
1536        &self.get(app).container
1537    }
1538
1539    fn container_data_mut(
1540        self: RenderHandle<Self>,
1541        app: &mut App,
1542    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
1543        &mut self.get_mut(app).container
1544    }
1545}
1546
1547impl<T: Clone + PartialEq + Debug + 'static> RenderBoxContainerDefaultsMixin
1548    for RenderSegmentedButton<T>
1549{
1550}
1551
1552impl<T: Clone + PartialEq + Debug + 'static> RenderObject for RenderSegmentedButton<T> {
1553    waft_rendering::render_object_accessors!();
1554
1555    fn debug_describe_children(
1556        self: RenderHandle<Self>,
1557        app: &App,
1558    ) -> Vec<Rc<dyn DiagnosticsNode>> {
1559        ContainerRenderObjectMixin::debug_describe_children(self, app)
1560    }
1561
1562    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1563        let constraints = self.constraints(app);
1564        let child_size = self.calculate_child_size(app, constraints);
1565
1566        let child_constraints =
1567            BoxConstraints::tight_for(Some(child_size.width()), Some(child_size.height()));
1568
1569        let mut child = self.first_child(app);
1570        while let Some(current) = child {
1571            current.layout(app, child_constraints, true);
1572            child = self.child_after(app, current);
1573        }
1574
1575        match self.text_direction(app) {
1576            TextDirection::Rtl => {
1577                let (last_child, first_child) = (self.last_child(app), self.first_child(app));
1578                self.layout_rects(
1579                    app,
1580                    |this, app, child| this.child_before(app, child),
1581                    last_child,
1582                    first_child,
1583                );
1584            }
1585            TextDirection::Ltr => {
1586                let (first_child, last_child) = (self.first_child(app), self.last_child(app));
1587                self.layout_rects(
1588                    app,
1589                    |this, app, child| this.child_after(app, child),
1590                    first_child,
1591                    last_child,
1592                );
1593            }
1594        }
1595
1596        let size = self.compute_overall_size_from_child_size(app, child_size);
1597        self.set_size(app, size);
1598    }
1599
1600    fn paint(
1601        self: RenderHandle<Self>,
1602        app: &mut App,
1603        context: &mut PaintingContext,
1604        offset: Offset,
1605    ) {
1606        let size = self.size(app);
1607        let text_direction = self.text_direction(app);
1608        let tap_target_vertical_padding = self.get(app).tap_target_vertical_padding;
1609        let enabled_border = self.get(app).enabled_border.clone();
1610        let disabled_border = self.get(app).disabled_border.clone();
1611        let direction = self.direction(app);
1612        let segments = self.get(app).segments.clone();
1613        let border_rect = Rect::from_ltwh(
1614            offset.dx(),
1615            offset.dy() + tap_target_vertical_padding / 2.0,
1616            size.width(),
1617            size.height() - tap_target_vertical_padding,
1618        );
1619        let border_clip_path = enabled_border.get_inner_path(border_rect, Some(text_direction));
1620        let (first_child, last_child) = (self.first_child(app), self.last_child(app));
1621        let mut child = first_child;
1622        let mut previous_child: Option<AnyRenderBox> = None;
1623        let mut index = 0;
1624        let mut enabled_clip_path: Option<PathBuilder> = None;
1625        let mut disabled_clip_path: Option<PathBuilder> = None;
1626
1627        while let Some(current) = child {
1628            let child_parent_data = current
1629                .as_object()
1630                .parent_data_of::<SegmentedButtonContainerBoxParentData>(app);
1631            let child_offset = child_parent_data.offset();
1632            let child_rect = child_parent_data
1633                .surrounding_rect
1634                .expect("laid out")
1635                .outer_rect()
1636                .shift(offset);
1637
1638            let canvas = context.canvas();
1639            canvas.save();
1640            canvas.clip_path(
1641                border_clip_path.as_valo(),
1642                border_clip_path.fill_type,
1643                waft_embedder::ClipOp::Intersect,
1644                true,
1645            );
1646            context.paint_child(app, current.as_object(), child_offset + offset);
1647            context.canvas().restore();
1648
1649            // Compute a clip rect for the outer border of the child.
1650            let (segment_left, segment_right, divider_pos);
1651            let border_outset = enabled_border
1652                .side()
1653                .stroke_outset()
1654                .max(disabled_border.side().stroke_outset());
1655            match text_direction {
1656                TextDirection::Rtl => {
1657                    segment_left = if Some(current) == last_child {
1658                        border_rect.left - border_outset
1659                    } else {
1660                        child_rect.left
1661                    };
1662                    segment_right = if Some(current) == first_child {
1663                        border_rect.right + border_outset
1664                    } else {
1665                        child_rect.right
1666                    };
1667                    divider_pos = segment_right;
1668                }
1669                TextDirection::Ltr => {
1670                    segment_left = if Some(current) == first_child {
1671                        border_rect.left - border_outset
1672                    } else {
1673                        child_rect.left
1674                    };
1675                    segment_right = if Some(current) == last_child {
1676                        border_rect.right + border_outset
1677                    } else {
1678                        child_rect.right
1679                    };
1680                    divider_pos = segment_left;
1681                }
1682            }
1683            let segment_clip_rect = Rect::from_ltrb(
1684                segment_left,
1685                border_rect.top - border_outset,
1686                segment_right,
1687                border_rect.bottom + border_outset,
1688            );
1689
1690            // Add the clip rect to the appropriate border clip path
1691            if segments[index].enabled {
1692                enabled_clip_path
1693                    .get_or_insert_with(PathBuilder::new)
1694                    .rect(segment_clip_rect.into());
1695            } else {
1696                disabled_clip_path
1697                    .get_or_insert_with(PathBuilder::new)
1698                    .rect(segment_clip_rect.into());
1699            }
1700
1701            // Paint the divider between this segment and the previous one.
1702            if previous_child.is_some() {
1703                let divider = if segments[index - 1].enabled || segments[index].enabled {
1704                    enabled_border.side().copy_with(None, None, None, Some(0.0))
1705                } else {
1706                    disabled_border
1707                        .side()
1708                        .copy_with(None, None, None, Some(0.0))
1709                };
1710                if direction == Axis::Horizontal {
1711                    let top = Offset::new(divider_pos, border_rect.top);
1712                    let bottom = Offset::new(divider_pos, border_rect.bottom);
1713                    draw_line(context.canvas(), top, bottom, &divider.to_paint());
1714                } else if direction == Axis::Vertical {
1715                    let start = Offset::new(border_rect.left, child_rect.top);
1716                    let end = Offset::new(border_rect.right, child_rect.top);
1717                    let canvas = context.canvas();
1718                    canvas.save();
1719                    canvas.clip_path(
1720                        border_clip_path.as_valo(),
1721                        border_clip_path.fill_type,
1722                        waft_embedder::ClipOp::Intersect,
1723                        true,
1724                    );
1725                    draw_line(canvas, start, end, &divider.to_paint());
1726                    canvas.restore();
1727                }
1728            }
1729
1730            previous_child = Some(current);
1731            child = self.child_after(app, current);
1732            index += 1;
1733        }
1734
1735        // Paint the outer border for both disabled and enabled clip rect if needed.
1736        let canvas = context.canvas();
1737        match (enabled_clip_path, disabled_clip_path) {
1738            (_, None) => {
1739                // Just paint the enabled border with no clip.
1740                enabled_border.paint(canvas, border_rect, Some(text_direction));
1741            }
1742            (None, Some(_)) => {
1743                // Just paint the disabled border with no.
1744                disabled_border.paint(canvas, border_rect, Some(text_direction));
1745            }
1746            (Some(enabled_clip_path), Some(disabled_clip_path)) => {
1747                // Paint both of them clipped appropriately for the children segments.
1748                let enabled_clip_path: waft_embedder::Path = enabled_clip_path.build().into();
1749                let disabled_clip_path: waft_embedder::Path = disabled_clip_path.build().into();
1750                canvas.save();
1751                canvas.clip_path(
1752                    enabled_clip_path.as_valo(),
1753                    enabled_clip_path.fill_type,
1754                    waft_embedder::ClipOp::Intersect,
1755                    true,
1756                );
1757                enabled_border.paint(canvas, border_rect, Some(text_direction));
1758                canvas.restore();
1759                canvas.save();
1760                canvas.clip_path(
1761                    disabled_clip_path.as_valo(),
1762                    disabled_clip_path.fill_type,
1763                    waft_embedder::ClipOp::Intersect,
1764                    true,
1765                );
1766                disabled_border.paint(canvas, border_rect, Some(text_direction));
1767                canvas.restore();
1768            }
1769        }
1770    }
1771
1772    fn visit_children(
1773        self: RenderHandle<Self>,
1774        app: &App,
1775        visitor: &mut dyn FnMut(AnyRenderObject),
1776    ) {
1777        ContainerRenderObjectMixin::visit_children(self, app, visitor)
1778    }
1779
1780    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
1781        ContainerRenderObjectMixin::did_attach(self, app, owner)
1782    }
1783
1784    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1785        ContainerRenderObjectMixin::did_detach(self, app)
1786    }
1787
1788    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1789        ContainerRenderObjectMixin::redepth_children(self, app)
1790    }
1791}
1792
1793impl<T: Clone + PartialEq + Debug + 'static> RenderBox for RenderSegmentedButton<T> {
1794    waft_rendering::render_box_accessors!();
1795
1796    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1797        if !child.parent_data_is::<SegmentedButtonContainerBoxParentData>(app) {
1798            child.set_parent_data(app, SegmentedButtonContainerBoxParentData::new());
1799        }
1800    }
1801
1802    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1803        let min_width = self.max_child_intrinsic(app, height, |child, app, height| {
1804            child.get_min_intrinsic_width(app, height)
1805        });
1806        min_width * self.child_count(app) as f64
1807    }
1808
1809    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1810        let max_width = self.max_child_intrinsic(app, height, |child, app, height| {
1811            child.get_max_intrinsic_width(app, height)
1812        });
1813        max_width * self.child_count(app) as f64
1814    }
1815
1816    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1817        self.max_child_intrinsic(app, width, |child, app, width| {
1818            child.get_min_intrinsic_height(app, width)
1819        })
1820    }
1821
1822    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1823        self.max_child_intrinsic(app, width, |child, app, width| {
1824            child.get_max_intrinsic_height(app, width)
1825        })
1826    }
1827
1828    fn compute_distance_to_actual_baseline(
1829        self: RenderHandle<Self>,
1830        app: &mut App,
1831        baseline: TextBaseline,
1832    ) -> Option<f64> {
1833        self.default_compute_distance_to_highest_actual_baseline(app, baseline)
1834    }
1835
1836    fn compute_dry_layout(
1837        self: RenderHandle<Self>,
1838        app: &mut App,
1839        constraints: BoxConstraints,
1840    ) -> Size {
1841        let child_size = self.calculate_child_size(app, constraints);
1842        self.compute_overall_size_from_child_size(app, child_size)
1843    }
1844
1845    fn compute_dry_baseline(
1846        self: RenderHandle<Self>,
1847        app: &mut App,
1848        constraints: BoxConstraints,
1849        baseline: TextBaseline,
1850    ) -> Option<f64> {
1851        let child_size = self.calculate_child_size(app, constraints);
1852        let child_constraints = BoxConstraints::tight(child_size);
1853
1854        let mut baseline_offset = BaselineOffset::NO_BASELINE;
1855        let mut child = self.first_child(app);
1856        while let Some(current) = child {
1857            baseline_offset = baseline_offset.min_of(BaselineOffset(current.get_dry_baseline(
1858                app,
1859                child_constraints,
1860                baseline,
1861            )));
1862            child = self.child_after(app, current);
1863        }
1864        baseline_offset.offset()
1865    }
1866
1867    fn hit_test_children(
1868        self: RenderHandle<Self>,
1869        app: &mut App,
1870        result: &mut BoxHitTestResult<'_>,
1871        position: Offset,
1872    ) -> bool {
1873        let mut child = self.last_child(app);
1874        while let Some(current) = child {
1875            let child_parent_data = current
1876                .as_object()
1877                .parent_data_of::<SegmentedButtonContainerBoxParentData>(app);
1878            let offset = child_parent_data.offset();
1879            let surrounding_rect = child_parent_data.surrounding_rect.expect("laid out");
1880            let previous_sibling = child_parent_data.previous_sibling();
1881            if surrounding_rect.contains(position) {
1882                return result.add_with_paint_offset(
1883                    Some(offset),
1884                    position,
1885                    |result, local_offset| {
1886                        debug_assert_eq!(local_offset, position - offset);
1887                        current.hit_test(app, result, local_offset)
1888                    },
1889                );
1890            }
1891            child = previous_sibling;
1892        }
1893        false
1894    }
1895}
1896
1897#[cfg(test)]
1898#[allow(deprecated, reason = "Dart's tests call `withOpacity`")]
1899pub(crate) mod tests {
1900    //! Ported from `test/segmented_button_test.dart`; the goldens, the semantics-tree cases and
1901    //! the `paints` cases that read an ordered call sequence are not ported.
1902
1903    use std::cell::RefCell;
1904
1905    use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey, SystemMouseCursors};
1906    use waft_widgets::{Center, Icon, IconData, Row, Text};
1907
1908    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
1909
1910    use super::*;
1911    use crate::icons::Icons;
1912    use crate::scaffold::Scaffold;
1913    use crate::test_support::{PaintInspection, material_app};
1914    use crate::theme_data::ThemeData;
1915    use crate::tooltip::tests::m3;
1916    use waft_rendering::testing::RecordedCall;
1917
1918    pub(crate) fn label(text: &str) -> Text {
1919        Text::new(text)
1920    }
1921
1922    pub(crate) fn numbered(values: &[i32]) -> Vec<ButtonSegment<i32>> {
1923        values
1924            .iter()
1925            .map(|value| ButtonSegment::new(*value).label(label(&value.to_string())))
1926            .collect()
1927    }
1928
1929    /// `MaterialApp(theme: theme, home: Scaffold(body: Center(child: button)))`.
1930    pub(crate) fn pump_button<T: Clone + PartialEq + Debug + 'static>(
1931        tester: &mut WidgetTester,
1932        theme: impl FnOnce(&App) -> ThemeData,
1933        button: SegmentedButton<T>,
1934    ) {
1935        let root = {
1936            let app = tester.cell.borrow();
1937            material_app(
1938                theme(&app),
1939                Scaffold::new()
1940                    .body(Center::new().child(button))
1941                    .into_widget(),
1942            )
1943        };
1944        tester.pump_widget(root);
1945    }
1946
1947    fn state_of(tester: &WidgetTester) -> Handle<SegmentedButtonState<i32>> {
1948        let element = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
1949        element
1950            .state_handle::<SegmentedButtonState<i32>>(&tester.cell.borrow())
1951            .expect("a segmented button state")
1952    }
1953
1954    // 'SegmentedButton releases state controllers for deleted segments'
1955    #[test]
1956    fn a_segmented_button_releases_the_state_controllers_of_deleted_segments() {
1957        test_widgets(|tester| {
1958            let key = waft_foundation::UniqueKey::new();
1959            pump_button(
1960                tester,
1961                m3,
1962                SegmentedButton::new(numbered(&[1, 2]), vec![2]).key(key.into()),
1963            );
1964            pump_button(
1965                tester,
1966                m3,
1967                SegmentedButton::new(numbered(&[2, 3]), vec![2]).key(key.into()),
1968            );
1969
1970            let state = state_of(tester);
1971            let app = tester.cell.borrow();
1972            let controllers = &app.get(state).states_controllers;
1973            assert_eq!(controllers.len(), 2);
1974            assert_eq!(controllers.first().expect("a controller").0.value, 2);
1975            assert_eq!(controllers.last().expect("a controller").0.value, 3);
1976        });
1977    }
1978
1979    // 'SegmentedButton is built with Material of type MaterialType.transparency'
1980    #[test]
1981    fn a_segmented_button_is_built_with_a_transparent_material() {
1982        test_widgets(|tester| {
1983            pump_button(
1984                tester,
1985                m3,
1986                SegmentedButton::new(
1987                    vec![
1988                        ButtonSegment::new(1).label(label("1")),
1989                        ButtonSegment::new(2).label(label("2")),
1990                        ButtonSegment::new(3).label(label("3")).enabled(false),
1991                    ],
1992                    vec![2],
1993                )
1994                .on_selection_changed(|_app, _selected| {}),
1995            );
1996
1997            // Expect SegmentedButton to be built with type MaterialType.transparency.
1998            let parent_material = tester.element(
1999                find::ancestor(
2000                    find::ancestor(find::text("1"), find::by_type::<Material>()).first(),
2001                    find::by_type::<Material>(),
2002                )
2003                .first(),
2004            );
2005            let material_type =
2006                tester.widget::<Material, _>(parent_material, |material| material.r#type);
2007            assert_eq!(material_type, MaterialType::Transparency);
2008        });
2009    }
2010
2011    /// The state a pumped selection and a recording callback give.
2012    struct Recording {
2013        callback_count: Rc<RefCell<u32>>,
2014        selection: Rc<RefCell<Vec<i32>>>,
2015    }
2016
2017    impl Recording {
2018        fn new(selection: Vec<i32>) -> Recording {
2019            Recording {
2020                callback_count: Rc::new(RefCell::new(0)),
2021                selection: Rc::new(RefCell::new(selection)),
2022            }
2023        }
2024
2025        fn callback_count(&self) -> u32 {
2026            *self.callback_count.borrow()
2027        }
2028
2029        fn selection(&self) -> Vec<i32> {
2030            self.selection.borrow().clone()
2031        }
2032
2033        fn on_selection_changed(&self) -> impl Fn(&mut App, Vec<i32>) + 'static {
2034            let (callback_count, selection) =
2035                (Rc::clone(&self.callback_count), Rc::clone(&self.selection));
2036            move |_app, selected| {
2037                *selection.borrow_mut() = selected;
2038                *callback_count.borrow_mut() += 1;
2039            }
2040        }
2041    }
2042
2043    fn sorted(mut values: Vec<i32>) -> Vec<i32> {
2044        values.sort();
2045        values
2046    }
2047
2048    // 'SegmentedButton supports exclusive choice by default'
2049    #[test]
2050    fn a_segmented_button_supports_exclusive_choice_by_default() {
2051        test_widgets(|tester| {
2052            let recording = Recording::new(vec![2]);
2053            let frame_with_selection = |tester: &mut WidgetTester, selected: i32| {
2054                pump_button(
2055                    tester,
2056                    m3,
2057                    SegmentedButton::new(numbered(&[1, 2, 3]), vec![selected])
2058                        .on_selection_changed(recording.on_selection_changed()),
2059                );
2060            };
2061
2062            frame_with_selection(tester, 2);
2063            assert_eq!(recording.selection(), [2]);
2064            assert_eq!(recording.callback_count(), 0);
2065
2066            // Tap on segment 1.
2067            tester.tap(find::text("1"));
2068            tester.pump_and_settle();
2069            assert_eq!(recording.callback_count(), 1);
2070            assert_eq!(recording.selection(), [1]);
2071
2072            // Update the selection in the widget
2073            frame_with_selection(tester, 1);
2074
2075            // Tap on segment 1 again should do nothing.
2076            tester.tap(find::text("1"));
2077            tester.pump_and_settle();
2078            assert_eq!(recording.callback_count(), 1);
2079            assert_eq!(recording.selection(), [1]);
2080
2081            // Tap on segment 3.
2082            tester.tap(find::text("3"));
2083            tester.pump_and_settle();
2084            assert_eq!(recording.callback_count(), 2);
2085            assert_eq!(recording.selection(), [3]);
2086        });
2087    }
2088
2089    // 'SegmentedButton supports multiple selected segments'
2090    #[test]
2091    fn a_segmented_button_supports_multiple_selected_segments() {
2092        test_widgets(|tester| {
2093            let recording = Recording::new(vec![1]);
2094            let frame_with_selection = |tester: &mut WidgetTester, selected: Vec<i32>| {
2095                pump_button(
2096                    tester,
2097                    m3,
2098                    SegmentedButton::new(numbered(&[1, 2, 3]), selected)
2099                        .multi_selection_enabled(true)
2100                        .on_selection_changed(recording.on_selection_changed()),
2101                );
2102            };
2103
2104            frame_with_selection(tester, recording.selection());
2105            assert_eq!(recording.selection(), [1]);
2106            assert_eq!(recording.callback_count(), 0);
2107
2108            // Tap on segment 2.
2109            tester.tap(find::text("2"));
2110            tester.pump_and_settle();
2111            assert_eq!(recording.callback_count(), 1);
2112            assert_eq!(sorted(recording.selection()), [1, 2]);
2113
2114            // Update the selection in the widget
2115            frame_with_selection(tester, vec![1, 2]);
2116            tester.pump_and_settle();
2117
2118            // Tap on segment 1 again should remove it from selection.
2119            tester.tap(find::text("1"));
2120            tester.pump_and_settle();
2121            assert_eq!(recording.callback_count(), 2);
2122            assert_eq!(recording.selection(), [2]);
2123
2124            // Update the selection in the widget
2125            frame_with_selection(tester, vec![2]);
2126            tester.pump_and_settle();
2127
2128            // Tap on segment 3.
2129            tester.tap(find::text("3"));
2130            tester.pump_and_settle();
2131            assert_eq!(recording.callback_count(), 3);
2132            assert_eq!(sorted(recording.selection()), [2, 3]);
2133        });
2134    }
2135
2136    // 'SegmentedButton allows for empty selection'
2137    #[test]
2138    fn a_segmented_button_allows_for_empty_selection() {
2139        test_widgets(|tester| {
2140            let recording = Recording::new(vec![1]);
2141            let frame_with_selection = |tester: &mut WidgetTester, selected: Vec<i32>| {
2142                pump_button(
2143                    tester,
2144                    m3,
2145                    SegmentedButton::new(numbered(&[1, 2, 3]), selected)
2146                        .empty_selection_allowed(true)
2147                        .on_selection_changed(recording.on_selection_changed()),
2148                );
2149            };
2150
2151            frame_with_selection(tester, vec![1]);
2152            assert_eq!(recording.selection(), [1]);
2153            assert_eq!(recording.callback_count(), 0);
2154
2155            // Tap on segment 1 should deselect it and make the selection empty.
2156            tester.tap(find::text("1"));
2157            tester.pump_and_settle();
2158            assert_eq!(recording.callback_count(), 1);
2159            assert_eq!(recording.selection(), Vec::<i32>::new());
2160
2161            // Update the selection in the widget
2162            frame_with_selection(tester, vec![]);
2163
2164            // Tap on segment 2 should select it.
2165            tester.tap(find::text("2"));
2166            tester.pump_and_settle();
2167            assert_eq!(recording.callback_count(), 2);
2168            assert_eq!(recording.selection(), [2]);
2169
2170            // Update the selection in the widget
2171            frame_with_selection(tester, vec![2]);
2172
2173            // Tap on segment 3.
2174            tester.tap(find::text("3"));
2175            tester.pump_and_settle();
2176            assert_eq!(recording.callback_count(), 3);
2177            assert_eq!(recording.selection(), [3]);
2178        });
2179    }
2180
2181    /// `find.descendant(of: find.widgetWithText(Row, text), matching: find.byIcon(icon))`.
2182    fn icons_in_rows_with_text(tester: &WidgetTester, text: &str, icon: &IconData) -> usize {
2183        find::descendant(find::widget_with_text::<Row>(text), find::by_icon(icon))
2184            .evaluate(tester)
2185            .len()
2186    }
2187
2188    /// `find.descendant(of: find.widgetWithIcon(Row, icon1), matching: find.byIcon(icon2))`.
2189    fn icons_in_rows_with_icon(tester: &WidgetTester, icon1: &IconData, icon2: &IconData) -> usize {
2190        find::descendant(find::widget_with_icon::<Row>(icon1), find::by_icon(icon2))
2191            .evaluate(tester)
2192            .len()
2193    }
2194
2195    fn count_icons(tester: &WidgetTester, icon: &IconData) -> usize {
2196        find::by_type::<Icon>()
2197            .evaluate(tester)
2198            .into_iter()
2199            .filter(|element| {
2200                tester.widget(*element, |widget: &Icon| widget.icon.as_ref() == Some(icon))
2201            })
2202            .count()
2203    }
2204
2205    // 'SegmentedButton shows checkboxes for selected segments'
2206    #[test]
2207    fn a_segmented_button_shows_checkboxes_for_selected_segments() {
2208        test_widgets(|tester| {
2209            let check = Icons::check();
2210            for selected in [1, 2, 2] {
2211                pump_button(
2212                    tester,
2213                    m3,
2214                    SegmentedButton::new(numbered(&[1, 2, 3]), vec![selected])
2215                        .on_selection_changed(|_app, _selected| {}),
2216                );
2217                assert_eq!(
2218                    icons_in_rows_with_text(tester, &selected.to_string(), &check),
2219                    1
2220                );
2221                assert_eq!(count_icons(tester, &check), 1);
2222            }
2223        });
2224    }
2225
2226    // 'SegmentedButton shows selected checkboxes in place of icon if it has a label as well'
2227    #[test]
2228    fn a_segmented_button_shows_selected_checkboxes_in_place_of_the_icon_of_a_labelled_segment() {
2229        test_widgets(|tester| {
2230            let icons = [Icons::add(), Icons::add_a_photo(), Icons::add_alarm()];
2231            let check = Icons::check();
2232            for selected in 1..=3 {
2233                let segments = (1..=3)
2234                    .map(|value| {
2235                        ButtonSegment::new(value)
2236                            .icon(Icon::new(Some(icons[value as usize - 1].clone())))
2237                            .label(label(&value.to_string()))
2238                    })
2239                    .collect();
2240                pump_button(
2241                    tester,
2242                    m3,
2243                    SegmentedButton::new(segments, vec![selected])
2244                        .on_selection_changed(|_app, _selected| {}),
2245                );
2246                for value in 1..=3 {
2247                    let text = value.to_string();
2248                    let shown = if value == selected {
2249                        &check
2250                    } else {
2251                        &icons[value as usize - 1]
2252                    };
2253                    assert_eq!(icons_in_rows_with_text(tester, &text, shown), 1);
2254                    if value == selected {
2255                        assert_eq!(count_icons(tester, &icons[value as usize - 1]), 0);
2256                    }
2257                }
2258            }
2259        });
2260    }
2261
2262    // 'SegmentedButton shows selected checkboxes next to icon if there is no label'
2263    #[test]
2264    fn a_segmented_button_shows_selected_checkboxes_next_to_the_icon_of_an_unlabelled_segment() {
2265        test_widgets(|tester| {
2266            let icons = [Icons::add(), Icons::add_a_photo(), Icons::add_alarm()];
2267            let check = Icons::check();
2268            for selected in 1..=3 {
2269                let segments = (1..=3)
2270                    .map(|value| {
2271                        ButtonSegment::new(value)
2272                            .icon(Icon::new(Some(icons[value as usize - 1].clone())))
2273                    })
2274                    .collect();
2275                pump_button(
2276                    tester,
2277                    m3,
2278                    SegmentedButton::new(segments, vec![selected])
2279                        .on_selection_changed(|_app, _selected| {}),
2280                );
2281                for value in 1..=3 {
2282                    let expected = usize::from(value == selected);
2283                    assert_eq!(
2284                        icons_in_rows_with_icon(tester, &icons[value as usize - 1], &check),
2285                        expected
2286                    );
2287                }
2288            }
2289        });
2290    }
2291
2292    fn tooltip_messages(tester: &WidgetTester) -> Vec<String> {
2293        find::by_type::<Tooltip>()
2294            .evaluate(tester)
2295            .into_iter()
2296            .filter_map(|element| {
2297                tester.widget(element, |tooltip: &Tooltip| tooltip.message.clone())
2298            })
2299            .collect()
2300    }
2301
2302    fn three_segments_with_tooltips(tooltips: bool) -> Vec<ButtonSegment<i32>> {
2303        let mut segments = numbered(&[1, 2, 3]);
2304        segments[2].enabled = false;
2305        if tooltips {
2306            segments[1].tooltip = Some("t2".to_string());
2307            segments[2].tooltip = Some("t3".to_string());
2308        }
2309        segments
2310    }
2311
2312    // 'SegmentedButton has no tooltips by default'
2313    #[test]
2314    fn a_segmented_button_has_no_tooltips_by_default() {
2315        test_widgets(|tester| {
2316            pump_button(
2317                tester,
2318                m3,
2319                SegmentedButton::new(three_segments_with_tooltips(false), vec![2])
2320                    .on_selection_changed(|_app, _selected| {}),
2321            );
2322
2323            assert!(find::by_type::<Tooltip>().evaluate(tester).is_empty());
2324        });
2325    }
2326
2327    // 'SegmentedButton has correct tooltips'
2328    #[test]
2329    fn a_segmented_button_has_the_tooltips_of_its_segments() {
2330        test_widgets(|tester| {
2331            pump_button(
2332                tester,
2333                m3,
2334                SegmentedButton::new(three_segments_with_tooltips(true), vec![2])
2335                    .on_selection_changed(|_app, _selected| {}),
2336            );
2337
2338            assert_eq!(find::by_type::<Tooltip>().evaluate(tester).len(), 2);
2339            assert_eq!(tooltip_messages(tester), ["t2", "t3"]);
2340        });
2341    }
2342
2343    // 'Disabled SegmentedButton has correct states when rebuilding'
2344    #[test]
2345    fn a_disabled_segmented_button_keeps_its_states_when_rebuilding() {
2346        test_widgets(|tester| {
2347            // Dart's `const SegmentedButton`: one widget the rebuild hands on again.
2348            let button = SegmentedButton::new(numbered(&[0]), vec![0]).into_widget();
2349            let root = {
2350                let app = tester.cell.borrow();
2351                material_app(
2352                    m3(&app),
2353                    Scaffold::new()
2354                        .body(Center::new().child(waft_widgets::StatefulBuilder::new(
2355                            move |_app, _context, set_state| {
2356                                waft_widgets::Column::new()
2357                                    .children([
2358                                        button.clone(),
2359                                        crate::elevated_button::ElevatedButton::new(
2360                                            Some(Listener::new(move |app| {
2361                                                set_state(app, &mut |_| {})
2362                                            })),
2363                                            Some(label("Trigger rebuild")),
2364                                        )
2365                                        .into_widget(),
2366                                    ])
2367                                    .into_widget()
2368                            },
2369                        )))
2370                        .into_widget(),
2371                )
2372            };
2373            tester.pump_widget(root);
2374            let states: WidgetStates = [WidgetState::Selected, WidgetState::Disabled]
2375                .into_iter()
2376                .collect();
2377            let first_states = |tester: &WidgetTester| {
2378                let state = state_of(tester);
2379                let app = tester.cell.borrow();
2380                let controller = app
2381                    .get(state)
2382                    .states_controllers
2383                    .first()
2384                    .expect("a controller")
2385                    .1
2386                    .clone();
2387                app.get(&controller).value().clone()
2388            };
2389            // Check the initial states.
2390            assert_eq!(first_states(tester), states);
2391            // Trigger a rebuild.
2392            tester.tap(find::text("Trigger rebuild"));
2393            tester.pump_and_settle();
2394            // Check the states after the rebuild.
2395            assert_eq!(first_states(tester), states);
2396        });
2397    }
2398
2399    fn segmented_button_width(tester: &WidgetTester) -> f64 {
2400        let element = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
2401        tester.get_size(element).width()
2402    }
2403
2404    fn scaffold_width(tester: &WidgetTester) -> f64 {
2405        let element = find::by_type::<Scaffold>().evaluate(tester)[0];
2406        tester.get_size(element).width()
2407    }
2408
2409    // 'SegmentedButton expands to fill the available width when expandedInsets is not null'
2410    #[test]
2411    fn a_segmented_button_with_expanded_insets_expands_to_the_available_width() {
2412        test_widgets(|tester| {
2413            let segments = vec![
2414                ButtonSegment::new(1).label(label("Segment 1")),
2415                ButtonSegment::new(2).label(label("Segment 2")),
2416            ];
2417            pump_button(
2418                tester,
2419                m3,
2420                SegmentedButton::new(segments, vec![1]).expanded_insets(EdgeInsets::ZERO),
2421            );
2422
2423            // The width of the SegmentedButton must be equal to the width of the parent widget.
2424            assert_eq!(segmented_button_width(tester), scaffold_width(tester));
2425        });
2426    }
2427
2428    // 'SegmentedButton does not expand when expandedInsets is null'
2429    #[test]
2430    fn a_segmented_button_without_expanded_insets_does_not_expand() {
2431        test_widgets(|tester| {
2432            let segments = vec![
2433                ButtonSegment::new(1).label(label("Segment 1")),
2434                ButtonSegment::new(2).label(label("Segment 2")),
2435            ];
2436            pump_button(tester, m3, SegmentedButton::new(segments, vec![1]));
2437
2438            // The width of the SegmentedButton must be less than the width of the parent widget.
2439            assert!(segmented_button_width(tester) < scaffold_width(tester));
2440        });
2441    }
2442
2443    // 'SegmentedButton vertical aligned children'
2444    #[test]
2445    fn a_vertical_segmented_button_stacks_its_segments() {
2446        test_widgets(|tester| {
2447            pump_button(
2448                tester,
2449                m3,
2450                SegmentedButton::new(numbered(&[0, 1, 2, 3]), vec![-1])
2451                    .direction(Axis::Vertical)
2452                    .on_selection_changed(|_app, _selected| {}),
2453            );
2454
2455            let mut previous_child_rect: Option<Rect> = None;
2456            for i in 0..=3 {
2457                let button = tester.element(
2458                    find::ancestor(find::text(&i.to_string()), find::by_type::<TextButton>())
2459                        .first(),
2460                );
2461                let current_child_rect = tester.get_rect(button);
2462                if let Some(previous) = previous_child_rect {
2463                    assert_eq!(current_child_rect.left, previous.left);
2464                    assert_eq!(current_child_rect.right, previous.right);
2465                    assert_eq!(current_child_rect.top, previous.top + previous.height());
2466                }
2467                previous_child_rect = Some(current_child_rect);
2468            }
2469        });
2470    }
2471
2472    // 'SegmentedButton does not crash at zero area'
2473    #[test]
2474    fn a_segmented_button_does_not_crash_at_zero_area() {
2475        test_widgets(|tester| {
2476            let root = {
2477                let app = tester.cell.borrow();
2478                material_app(
2479                    m3(&app),
2480                    Center::new()
2481                        .child(SizedBox::shrink().child(SegmentedButton::new(
2482                            vec![ButtonSegment::new("X").label(label("X"))],
2483                            vec!["X"],
2484                        )))
2485                        .into_widget(),
2486                )
2487            };
2488            tester.pump_widget(root);
2489
2490            let element = find::by_type::<SegmentedButton<&str>>().evaluate(tester)[0];
2491            let size = tester.get_size(element);
2492            assert_eq!(size, Size::ZERO);
2493        });
2494    }
2495
2496    // 'SegmentedButton should expand to fill the full width'
2497    #[test]
2498    fn a_vertical_segmented_button_expands_to_fill_the_full_width() {
2499        test_widgets(|tester| {
2500            const SCREEN_WIDTH: f64 = 800.0;
2501            let segments = ["All", "Top free", "Top paid"]
2502                .iter()
2503                .map(|value| ButtonSegment::new(*value).label(label(value)))
2504                .collect();
2505            let root = {
2506                let app = tester.cell.borrow();
2507                material_app(
2508                    m3(&app),
2509                    Scaffold::new()
2510                        .body(
2511                            Center::new().child(
2512                                SizedBox::new().width(f64::INFINITY).child(
2513                                    SegmentedButton::new(segments, vec!["All"])
2514                                        .direction(Axis::Vertical),
2515                                ),
2516                            ),
2517                        )
2518                        .into_widget(),
2519                )
2520            };
2521            tester.pump_widget(root);
2522            tester.pump_and_settle();
2523
2524            let button = find::by_type::<SegmentedButton<&str>>().evaluate(tester)[0];
2525            assert_eq!(tester.get_size(button).width(), SCREEN_WIDTH);
2526            for material in find::descendant(
2527                find::by_type::<SegmentedButton<&str>>(),
2528                find::by_type::<Material>(),
2529            )
2530            .evaluate(tester)
2531            {
2532                assert_eq!(tester.get_size(material).width(), SCREEN_WIDTH);
2533            }
2534        });
2535    }
2536
2537    // 'SegmentedButton has expected default mouse cursor on hover'
2538    #[test]
2539    fn a_segmented_button_has_the_basic_mouse_cursor_on_hover() {
2540        test_widgets(|tester| {
2541            pump_button(
2542                tester,
2543                m3,
2544                SegmentedButton::new(numbered(&[0, 1]), vec![0])
2545                    .on_selection_changed(|_app, _selected| {}),
2546            );
2547
2548            let mut gesture = TestPointer::mouse(1, 0);
2549            tester.add_pointer(&mut gesture, Offset::new(10.0, 10.0));
2550            assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
2551
2552            let center = text_center(tester, "0");
2553            tester.move_to(&mut gesture, center, false);
2554            tester.pump();
2555            assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
2556        });
2557    }
2558
2559    pub(crate) fn text_center(tester: &WidgetTester, text: &str) -> Offset {
2560        let element = find::text(text).evaluate(tester)[0];
2561        tester.get_rect(element).center()
2562    }
2563
2564    // 'SegmentedButton has expected mouse cursor when explicitly configured'
2565    #[test]
2566    fn a_segmented_button_has_the_mouse_cursor_it_is_configured_with() {
2567        test_widgets(|tester| {
2568            pump_button(
2569                tester,
2570                m3,
2571                SegmentedButton::new(numbered(&[0, 1]), vec![0])
2572                    .style(
2573                        ButtonStyle::new().mouse_cursor(Rc::new(WidgetStatePropertyAll::new(
2574                            Some(MouseCursorRef::from(SystemMouseCursors::GRAB)),
2575                        ))),
2576                    )
2577                    .on_selection_changed(|_app, _selected| {}),
2578            );
2579
2580            let mut gesture = TestPointer::mouse(1, 0);
2581            let element = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
2582            let center = tester.get_rect(element).center();
2583            tester.add_pointer(&mut gesture, center);
2584
2585            assert_eq!(tester.active_cursor(1), SystemMouseCursors::GRAB.into());
2586        });
2587    }
2588
2589    pub(crate) fn argb(color: Color) -> u32 {
2590        color.to_argb32()
2591    }
2592
2593    /// The colors of the rects the ink features of every material draw: Dart's
2594    /// `getOverlayColor`, which reads the ink render object the hovered segment's ink is on.
2595    pub(crate) fn ink_rect_colors(tester: &WidgetTester) -> Vec<u32> {
2596        tester
2597            .all::<crate::material::RenderInkFeatures>()
2598            .into_iter()
2599            .flat_map(|render| {
2600                let mut canvas = waft_embedder::Canvas::new();
2601                render.paint_ink_features(&mut tester.cell.borrow_mut(), &mut canvas, Offset::ZERO);
2602                crate::test_support::draw_calls(canvas.build().ops())
2603            })
2604            .filter_map(|drawn| match drawn {
2605                RecordedCall::Rect { color, .. } => Some(color.value()),
2606                _ => None,
2607            })
2608            .collect()
2609    }
2610
2611    pub(crate) fn mouse_at(tester: &mut WidgetTester, at: Offset) -> TestPointer {
2612        let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
2613        tester.add_pointer(&mut gesture, at);
2614        tester.move_to(&mut gesture, at, false);
2615        gesture
2616    }
2617
2618    fn enabled_states() -> WidgetStates {
2619        WidgetStates::new()
2620    }
2621
2622    fn disabled_states() -> WidgetStates {
2623        [WidgetState::Disabled].into_iter().collect()
2624    }
2625
2626    fn selected_states() -> WidgetStates {
2627        [WidgetState::Selected].into_iter().collect()
2628    }
2629
2630    fn button_style_of(tester: &WidgetTester, index: usize) -> ButtonStyle {
2631        let button = find::by_type::<TextButton>().evaluate(tester)[index];
2632        tester.widget(button, |button: &TextButton| {
2633            button
2634                .button_style_button_data()
2635                .style
2636                .clone()
2637                .expect("a style")
2638        })
2639    }
2640
2641    // 'SegmentedButton default overlayColor and foregroundColor resolve pressed state'
2642    #[test]
2643    fn a_segmented_button_resolves_its_default_overlay_and_foreground_colors_when_pressed() {
2644        test_widgets(|tester| {
2645            let theme = ThemeData::new(&tester.cell.borrow());
2646            pump_button(
2647                tester,
2648                m3,
2649                SegmentedButton::new(numbered(&[1, 2]), vec![1])
2650                    .on_selection_changed(|_app, _selected| {}),
2651            );
2652            let on_surface = theme.color_scheme.on_surface();
2653            let material = find::descendant(
2654                find::by_type::<TextButton>().last(),
2655                find::by_type::<Material>(),
2656            )
2657            .first();
2658            let text_color = |tester: &WidgetTester| {
2659                tester.widget(&material, |material: &Material| {
2660                    material
2661                        .text_style
2662                        .as_ref()
2663                        .and_then(|style| style.color.as_deref().copied())
2664                })
2665            };
2666
2667            // Hovered.
2668            let center = text_center(tester, "2");
2669            let mut gesture = mouse_at(tester, center);
2670            tester.pump_and_settle();
2671            assert!(ink_rect_colors(tester).contains(&argb(on_surface.with_opacity(0.08))));
2672            assert_eq!(text_color(tester), Some(on_surface));
2673
2674            // Highlighted (pressed).
2675            tester.down(&mut gesture, center);
2676            tester.pump_and_settle();
2677            let colors = ink_rect_colors(tester);
2678            assert!(colors.contains(&argb(on_surface.with_opacity(0.1))));
2679            assert_eq!(text_color(tester), Some(on_surface));
2680        });
2681    }
2682
2683    // 'SegmentedButton.styleFrom is applied to the SegmentedButton'
2684    #[test]
2685    fn a_segmented_button_applies_the_style_from_style_from() {
2686        test_widgets(|tester| {
2687            let foreground_color = Color::new(0xfffffff0);
2688            let background_color = Color::new(0xfffffff1);
2689            let selected_background_color = Color::new(0xfffffff2);
2690            let selected_foreground_color = Color::new(0xfffffff3);
2691            let disabled_background_color = Color::new(0xfffffff4);
2692            let disabled_foreground_color = Color::new(0xfffffff5);
2693            let enabled_mouse_cursor: MouseCursorRef = SystemMouseCursors::TEXT.into();
2694            let disabled_mouse_cursor: MouseCursorRef = SystemMouseCursors::GRAB.into();
2695
2696            let style_from_style = SegmentedButton::<i32>::style_from()
2697                .foreground_color(foreground_color)
2698                .background_color(background_color)
2699                .selected_foreground_color(selected_foreground_color)
2700                .selected_background_color(selected_background_color)
2701                .disabled_foreground_color(disabled_foreground_color)
2702                .disabled_background_color(disabled_background_color)
2703                .shadow_color(Color::new(0xfffffff6))
2704                .surface_tint_color(Color::new(0xfffffff7))
2705                .elevation(1.0)
2706                .text_style(TextStyle::new().color(Color::new(0xfffffff8)))
2707                .padding(EdgeInsets::all(2.0).into())
2708                .side(BorderSide {
2709                    color: Color::new(0xfffffff9),
2710                    ..BorderSide::default()
2711                })
2712                .shape(RoundedRectangleBorder {
2713                    border_radius: waft_painting::BorderRadius::all(Radius::circular(3.0)).into(),
2714                    ..RoundedRectangleBorder::default()
2715                })
2716                .enabled_mouse_cursor(enabled_mouse_cursor.clone())
2717                .disabled_mouse_cursor(disabled_mouse_cursor.clone())
2718                .visual_density(VisualDensity::COMPACT)
2719                .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
2720                .animation_duration(Duration::from_millis(100))
2721                .enable_feedback(true)
2722                .alignment(AlignmentGeometry::CENTER)
2723                .splash_factory(crate::no_splash::NoSplash::splash_factory())
2724                .build();
2725
2726            let mut segments = numbered(&[1, 2, 3]);
2727            segments[2].enabled = false;
2728            pump_button(
2729                tester,
2730                m3,
2731                SegmentedButton::new(segments, vec![2])
2732                    .style(style_from_style.clone())
2733                    .on_selection_changed(|_app, _selected| {})
2734                    .selected_icon(Icon::new(Some(Icons::alarm()))),
2735            );
2736
2737            // Test provided button style is applied to the enabled button segment.
2738            let button_style = button_style_of(tester, 0);
2739            let resolve_color = |property: &Option<WidgetStatePropertyRef<Option<Color>>>,
2740                                 states: &WidgetStates| {
2741                property
2742                    .as_ref()
2743                    .and_then(|property| property.resolve(states))
2744            };
2745            assert_eq!(
2746                resolve_color(&button_style.foreground_color, &enabled_states()),
2747                Some(foreground_color)
2748            );
2749            assert_eq!(
2750                resolve_color(&button_style.background_color, &enabled_states()),
2751                Some(background_color)
2752            );
2753            assert_eq!(button_style.overlay_color, style_from_style.overlay_color);
2754            assert_eq!(
2755                button_style.surface_tint_color,
2756                style_from_style.surface_tint_color
2757            );
2758            assert_eq!(button_style.elevation, style_from_style.elevation);
2759            assert_eq!(button_style.text_style, style_from_style.text_style);
2760            assert_eq!(button_style.padding, style_from_style.padding);
2761            assert_eq!(
2762                button_style
2763                    .mouse_cursor
2764                    .as_ref()
2765                    .and_then(|property| property.resolve(&enabled_states())),
2766                Some(enabled_mouse_cursor.clone())
2767            );
2768            assert_eq!(button_style.visual_density, style_from_style.visual_density);
2769            assert_eq!(
2770                button_style.tap_target_size,
2771                style_from_style.tap_target_size
2772            );
2773            assert_eq!(
2774                button_style.animation_duration,
2775                style_from_style.animation_duration
2776            );
2777            assert_eq!(
2778                button_style.enable_feedback,
2779                style_from_style.enable_feedback
2780            );
2781            assert_eq!(button_style.alignment, style_from_style.alignment);
2782            assert_eq!(button_style.splash_factory, style_from_style.splash_factory);
2783
2784            // Test provided button style is applied selected button segment.
2785            let button_style = button_style_of(tester, 1);
2786            assert_eq!(
2787                resolve_color(&button_style.foreground_color, &selected_states()),
2788                Some(selected_foreground_color)
2789            );
2790            assert_eq!(
2791                resolve_color(&button_style.background_color, &selected_states()),
2792                Some(selected_background_color)
2793            );
2794            assert_eq!(
2795                button_style
2796                    .mouse_cursor
2797                    .as_ref()
2798                    .and_then(|property| property.resolve(&enabled_states())),
2799                Some(enabled_mouse_cursor)
2800            );
2801
2802            // Test provided button style is applied disabled button segment.
2803            let button_style = button_style_of(tester, 2);
2804            assert_eq!(
2805                resolve_color(&button_style.foreground_color, &disabled_states()),
2806                Some(disabled_foreground_color)
2807            );
2808            assert_eq!(
2809                resolve_color(&button_style.background_color, &disabled_states()),
2810                Some(disabled_background_color)
2811            );
2812            assert_eq!(
2813                button_style
2814                    .mouse_cursor
2815                    .as_ref()
2816                    .and_then(|property| property.resolve(&disabled_states())),
2817                Some(disabled_mouse_cursor)
2818            );
2819
2820            // Test provided button style is applied to the segmented button material.
2821            let segmented_button = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
2822            let material = find::descendant(
2823                find::by_type::<SegmentedButton<i32>>(),
2824                find::by_type::<Material>(),
2825            )
2826            .evaluate(tester)[0];
2827            let (elevation, shadow_color, surface_tint_color) =
2828                tester.widget(material, |material: &Material| {
2829                    (
2830                        material.elevation,
2831                        material.shadow_color,
2832                        material.surface_tint_color,
2833                    )
2834                });
2835            let resolve = |property: &Option<WidgetStatePropertyRef<Option<f64>>>| {
2836                property
2837                    .as_ref()
2838                    .and_then(|property| property.resolve(&enabled_states()))
2839            };
2840            assert_eq!(Some(elevation), resolve(&style_from_style.elevation));
2841            assert_eq!(
2842                shadow_color,
2843                resolve_color(&style_from_style.shadow_color, &enabled_states())
2844            );
2845            assert_eq!(
2846                surface_tint_color,
2847                resolve_color(&style_from_style.surface_tint_color, &enabled_states())
2848            );
2849
2850            // Test provided button style border is applied to the segmented button border.
2851            let side_color: waft_embedder::valo::Color = style_from_style
2852                .side
2853                .as_ref()
2854                .and_then(|property| property.resolve(&enabled_states()))
2855                .expect("styleFrom gives a side")
2856                .color
2857                .into();
2858            let render = tester.render_object(segmented_button);
2859            assert!(tester.painted_ops(render).iter().any(|op| matches!(
2860                op,
2861                waft_embedder::valo::Op::DrawPath { path, paint, .. }
2862                    if path.elements().count() == 2 && paint.color == side_color
2863            )));
2864
2865            // Test foreground color is applied to the overlay color.
2866            let center = text_center(tester, "1");
2867            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
2868            tester.add_pointer(&mut gesture, center);
2869            tester.down(&mut gesture, center);
2870            tester.pump_and_settle();
2871            assert!(ink_rect_colors(tester).contains(&argb(foreground_color.with_opacity(0.08))));
2872        });
2873    }
2874
2875    fn overlay_style(color: Color) -> ButtonStyle {
2876        crate::icon_button::IconButton::style_from()
2877            .overlay_color(color)
2878            .build()
2879    }
2880
2881    // 'SegmentedButton.styleFrom overlayColor overrides default overlay color'
2882    #[test]
2883    fn a_style_from_overlay_color_overrides_the_default_overlay_color() {
2884        test_widgets(|tester| {
2885            let overlay_color = Color::new(0xffff0000);
2886            pump_button(
2887                tester,
2888                m3,
2889                SegmentedButton::new(
2890                    vec![
2891                        ButtonSegment::new(0).label(label("Option 1")),
2892                        ButtonSegment::new(1).label(label("Option 2")),
2893                    ],
2894                    vec![1],
2895                )
2896                .style(overlay_style(overlay_color))
2897                .on_selection_changed(|_app, _selected| {}),
2898            );
2899
2900            // Hovered selected segment,
2901            let center = text_center(tester, "Option 1");
2902            let mut gesture = mouse_at(tester, center);
2903            tester.pump_and_settle();
2904            assert!(ink_rect_colors(tester).contains(&argb(overlay_color.with_opacity(0.08))));
2905
2906            // Hovered unselected segment,
2907            let center = text_center(tester, "Option 2");
2908            tester.move_to(&mut gesture, center, false);
2909            tester.pump_and_settle();
2910            assert!(ink_rect_colors(tester).contains(&argb(overlay_color.with_opacity(0.08))));
2911
2912            // Highlighted unselected segment (pressed).
2913            let center = text_center(tester, "Option 1");
2914            tester.down(&mut gesture, center);
2915            tester.pump_and_settle();
2916            let colors = ink_rect_colors(tester);
2917            assert!(colors.contains(&argb(overlay_color.with_opacity(0.08))));
2918            assert!(colors.contains(&argb(overlay_color.with_opacity(0.1))));
2919            // Remove pressed and hovered states,
2920            tester.up(&gesture);
2921            tester.pump_and_settle();
2922            tester.move_to(&mut gesture, Offset::new(0.0, 50.0), false);
2923            tester.pump_and_settle();
2924
2925            // Highlighted selected segment (pressed)
2926            let center = text_center(tester, "Option 2");
2927            tester.down(&mut gesture, center);
2928            tester.pump_and_settle();
2929            let colors = ink_rect_colors(tester);
2930            assert!(colors.contains(&argb(overlay_color.with_opacity(0.08))));
2931            assert!(colors.contains(&argb(overlay_color.with_opacity(0.1))));
2932            // Remove pressed and hovered states,
2933            tester.up(&gesture);
2934            tester.pump_and_settle();
2935            tester.move_to(&mut gesture, Offset::new(0.0, 50.0), false);
2936            tester.pump_and_settle();
2937
2938            // Focused unselected segment.
2939            tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
2940            tester.pump_and_settle();
2941            assert!(ink_rect_colors(tester).contains(&argb(overlay_color.with_opacity(0.1))));
2942
2943            // Focused selected segment.
2944            tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
2945            tester.pump_and_settle();
2946            assert!(ink_rect_colors(tester).contains(&argb(overlay_color.with_opacity(0.1))));
2947        });
2948    }
2949
2950    // 'SegmentedButton.styleFrom can customize the button icon'
2951    #[test]
2952    fn a_style_from_icon_color_size_and_disabled_icon_color_customize_the_button_icon() {
2953        test_widgets(|tester| {
2954            let icon_color = Color::new(0xFFF000FF);
2955            let icon_size = 32.0;
2956            let disabled_icon_color = Color::new(0xFFFFF000);
2957            let build_button = |enabled: bool| {
2958                let segments = vec![
2959                    ButtonSegment::new(0)
2960                        .label(label("Add"))
2961                        .icon(Icon::new(Some(Icons::add()))),
2962                    ButtonSegment::new(1)
2963                        .label(label("Subtract"))
2964                        .icon(Icon::new(Some(Icons::remove()))),
2965                ];
2966                let button = SegmentedButton::new(segments, vec![0])
2967                    .style(
2968                        SegmentedButton::<i32>::style_from()
2969                            .icon_color(icon_color)
2970                            .icon_size(icon_size)
2971                            .disabled_icon_color(disabled_icon_color)
2972                            .build(),
2973                    )
2974                    .show_selected_icon(false);
2975                if enabled {
2976                    button.on_selection_changed(|_app, _selected| {})
2977                } else {
2978                    button
2979                }
2980            };
2981
2982            // Test enabled button.
2983            pump_button(tester, m3, build_button(true));
2984            let icon = tester.element(find::by_icon(&Icons::add()).first());
2985            assert_eq!(tester.get_size(icon), Size::new(icon_size, icon_size));
2986            assert_eq!(
2987                tester.glyph_style(icon).color.as_deref().copied(),
2988                Some(icon_color)
2989            );
2990
2991            // Test disabled button.
2992            pump_button(tester, m3, build_button(false));
2993            tester.pump_and_settle();
2994            let icon = tester.element(find::by_icon(&Icons::add()).first());
2995            assert_eq!(
2996                tester.glyph_style(icon).color.as_deref().copied(),
2997                Some(disabled_icon_color)
2998            );
2999        });
3000    }
3001
3002    /// Dart's `paints..rrect(color:)` on the segmented button.
3003    fn paints_rrect_of_color(tester: &WidgetTester, color: Color) -> bool {
3004        waft_rendering::testing::paints(
3005            &tester.painted_ops(tester.render_object(find::by_type::<SegmentedButton<i32>>())),
3006            &[waft_rendering::testing::PaintCall::rrect(Some(color))],
3007        )
3008        .is_ok()
3009    }
3010
3011    fn border_side_style(
3012        entries: Vec<(waft_widgets::WidgetStatesConstraintRef, Option<BorderSide>)>,
3013    ) -> ButtonStyle {
3014        ButtonStyle::new().side(<dyn WidgetStateProperty<Option<BorderSide>>>::from_map(
3015            entries,
3016        ))
3017    }
3018
3019    fn side_of(color: u32) -> Option<BorderSide> {
3020        Some(BorderSide {
3021            color: Color::new(color),
3022            ..BorderSide::default()
3023        })
3024    }
3025
3026    fn pump_sided(
3027        tester: &mut WidgetTester,
3028        enabled: bool,
3029        style: ButtonStyle,
3030        selected: Vec<i32>,
3031    ) {
3032        let segments = vec![
3033            ButtonSegment::new(0)
3034                .label(label("Add"))
3035                .icon(Icon::new(Some(Icons::add()))),
3036            ButtonSegment::new(1)
3037                .label(label("Subtract"))
3038                .icon(Icon::new(Some(Icons::remove()))),
3039            ButtonSegment::new(2)
3040                .label(label("Multiply"))
3041                .icon(Icon::new(Some(Icons::multiple_stop()))),
3042        ];
3043        let mut button = SegmentedButton::new(segments, selected)
3044            .style(style)
3045            .show_selected_icon(false)
3046            .empty_selection_allowed(true);
3047        if enabled {
3048            button = button.on_selection_changed(|_app, _selected| {});
3049        }
3050        pump_button(tester, m3, button);
3051    }
3052
3053    // 'SegmentedButton border sides respect states'
3054    #[test]
3055    fn a_segmented_button_border_sides_respect_states() {
3056        test_widgets(|tester| {
3057            let disabled_color = 0xFF999999;
3058            let hovered_color = 0xFF0000FF;
3059            let focused_color = 0xFF00FF00;
3060            let selected_color = 0xFF001234;
3061            let hovered_selected_color = 0xFF32CD32;
3062            let focused_selected_color = 0xFF0000CD;
3063            let enabled_color = 0xFFFF0000;
3064
3065            pump_sided(
3066                tester,
3067                true,
3068                border_side_style(vec![
3069                    (WidgetState::Hovered.into(), side_of(hovered_color)),
3070                    (WidgetState::Focused.into(), side_of(focused_color)),
3071                    (WidgetState::any(), side_of(enabled_color)),
3072                ]),
3073                vec![],
3074            );
3075
3076            assert!(paints_rrect_of_color(tester, Color::new(enabled_color)));
3077
3078            // Hovered.
3079            let center = text_center(tester, "Add");
3080            let mut gesture = mouse_at(tester, center);
3081            tester.pump_and_settle();
3082
3083            assert!(paints_rrect_of_color(tester, Color::new(hovered_color)));
3084
3085            tester.send(&gesture, waft_embedder::PointerChange::Remove);
3086            tester.pump_and_settle();
3087
3088            // Focused.
3089            tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
3090            tester.pump_and_settle();
3091
3092            assert!(paints_rrect_of_color(tester, Color::new(focused_color)));
3093
3094            pump_sided(
3095                tester,
3096                true,
3097                border_side_style(vec![
3098                    (
3099                        WidgetState::Hovered & WidgetState::Selected,
3100                        side_of(hovered_selected_color),
3101                    ),
3102                    (
3103                        WidgetState::Focused & WidgetState::Selected,
3104                        side_of(focused_selected_color),
3105                    ),
3106                    (WidgetState::Hovered.into(), side_of(hovered_color)),
3107                    (WidgetState::Focused.into(), side_of(focused_color)),
3108                    (WidgetState::any(), side_of(enabled_color)),
3109                ]),
3110                vec![1],
3111            );
3112            tester.pump_and_settle();
3113
3114            // Hovered.
3115            let center = text_center(tester, "Add");
3116            gesture = mouse_at(tester, center);
3117            tester.pump_and_settle();
3118
3119            assert!(paints_rrect_of_color(
3120                tester,
3121                Color::new(hovered_selected_color)
3122            ));
3123
3124            tester.send(&gesture, waft_embedder::PointerChange::Remove);
3125            tester.pump_and_settle();
3126
3127            // Focused.
3128            tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
3129            tester.pump_and_settle();
3130
3131            assert!(paints_rrect_of_color(
3132                tester,
3133                Color::new(focused_selected_color)
3134            ));
3135
3136            pump_sided(
3137                tester,
3138                false,
3139                border_side_style(vec![
3140                    (WidgetState::Disabled.into(), side_of(disabled_color)),
3141                    (WidgetState::any(), side_of(enabled_color)),
3142                ]),
3143                vec![],
3144            );
3145            tester.pump_and_settle();
3146
3147            assert!(paints_rrect_of_color(tester, Color::new(disabled_color)));
3148
3149            pump_sided(
3150                tester,
3151                true,
3152                border_side_style(vec![
3153                    (WidgetState::Selected.into(), side_of(selected_color)),
3154                    (WidgetState::any(), side_of(enabled_color)),
3155                ]),
3156                vec![1],
3157            );
3158            tester.pump_and_settle();
3159
3160            assert!(paints_rrect_of_color(tester, Color::new(selected_color)));
3161        });
3162    }
3163
3164    // 'SegmentedButton border sides respect disabled state'
3165    #[test]
3166    fn a_segmented_button_border_sides_respect_the_disabled_state_of_a_segment() {
3167        test_widgets(|tester| {
3168            let disabled_color = 0xFF999999;
3169            let enabled_color = 0xFFFF0000;
3170            pump_button(
3171                tester,
3172                m3,
3173                SegmentedButton::new(
3174                    vec![
3175                        ButtonSegment::new(0).label(label("0")),
3176                        ButtonSegment::new(1).label(label("1")).enabled(false),
3177                    ],
3178                    vec![0],
3179                )
3180                .style(border_side_style(vec![
3181                    (WidgetState::Disabled.into(), side_of(disabled_color)),
3182                    (WidgetState::any(), side_of(enabled_color)),
3183                ]))
3184                .on_selection_changed(|_app, _selected| {}),
3185            );
3186            tester.pump_and_settle();
3187
3188            // First segment has an enabled border, the second a disabled one, in that order.
3189            let element = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
3190            waft_rendering::testing::assert_paints(
3191                &tester.painted_ops(tester.render_object(element)),
3192                &[
3193                    waft_rendering::testing::PaintCall::rrect(Some(Color::new(enabled_color))),
3194                    waft_rendering::testing::PaintCall::rrect(Some(Color::new(disabled_color))),
3195                ],
3196            );
3197        });
3198    }
3199
3200    // 'Min button hit target height is 48.0 and min (painted) button height is 40 by default
3201    // with standard density and MaterialTapTargetSize.padded'
3202    #[test]
3203    fn a_segmented_button_is_48_high_to_hit_and_40_high_painted_by_default() {
3204        test_widgets(|tester| {
3205            use waft_embedder::valo::{Op, PaintStyle};
3206            let theme = ThemeData::new(&tester.cell.borrow());
3207            let icons = [
3208                Icons::calendar_view_day(),
3209                Icons::calendar_view_week(),
3210                Icons::calendar_view_month(),
3211                Icons::calendar_today(),
3212            ];
3213            let segments = ["Day", "Week", "Month", "Year"]
3214                .iter()
3215                .enumerate()
3216                .map(|(value, text)| {
3217                    ButtonSegment::new(value as i32)
3218                        .label(label(text))
3219                        .icon(Icon::new(Some(icons[value].clone())))
3220                })
3221                .collect();
3222            pump_button(
3223                tester,
3224                m3,
3225                SegmentedButton::new(segments, vec![0]).on_selection_changed(|_app, _value| {}),
3226            );
3227
3228            assert_eq!(theme.visual_density, VisualDensity::STANDARD);
3229            assert_eq!(
3230                theme.material_tap_target_size,
3231                MaterialTapTargetSize::Padded
3232            );
3233
3234            let button = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
3235            assert_eq!(tester.get_size(button).height(), 48.0);
3236            // Button border height is button.bottom(43.5) - button.top(4.5) + stoke width(1) = 40.
3237            let mut canvas = waft_embedder::Canvas::new();
3238            waft_painting::draw_rrect(
3239                &mut canvas,
3240                RRect::from_rect_and_corners(
3241                    Rect::from_ltrb(0.5, 4.5, 497.5, 43.5),
3242                    Radius::circular(19.5),
3243                    Radius::circular(19.5),
3244                    Radius::circular(19.5),
3245                    Radius::circular(19.5),
3246                ),
3247                &waft_embedder::Paint::default(),
3248            );
3249            let expected = canvas.build();
3250            let Some(Op::DrawPath {
3251                path: expected_path,
3252                ..
3253            }) = expected.ops().first()
3254            else {
3255                panic!("draw_rrect records a path");
3256            };
3257            let render = tester.render_object(button);
3258            assert!(tester.painted_ops(render).iter().any(|op| matches!(
3259                op,
3260                Op::DrawPath { path, paint, .. }
3261                    if path == expected_path
3262                        && matches!(paint.style, PaintStyle::Stroke(ref stroke) if stroke.width == 1.0)
3263            )));
3264        });
3265    }
3266
3267    // 'Focused segment does not lose focus when its selection state changes'
3268    #[test]
3269    fn a_focused_segment_keeps_its_focus_when_its_selection_state_changes() {
3270        test_widgets(|tester| {
3271            let recording = Recording::new(vec![1]);
3272            let frame_with_selection = |tester: &mut WidgetTester, selected: Vec<i32>| {
3273                pump_button(
3274                    tester,
3275                    m3,
3276                    SegmentedButton::new(numbered(&[1, 2]), selected)
3277                        .multi_selection_enabled(true)
3278                        .on_selection_changed(recording.on_selection_changed()),
3279                );
3280            };
3281
3282            frame_with_selection(tester, recording.selection());
3283            assert_eq!(recording.selection(), [1]);
3284            assert_eq!(recording.callback_count(), 0);
3285
3286            // Select segment 2.
3287            frame_with_selection(tester, vec![1, 2]);
3288            tester.pump_and_settle();
3289
3290            let segment_2_has_focus = |tester: &WidgetTester, request: bool| {
3291                let element = find::text("2").evaluate(tester)[0];
3292                let mut app = tester.cell.borrow_mut();
3293                let node = waft_widgets::Focus::of(&mut app, element, false, true);
3294                if request {
3295                    node.request_focus(&mut app, None);
3296                }
3297                node.has_focus(&app)
3298            };
3299
3300            // Set focus on segment 2.
3301            segment_2_has_focus(tester, true);
3302            tester.pump_and_settle();
3303            assert!(segment_2_has_focus(tester, false));
3304
3305            // Unselect segment 2.
3306            frame_with_selection(tester, vec![1]);
3307            tester.pump_and_settle();
3308
3309            // The button should still be focused.
3310            assert!(segment_2_has_focus(tester, false));
3311        });
3312    }
3313
3314    // 'SegmentedButton clips border path when drawing segments': each segment clipped to the
3315    // border, and the selected one's fill. The second segment's path, drawn at alpha 0, is a draw
3316    // with no visible effect (PORTING.md, `## Skipped`).
3317    #[test]
3318    fn a_segmented_button_clips_each_segment_to_the_border() {
3319        test_widgets(|tester| {
3320            use waft_rendering::testing::{PaintCall, assert_paints};
3321            pump_button(
3322                tester,
3323                m3,
3324                SegmentedButton::new(
3325                    vec![
3326                        ButtonSegment::new(0).label(label("Option 1")),
3327                        ButtonSegment::new(1).label(label("Option 2")),
3328                    ],
3329                    vec![0],
3330                )
3331                .on_selection_changed(|_app, _selected| {}),
3332            );
3333
3334            let element = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
3335            let render = tester.render_object(element);
3336            assert_paints(
3337                &tester.painted_ops(render),
3338                &[
3339                    PaintCall::Save,
3340                    // Clip the border.
3341                    PaintCall::Clip,
3342                    // Draw segment 0.
3343                    PaintCall::path(Some(Color::new(0xffe8def8))),
3344                    PaintCall::Save,
3345                    // Clip the border.
3346                    PaintCall::Clip,
3347                ],
3348            );
3349        });
3350    }
3351
3352    // 'SegmentedButton dividers matches border rect size'
3353    #[test]
3354    fn a_segmented_button_divider_matches_the_border_rect_size() {
3355        test_widgets(|tester| {
3356            use waft_embedder::valo::Op;
3357            pump_button(
3358                tester,
3359                m3,
3360                SegmentedButton::new(
3361                    vec![
3362                        ButtonSegment::new(0).label(label("Option 1")),
3363                        ButtonSegment::new(1).label(label("Option 2")),
3364                    ],
3365                    vec![0],
3366                )
3367                .on_selection_changed(|_app, _selected| {}),
3368            );
3369
3370            const TAP_TARGET_SIZE: f64 = 48.0;
3371            // Dart's x, 166.8000030517578, is 166.8 at f32; Waft's text measures one f32 step
3372            // narrower (166.79998779296875), so x is compared within f32 rounding.
3373            let within_f32 = |actual: f64, expected: f64| {
3374                (actual - expected).abs() <= f64::from(f32::EPSILON) * expected.abs().max(1.0)
3375            };
3376            let (p1, p2) = (
3377                Offset::new(166.8000030517578, 4.0),
3378                Offset::new(166.8000030517578, TAP_TARGET_SIZE - 4.0),
3379            );
3380            let element = find::by_type::<SegmentedButton<i32>>().evaluate(tester)[0];
3381            let render = tester.render_object(element);
3382            let lines: Vec<(Offset, Offset)> = tester
3383                .painted_ops(render)
3384                .iter()
3385                .filter_map(|op| match op {
3386                    Op::DrawPath { path, paint, .. }
3387                        if matches!(paint.style, waft_embedder::valo::PaintStyle::Stroke(_))
3388                            && path.elements().count() == 2 =>
3389                    {
3390                        let bounds = path.bounds();
3391                        Some((
3392                            Offset::new(f64::from(bounds.x), f64::from(bounds.y)),
3393                            Offset::new(
3394                                f64::from(bounds.x + bounds.width),
3395                                f64::from(bounds.y + bounds.height),
3396                            ),
3397                        ))
3398                    }
3399                    _ => None,
3400                })
3401                .collect();
3402            assert!(
3403                lines.iter().any(|(a, b)| {
3404                    within_f32(a.dx(), p1.dx())
3405                        && a.dy() == p1.dy()
3406                        && within_f32(b.dx(), p2.dx())
3407                        && b.dy() == p2.dy()
3408                }),
3409                "lines painted: {lines:?}"
3410            );
3411        });
3412    }
3413
3414    /// Dart's `_RenderSegmentedButton` fills no properties of its own; its
3415    /// `ContainerRenderObjectMixin` names the children `child 1`, `child 2`, ….
3416    #[test]
3417    fn a_segmented_button_describes_its_children_in_order() {
3418        use waft_foundation::{AppCell, DiagnosticsNode};
3419        use waft_painting::StadiumBorder;
3420        use waft_rendering::{BoxConstraints, RenderConstrainedBox};
3421
3422        let cell = AppCell::new();
3423        let mut app = cell.borrow_mut();
3424        let border = || OutlinedBorderRef::new(StadiumBorder::default());
3425        let render = RenderSegmentedButton::<i32>::new(
3426            &mut app,
3427            Vec::new(),
3428            border(),
3429            border(),
3430            TextDirection::Ltr,
3431            0.0,
3432            false,
3433            Axis::Horizontal,
3434        );
3435        let child = |app: &mut App| {
3436            RenderConstrainedBox::new(app, BoxConstraints::tight(Size::new(10.0, 10.0)), None)
3437                .as_box()
3438        };
3439        let first = child(&mut app);
3440        let second = child(&mut app);
3441        render.insert(&mut app, first, None);
3442        render.insert(&mut app, second, None);
3443
3444        let node = render.as_object().to_diagnostics_node(&app, None);
3445        let names: Vec<&str> = node
3446            .children()
3447            .iter()
3448            .filter_map(|child| child.name())
3449            .collect();
3450        assert_eq!(names, ["child 1", "child 2"]);
3451    }
3452}